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/iden3/go-iden3-crypto/babyjub"
11)
12
13const (
14 // L1UserTxBytesLen is the length of the byte array that represents the L1Tx
15 L1UserTxBytesLen = 72
16 // L1CoordinatorTxBytesLen is the length of the byte array that represents the L1CoordinatorTx
17 L1CoordinatorTxBytesLen = 101
18)
19
20// L1Tx is a struct that represents a L1 tx
21type L1Tx struct {
22 // Stored in DB: mandatory fileds
23
24 // TxID (12 bytes) for L1Tx is:
25 // bytes: | 1 | 8 | 2 | 1 |
26 // values: | type | ToForgeL1TxsNum | Position | 0 (padding) |
27 // where type:
28 // - L1UserTx: 0
29 // - L1CoordinatorTx: 1
30 TxID TxID `meddler:"id"`
31 ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
32 Position int `meddler:"position"`
33 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
34 FromIdx Idx `meddler:"from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
35 FromEthAddr ethCommon.Address `meddler:"from_eth_addr,zeroisnull"`
36 FromBJJ *babyjub.PublicKey `meddler:"from_bjj,zeroisnull"`
37 ToIdx Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
38 TokenID TokenID `meddler:"token_id"`
39 Amount *big.Int `meddler:"amount,bigint"`
40 LoadAmount *big.Int `meddler:"load_amount,bigint"`
41 EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
42 Type TxType `meddler:"type"`
43 BatchNum *BatchNum `meddler:"batch_num"`
44}
45
46// NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
47// from the L1Tx values
48func NewL1Tx(l1Tx *L1Tx) (*L1Tx, error) {
49 // calculate TxType
50 var txType TxType
51 if l1Tx.FromIdx == 0 {
52 if l1Tx.ToIdx == Idx(0) {
53 txType = TxTypeCreateAccountDeposit
54 } else if l1Tx.ToIdx >= IdxUserThreshold {
55 txType = TxTypeCreateAccountDepositTransfer
56 } else {
57 return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
58 }
59 } else if l1Tx.FromIdx >= IdxUserThreshold {
60 if l1Tx.ToIdx == Idx(0) {
61 txType = TxTypeDeposit
62 } else if l1Tx.ToIdx == Idx(1) {
63 txType = TxTypeForceExit
64 } else if l1Tx.ToIdx >= IdxUserThreshold {
65 if l1Tx.LoadAmount.Int64() == int64(0) {
66 txType = TxTypeForceTransfer
67 } else {
68 txType = TxTypeDepositTransfer
69 }
70 } else {
71 return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
72 }
73 } else {
74 return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid FromIdx value: %d", l1Tx.FromIdx)
75 }
76
77 if l1Tx.Type != "" && l1Tx.Type != txType {
78 return l1Tx, fmt.Errorf("L1Tx.Type: %s, should be: %s", l1Tx.Type, txType)
79 }
80 l1Tx.Type = txType
81
82 txID, err := l1Tx.CalcTxID()
83 if err != nil {
84 return nil, err
85 }
86 l1Tx.TxID = *txID
87
88 return l1Tx, nil
89}
90
91// CalcTxID calculates the TxId of the L1Tx
92func (tx *L1Tx) CalcTxID() (*TxID, error) {
93 var txID TxID
94 if tx.UserOrigin {
95 if tx.ToForgeL1TxsNum == nil {
96 return nil, fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil")
97 }
98 txID[0] = TxIDPrefixL1UserTx
99 var toForgeL1TxsNumBytes [8]byte
100 binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
101 copy(txID[1:9], toForgeL1TxsNumBytes[:])
102 } else {
103 if tx.BatchNum == nil {
104 return nil, fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil")
105 }
106 txID[0] = TxIDPrefixL1CoordTx
107 var batchNumBytes [8]byte
108 binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
109 copy(txID[1:9], batchNumBytes[:])
110 }
111 var positionBytes [2]byte
112 binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
113 copy(txID[9:11], positionBytes[:])
114
115 return &txID, nil
116}
117
118// Tx returns a *Tx from the L1Tx
119func (tx L1Tx) Tx() Tx {
120 f := new(big.Float).SetInt(tx.Amount)
121 amountFloat, _ := f.Float64()
122 userOrigin := new(bool)
123 *userOrigin = tx.UserOrigin
124 genericTx := Tx{
125 IsL1: true,
126 TxID: tx.TxID,
127 Type: tx.Type,
128 Position: tx.Position,
129 FromIdx: tx.FromIdx,
130 ToIdx: tx.ToIdx,
131 Amount: tx.Amount,
132 AmountFloat: amountFloat,
133 TokenID: tx.TokenID,
134 ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
135 UserOrigin: userOrigin,
136 FromEthAddr: tx.FromEthAddr,
137 FromBJJ: tx.FromBJJ,
138 LoadAmount: tx.LoadAmount,
139 EthBlockNum: tx.EthBlockNum,
140 }
141 if tx.LoadAmount != nil {
142 lf := new(big.Float).SetInt(tx.LoadAmount)
143 loadAmountFloat, _ := lf.Float64()
144 genericTx.LoadAmountFloat = &loadAmountFloat
145 }
146 return genericTx
147}
148
149// BytesGeneric returns the generic representation of a L1Tx. This method is
150// used to compute the []byte representation of a L1UserTx, and also to compute
151// the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
152// for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
153func (tx *L1Tx) BytesGeneric() ([]byte, error) {
154 var b [L1UserTxBytesLen]byte
155 copy(b[0:20], tx.FromEthAddr.Bytes())
156 pkCompL := tx.FromBJJ.Compress()
157 pkCompB := SwapEndianness(pkCompL[:])
158 copy(b[20:52], pkCompB[:])
159 fromIdxBytes, err := tx.FromIdx.Bytes()
160 if err != nil {
161 return nil, err
162 }
163 copy(b[52:58], fromIdxBytes[:])
164 loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
165 if err != nil {
166 return nil, err
167 }
168 copy(b[58:60], loadAmountFloat16.Bytes())
169 amountFloat16, err := NewFloat16(tx.Amount)
170 if err != nil {
171 return nil, err
172 }
173 copy(b[60:62], amountFloat16.Bytes())
174 copy(b[62:66], tx.TokenID.Bytes())
175 toIdxBytes, err := tx.ToIdx.Bytes()
176 if err != nil {
177 return nil, err
178 }
179 copy(b[66:72], toIdxBytes[:])
180 return b[:], nil
181}
182
183// BytesUser encodes a L1UserTx into []byte
184func (tx *L1Tx) BytesUser() ([]byte, error) {
185 if !tx.UserOrigin {
186 return nil, fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx")
187 }
188 return tx.BytesGeneric()
189}
190
191// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
192func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
193 if tx.UserOrigin {
194 return nil, fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx")
195 }
196 var b [L1CoordinatorTxBytesLen]byte
197 v := compressedSignatureBytes[64]
198 s := compressedSignatureBytes[32:64]
199 r := compressedSignatureBytes[0:32]
200 b[0] = v
201 copy(b[1:33], s)
202 copy(b[33:65], r)
203 pkCompL := tx.FromBJJ.Compress()
204 pkCompB := SwapEndianness(pkCompL[:])
205 copy(b[65:97], pkCompB[:])
206 copy(b[97:101], tx.TokenID.Bytes())
207 return b[:], nil
208}
209
210// L1UserTxFromBytes decodes a L1Tx from []byte
211func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
212 if len(b) != L1UserTxBytesLen {
213 return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
214 }
215
216 tx := &L1Tx{
217 UserOrigin: true,
218 }
219 var err error
220 tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
221
222 pkCompB := b[20:52]
223 pkCompL := SwapEndianness(pkCompB)
224 var pkComp babyjub.PublicKeyComp
225 copy(pkComp[:], pkCompL)
226 tx.FromBJJ, err = pkComp.Decompress()
227 if err != nil {
228 return nil, err
229 }
230 fromIdx, err := IdxFromBytes(b[52:58])
231 if err != nil {
232 return nil, err
233 }
234 tx.FromIdx = fromIdx
235 tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
236 tx.Amount = Float16FromBytes(b[60:62]).BigInt()
237 tx.TokenID, err = TokenIDFromBytes(b[62:66])
238 if err != nil {
239 return nil, err
240 }
241 tx.ToIdx, err = IdxFromBytes(b[66:72])
242 if err != nil {
243 return nil, err
244 }
245
246 return tx, nil
247}
248
249// L1CoordinatorTxFromBytes decodes a L1Tx from []byte
250func L1CoordinatorTxFromBytes(b []byte) (*L1Tx, error) {
251 if len(b) != L1CoordinatorTxBytesLen {
252 return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
253 }
254
255 bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
256 bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
257
258 tx := &L1Tx{
259 UserOrigin: false,
260 }
261 var err error
262 // Ethereum adds 27 to v
263 v := b[0] - byte(27) //nolint:gomnd
264 s := b[1:33]
265 r := b[33:65]
266
267 pkCompB := b[65:97]
268 pkCompL := SwapEndianness(pkCompB)
269 var pkComp babyjub.PublicKeyComp
270 copy(pkComp[:], pkCompL)
271 tx.FromBJJ, err = pkComp.Decompress()
272 if err != nil {
273 return nil, err
274 }
275 tx.TokenID, err = TokenIDFromBytes(b[97:101])
276 if err != nil {
277 return nil, err
278 }
279
280 var data []byte
281 data = append(data, bytesMessage1...)
282 data = append(data, bytesMessage2...)
283 data = append(data, pkCompB...)
284 var signature []byte
285 signature = append(signature, r[:]...)
286 signature = append(signature, s[:]...)
287 signature = append(signature, v)
288 hash := crypto.Keccak256(data)
289 pubKeyBytes, err := crypto.Ecrecover(hash, signature)
290 if err != nil {
291 return nil, err
292 }
293 pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
294 if err != nil {
295 return nil, err
296 }
297 tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
298 tx.Amount = big.NewInt(0)
299 tx.LoadAmount = big.NewInt(0)
300 return tx, nil
301}