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