hermez-node/common/pooll2tx.go
common/pooll2tx.goRaw
1package common
2
3import (
4 "fmt"
5 "math/big"
6 "time"
7
8 ethCommon "github.com/ethereum/go-ethereum/common"
9 "github.com/iden3/go-iden3-crypto/babyjub"
10 "github.com/iden3/go-iden3-crypto/poseidon"
11)
12
13// PoolL2Tx is a struct that represents a L2Tx sent by an account to the coordinator hat is waiting to be forged
14type PoolL2Tx struct {
15 // Stored in DB: mandatory fileds
16 TxID TxID `meddler:"tx_id"`
17 FromIdx Idx `meddler:"from_idx"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
18 ToIdx Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
19 ToEthAddr ethCommon.Address `meddler:"to_eth_addr"`
20 ToBJJ *babyjub.PublicKey `meddler:"to_bjj"` // TODO: stop using json, use scanner/valuer
21 TokenID TokenID `meddler:"token_id"`
22 Amount *big.Int `meddler:"amount,bigint"` // TODO: change to float16
23 AmountFloat float64 `meddler:"amount_f"` // TODO: change to float16
24 USD *float64 `meddler:"value_usd"` // TODO: change to float16
25 Fee FeeSelector `meddler:"fee"`
26 Nonce Nonce `meddler:"nonce"` // effective 40 bits used
27 State PoolL2TxState `meddler:"state"`
28 Signature *babyjub.Signature `meddler:"signature"` // tx signature
29 Timestamp time.Time `meddler:"timestamp,utctime"` // time when added to the tx pool
30 // Stored in DB: optional fileds, may be uninitialized
31 BatchNum BatchNum `meddler:"batch_num,zeroisnull"` // batchNum in which this tx was forged. Presence indicates "forged" state.
32 RqFromIdx Idx `meddler:"rq_from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
33 RqToIdx Idx `meddler:"rq_to_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
34 RqToEthAddr ethCommon.Address `meddler:"rq_to_eth_addr"`
35 RqToBJJ *babyjub.PublicKey `meddler:"rq_to_bjj"` // TODO: stop using json, use scanner/valuer
36 RqTokenID TokenID `meddler:"rq_token_id,zeroisnull"`
37 RqAmount *big.Int `meddler:"rq_amount,bigintnull"` // TODO: change to float16
38 RqFee FeeSelector `meddler:"rq_fee,zeroisnull"`
39 RqNonce uint64 `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
40 AbsoluteFee *float64 `meddler:"fee_usd"`
41 AbsoluteFeeUpdate *time.Time `meddler:"usd_update,utctime"`
42 Type TxType `meddler:"tx_type"`
43 // Extra metadata, may be uninitialized
44 RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
45 TokenSymbol string `meddler:"token_symbol"`
46}
47
48// TxCompressedData spec:
49// [ 1 bits ] toBJJSign // 1 byte
50// [ 8 bits ] userFee // 1 byte
51// [ 40 bits ] nonce // 5 bytes
52// [ 32 bits ] tokenID // 4 bytes
53// [ 16 bits ] amountFloat16 // 2 bytes
54// [ 48 bits ] toIdx // 6 bytes
55// [ 48 bits ] fromIdx // 6 bytes
56// [ 16 bits ] chainId // 2 bytes
57// [ 32 bits ] signatureConstant // 4 bytes
58// Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
59func (tx *PoolL2Tx) TxCompressedData() (*big.Int, error) {
60 // sigconstant
61 sc, ok := new(big.Int).SetString("3322668559", 10)
62 if !ok {
63 return nil, fmt.Errorf("error parsing SignatureConstant")
64 }
65
66 amountFloat16, err := NewFloat16(tx.Amount)
67 if err != nil {
68 return nil, err
69 }
70 var b [31]byte
71 toBJJSign := byte(0)
72 if babyjub.PointCoordSign(tx.ToBJJ.X) {
73 toBJJSign = byte(1)
74 }
75 b[0] = toBJJSign
76 b[1] = byte(tx.Fee)
77 nonceBytes, err := tx.Nonce.Bytes()
78 if err != nil {
79 return nil, err
80 }
81 copy(b[2:7], nonceBytes[:])
82 copy(b[7:11], tx.TokenID.Bytes())
83 copy(b[11:13], amountFloat16.Bytes())
84 toIdxBytes, err := tx.ToIdx.Bytes()
85 if err != nil {
86 return nil, err
87 }
88 copy(b[13:19], toIdxBytes[:])
89 fromIdxBytes, err := tx.FromIdx.Bytes()
90 if err != nil {
91 return nil, err
92 }
93 copy(b[19:25], fromIdxBytes[:])
94 copy(b[25:27], []byte{0, 1, 0, 0}) // TODO check js implementation (unexpected behaviour from test vector generated from js)
95 copy(b[27:31], sc.Bytes())
96
97 bi := new(big.Int).SetBytes(b[:])
98 return bi, nil
99}
100
101// TxCompressedDataV2 spec:
102// [ 1 bits ] toBJJSign // 1 byte
103// [ 8 bits ] userFee // 1 byte
104// [ 40 bits ] nonce // 5 bytes
105// [ 32 bits ] tokenID // 4 bytes
106// [ 16 bits ] amountFloat16 // 2 bytes
107// [ 48 bits ] toIdx // 6 bytes
108// [ 48 bits ] fromIdx // 6 bytes
109// Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
110func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
111 amountFloat16, err := NewFloat16(tx.Amount)
112 if err != nil {
113 return nil, err
114 }
115 var b [25]byte
116 toBJJSign := byte(0)
117 if babyjub.PointCoordSign(tx.ToBJJ.X) {
118 toBJJSign = byte(1)
119 }
120 b[0] = toBJJSign
121 b[1] = byte(tx.Fee)
122 nonceBytes, err := tx.Nonce.Bytes()
123 if err != nil {
124 return nil, err
125 }
126 copy(b[2:7], nonceBytes[:])
127 copy(b[7:11], tx.TokenID.Bytes())
128 copy(b[11:13], amountFloat16.Bytes())
129 toIdxBytes, err := tx.ToIdx.Bytes()
130 if err != nil {
131 return nil, err
132 }
133 copy(b[13:19], toIdxBytes[:])
134 fromIdxBytes, err := tx.FromIdx.Bytes()
135 if err != nil {
136 return nil, err
137 }
138 copy(b[19:25], fromIdxBytes[:])
139
140 bi := new(big.Int).SetBytes(b[:])
141 return bi, nil
142}
143
144// HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will be signed by the sender.
145func (tx *PoolL2Tx) HashToSign() (*big.Int, error) {
146 toCompressedData, err := tx.TxCompressedData()
147 if err != nil {
148 return nil, err
149 }
150 toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
151 toBJJAy := tx.ToBJJ.Y
152 rqTxCompressedDataV2, err := tx.TxCompressedDataV2()
153 if err != nil {
154 return nil, err
155 }
156
157 return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJAy, rqTxCompressedDataV2, EthAddrToBigInt(tx.RqToEthAddr), tx.RqToBJJ.Y})
158}
159
160// VerifySignature returns true if the signature verification is correct for the given PublicKey
161func (tx *PoolL2Tx) VerifySignature(pk *babyjub.PublicKey) bool {
162 h, err := tx.HashToSign()
163 if err != nil {
164 return false
165 }
166 return pk.VerifyPoseidon(h, tx.Signature)
167}
168
169// L2Tx returns a *L2Tx from the PoolL2Tx
170func (tx *PoolL2Tx) L2Tx() *L2Tx {
171 return &L2Tx{
172 TxID: tx.TxID,
173 BatchNum: tx.BatchNum,
174 FromIdx: tx.FromIdx,
175 ToIdx: tx.ToIdx,
176 Amount: tx.Amount,
177 Fee: tx.Fee,
178 Nonce: tx.Nonce,
179 Type: tx.Type,
180 }
181}
182
183// Tx returns a *Tx from the PoolL2Tx
184func (tx *PoolL2Tx) Tx() *Tx {
185 return &Tx{
186 TxID: tx.TxID,
187 FromIdx: tx.FromIdx,
188 ToIdx: tx.ToIdx,
189 Amount: tx.Amount,
190 Nonce: &tx.Nonce,
191 Fee: &tx.Fee,
192 Type: tx.Type,
193 }
194}
195
196// PoolL2TxsToL2Txs returns an array of []*L2Tx from an array of []*PoolL2Tx
197func PoolL2TxsToL2Txs(txs []*PoolL2Tx) []*L2Tx {
198 var r []*L2Tx
199 for _, tx := range txs {
200 r = append(r, tx.L2Tx())
201 }
202 return r
203}
204
205// PoolL2TxState is a struct that represents the status of a L2 transaction
206type PoolL2TxState string
207
208const (
209 // PoolL2TxStatePending represents a valid L2Tx that hasn't started the forging process
210 PoolL2TxStatePending PoolL2TxState = "pend"
211 // PoolL2TxStateForging represents a valid L2Tx that has started the forging process
212 PoolL2TxStateForging PoolL2TxState = "fing"
213 // PoolL2TxStateForged represents a L2Tx that has already been forged
214 PoolL2TxStateForged PoolL2TxState = "fged"
215 // PoolL2TxStateInvalid represents a L2Tx that has been invalidated
216 PoolL2TxStateInvalid PoolL2TxState = "invl"
217)