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.LoadAmount (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 LoadAmount *big.Int `meddler:"load_amount,bigint"`
44 // EffectiveLoadAmount only applies to L1UserTx.
45 EffectiveLoadAmount *big.Int `meddler:"effective_load_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.LoadAmount.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 LoadAmount: tx.EffectiveLoadAmount,
144 EthBlockNum: tx.EthBlockNum,
145 }
146 if tx.LoadAmount != nil {
147 lf := new(big.Float).SetInt(tx.LoadAmount)
148 loadAmountFloat, _ := lf.Float64()
149 genericTx.LoadAmountFloat = &loadAmountFloat
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// BytesGeneric returns the generic representation of a L1Tx. This method is
221// used to compute the []byte representation of a L1UserTx, and also to compute
222// the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
223// for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
224func (tx *L1Tx) BytesGeneric() ([]byte, error) {
225 var b [L1UserTxBytesLen]byte
226 copy(b[0:20], tx.FromEthAddr.Bytes())
227 if tx.FromBJJ != nil {
228 pkCompL := tx.FromBJJ.Compress()
229 pkCompB := SwapEndianness(pkCompL[:])
230 copy(b[20:52], pkCompB[:])
231 }
232 fromIdxBytes, err := tx.FromIdx.Bytes()
233 if err != nil {
234 return nil, tracerr.Wrap(err)
235 }
236 copy(b[52:58], fromIdxBytes[:])
237 loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
238 if err != nil {
239 return nil, tracerr.Wrap(err)
240 }
241 copy(b[58:60], loadAmountFloat16.Bytes())
242 amountFloat16, err := NewFloat16(tx.Amount)
243 if err != nil {
244 return nil, tracerr.Wrap(err)
245 }
246 copy(b[60:62], amountFloat16.Bytes())
247 copy(b[62:66], tx.TokenID.Bytes())
248 toIdxBytes, err := tx.ToIdx.Bytes()
249 if err != nil {
250 return nil, tracerr.Wrap(err)
251 }
252 copy(b[66:72], toIdxBytes[:])
253 return b[:], nil
254}
255
256// BytesUser encodes a L1UserTx into []byte
257func (tx *L1Tx) BytesUser() ([]byte, error) {
258 if !tx.UserOrigin {
259 return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx"))
260 }
261 return tx.BytesGeneric()
262}
263
264// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
265func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
266 if tx.UserOrigin {
267 return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx"))
268 }
269 var b [L1CoordinatorTxBytesLen]byte
270 v := compressedSignatureBytes[64]
271 s := compressedSignatureBytes[32:64]
272 r := compressedSignatureBytes[0:32]
273 b[0] = v
274 copy(b[1:33], s)
275 copy(b[33:65], r)
276 pkCompL := tx.FromBJJ.Compress()
277 pkCompB := SwapEndianness(pkCompL[:])
278 copy(b[65:97], pkCompB[:])
279 copy(b[97:101], tx.TokenID.Bytes())
280 return b[:], nil
281}
282
283// L1UserTxFromBytes decodes a L1Tx from []byte
284func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
285 if len(b) != L1UserTxBytesLen {
286 return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b)))
287 }
288
289 tx := &L1Tx{
290 UserOrigin: true,
291 }
292 var err error
293 tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
294
295 pkCompB := b[20:52]
296 pkCompL := SwapEndianness(pkCompB)
297 var pkComp babyjub.PublicKeyComp
298 copy(pkComp[:], pkCompL)
299 tx.FromBJJ, err = pkComp.Decompress()
300 if err != nil {
301 return nil, tracerr.Wrap(err)
302 }
303 fromIdx, err := IdxFromBytes(b[52:58])
304 if err != nil {
305 return nil, tracerr.Wrap(err)
306 }
307 tx.FromIdx = fromIdx
308 tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
309 tx.Amount = Float16FromBytes(b[60:62]).BigInt()
310 tx.TokenID, err = TokenIDFromBytes(b[62:66])
311 if err != nil {
312 return nil, tracerr.Wrap(err)
313 }
314 tx.ToIdx, err = IdxFromBytes(b[66:72])
315 if err != nil {
316 return nil, tracerr.Wrap(err)
317 }
318
319 return tx, nil
320}
321
322func signHash(data []byte) []byte {
323 msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
324 return crypto.Keccak256([]byte(msg))
325}
326
327// L1CoordinatorTxFromBytes decodes a L1Tx from []byte
328func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) {
329 if len(b) != L1CoordinatorTxBytesLen {
330 return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b)))
331 }
332
333 bytesMessage := []byte("I authorize this babyjubjub key for hermez rollup account creation")
334
335 tx := &L1Tx{
336 UserOrigin: false,
337 }
338 var err error
339 v := b[0]
340 s := b[1:33]
341 r := b[33:65]
342 pkCompB := b[65:97]
343 pkCompL := SwapEndianness(pkCompB)
344 var pkComp babyjub.PublicKeyComp
345 copy(pkComp[:], pkCompL)
346 tx.FromBJJ, err = pkComp.Decompress()
347 if err != nil {
348 return nil, tracerr.Wrap(err)
349 }
350 tx.TokenID, err = TokenIDFromBytes(b[97:101])
351 if err != nil {
352 return nil, tracerr.Wrap(err)
353 }
354 tx.Amount = big.NewInt(0)
355 tx.LoadAmount = big.NewInt(0)
356 if int(v) > 0 {
357 // L1CoordinatorTX ETH
358 // Ethereum adds 27 to v
359 v = b[0] - byte(27) //nolint:gomnd
360 chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
361 var data []byte
362 data = append(data, bytesMessage...)
363 data = append(data, pkCompB...)
364 data = append(data, chainIDBytes[:]...)
365 data = append(data, hermezAddress.Bytes()...)
366 var signature []byte
367 signature = append(signature, r[:]...)
368 signature = append(signature, s[:]...)
369 signature = append(signature, v)
370 hash := signHash(data)
371 pubKeyBytes, err := crypto.Ecrecover(hash, signature)
372 if err != nil {
373 return nil, tracerr.Wrap(err)
374 }
375 pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
376 if err != nil {
377 return nil, tracerr.Wrap(err)
378 }
379 tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
380 } else {
381 // L1Coordinator Babyjub
382 tx.FromEthAddr = RollupConstEthAddressInternalOnly
383 }
384 return tx, nil
385}