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 // L1TxBytesLen is the length of the byte array that represents the L1Tx
15 L1TxBytesLen = 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
31 ToForgeL1TxsNum *int64 // toForgeL1TxsNum in which the tx was forged / will be forged
32 Position int
33 UserOrigin bool // 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 // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
35 FromEthAddr ethCommon.Address
36 FromBJJ *babyjub.PublicKey
37 ToIdx Idx // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
38 TokenID TokenID
39 Amount *big.Int
40 LoadAmount *big.Int
41 EthBlockNum int64 // Ethereum Block Number in which this L1Tx was added to the queue
42 Type TxType
43 BatchNum *BatchNum
44 USD *float64
45 LoadAmountUSD *float64
46}
47
48// NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
49// from the L1Tx values
50func NewL1Tx(l1Tx *L1Tx) (*L1Tx, error) {
51 // calculate TxType
52 var txType TxType
53 if l1Tx.FromIdx == nil {
54 if l1Tx.ToIdx == Idx(0) {
55 txType = TxTypeCreateAccountDeposit
56 } else if l1Tx.ToIdx >= IdxUserThreshold {
57 txType = TxTypeCreateAccountDepositTransfer
58 } else {
59 return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
60 }
61 } else if *l1Tx.FromIdx >= IdxUserThreshold {
62 if l1Tx.ToIdx == Idx(0) {
63 txType = TxTypeDeposit
64 } else if l1Tx.ToIdx == Idx(1) {
65 txType = TxTypeExit
66 } else if l1Tx.ToIdx >= IdxUserThreshold {
67 if l1Tx.LoadAmount.Int64() == int64(0) {
68 txType = TxTypeForceTransfer
69 } else {
70 txType = TxTypeDepositTransfer
71 }
72 } else {
73 return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
74 }
75 } else {
76 return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid FromIdx value: %d", l1Tx.FromIdx)
77 }
78
79 if l1Tx.Type != "" && l1Tx.Type != txType {
80 return l1Tx, fmt.Errorf("L1Tx.Type: %s, should be: %s", l1Tx.Type, txType)
81 }
82 l1Tx.Type = txType
83
84 var txid [TxIDLen]byte
85 if !l1Tx.UserOrigin {
86 txid[0] = TxIDPrefixL1CoordTx
87 }
88 var toForgeL1TxsNumBytes [8]byte
89 var toForge uint64 = 0
90 if l1Tx.ToForgeL1TxsNum != nil {
91 toForge = uint64(*l1Tx.ToForgeL1TxsNum)
92 }
93 binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], toForge)
94 copy(txid[1:9], toForgeL1TxsNumBytes[:])
95
96 var positionBytes [2]byte
97 binary.BigEndian.PutUint16(positionBytes[:], uint16(l1Tx.Position))
98 copy(txid[9:11], positionBytes[:])
99 l1Tx.TxID = TxID(txid)
100
101 return l1Tx, nil
102}
103
104// Tx returns a *Tx from the L1Tx
105func (tx *L1Tx) Tx() *Tx {
106 f := new(big.Float).SetInt(tx.Amount)
107 amountFloat, _ := f.Float64()
108 userOrigin := new(bool)
109 *userOrigin = tx.UserOrigin
110 fromEthAddr := new(ethCommon.Address)
111 *fromEthAddr = tx.FromEthAddr
112 toIdx := new(Idx)
113 *toIdx = tx.ToIdx
114 genericTx := &Tx{
115 IsL1: true,
116 TxID: tx.TxID,
117 Type: tx.Type,
118 Position: tx.Position,
119 FromIdx: tx.FromIdx,
120 ToIdx: toIdx,
121 Amount: tx.Amount,
122 AmountFloat: amountFloat,
123 TokenID: tx.TokenID,
124 ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
125 UserOrigin: userOrigin,
126 FromEthAddr: fromEthAddr,
127 FromBJJ: tx.FromBJJ,
128 LoadAmount: tx.LoadAmount,
129 EthBlockNum: tx.EthBlockNum,
130 USD: tx.USD,
131 LoadAmountUSD: tx.LoadAmountUSD,
132 }
133 if tx.LoadAmount != nil {
134 lf := new(big.Float).SetInt(tx.LoadAmount)
135 loadAmountFloat, _ := lf.Float64()
136 genericTx.LoadAmountFloat = &loadAmountFloat
137 }
138 return genericTx
139}
140
141// Bytes encodes a L1Tx into []byte
142func (tx *L1Tx) Bytes() ([]byte, error) {
143 var b [L1TxBytesLen]byte
144 copy(b[0:20], tx.FromEthAddr.Bytes())
145 pkComp := tx.FromBJJ.Compress()
146 copy(b[20:52], pkComp[:])
147 fromIdxBytes, err := tx.FromIdx.Bytes()
148 if err != nil {
149 return nil, err
150 }
151 copy(b[52:58], fromIdxBytes[:])
152 loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
153 if err != nil {
154 return nil, err
155 }
156 copy(b[58:60], loadAmountFloat16.Bytes())
157 amountFloat16, err := NewFloat16(tx.Amount)
158 if err != nil {
159 return nil, err
160 }
161 copy(b[60:62], amountFloat16.Bytes())
162 copy(b[62:66], tx.TokenID.Bytes())
163 toIdxBytes, err := tx.ToIdx.Bytes()
164 if err != nil {
165 return nil, err
166 }
167 copy(b[66:72], toIdxBytes[:])
168 return b[:], nil
169}
170
171// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
172func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
173 var b [L1CoordinatorTxBytesLen]byte
174 v := compressedSignatureBytes[64]
175 s := compressedSignatureBytes[32:64]
176 r := compressedSignatureBytes[0:32]
177 b[0] = v
178 copy(b[1:33], s)
179 copy(b[33:65], r)
180 pkComp := tx.FromBJJ.Compress()
181 copy(b[65:97], pkComp[:])
182 copy(b[97:101], tx.TokenID.Bytes())
183 return b[:], nil
184}
185
186// L1TxFromBytes decodes a L1Tx from []byte
187func L1TxFromBytes(b []byte) (*L1Tx, error) {
188 if len(b) != L1TxBytesLen {
189 return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
190 }
191
192 tx := &L1Tx{}
193 var err error
194 tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
195 pkCompB := b[20:52]
196 var pkComp babyjub.PublicKeyComp
197 copy(pkComp[:], pkCompB)
198 tx.FromBJJ, err = pkComp.Decompress()
199 if err != nil {
200 return nil, err
201 }
202 fromIdx, err := IdxFromBytes(b[52:58])
203 if err != nil {
204 return nil, err
205 }
206 if fromIdx != 0 {
207 tx.FromIdx = new(Idx)
208 *tx.FromIdx = fromIdx
209 }
210 tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
211 tx.Amount = Float16FromBytes(b[60:62]).BigInt()
212 tx.TokenID, err = TokenIDFromBytes(b[62:66])
213 if err != nil {
214 return nil, err
215 }
216 tx.ToIdx, err = IdxFromBytes(b[66:72])
217 if err != nil {
218 return nil, err
219 }
220
221 return tx, nil
222}
223
224// L1TxFromCoordinatorBytes decodes a L1Tx from []byte
225func L1TxFromCoordinatorBytes(b []byte) (*L1Tx, error) {
226 if len(b) != L1CoordinatorTxBytesLen {
227 return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
228 }
229
230 bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
231 bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
232
233 tx := &L1Tx{}
234 var err error
235 // Ethereum adds 27 to v
236 v := b[0] - byte(27) //nolint:gomnd
237 s := b[1:33]
238 r := b[33:65]
239
240 pkCompB := b[65:97]
241 var pkComp babyjub.PublicKeyComp
242 copy(pkComp[:], pkCompB)
243 tx.FromBJJ, err = pkComp.Decompress()
244 if err != nil {
245 return nil, err
246 }
247 tx.TokenID, err = TokenIDFromBytes(b[97:101])
248 if err != nil {
249 return nil, err
250 }
251
252 var data []byte
253 data = append(data, bytesMessage1...)
254 data = append(data, bytesMessage2...)
255 data = append(data, pkCompB...)
256 var signature []byte
257 signature = append(signature, r[:]...)
258 signature = append(signature, s[:]...)
259 signature = append(signature, v)
260 hash := crypto.Keccak256(data)
261 pubKeyBytes, err := crypto.Ecrecover(hash, signature)
262 if err != nil {
263 return nil, err
264 }
265 pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
266 if err != nil {
267 return nil, err
268 }
269 tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
270 return tx, nil
271}