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