hermez-node/common/pooll2tx.go
common/pooll2tx.goRaw
1package common
2
3import (
4 "encoding/binary"
5 "errors"
6 "fmt"
7 "math/big"
8 "time"
9
10 ethCommon "github.com/ethereum/go-ethereum/common"
11 "github.com/hermeznetwork/tracerr"
12 "github.com/iden3/go-iden3-crypto/babyjub"
13 "github.com/iden3/go-iden3-crypto/poseidon"
14)
15
16// EmptyBJJComp contains the 32 byte array of a empty BabyJubJub PublicKey
17// Compressed. It is a valid point in the BabyJubJub curve, so does not give
18// errors when being decompressed.
19var EmptyBJJComp = babyjub.PublicKeyComp([32]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
20
21// PoolL2Tx is a struct that represents a L2Tx sent by an account to the
22// coordinator that is waiting to be forged
23type PoolL2Tx struct {
24 // Stored in DB: mandatory fileds
25
26 // TxID (12 bytes) for L2Tx is:
27 // bytes: | 1 | 6 | 5 |
28 // values: | type | FromIdx | Nonce |
29 TxID TxID `meddler:"tx_id"`
30 FromIdx Idx `meddler:"from_idx"`
31 ToIdx Idx `meddler:"to_idx,zeroisnull"`
32 // AuxToIdx is only used internally at the StateDB to avoid repeated
33 // computation when processing transactions (from Synchronizer,
34 // TxSelector, BatchBuilder)
35 AuxToIdx Idx `meddler:"-"`
36 ToEthAddr ethCommon.Address `meddler:"to_eth_addr,zeroisnull"`
37 ToBJJ babyjub.PublicKeyComp `meddler:"to_bjj,zeroisnull"`
38 TokenID TokenID `meddler:"token_id"`
39 Amount *big.Int `meddler:"amount,bigint"` // TODO: change to float16
40 Fee FeeSelector `meddler:"fee"`
41 Nonce Nonce `meddler:"nonce"` // effective 40 bits used
42 State PoolL2TxState `meddler:"state"`
43 Signature babyjub.SignatureComp `meddler:"signature"` // tx signature
44 Timestamp time.Time `meddler:"timestamp,utctime"` // time when added to the tx pool
45 // Stored in DB: optional fileds, may be uninitialized
46 RqFromIdx Idx `meddler:"rq_from_idx,zeroisnull"`
47 RqToIdx Idx `meddler:"rq_to_idx,zeroisnull"`
48 RqToEthAddr ethCommon.Address `meddler:"rq_to_eth_addr,zeroisnull"`
49 RqToBJJ babyjub.PublicKeyComp `meddler:"rq_to_bjj,zeroisnull"`
50 RqTokenID TokenID `meddler:"rq_token_id,zeroisnull"`
51 RqAmount *big.Int `meddler:"rq_amount,bigintnull"` // TODO: change to float16
52 RqFee FeeSelector `meddler:"rq_fee,zeroisnull"`
53 RqNonce Nonce `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
54 AbsoluteFee float64 `meddler:"fee_usd,zeroisnull"`
55 AbsoluteFeeUpdate time.Time `meddler:"usd_update,utctimez"`
56 Type TxType `meddler:"tx_type"`
57 // Extra metadata, may be uninitialized
58 RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
59}
60
61// NewPoolL2Tx returns the given L2Tx with the TxId & Type parameters calculated
62// from the L2Tx values
63func NewPoolL2Tx(tx *PoolL2Tx) (*PoolL2Tx, error) {
64 txTypeOld := tx.Type
65 if err := tx.SetType(); err != nil {
66 return nil, tracerr.Wrap(err)
67 }
68 // If original Type doesn't match the correct one, return error
69 if txTypeOld != "" && txTypeOld != tx.Type {
70 return nil, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s",
71 tx.Type, txTypeOld))
72 }
73
74 txIDOld := tx.TxID
75 if err := tx.SetID(); err != nil {
76 return nil, tracerr.Wrap(err)
77 }
78 // If original TxID doesn't match the correct one, return error
79 if txIDOld != (TxID{}) && txIDOld != tx.TxID {
80 return tx, tracerr.Wrap(fmt.Errorf("PoolL2Tx.TxID: %s, should be: %s",
81 tx.TxID.String(), txIDOld.String()))
82 }
83
84 return tx, nil
85}
86
87// SetType sets the type of the transaction
88func (tx *PoolL2Tx) SetType() error {
89 if tx.ToIdx >= IdxUserThreshold {
90 tx.Type = TxTypeTransfer
91 } else if tx.ToIdx == 1 {
92 tx.Type = TxTypeExit
93 } else if tx.ToIdx == 0 {
94 if tx.ToBJJ != EmptyBJJComp && tx.ToEthAddr == FFAddr {
95 tx.Type = TxTypeTransferToBJJ
96 } else if tx.ToEthAddr != FFAddr && tx.ToEthAddr != EmptyAddr {
97 tx.Type = TxTypeTransferToEthAddr
98 }
99 } else {
100 return tracerr.Wrap(errors.New("malformed transaction"))
101 }
102 return nil
103}
104
105// SetID sets the ID of the transaction. Uses (FromIdx, Nonce).
106func (tx *PoolL2Tx) SetID() error {
107 tx.TxID[0] = TxIDPrefixL2Tx
108 fromIdxBytes, err := tx.FromIdx.Bytes()
109 if err != nil {
110 return tracerr.Wrap(err)
111 }
112 copy(tx.TxID[1:7], fromIdxBytes[:])
113 nonceBytes, err := tx.Nonce.Bytes()
114 if err != nil {
115 return tracerr.Wrap(err)
116 }
117 copy(tx.TxID[7:12], nonceBytes[:])
118 return nil
119}
120
121// TxCompressedData spec:
122// [ 1 bits ] toBJJSign // 1 byte
123// [ 8 bits ] userFee // 1 byte
124// [ 40 bits ] nonce // 5 bytes
125// [ 32 bits ] tokenID // 4 bytes
126// [ 16 bits ] amountFloat16 // 2 bytes
127// [ 48 bits ] toIdx // 6 bytes
128// [ 48 bits ] fromIdx // 6 bytes
129// [ 16 bits ] chainId // 2 bytes
130// [ 32 bits ] signatureConstant // 4 bytes
131// Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
132func (tx *PoolL2Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
133 amountFloat16, err := NewFloat16(tx.Amount)
134 if err != nil {
135 return nil, tracerr.Wrap(err)
136 }
137 var b [31]byte
138
139 toBJJSign := byte(0)
140 pkSign, _ := babyjub.UnpackSignY(tx.ToBJJ)
141 if pkSign {
142 toBJJSign = byte(1)
143 }
144
145 b[0] = toBJJSign
146 b[1] = byte(tx.Fee)
147 nonceBytes, err := tx.Nonce.Bytes()
148 if err != nil {
149 return nil, tracerr.Wrap(err)
150 }
151 copy(b[2:7], nonceBytes[:])
152 copy(b[7:11], tx.TokenID.Bytes())
153 copy(b[11:13], amountFloat16.Bytes())
154 toIdxBytes, err := tx.ToIdx.Bytes()
155 if err != nil {
156 return nil, tracerr.Wrap(err)
157 }
158 copy(b[13:19], toIdxBytes[:])
159 fromIdxBytes, err := tx.FromIdx.Bytes()
160 if err != nil {
161 return nil, tracerr.Wrap(err)
162 }
163 copy(b[19:25], fromIdxBytes[:])
164 binary.BigEndian.PutUint16(b[25:27], chainID)
165 copy(b[27:31], SignatureConstantBytes[:])
166
167 bi := new(big.Int).SetBytes(b[:])
168 return bi, nil
169}
170
171// TxCompressedDataV2 spec:
172// [ 1 bits ] toBJJSign // 1 byte
173// [ 8 bits ] userFee // 1 byte
174// [ 40 bits ] nonce // 5 bytes
175// [ 32 bits ] tokenID // 4 bytes
176// [ 16 bits ] amountFloat16 // 2 bytes
177// [ 48 bits ] toIdx // 6 bytes
178// [ 48 bits ] fromIdx // 6 bytes
179// Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
180func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
181 if tx.Amount == nil {
182 tx.Amount = big.NewInt(0)
183 }
184 amountFloat16, err := NewFloat16(tx.Amount)
185 if err != nil {
186 return nil, tracerr.Wrap(err)
187 }
188 var b [25]byte
189 toBJJSign := byte(0)
190 if tx.ToBJJ != EmptyBJJComp {
191 sign, _ := babyjub.UnpackSignY(tx.ToBJJ)
192 if sign {
193 toBJJSign = byte(1)
194 }
195 }
196 b[0] = toBJJSign
197 b[1] = byte(tx.Fee)
198 nonceBytes, err := tx.Nonce.Bytes()
199 if err != nil {
200 return nil, tracerr.Wrap(err)
201 }
202 copy(b[2:7], nonceBytes[:])
203 copy(b[7:11], tx.TokenID.Bytes())
204 copy(b[11:13], amountFloat16.Bytes())
205 toIdxBytes, err := tx.ToIdx.Bytes()
206 if err != nil {
207 return nil, tracerr.Wrap(err)
208 }
209 copy(b[13:19], toIdxBytes[:])
210 fromIdxBytes, err := tx.FromIdx.Bytes()
211 if err != nil {
212 return nil, tracerr.Wrap(err)
213 }
214 copy(b[19:25], fromIdxBytes[:])
215
216 bi := new(big.Int).SetBytes(b[:])
217 return bi, nil
218}
219
220// RqTxCompressedDataV2 is like the TxCompressedDataV2 but using the 'Rq'
221// parameters. In a future iteration of the hermez-node, the 'Rq' parameters
222// can be inside a struct, which contains the 'Rq' transaction grouped inside,
223// so then computing the 'RqTxCompressedDataV2' would be just calling
224// 'tx.Rq.TxCompressedDataV2()'.
225// RqTxCompressedDataV2 spec:
226// [ 1 bits ] rqToBJJSign // 1 byte
227// [ 8 bits ] rqUserFee // 1 byte
228// [ 40 bits ] rqNonce // 5 bytes
229// [ 32 bits ] rqTokenID // 4 bytes
230// [ 16 bits ] rqAmountFloat16 // 2 bytes
231// [ 48 bits ] rqToIdx // 6 bytes
232// [ 48 bits ] rqFromIdx // 6 bytes
233// Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
234func (tx *PoolL2Tx) RqTxCompressedDataV2() (*big.Int, error) {
235 if tx.RqAmount == nil {
236 tx.RqAmount = big.NewInt(0)
237 }
238 amountFloat16, err := NewFloat16(tx.RqAmount)
239 if err != nil {
240 return nil, tracerr.Wrap(err)
241 }
242 var b [25]byte
243 rqToBJJSign := byte(0)
244 if tx.RqToBJJ != EmptyBJJComp {
245 sign, _ := babyjub.UnpackSignY(tx.RqToBJJ)
246 if sign {
247 rqToBJJSign = byte(1)
248 }
249 }
250 b[0] = rqToBJJSign
251 b[1] = byte(tx.RqFee)
252 nonceBytes, err := tx.RqNonce.Bytes()
253 if err != nil {
254 return nil, tracerr.Wrap(err)
255 }
256 copy(b[2:7], nonceBytes[:])
257 copy(b[7:11], tx.RqTokenID.Bytes())
258 copy(b[11:13], amountFloat16.Bytes())
259 toIdxBytes, err := tx.RqToIdx.Bytes()
260 if err != nil {
261 return nil, tracerr.Wrap(err)
262 }
263 copy(b[13:19], toIdxBytes[:])
264 fromIdxBytes, err := tx.RqFromIdx.Bytes()
265 if err != nil {
266 return nil, tracerr.Wrap(err)
267 }
268 copy(b[19:25], fromIdxBytes[:])
269
270 bi := new(big.Int).SetBytes(b[:])
271 return bi, nil
272}
273
274// HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will be signed by the sender.
275func (tx *PoolL2Tx) HashToSign(chainID uint16) (*big.Int, error) {
276 toCompressedData, err := tx.TxCompressedData(chainID)
277 if err != nil {
278 return nil, tracerr.Wrap(err)
279 }
280 toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
281 rqToEthAddr := EthAddrToBigInt(tx.RqToEthAddr)
282
283 _, toBJJY := babyjub.UnpackSignY(tx.ToBJJ)
284
285 rqTxCompressedDataV2, err := tx.RqTxCompressedDataV2()
286 if err != nil {
287 return nil, tracerr.Wrap(err)
288 }
289
290 _, rqToBJJY := babyjub.UnpackSignY(tx.RqToBJJ)
291
292 return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJY, rqTxCompressedDataV2, rqToEthAddr, rqToBJJY})
293}
294
295// VerifySignature returns true if the signature verification is correct for the given PublicKeyComp
296func (tx *PoolL2Tx) VerifySignature(chainID uint16, pkComp babyjub.PublicKeyComp) bool {
297 h, err := tx.HashToSign(chainID)
298 if err != nil {
299 return false
300 }
301 s, err := tx.Signature.Decompress()
302 if err != nil {
303 return false
304 }
305 pk, err := pkComp.Decompress()
306 if err != nil {
307 return false
308 }
309 return pk.VerifyPoseidon(h, s)
310}
311
312// L2Tx returns a *L2Tx from the PoolL2Tx
313func (tx PoolL2Tx) L2Tx() L2Tx {
314 var toIdx Idx
315 if tx.ToIdx == Idx(0) {
316 toIdx = tx.AuxToIdx
317 } else {
318 toIdx = tx.ToIdx
319 }
320 return L2Tx{
321 TxID: tx.TxID,
322 FromIdx: tx.FromIdx,
323 ToIdx: toIdx,
324 Amount: tx.Amount,
325 Fee: tx.Fee,
326 Nonce: tx.Nonce,
327 Type: tx.Type,
328 }
329}
330
331// Tx returns a *Tx from the PoolL2Tx
332func (tx PoolL2Tx) Tx() Tx {
333 return Tx{
334 TxID: tx.TxID,
335 FromIdx: tx.FromIdx,
336 ToIdx: tx.ToIdx,
337 Amount: tx.Amount,
338 TokenID: tx.TokenID,
339 Nonce: &tx.Nonce,
340 Fee: &tx.Fee,
341 Type: tx.Type,
342 }
343}
344
345// PoolL2TxsToL2Txs returns an array of []L2Tx from an array of []PoolL2Tx
346func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error) {
347 l2Txs := make([]L2Tx, len(txs))
348 for i, poolTx := range txs {
349 l2Txs[i] = poolTx.L2Tx()
350 }
351 return l2Txs, nil
352}
353
354// TxIDsFromPoolL2Txs returns an array of TxID from the []PoolL2Tx
355func TxIDsFromPoolL2Txs(txs []PoolL2Tx) []TxID {
356 txIDs := make([]TxID, len(txs))
357 for i, tx := range txs {
358 txIDs[i] = tx.TxID
359 }
360 return txIDs
361}
362
363// PoolL2TxState is a string that represents the status of a L2 transaction
364type PoolL2TxState string
365
366const (
367 // PoolL2TxStatePending represents a valid L2Tx that hasn't started the
368 // forging process
369 PoolL2TxStatePending PoolL2TxState = "pend"
370 // PoolL2TxStateForging represents a valid L2Tx that has started the
371 // forging process
372 PoolL2TxStateForging PoolL2TxState = "fing"
373 // PoolL2TxStateForged represents a L2Tx that has already been forged
374 PoolL2TxStateForged PoolL2TxState = "fged"
375 // PoolL2TxStateInvalid represents a L2Tx that has been invalidated
376 PoolL2TxStateInvalid PoolL2TxState = "invl"
377)