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 if tx.FromBJJ != nil {
157 pkCompL := tx.FromBJJ.Compress()
158 pkCompB := SwapEndianness(pkCompL[:])
159 copy(b[20:52], pkCompB[:])
160 }
161 fromIdxBytes, err := tx.FromIdx.Bytes()
162 if err != nil {
163 return nil, err
164 }
165 copy(b[52:58], fromIdxBytes[:])
166 loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
167 if err != nil {
168 return nil, err
169 }
170 copy(b[58:60], loadAmountFloat16.Bytes())
171 amountFloat16, err := NewFloat16(tx.Amount)
172 if err != nil {
173 return nil, err
174 }
175 copy(b[60:62], amountFloat16.Bytes())
176 copy(b[62:66], tx.TokenID.Bytes())
177 toIdxBytes, err := tx.ToIdx.Bytes()
178 if err != nil {
179 return nil, err
180 }
181 copy(b[66:72], toIdxBytes[:])
182 return b[:], nil
183}
184
185// BytesUser encodes a L1UserTx into []byte
186func (tx *L1Tx) BytesUser() ([]byte, error) {
187 if !tx.UserOrigin {
188 return nil, fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx")
189 }
190 return tx.BytesGeneric()
191}
192
193// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
194func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
195 if tx.UserOrigin {
196 return nil, fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx")
197 }
198 var b [L1CoordinatorTxBytesLen]byte
199 v := compressedSignatureBytes[64]
200 s := compressedSignatureBytes[32:64]
201 r := compressedSignatureBytes[0:32]
202 b[0] = v
203 copy(b[1:33], s)
204 copy(b[33:65], r)
205 pkCompL := tx.FromBJJ.Compress()
206 pkCompB := SwapEndianness(pkCompL[:])
207 copy(b[65:97], pkCompB[:])
208 copy(b[97:101], tx.TokenID.Bytes())
209 return b[:], nil
210}
211
212// L1UserTxFromBytes decodes a L1Tx from []byte
213func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
214 if len(b) != L1UserTxBytesLen {
215 return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
216 }
217
218 tx := &L1Tx{
219 UserOrigin: true,
220 }
221 var err error
222 tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
223
224 pkCompB := b[20:52]
225 pkCompL := SwapEndianness(pkCompB)
226 var pkComp babyjub.PublicKeyComp
227 copy(pkComp[:], pkCompL)
228 tx.FromBJJ, err = pkComp.Decompress()
229 if err != nil {
230 return nil, err
231 }
232 fromIdx, err := IdxFromBytes(b[52:58])
233 if err != nil {
234 return nil, err
235 }
236 tx.FromIdx = fromIdx
237 tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
238 tx.Amount = Float16FromBytes(b[60:62]).BigInt()
239 tx.TokenID, err = TokenIDFromBytes(b[62:66])
240 if err != nil {
241 return nil, err
242 }
243 tx.ToIdx, err = IdxFromBytes(b[66:72])
244 if err != nil {
245 return nil, err
246 }
247
248 return tx, nil
249}
250
251// L1CoordinatorTxFromBytes decodes a L1Tx from []byte
252func L1CoordinatorTxFromBytes(b []byte) (*L1Tx, error) {
253 if len(b) != L1CoordinatorTxBytesLen {
254 return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
255 }
256
257 bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
258 bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
259
260 tx := &L1Tx{
261 UserOrigin: false,
262 }
263 var err error
264 // Ethereum adds 27 to v
265 v := b[0] - byte(27) //nolint:gomnd
266 s := b[1:33]
267 r := b[33:65]
268
269 pkCompB := b[65:97]
270 pkCompL := SwapEndianness(pkCompB)
271 var pkComp babyjub.PublicKeyComp
272 copy(pkComp[:], pkCompL)
273 tx.FromBJJ, err = pkComp.Decompress()
274 if err != nil {
275 return nil, err
276 }
277 tx.TokenID, err = TokenIDFromBytes(b[97:101])
278 if err != nil {
279 return nil, err
280 }
281
282 var data []byte
283 data = append(data, bytesMessage1...)
284 data = append(data, bytesMessage2...)
285 data = append(data, pkCompB...)
286 var signature []byte
287 signature = append(signature, r[:]...)
288 signature = append(signature, s[:]...)
289 signature = append(signature, v)
290 hash := crypto.Keccak256(data)
291 pubKeyBytes, err := crypto.Ecrecover(hash, signature)
292 if err != nil {
293 return nil, err
294 }
295 pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
296 if err != nil {
297 return nil, err
298 }
299 tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
300 tx.Amount = big.NewInt(0)
301 tx.LoadAmount = big.NewInt(0)
302 return tx, nil
303}