arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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// TxCompressedData spec:
150// [ 1 bits  ] empty (toBJJSign) // 1 byte
151// [ 8 bits  ] empty (userFee) // 1 byte
152// [ 40 bits ] empty (nonce) // 5 bytes
153// [ 32 bits ] tokenID // 4 bytes
154// [ 16 bits ] amountFloat16 // 2 bytes
155// [ 48 bits ] toIdx // 6 bytes
156// [ 48 bits ] fromIdx // 6 bytes
157// [ 16 bits ] chainId // 2 bytes
158// [ 32 bits ] empty (signatureConstant) // 4 bytes
159// Total bits compressed data:  241 bits // 31 bytes in *big.Int representation
160func (tx L1Tx) TxCompressedData() (*big.Int, error) {
161	amountFloat16, err := NewFloat16(tx.Amount)
162	if err != nil {
163		return nil, err
164	}
165	var b [31]byte
166	// b[0:7] empty: no fee neither nonce
167	copy(b[7:11], tx.TokenID.Bytes())
168	copy(b[11:13], amountFloat16.Bytes())
169	toIdxBytes, err := tx.ToIdx.Bytes()
170	if err != nil {
171		return nil, err
172	}
173	copy(b[13:19], toIdxBytes[:])
174	fromIdxBytes, err := tx.FromIdx.Bytes()
175	if err != nil {
176		return nil, err
177	}
178	copy(b[19:25], fromIdxBytes[:])
179	copy(b[25:27], []byte{0, 1}) // TODO this will be generated by the ChainID config parameter
180	// b[27:] empty: no signature
181
182	bi := new(big.Int).SetBytes(b[:])
183	return bi, nil
184}
185
186// BytesGeneric returns the generic representation of a L1Tx. This method is
187// used to compute the []byte representation of a L1UserTx, and also to compute
188// the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
189// for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
190func (tx *L1Tx) BytesGeneric() ([]byte, error) {
191	var b [L1UserTxBytesLen]byte
192	copy(b[0:20], tx.FromEthAddr.Bytes())
193	if tx.FromBJJ != nil {
194		pkCompL := tx.FromBJJ.Compress()
195		pkCompB := SwapEndianness(pkCompL[:])
196		copy(b[20:52], pkCompB[:])
197	}
198	fromIdxBytes, err := tx.FromIdx.Bytes()
199	if err != nil {
200		return nil, err
201	}
202	copy(b[52:58], fromIdxBytes[:])
203	loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
204	if err != nil {
205		return nil, err
206	}
207	copy(b[58:60], loadAmountFloat16.Bytes())
208	amountFloat16, err := NewFloat16(tx.Amount)
209	if err != nil {
210		return nil, err
211	}
212	copy(b[60:62], amountFloat16.Bytes())
213	copy(b[62:66], tx.TokenID.Bytes())
214	toIdxBytes, err := tx.ToIdx.Bytes()
215	if err != nil {
216		return nil, err
217	}
218	copy(b[66:72], toIdxBytes[:])
219	return b[:], nil
220}
221
222// BytesUser encodes a L1UserTx into []byte
223func (tx *L1Tx) BytesUser() ([]byte, error) {
224	if !tx.UserOrigin {
225		return nil, fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx")
226	}
227	return tx.BytesGeneric()
228}
229
230// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
231func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
232	if tx.UserOrigin {
233		return nil, fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx")
234	}
235	var b [L1CoordinatorTxBytesLen]byte
236	v := compressedSignatureBytes[64]
237	s := compressedSignatureBytes[32:64]
238	r := compressedSignatureBytes[0:32]
239	b[0] = v
240	copy(b[1:33], s)
241	copy(b[33:65], r)
242	pkCompL := tx.FromBJJ.Compress()
243	pkCompB := SwapEndianness(pkCompL[:])
244	copy(b[65:97], pkCompB[:])
245	copy(b[97:101], tx.TokenID.Bytes())
246	return b[:], nil
247}
248
249// L1UserTxFromBytes decodes a L1Tx from []byte
250func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
251	if len(b) != L1UserTxBytesLen {
252		return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
253	}
254
255	tx := &L1Tx{
256		UserOrigin: true,
257	}
258	var err error
259	tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
260
261	pkCompB := b[20:52]
262	pkCompL := SwapEndianness(pkCompB)
263	var pkComp babyjub.PublicKeyComp
264	copy(pkComp[:], pkCompL)
265	tx.FromBJJ, err = pkComp.Decompress()
266	if err != nil {
267		return nil, err
268	}
269	fromIdx, err := IdxFromBytes(b[52:58])
270	if err != nil {
271		return nil, err
272	}
273	tx.FromIdx = fromIdx
274	tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
275	tx.Amount = Float16FromBytes(b[60:62]).BigInt()
276	tx.TokenID, err = TokenIDFromBytes(b[62:66])
277	if err != nil {
278		return nil, err
279	}
280	tx.ToIdx, err = IdxFromBytes(b[66:72])
281	if err != nil {
282		return nil, err
283	}
284
285	return tx, nil
286}
287
288// L1CoordinatorTxFromBytes decodes a L1Tx from []byte
289func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) {
290	if len(b) != L1CoordinatorTxBytesLen {
291		return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
292	}
293
294	bytesMessage1 := []byte("\x19Ethereum Signed Message:\n120")
295	bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
296
297	tx := &L1Tx{
298		UserOrigin: false,
299	}
300	var err error
301	v := b[0]
302	s := b[1:33]
303	r := b[33:65]
304	pkCompB := b[65:97]
305	pkCompL := SwapEndianness(pkCompB)
306	var pkComp babyjub.PublicKeyComp
307	copy(pkComp[:], pkCompL)
308	tx.FromBJJ, err = pkComp.Decompress()
309	if err != nil {
310		return nil, err
311	}
312	tx.TokenID, err = TokenIDFromBytes(b[97:101])
313	if err != nil {
314		return nil, err
315	}
316	tx.Amount = big.NewInt(0)
317	tx.LoadAmount = big.NewInt(0)
318	if int(v) > 0 {
319		// L1CoordinatorTX ETH
320		// Ethereum adds 27 to v
321		v = b[0] - byte(27) //nolint:gomnd
322		chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
323		hermezAddressBytes := ethCommon.LeftPadBytes(hermezAddress.Bytes(), 32)
324		var data []byte
325		data = append(data, bytesMessage1...)
326		data = append(data, bytesMessage2...)
327		data = append(data, pkCompB...)
328		data = append(data, chainIDBytes[:]...)
329		data = append(data, hermezAddressBytes...)
330		var signature []byte
331		signature = append(signature, r[:]...)
332		signature = append(signature, s[:]...)
333		signature = append(signature, v)
334		hash := crypto.Keccak256(data)
335		pubKeyBytes, err := crypto.Ecrecover(hash, signature)
336		if err != nil {
337			return nil, err
338		}
339		pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
340		if err != nil {
341			return nil, err
342		}
343		tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
344	} else {
345		// L1Coordinator Babyjub
346		tx.FromEthAddr = RollupConstEthAddressInternalOnly
347	}
348	return tx, nil
349}