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