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
106func (tx *PoolL2Tx) SetID() error {
107 txID, err := tx.L2Tx().CalculateTxID()
108 if err != nil {
109 return tracerr.Wrap(err)
110 }
111 tx.TxID = txID
112 return nil
113}
114
115// TxCompressedData spec:
116// [ 1 bits ] toBJJSign // 1 byte
117// [ 8 bits ] userFee // 1 byte
118// [ 40 bits ] nonce // 5 bytes
119// [ 32 bits ] tokenID // 4 bytes
120// [ 16 bits ] amountFloat16 // 2 bytes
121// [ 48 bits ] toIdx // 6 bytes
122// [ 48 bits ] fromIdx // 6 bytes
123// [ 16 bits ] chainId // 2 bytes
124// [ 32 bits ] signatureConstant // 4 bytes
125// Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
126func (tx *PoolL2Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
127 amountFloat16, err := NewFloat16(tx.Amount)
128 if err != nil {
129 return nil, tracerr.Wrap(err)
130 }
131 var b [31]byte
132
133 toBJJSign := byte(0)
134 pkSign, _ := babyjub.UnpackSignY(tx.ToBJJ)
135 if pkSign {
136 toBJJSign = byte(1)
137 }
138
139 b[0] = toBJJSign
140 b[1] = byte(tx.Fee)
141 nonceBytes, err := tx.Nonce.Bytes()
142 if err != nil {
143 return nil, tracerr.Wrap(err)
144 }
145 copy(b[2:7], nonceBytes[:])
146 copy(b[7:11], tx.TokenID.Bytes())
147 copy(b[11:13], amountFloat16.Bytes())
148 toIdxBytes, err := tx.ToIdx.Bytes()
149 if err != nil {
150 return nil, tracerr.Wrap(err)
151 }
152 copy(b[13:19], toIdxBytes[:])
153 fromIdxBytes, err := tx.FromIdx.Bytes()
154 if err != nil {
155 return nil, tracerr.Wrap(err)
156 }
157 copy(b[19:25], fromIdxBytes[:])
158 binary.BigEndian.PutUint16(b[25:27], chainID)
159 copy(b[27:31], SignatureConstantBytes[:])
160
161 bi := new(big.Int).SetBytes(b[:])
162 return bi, nil
163}
164
165// TxCompressedDataEmpty calculates the TxCompressedData of an empty
166// transaction
167func TxCompressedDataEmpty(chainID uint16) *big.Int {
168 var b [31]byte
169 binary.BigEndian.PutUint16(b[25:27], chainID)
170 copy(b[27:31], SignatureConstantBytes[:])
171 bi := new(big.Int).SetBytes(b[:])
172 return bi
173}
174
175// TxCompressedDataV2 spec:
176// [ 1 bits ] toBJJSign // 1 byte
177// [ 8 bits ] userFee // 1 byte
178// [ 40 bits ] nonce // 5 bytes
179// [ 32 bits ] tokenID // 4 bytes
180// [ 16 bits ] amountFloat16 // 2 bytes
181// [ 48 bits ] toIdx // 6 bytes
182// [ 48 bits ] fromIdx // 6 bytes
183// Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
184func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
185 if tx.Amount == nil {
186 tx.Amount = big.NewInt(0)
187 }
188 amountFloat16, err := NewFloat16(tx.Amount)
189 if err != nil {
190 return nil, tracerr.Wrap(err)
191 }
192 var b [25]byte
193 toBJJSign := byte(0)
194 if tx.ToBJJ != EmptyBJJComp {
195 sign, _ := babyjub.UnpackSignY(tx.ToBJJ)
196 if sign {
197 toBJJSign = byte(1)
198 }
199 }
200 b[0] = toBJJSign
201 b[1] = byte(tx.Fee)
202 nonceBytes, err := tx.Nonce.Bytes()
203 if err != nil {
204 return nil, tracerr.Wrap(err)
205 }
206 copy(b[2:7], nonceBytes[:])
207 copy(b[7:11], tx.TokenID.Bytes())
208 copy(b[11:13], amountFloat16.Bytes())
209 toIdxBytes, err := tx.ToIdx.Bytes()
210 if err != nil {
211 return nil, tracerr.Wrap(err)
212 }
213 copy(b[13:19], toIdxBytes[:])
214 fromIdxBytes, err := tx.FromIdx.Bytes()
215 if err != nil {
216 return nil, tracerr.Wrap(err)
217 }
218 copy(b[19:25], fromIdxBytes[:])
219
220 bi := new(big.Int).SetBytes(b[:])
221 return bi, nil
222}
223
224// RqTxCompressedDataV2 is like the TxCompressedDataV2 but using the 'Rq'
225// parameters. In a future iteration of the hermez-node, the 'Rq' parameters
226// can be inside a struct, which contains the 'Rq' transaction grouped inside,
227// so then computing the 'RqTxCompressedDataV2' would be just calling
228// 'tx.Rq.TxCompressedDataV2()'.
229// RqTxCompressedDataV2 spec:
230// [ 1 bits ] rqToBJJSign // 1 byte
231// [ 8 bits ] rqUserFee // 1 byte
232// [ 40 bits ] rqNonce // 5 bytes
233// [ 32 bits ] rqTokenID // 4 bytes
234// [ 16 bits ] rqAmountFloat16 // 2 bytes
235// [ 48 bits ] rqToIdx // 6 bytes
236// [ 48 bits ] rqFromIdx // 6 bytes
237// Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
238func (tx *PoolL2Tx) RqTxCompressedDataV2() (*big.Int, error) {
239 if tx.RqAmount == nil {
240 tx.RqAmount = big.NewInt(0)
241 }
242 amountFloat16, err := NewFloat16(tx.RqAmount)
243 if err != nil {
244 return nil, tracerr.Wrap(err)
245 }
246 var b [25]byte
247 rqToBJJSign := byte(0)
248 if tx.RqToBJJ != EmptyBJJComp {
249 sign, _ := babyjub.UnpackSignY(tx.RqToBJJ)
250 if sign {
251 rqToBJJSign = byte(1)
252 }
253 }
254 b[0] = rqToBJJSign
255 b[1] = byte(tx.RqFee)
256 nonceBytes, err := tx.RqNonce.Bytes()
257 if err != nil {
258 return nil, tracerr.Wrap(err)
259 }
260 copy(b[2:7], nonceBytes[:])
261 copy(b[7:11], tx.RqTokenID.Bytes())
262 copy(b[11:13], amountFloat16.Bytes())
263 toIdxBytes, err := tx.RqToIdx.Bytes()
264 if err != nil {
265 return nil, tracerr.Wrap(err)
266 }
267 copy(b[13:19], toIdxBytes[:])
268 fromIdxBytes, err := tx.RqFromIdx.Bytes()
269 if err != nil {
270 return nil, tracerr.Wrap(err)
271 }
272 copy(b[19:25], fromIdxBytes[:])
273
274 bi := new(big.Int).SetBytes(b[:])
275 return bi, nil
276}
277
278// HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will
279// be signed by the sender.
280func (tx *PoolL2Tx) HashToSign(chainID uint16) (*big.Int, error) {
281 toCompressedData, err := tx.TxCompressedData(chainID)
282 if err != nil {
283 return nil, tracerr.Wrap(err)
284 }
285 toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
286 rqToEthAddr := EthAddrToBigInt(tx.RqToEthAddr)
287
288 _, toBJJY := babyjub.UnpackSignY(tx.ToBJJ)
289
290 rqTxCompressedDataV2, err := tx.RqTxCompressedDataV2()
291 if err != nil {
292 return nil, tracerr.Wrap(err)
293 }
294
295 _, rqToBJJY := babyjub.UnpackSignY(tx.RqToBJJ)
296
297 return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJY, rqTxCompressedDataV2, rqToEthAddr, rqToBJJY})
298}
299
300// VerifySignature returns true if the signature verification is correct for the given PublicKeyComp
301func (tx *PoolL2Tx) VerifySignature(chainID uint16, pkComp babyjub.PublicKeyComp) bool {
302 h, err := tx.HashToSign(chainID)
303 if err != nil {
304 return false
305 }
306 s, err := tx.Signature.Decompress()
307 if err != nil {
308 return false
309 }
310 pk, err := pkComp.Decompress()
311 if err != nil {
312 return false
313 }
314 return pk.VerifyPoseidon(h, s)
315}
316
317// L2Tx returns a *L2Tx from the PoolL2Tx
318func (tx PoolL2Tx) L2Tx() L2Tx {
319 var toIdx Idx
320 if tx.ToIdx == Idx(0) {
321 toIdx = tx.AuxToIdx
322 } else {
323 toIdx = tx.ToIdx
324 }
325 return L2Tx{
326 TxID: tx.TxID,
327 FromIdx: tx.FromIdx,
328 ToIdx: toIdx,
329 TokenID: tx.TokenID,
330 Amount: tx.Amount,
331 Fee: tx.Fee,
332 Nonce: tx.Nonce,
333 Type: tx.Type,
334 }
335}
336
337// Tx returns a *Tx from the PoolL2Tx
338func (tx PoolL2Tx) Tx() Tx {
339 return Tx{
340 TxID: tx.TxID,
341 FromIdx: tx.FromIdx,
342 ToIdx: tx.ToIdx,
343 Amount: tx.Amount,
344 TokenID: tx.TokenID,
345 Nonce: &tx.Nonce,
346 Fee: &tx.Fee,
347 Type: tx.Type,
348 }
349}
350
351// PoolL2TxsToL2Txs returns an array of []L2Tx from an array of []PoolL2Tx
352func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error) {
353 l2Txs := make([]L2Tx, len(txs))
354 for i, poolTx := range txs {
355 l2Txs[i] = poolTx.L2Tx()
356 }
357 return l2Txs, nil
358}
359
360// TxIDsFromPoolL2Txs returns an array of TxID from the []PoolL2Tx
361func TxIDsFromPoolL2Txs(txs []PoolL2Tx) []TxID {
362 txIDs := make([]TxID, len(txs))
363 for i, tx := range txs {
364 txIDs[i] = tx.TxID
365 }
366 return txIDs
367}
368
369// PoolL2TxState is a string that represents the status of a L2 transaction
370type PoolL2TxState string
371
372const (
373 // PoolL2TxStatePending represents a valid L2Tx that hasn't started the
374 // forging process
375 PoolL2TxStatePending PoolL2TxState = "pend"
376 // PoolL2TxStateForging represents a valid L2Tx that has started the
377 // forging process
378 PoolL2TxStateForging PoolL2TxState = "fing"
379 // PoolL2TxStateForged represents a L2Tx that has already been forged
380 PoolL2TxStateForged PoolL2TxState = "fged"
381 // PoolL2TxStateInvalid represents a L2Tx that has been invalidated
382 PoolL2TxStateInvalid PoolL2TxState = "invl"
383)