hermez-node/common/l1tx.go
common/l1tx.goRaw
1package common
2
3import (
4 "encoding/binary"
5 "fmt"
6 "math/big"
7
8 ethCommon "github.com/ethereum/go-ethereum/common"
9 ethCrypto "github.com/ethereum/go-ethereum/crypto"
10 "github.com/hermeznetwork/tracerr"
11 "github.com/iden3/go-iden3-crypto/babyjub"
12)
13
14const (
15 // L1UserTxBytesLen is the length of the byte array that represents the L1Tx
16 L1UserTxBytesLen = 72
17 // L1CoordinatorTxBytesLen is the length of the byte array that represents the L1CoordinatorTx
18 L1CoordinatorTxBytesLen = 101
19)
20
21// L1Tx is a struct that represents a L1 tx
22type L1Tx struct {
23 // Stored in DB: mandatory fileds
24
25 // TxID (12 bytes) for L1Tx is:
26 // bytes: | 1 | 8 | 2 | 1 |
27 // values: | type | ToForgeL1TxsNum | Position | 0 (padding) |
28 // where type:
29 // - L1UserTx: 0
30 // - L1CoordinatorTx: 1
31 TxID TxID `meddler:"id"`
32 ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
33 Position int `meddler:"position"`
34 UserOrigin bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
35 FromIdx Idx `meddler:"from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.DepositAmount (deposit)
36 EffectiveFromIdx Idx `meddler:"effective_from_idx,zeroisnull"`
37 FromEthAddr ethCommon.Address `meddler:"from_eth_addr,zeroisnull"`
38 FromBJJ babyjub.PublicKeyComp `meddler:"from_bjj,zeroisnull"`
39 ToIdx Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
40 TokenID TokenID `meddler:"token_id"`
41 Amount *big.Int `meddler:"amount,bigint"`
42 // EffectiveAmount only applies to L1UserTx.
43 EffectiveAmount *big.Int `meddler:"effective_amount,bigintnull"`
44 DepositAmount *big.Int `meddler:"deposit_amount,bigint"`
45 // EffectiveDepositAmount only applies to L1UserTx.
46 EffectiveDepositAmount *big.Int `meddler:"effective_deposit_amount,bigintnull"`
47 EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
48 Type TxType `meddler:"type"`
49 BatchNum *BatchNum `meddler:"batch_num"`
50}
51
52// NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
53// from the L1Tx values
54func NewL1Tx(tx *L1Tx) (*L1Tx, error) {
55 txTypeOld := tx.Type
56 if err := tx.SetType(); err != nil {
57 return nil, tracerr.Wrap(err)
58 }
59 // If original Type doesn't match the correct one, return error
60 if txTypeOld != "" && txTypeOld != tx.Type {
61 return nil, tracerr.Wrap(fmt.Errorf("L1Tx.Type: %s, should be: %s",
62 tx.Type, txTypeOld))
63 }
64
65 txIDOld := tx.TxID
66 if err := tx.SetID(); err != nil {
67 return nil, tracerr.Wrap(err)
68 }
69 // If original TxID doesn't match the correct one, return error
70 if txIDOld != (TxID{}) && txIDOld != tx.TxID {
71 return tx, tracerr.Wrap(fmt.Errorf("L1Tx.TxID: %s, should be: %s",
72 tx.TxID.String(), txIDOld.String()))
73 }
74
75 return tx, nil
76}
77
78// SetType sets the type of the transaction
79func (tx *L1Tx) SetType() error {
80 if tx.FromIdx == 0 {
81 if tx.ToIdx == Idx(0) {
82 tx.Type = TxTypeCreateAccountDeposit
83 } else if tx.ToIdx >= IdxUserThreshold {
84 tx.Type = TxTypeCreateAccountDepositTransfer
85 } else {
86 return tracerr.Wrap(fmt.Errorf(
87 "Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
88 }
89 } else if tx.FromIdx >= IdxUserThreshold {
90 if tx.ToIdx == Idx(0) {
91 tx.Type = TxTypeDeposit
92 } else if tx.ToIdx == Idx(1) {
93 tx.Type = TxTypeForceExit
94 } else if tx.ToIdx >= IdxUserThreshold {
95 if tx.DepositAmount.Int64() == int64(0) {
96 tx.Type = TxTypeForceTransfer
97 } else {
98 tx.Type = TxTypeDepositTransfer
99 }
100 } else {
101 return tracerr.Wrap(fmt.Errorf(
102 "Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
103 }
104 } else {
105 return tracerr.Wrap(fmt.Errorf(
106 "Can not determine type of L1Tx, invalid FromIdx value: %d", tx.FromIdx))
107 }
108 return nil
109}
110
111// SetID sets the ID of the transaction. For L1UserTx uses (ToForgeL1TxsNum,
112// Position), for L1CoordinatorTx uses (BatchNum, Position).
113func (tx *L1Tx) SetID() error {
114 var b []byte
115 if tx.UserOrigin {
116 if tx.ToForgeL1TxsNum == nil {
117 return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil"))
118 }
119 tx.TxID[0] = TxIDPrefixL1UserTx
120
121 var toForgeL1TxsNumBytes [8]byte
122 binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
123 b = append(b, toForgeL1TxsNumBytes[:]...)
124 } else {
125 if tx.BatchNum == nil {
126 return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil"))
127 }
128 tx.TxID[0] = TxIDPrefixL1CoordTx
129
130 var batchNumBytes [8]byte
131 binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
132 b = append(b, batchNumBytes[:]...)
133 }
134 var positionBytes [2]byte
135 binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
136 b = append(b, positionBytes[:]...)
137
138 // calculate hash
139 h := ethCrypto.Keccak256Hash(b).Bytes()
140
141 copy(tx.TxID[1:], h)
142
143 return nil
144}
145
146// Tx returns a *Tx from the L1Tx
147func (tx L1Tx) Tx() Tx {
148 f := new(big.Float).SetInt(tx.EffectiveAmount)
149 amountFloat, _ := f.Float64()
150 userOrigin := new(bool)
151 *userOrigin = tx.UserOrigin
152 genericTx := Tx{
153 IsL1: true,
154 TxID: tx.TxID,
155 Type: tx.Type,
156 Position: tx.Position,
157 FromIdx: tx.FromIdx,
158 ToIdx: tx.ToIdx,
159 Amount: tx.EffectiveAmount,
160 AmountFloat: amountFloat,
161 TokenID: tx.TokenID,
162 ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
163 UserOrigin: userOrigin,
164 FromEthAddr: tx.FromEthAddr,
165 FromBJJ: tx.FromBJJ,
166 DepositAmount: tx.EffectiveDepositAmount,
167 EthBlockNum: tx.EthBlockNum,
168 }
169 if tx.DepositAmount != nil {
170 lf := new(big.Float).SetInt(tx.DepositAmount)
171 depositAmountFloat, _ := lf.Float64()
172 genericTx.DepositAmountFloat = &depositAmountFloat
173 }
174 return genericTx
175}
176
177// TxCompressedData spec:
178// [ 1 bits ] empty (toBJJSign) // 1 byte
179// [ 8 bits ] empty (userFee) // 1 byte
180// [ 40 bits ] empty (nonce) // 5 bytes
181// [ 32 bits ] tokenID // 4 bytes
182// [ 16 bits ] amountFloat16 // 2 bytes
183// [ 48 bits ] toIdx // 6 bytes
184// [ 48 bits ] fromIdx // 6 bytes
185// [ 16 bits ] chainId // 2 bytes
186// [ 32 bits ] empty (signatureConstant) // 4 bytes
187// Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
188func (tx L1Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
189 amountFloat16, err := NewFloat16(tx.Amount)
190 if err != nil {
191 return nil, tracerr.Wrap(err)
192 }
193
194 var b [31]byte
195 // b[0:7] empty: no ToBJJSign, no fee, no nonce
196 copy(b[7:11], tx.TokenID.Bytes())
197 copy(b[11:13], amountFloat16.Bytes())
198 toIdxBytes, err := tx.ToIdx.Bytes()
199 if err != nil {
200 return nil, tracerr.Wrap(err)
201 }
202 copy(b[13:19], toIdxBytes[:])
203 fromIdxBytes, err := tx.FromIdx.Bytes()
204 if err != nil {
205 return nil, tracerr.Wrap(err)
206 }
207 copy(b[19:25], fromIdxBytes[:])
208 binary.BigEndian.PutUint16(b[25:27], chainID)
209 copy(b[27:31], SignatureConstantBytes[:])
210
211 bi := new(big.Int).SetBytes(b[:])
212 return bi, nil
213}
214
215// BytesDataAvailability encodes a L1Tx into []byte for the Data Availability
216// [ fromIdx | toIdx | amountFloat16 | Fee ]
217func (tx *L1Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
218 idxLen := nLevels / 8 //nolint:gomnd
219
220 b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
221
222 fromIdxBytes, err := tx.FromIdx.Bytes()
223 if err != nil {
224 return nil, tracerr.Wrap(err)
225 }
226 copy(b[0:idxLen], fromIdxBytes[6-idxLen:])
227 toIdxBytes, err := tx.ToIdx.Bytes()
228 if err != nil {
229 return nil, tracerr.Wrap(err)
230 }
231 copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
232
233 if tx.EffectiveAmount != nil {
234 amountFloat16, err := NewFloat16(tx.EffectiveAmount)
235 if err != nil {
236 return nil, tracerr.Wrap(err)
237 }
238 copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
239 }
240 // fee = 0 (as is L1Tx) b[10:11]
241 return b[:], nil
242}
243
244// L1TxFromDataAvailability decodes a L1Tx from []byte (Data Availability)
245func L1TxFromDataAvailability(b []byte, nLevels uint32) (*L1Tx, error) {
246 idxLen := nLevels / 8 //nolint:gomnd
247
248 fromIdxBytes := b[0:idxLen]
249 toIdxBytes := b[idxLen : idxLen*2]
250 amountBytes := b[idxLen*2 : idxLen*2+2]
251
252 l1tx := L1Tx{}
253 fromIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(fromIdxBytes, 6))
254 if err != nil {
255 return nil, tracerr.Wrap(err)
256 }
257 l1tx.FromIdx = fromIdx
258 toIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(toIdxBytes, 6))
259 if err != nil {
260 return nil, tracerr.Wrap(err)
261 }
262 l1tx.ToIdx = toIdx
263 l1tx.EffectiveAmount = Float16FromBytes(amountBytes).BigInt()
264 return &l1tx, nil
265}
266
267// BytesGeneric returns the generic representation of a L1Tx. This method is
268// used to compute the []byte representation of a L1UserTx, and also to compute
269// the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
270// for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
271func (tx *L1Tx) BytesGeneric() ([]byte, error) {
272 var b [L1UserTxBytesLen]byte
273 copy(b[0:20], tx.FromEthAddr.Bytes())
274 if tx.FromBJJ != EmptyBJJComp {
275 pkCompL := tx.FromBJJ
276 pkCompB := SwapEndianness(pkCompL[:])
277 copy(b[20:52], pkCompB[:])
278 }
279 fromIdxBytes, err := tx.FromIdx.Bytes()
280 if err != nil {
281 return nil, tracerr.Wrap(err)
282 }
283 copy(b[52:58], fromIdxBytes[:])
284 depositAmountFloat16, err := NewFloat16(tx.DepositAmount)
285 if err != nil {
286 return nil, tracerr.Wrap(err)
287 }
288 copy(b[58:60], depositAmountFloat16.Bytes())
289 amountFloat16, err := NewFloat16(tx.Amount)
290 if err != nil {
291 return nil, tracerr.Wrap(err)
292 }
293 copy(b[60:62], amountFloat16.Bytes())
294 copy(b[62:66], tx.TokenID.Bytes())
295 toIdxBytes, err := tx.ToIdx.Bytes()
296 if err != nil {
297 return nil, tracerr.Wrap(err)
298 }
299 copy(b[66:72], toIdxBytes[:])
300 return b[:], nil
301}
302
303// BytesUser encodes a L1UserTx into []byte
304func (tx *L1Tx) BytesUser() ([]byte, error) {
305 if !tx.UserOrigin {
306 return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx"))
307 }
308 return tx.BytesGeneric()
309}
310
311// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
312func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
313 if tx.UserOrigin {
314 return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx"))
315 }
316 var b [L1CoordinatorTxBytesLen]byte
317 v := compressedSignatureBytes[64]
318 s := compressedSignatureBytes[32:64]
319 r := compressedSignatureBytes[0:32]
320 b[0] = v
321 copy(b[1:33], s)
322 copy(b[33:65], r)
323 pkCompL := tx.FromBJJ
324 pkCompB := SwapEndianness(pkCompL[:])
325 copy(b[65:97], pkCompB[:])
326 copy(b[97:101], tx.TokenID.Bytes())
327 return b[:], nil
328}
329
330// L1UserTxFromBytes decodes a L1Tx from []byte
331func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
332 if len(b) != L1UserTxBytesLen {
333 return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b)))
334 }
335
336 tx := &L1Tx{
337 UserOrigin: true,
338 }
339 var err error
340 tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
341
342 pkCompB := b[20:52]
343 pkCompL := SwapEndianness(pkCompB)
344 copy(tx.FromBJJ[:], pkCompL)
345 fromIdx, err := IdxFromBytes(b[52:58])
346 if err != nil {
347 return nil, tracerr.Wrap(err)
348 }
349 tx.FromIdx = fromIdx
350 tx.DepositAmount = Float16FromBytes(b[58:60]).BigInt()
351 tx.Amount = Float16FromBytes(b[60:62]).BigInt()
352 tx.TokenID, err = TokenIDFromBytes(b[62:66])
353 if err != nil {
354 return nil, tracerr.Wrap(err)
355 }
356 tx.ToIdx, err = IdxFromBytes(b[66:72])
357 if err != nil {
358 return nil, tracerr.Wrap(err)
359 }
360
361 return tx, nil
362}
363
364func signHash(data []byte) []byte {
365 msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
366 return ethCrypto.Keccak256([]byte(msg))
367}
368
369// L1CoordinatorTxFromBytes decodes a L1Tx from []byte
370func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) {
371 if len(b) != L1CoordinatorTxBytesLen {
372 return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b)))
373 }
374
375 bytesMessage := []byte("I authorize this babyjubjub key for hermez rollup account creation")
376
377 tx := &L1Tx{
378 UserOrigin: false,
379 }
380 var err error
381 v := b[0]
382 s := b[1:33]
383 r := b[33:65]
384 pkCompB := b[65:97]
385 pkCompL := SwapEndianness(pkCompB)
386 copy(tx.FromBJJ[:], pkCompL)
387 tx.TokenID, err = TokenIDFromBytes(b[97:101])
388 if err != nil {
389 return nil, tracerr.Wrap(err)
390 }
391 tx.Amount = big.NewInt(0)
392 tx.DepositAmount = big.NewInt(0)
393 if int(v) > 0 {
394 // L1CoordinatorTX ETH
395 // Ethereum adds 27 to v
396 v = b[0] - byte(27) //nolint:gomnd
397 chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
398 var data []byte
399 data = append(data, bytesMessage...)
400 data = append(data, pkCompB...)
401 data = append(data, chainIDBytes[:]...)
402 data = append(data, hermezAddress.Bytes()...)
403 var signature []byte
404 signature = append(signature, r[:]...)
405 signature = append(signature, s[:]...)
406 signature = append(signature, v)
407 hash := signHash(data)
408 pubKeyBytes, err := ethCrypto.Ecrecover(hash, signature)
409 if err != nil {
410 return nil, tracerr.Wrap(err)
411 }
412 pubKey, err := ethCrypto.UnmarshalPubkey(pubKeyBytes)
413 if err != nil {
414 return nil, tracerr.Wrap(err)
415 }
416 tx.FromEthAddr = ethCrypto.PubkeyToAddress(*pubKey)
417 } else {
418 // L1Coordinator Babyjub
419 tx.FromEthAddr = RollupConstEthAddressInternalOnly
420 }
421 return tx, nil
422}