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 "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 if tx.UserOrigin {
115 if tx.ToForgeL1TxsNum == nil {
116 return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil"))
117 }
118 tx.TxID[0] = TxIDPrefixL1UserTx
119 var toForgeL1TxsNumBytes [8]byte
120 binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
121 copy(tx.TxID[1:9], toForgeL1TxsNumBytes[:])
122 } else {
123 if tx.BatchNum == nil {
124 return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil"))
125 }
126 tx.TxID[0] = TxIDPrefixL1CoordTx
127 var batchNumBytes [8]byte
128 binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
129 copy(tx.TxID[1:9], batchNumBytes[:])
130 }
131 var positionBytes [2]byte
132 binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
133 copy(tx.TxID[9:11], positionBytes[:])
134
135 return nil
136}
137
138// Tx returns a *Tx from the L1Tx
139func (tx L1Tx) Tx() Tx {
140 f := new(big.Float).SetInt(tx.EffectiveAmount)
141 amountFloat, _ := f.Float64()
142 userOrigin := new(bool)
143 *userOrigin = tx.UserOrigin
144 genericTx := Tx{
145 IsL1: true,
146 TxID: tx.TxID,
147 Type: tx.Type,
148 Position: tx.Position,
149 FromIdx: tx.FromIdx,
150 ToIdx: tx.ToIdx,
151 Amount: tx.EffectiveAmount,
152 AmountFloat: amountFloat,
153 TokenID: tx.TokenID,
154 ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
155 UserOrigin: userOrigin,
156 FromEthAddr: tx.FromEthAddr,
157 FromBJJ: tx.FromBJJ,
158 DepositAmount: tx.EffectiveDepositAmount,
159 EthBlockNum: tx.EthBlockNum,
160 }
161 if tx.DepositAmount != nil {
162 lf := new(big.Float).SetInt(tx.DepositAmount)
163 depositAmountFloat, _ := lf.Float64()
164 genericTx.DepositAmountFloat = &depositAmountFloat
165 }
166 return genericTx
167}
168
169// TxCompressedData spec:
170// [ 1 bits ] empty (toBJJSign) // 1 byte
171// [ 8 bits ] empty (userFee) // 1 byte
172// [ 40 bits ] empty (nonce) // 5 bytes
173// [ 32 bits ] tokenID // 4 bytes
174// [ 16 bits ] amountFloat16 // 2 bytes
175// [ 48 bits ] toIdx // 6 bytes
176// [ 48 bits ] fromIdx // 6 bytes
177// [ 16 bits ] chainId // 2 bytes
178// [ 32 bits ] empty (signatureConstant) // 4 bytes
179// Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
180func (tx L1Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
181 amountFloat16, err := NewFloat16(tx.Amount)
182 if err != nil {
183 return nil, tracerr.Wrap(err)
184 }
185
186 var b [31]byte
187 // b[0:7] empty: no ToBJJSign, no fee, no nonce
188 copy(b[7:11], tx.TokenID.Bytes())
189 copy(b[11:13], amountFloat16.Bytes())
190 toIdxBytes, err := tx.ToIdx.Bytes()
191 if err != nil {
192 return nil, tracerr.Wrap(err)
193 }
194 copy(b[13:19], toIdxBytes[:])
195 fromIdxBytes, err := tx.FromIdx.Bytes()
196 if err != nil {
197 return nil, tracerr.Wrap(err)
198 }
199 copy(b[19:25], fromIdxBytes[:])
200 binary.BigEndian.PutUint16(b[25:27], chainID)
201 copy(b[27:31], SignatureConstantBytes[:])
202
203 bi := new(big.Int).SetBytes(b[:])
204 return bi, nil
205}
206
207// BytesDataAvailability encodes a L1Tx into []byte for the Data Availability
208// [ fromIdx | toIdx | amountFloat16 | Fee ]
209func (tx *L1Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
210 idxLen := nLevels / 8 //nolint:gomnd
211
212 b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
213
214 fromIdxBytes, err := tx.FromIdx.Bytes()
215 if err != nil {
216 return nil, tracerr.Wrap(err)
217 }
218 copy(b[0:idxLen], fromIdxBytes[6-idxLen:])
219 toIdxBytes, err := tx.ToIdx.Bytes()
220 if err != nil {
221 return nil, tracerr.Wrap(err)
222 }
223 copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
224
225 if tx.EffectiveAmount != nil {
226 amountFloat16, err := NewFloat16(tx.EffectiveAmount)
227 if err != nil {
228 return nil, tracerr.Wrap(err)
229 }
230 copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
231 }
232 // fee = 0 (as is L1Tx) b[10:11]
233 return b[:], nil
234}
235
236// L1TxFromDataAvailability decodes a L1Tx from []byte (Data Availability)
237func L1TxFromDataAvailability(b []byte, nLevels uint32) (*L1Tx, error) {
238 idxLen := nLevels / 8 //nolint:gomnd
239
240 fromIdxBytes := b[0:idxLen]
241 toIdxBytes := b[idxLen : idxLen*2]
242 amountBytes := b[idxLen*2 : idxLen*2+2]
243
244 l1tx := L1Tx{}
245 fromIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(fromIdxBytes, 6))
246 if err != nil {
247 return nil, tracerr.Wrap(err)
248 }
249 l1tx.FromIdx = fromIdx
250 toIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(toIdxBytes, 6))
251 if err != nil {
252 return nil, tracerr.Wrap(err)
253 }
254 l1tx.ToIdx = toIdx
255 l1tx.EffectiveAmount = Float16FromBytes(amountBytes).BigInt()
256 return &l1tx, nil
257}
258
259// BytesGeneric returns the generic representation of a L1Tx. This method is
260// used to compute the []byte representation of a L1UserTx, and also to compute
261// the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
262// for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
263func (tx *L1Tx) BytesGeneric() ([]byte, error) {
264 var b [L1UserTxBytesLen]byte
265 copy(b[0:20], tx.FromEthAddr.Bytes())
266 if tx.FromBJJ != EmptyBJJComp {
267 pkCompL := tx.FromBJJ
268 pkCompB := SwapEndianness(pkCompL[:])
269 copy(b[20:52], pkCompB[:])
270 }
271 fromIdxBytes, err := tx.FromIdx.Bytes()
272 if err != nil {
273 return nil, tracerr.Wrap(err)
274 }
275 copy(b[52:58], fromIdxBytes[:])
276 depositAmountFloat16, err := NewFloat16(tx.DepositAmount)
277 if err != nil {
278 return nil, tracerr.Wrap(err)
279 }
280 copy(b[58:60], depositAmountFloat16.Bytes())
281 amountFloat16, err := NewFloat16(tx.Amount)
282 if err != nil {
283 return nil, tracerr.Wrap(err)
284 }
285 copy(b[60:62], amountFloat16.Bytes())
286 copy(b[62:66], tx.TokenID.Bytes())
287 toIdxBytes, err := tx.ToIdx.Bytes()
288 if err != nil {
289 return nil, tracerr.Wrap(err)
290 }
291 copy(b[66:72], toIdxBytes[:])
292 return b[:], nil
293}
294
295// BytesUser encodes a L1UserTx into []byte
296func (tx *L1Tx) BytesUser() ([]byte, error) {
297 if !tx.UserOrigin {
298 return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx"))
299 }
300 return tx.BytesGeneric()
301}
302
303// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
304func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
305 if tx.UserOrigin {
306 return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx"))
307 }
308 var b [L1CoordinatorTxBytesLen]byte
309 v := compressedSignatureBytes[64]
310 s := compressedSignatureBytes[32:64]
311 r := compressedSignatureBytes[0:32]
312 b[0] = v
313 copy(b[1:33], s)
314 copy(b[33:65], r)
315 pkCompL := tx.FromBJJ
316 pkCompB := SwapEndianness(pkCompL[:])
317 copy(b[65:97], pkCompB[:])
318 copy(b[97:101], tx.TokenID.Bytes())
319 return b[:], nil
320}
321
322// L1UserTxFromBytes decodes a L1Tx from []byte
323func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
324 if len(b) != L1UserTxBytesLen {
325 return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b)))
326 }
327
328 tx := &L1Tx{
329 UserOrigin: true,
330 }
331 var err error
332 tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
333
334 pkCompB := b[20:52]
335 pkCompL := SwapEndianness(pkCompB)
336 copy(tx.FromBJJ[:], pkCompL)
337 fromIdx, err := IdxFromBytes(b[52:58])
338 if err != nil {
339 return nil, tracerr.Wrap(err)
340 }
341 tx.FromIdx = fromIdx
342 tx.DepositAmount = Float16FromBytes(b[58:60]).BigInt()
343 tx.Amount = Float16FromBytes(b[60:62]).BigInt()
344 tx.TokenID, err = TokenIDFromBytes(b[62:66])
345 if err != nil {
346 return nil, tracerr.Wrap(err)
347 }
348 tx.ToIdx, err = IdxFromBytes(b[66:72])
349 if err != nil {
350 return nil, tracerr.Wrap(err)
351 }
352
353 return tx, nil
354}
355
356func signHash(data []byte) []byte {
357 msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
358 return crypto.Keccak256([]byte(msg))
359}
360
361// L1CoordinatorTxFromBytes decodes a L1Tx from []byte
362func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) {
363 if len(b) != L1CoordinatorTxBytesLen {
364 return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b)))
365 }
366
367 bytesMessage := []byte("I authorize this babyjubjub key for hermez rollup account creation")
368
369 tx := &L1Tx{
370 UserOrigin: false,
371 }
372 var err error
373 v := b[0]
374 s := b[1:33]
375 r := b[33:65]
376 pkCompB := b[65:97]
377 pkCompL := SwapEndianness(pkCompB)
378 copy(tx.FromBJJ[:], pkCompL)
379 tx.TokenID, err = TokenIDFromBytes(b[97:101])
380 if err != nil {
381 return nil, tracerr.Wrap(err)
382 }
383 tx.Amount = big.NewInt(0)
384 tx.DepositAmount = big.NewInt(0)
385 if int(v) > 0 {
386 // L1CoordinatorTX ETH
387 // Ethereum adds 27 to v
388 v = b[0] - byte(27) //nolint:gomnd
389 chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
390 var data []byte
391 data = append(data, bytesMessage...)
392 data = append(data, pkCompB...)
393 data = append(data, chainIDBytes[:]...)
394 data = append(data, hermezAddress.Bytes()...)
395 var signature []byte
396 signature = append(signature, r[:]...)
397 signature = append(signature, s[:]...)
398 signature = append(signature, v)
399 hash := signHash(data)
400 pubKeyBytes, err := crypto.Ecrecover(hash, signature)
401 if err != nil {
402 return nil, tracerr.Wrap(err)
403 }
404 pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
405 if err != nil {
406 return nil, tracerr.Wrap(err)
407 }
408 tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
409 } else {
410 // L1Coordinator Babyjub
411 tx.FromEthAddr = RollupConstEthAddressInternalOnly
412 }
413 return tx, nil
414}