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