hermez-node/common/l2tx.go
common/l2tx.goRaw
1package common
2
3import (
4 "crypto/sha256"
5 "fmt"
6 "math/big"
7
8 "github.com/hermeznetwork/tracerr"
9)
10
11// L2Tx is a struct that represents an already forged L2 tx
12type L2Tx struct {
13 // Stored in DB: mandatory fileds
14 TxID TxID `meddler:"id"`
15 BatchNum BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged.
16 Position int `meddler:"position"`
17 FromIdx Idx `meddler:"from_idx"`
18 ToIdx Idx `meddler:"to_idx"`
19 // TokenID is filled by the TxProcessor
20 TokenID TokenID `meddler:"token_id"`
21 Amount *big.Int `meddler:"amount,bigint"`
22 Fee FeeSelector `meddler:"fee"`
23 // Nonce is filled by the TxProcessor
24 Nonce Nonce `meddler:"nonce"`
25 Type TxType `meddler:"type"`
26 EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L2Tx was added to the queue
27}
28
29// NewL2Tx returns the given L2Tx with the TxId & Type parameters calculated
30// from the L2Tx values
31func NewL2Tx(tx *L2Tx) (*L2Tx, error) {
32 txTypeOld := tx.Type
33 if err := tx.SetType(); err != nil {
34 return nil, tracerr.Wrap(err)
35 }
36 // If original Type doesn't match the correct one, return error
37 if txTypeOld != "" && txTypeOld != tx.Type {
38 return nil, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s",
39 tx.Type, txTypeOld))
40 }
41
42 txIDOld := tx.TxID
43 if err := tx.SetID(); err != nil {
44 return nil, tracerr.Wrap(err)
45 }
46 // If original TxID doesn't match the correct one, return error
47 if txIDOld != (TxID{}) && txIDOld != tx.TxID {
48 return tx, tracerr.Wrap(fmt.Errorf("L2Tx.TxID: %s, should be: %s",
49 tx.TxID.String(), txIDOld.String()))
50 }
51
52 return tx, nil
53}
54
55// SetType sets the type of the transaction. Uses (FromIdx, Nonce).
56func (tx *L2Tx) SetType() error {
57 if tx.ToIdx == Idx(1) {
58 tx.Type = TxTypeExit
59 } else if tx.ToIdx >= IdxUserThreshold {
60 tx.Type = TxTypeTransfer
61 } else {
62 return tracerr.Wrap(fmt.Errorf(
63 "cannot determine type of L2Tx, invalid ToIdx value: %d", tx.ToIdx))
64 }
65 return nil
66}
67
68// SetID sets the ID of the transaction
69func (tx *L2Tx) SetID() error {
70 txID, err := tx.CalculateTxID()
71 if err != nil {
72 return err
73 }
74 tx.TxID = txID
75 return nil
76}
77
78// CalculateTxID returns the TxID of the transaction. This method is used to
79// set the TxID for L2Tx and for PoolL2Tx.
80func (tx L2Tx) CalculateTxID() ([TxIDLen]byte, error) {
81 var txID TxID
82 var b []byte
83 // FromIdx
84 fromIdxBytes, err := tx.FromIdx.Bytes()
85 if err != nil {
86 return txID, tracerr.Wrap(err)
87 }
88 b = append(b, fromIdxBytes[:]...)
89 // TokenID
90 b = append(b, tx.TokenID.Bytes()[:]...)
91 // Amount
92 amountFloat16, err := NewFloat16(tx.Amount)
93 if err != nil {
94 return txID, tracerr.Wrap(fmt.Errorf("%s: %d", err, tx.Amount))
95 }
96 b = append(b, amountFloat16.Bytes()...)
97 // Nonce
98 nonceBytes, err := tx.Nonce.Bytes()
99 if err != nil {
100 return txID, tracerr.Wrap(err)
101 }
102 b = append(b, nonceBytes[:]...)
103 // Fee
104 b = append(b, byte(tx.Fee))
105
106 // calculate hash
107 h := sha256.New()
108 _, err = h.Write(b)
109 if err != nil {
110 return txID, tracerr.Wrap(err)
111 }
112 r := h.Sum(nil)
113
114 txID[0] = TxIDPrefixL2Tx
115 copy(txID[1:], r)
116 return txID, nil
117}
118
119// Tx returns a *Tx from the L2Tx
120func (tx *L2Tx) Tx() *Tx {
121 batchNum := new(BatchNum)
122 *batchNum = tx.BatchNum
123 fee := new(FeeSelector)
124 *fee = tx.Fee
125 nonce := new(Nonce)
126 *nonce = tx.Nonce
127 return &Tx{
128 IsL1: false,
129 TxID: tx.TxID,
130 Type: tx.Type,
131 Position: tx.Position,
132 FromIdx: tx.FromIdx,
133 ToIdx: tx.ToIdx,
134 TokenID: tx.TokenID,
135 Amount: tx.Amount,
136 BatchNum: batchNum,
137 EthBlockNum: tx.EthBlockNum,
138 Fee: fee,
139 Nonce: nonce,
140 }
141}
142
143// PoolL2Tx returns the data structure of PoolL2Tx with the parameters of a
144// L2Tx filled
145func (tx L2Tx) PoolL2Tx() *PoolL2Tx {
146 return &PoolL2Tx{
147 TxID: tx.TxID,
148 FromIdx: tx.FromIdx,
149 ToIdx: tx.ToIdx,
150 TokenID: tx.TokenID,
151 Amount: tx.Amount,
152 Fee: tx.Fee,
153 Nonce: tx.Nonce,
154 Type: tx.Type,
155 }
156}
157
158// L2TxsToPoolL2Txs returns an array of []*PoolL2Tx from an array of []*L2Tx,
159// where the PoolL2Tx only have the parameters of a L2Tx filled.
160func L2TxsToPoolL2Txs(txs []L2Tx) []PoolL2Tx {
161 var r []PoolL2Tx
162 for _, tx := range txs {
163 r = append(r, *tx.PoolL2Tx())
164 }
165 return r
166}
167
168// TxIDsFromL2Txs returns an array of TxID from the []L2Tx
169func TxIDsFromL2Txs(txs []L2Tx) []TxID {
170 txIDs := make([]TxID, len(txs))
171 for i, tx := range txs {
172 txIDs[i] = tx.TxID
173 }
174 return txIDs
175}
176
177// BytesDataAvailability encodes a L2Tx into []byte for the Data Availability
178// [ fromIdx | toIdx | amountFloat16 | Fee ]
179func (tx L2Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
180 idxLen := nLevels / 8 //nolint:gomnd
181
182 b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
183
184 fromIdxBytes, err := tx.FromIdx.Bytes()
185 if err != nil {
186 return nil, tracerr.Wrap(err)
187 }
188 copy(b[0:idxLen], fromIdxBytes[6-idxLen:]) // [6-idxLen:] as is BigEndian
189
190 toIdxBytes, err := tx.ToIdx.Bytes()
191 if err != nil {
192 return nil, tracerr.Wrap(err)
193 }
194 copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
195
196 amountFloat16, err := NewFloat16(tx.Amount)
197 if err != nil {
198 return nil, tracerr.Wrap(err)
199 }
200
201 copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
202 b[idxLen*2+2] = byte(tx.Fee)
203
204 return b[:], nil
205}
206
207// L2TxFromBytesDataAvailability decodes a L2Tx from []byte (Data Availability)
208func L2TxFromBytesDataAvailability(b []byte, nLevels int) (*L2Tx, error) {
209 idxLen := nLevels / 8 //nolint:gomnd
210 tx := &L2Tx{}
211 var err error
212
213 var paddedFromIdxBytes [6]byte
214 copy(paddedFromIdxBytes[6-idxLen:], b[0:idxLen])
215 tx.FromIdx, err = IdxFromBytes(paddedFromIdxBytes[:])
216 if err != nil {
217 return nil, tracerr.Wrap(err)
218 }
219
220 var paddedToIdxBytes [6]byte
221 copy(paddedToIdxBytes[6-idxLen:6], b[idxLen:idxLen*2])
222 tx.ToIdx, err = IdxFromBytes(paddedToIdxBytes[:])
223 if err != nil {
224 return nil, tracerr.Wrap(err)
225 }
226
227 tx.Amount = Float16FromBytes(b[idxLen*2 : idxLen*2+2]).BigInt()
228 tx.Fee = FeeSelector(b[idxLen*2+2])
229 return tx, nil
230}