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/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.DepositAmount (deposit)
 36	EffectiveFromIdx Idx                   `meddler:"effective_from_idx,zeroisnull"`
 37	FromEthAddr      ethCommon.Address     `meddler:"from_eth_addr,zeroisnull"`
 38	FromBJJ          babyjub.PublicKeyComp `meddler:"from_bjj,zeroisnull"`
 39	ToIdx            Idx                   `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
 40	TokenID          TokenID               `meddler:"token_id"`
 41	Amount           *big.Int              `meddler:"amount,bigint"`
 42	// EffectiveAmount only applies to L1UserTx.
 43	EffectiveAmount *big.Int `meddler:"effective_amount,bigintnull"`
 44	DepositAmount   *big.Int `meddler:"deposit_amount,bigint"`
 45	// EffectiveDepositAmount only applies to L1UserTx.
 46	EffectiveDepositAmount *big.Int  `meddler:"effective_deposit_amount,bigintnull"`
 47	EthBlockNum            int64     `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
 48	Type                   TxType    `meddler:"type"`
 49	BatchNum               *BatchNum `meddler:"batch_num"`
 50}
 51
 52// NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
 53// from the L1Tx values
 54func NewL1Tx(tx *L1Tx) (*L1Tx, error) {
 55	txTypeOld := tx.Type
 56	if err := tx.SetType(); err != nil {
 57		return nil, tracerr.Wrap(err)
 58	}
 59	// If original Type doesn't match the correct one, return error
 60	if txTypeOld != "" && txTypeOld != tx.Type {
 61		return nil, tracerr.Wrap(fmt.Errorf("L1Tx.Type: %s, should be: %s",
 62			tx.Type, txTypeOld))
 63	}
 64
 65	txIDOld := tx.TxID
 66	if err := tx.SetID(); err != nil {
 67		return nil, tracerr.Wrap(err)
 68	}
 69	// If original TxID doesn't match the correct one, return error
 70	if txIDOld != (TxID{}) && txIDOld != tx.TxID {
 71		return tx, tracerr.Wrap(fmt.Errorf("L1Tx.TxID: %s, should be: %s",
 72			tx.TxID.String(), txIDOld.String()))
 73	}
 74
 75	return tx, nil
 76}
 77
 78// SetType sets the type of the transaction
 79func (tx *L1Tx) SetType() error {
 80	if tx.FromIdx == 0 {
 81		if tx.ToIdx == Idx(0) {
 82			tx.Type = TxTypeCreateAccountDeposit
 83		} else if tx.ToIdx >= IdxUserThreshold {
 84			tx.Type = TxTypeCreateAccountDepositTransfer
 85		} else {
 86			return tracerr.Wrap(fmt.Errorf(
 87				"Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
 88		}
 89	} else if tx.FromIdx >= IdxUserThreshold {
 90		if tx.ToIdx == Idx(0) {
 91			tx.Type = TxTypeDeposit
 92		} else if tx.ToIdx == Idx(1) {
 93			tx.Type = TxTypeForceExit
 94		} else if tx.ToIdx >= IdxUserThreshold {
 95			if tx.DepositAmount.Int64() == int64(0) {
 96				tx.Type = TxTypeForceTransfer
 97			} else {
 98				tx.Type = TxTypeDepositTransfer
 99			}
100		} else {
101			return tracerr.Wrap(fmt.Errorf(
102				"Can not determine type of L1Tx, invalid ToIdx value: %d", tx.ToIdx))
103		}
104	} else {
105		return tracerr.Wrap(fmt.Errorf(
106			"Can not determine type of L1Tx, invalid FromIdx value: %d", tx.FromIdx))
107	}
108	return nil
109}
110
111// SetID sets the ID of the transaction.  For L1UserTx uses (ToForgeL1TxsNum,
112// Position), for L1CoordinatorTx uses (BatchNum, Position).
113func (tx *L1Tx) SetID() error {
114	if tx.UserOrigin {
115		if tx.ToForgeL1TxsNum == nil {
116			return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil"))
117		}
118		tx.TxID[0] = TxIDPrefixL1UserTx
119		var toForgeL1TxsNumBytes [8]byte
120		binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
121		copy(tx.TxID[1:9], toForgeL1TxsNumBytes[:])
122	} else {
123		if tx.BatchNum == nil {
124			return tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil"))
125		}
126		tx.TxID[0] = TxIDPrefixL1CoordTx
127		var batchNumBytes [8]byte
128		binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
129		copy(tx.TxID[1:9], batchNumBytes[:])
130	}
131	var positionBytes [2]byte
132	binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
133	copy(tx.TxID[9:11], positionBytes[:])
134
135	return nil
136}
137
138// Tx returns a *Tx from the L1Tx
139func (tx L1Tx) Tx() Tx {
140	f := new(big.Float).SetInt(tx.EffectiveAmount)
141	amountFloat, _ := f.Float64()
142	userOrigin := new(bool)
143	*userOrigin = tx.UserOrigin
144	genericTx := Tx{
145		IsL1:            true,
146		TxID:            tx.TxID,
147		Type:            tx.Type,
148		Position:        tx.Position,
149		FromIdx:         tx.FromIdx,
150		ToIdx:           tx.ToIdx,
151		Amount:          tx.EffectiveAmount,
152		AmountFloat:     amountFloat,
153		TokenID:         tx.TokenID,
154		ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
155		UserOrigin:      userOrigin,
156		FromEthAddr:     tx.FromEthAddr,
157		FromBJJ:         tx.FromBJJ,
158		DepositAmount:   tx.EffectiveDepositAmount,
159		EthBlockNum:     tx.EthBlockNum,
160	}
161	if tx.DepositAmount != nil {
162		lf := new(big.Float).SetInt(tx.DepositAmount)
163		depositAmountFloat, _ := lf.Float64()
164		genericTx.DepositAmountFloat = &depositAmountFloat
165	}
166	return genericTx
167}
168
169// TxCompressedData spec:
170// [ 1 bits  ] empty (toBJJSign) // 1 byte
171// [ 8 bits  ] empty (userFee) // 1 byte
172// [ 40 bits ] empty (nonce) // 5 bytes
173// [ 32 bits ] tokenID // 4 bytes
174// [ 16 bits ] amountFloat16 // 2 bytes
175// [ 48 bits ] toIdx // 6 bytes
176// [ 48 bits ] fromIdx // 6 bytes
177// [ 16 bits ] chainId // 2 bytes
178// [ 32 bits ] empty (signatureConstant) // 4 bytes
179// Total bits compressed data:  241 bits // 31 bytes in *big.Int representation
180func (tx L1Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
181	amountFloat16, err := NewFloat16(tx.Amount)
182	if err != nil {
183		return nil, tracerr.Wrap(err)
184	}
185
186	var b [31]byte
187	// b[0:7] empty: no ToBJJSign, no fee, no nonce
188	copy(b[7:11], tx.TokenID.Bytes())
189	copy(b[11:13], amountFloat16.Bytes())
190	toIdxBytes, err := tx.ToIdx.Bytes()
191	if err != nil {
192		return nil, tracerr.Wrap(err)
193	}
194	copy(b[13:19], toIdxBytes[:])
195	fromIdxBytes, err := tx.FromIdx.Bytes()
196	if err != nil {
197		return nil, tracerr.Wrap(err)
198	}
199	copy(b[19:25], fromIdxBytes[:])
200	binary.BigEndian.PutUint16(b[25:27], chainID)
201	copy(b[27:31], SignatureConstantBytes[:])
202
203	bi := new(big.Int).SetBytes(b[:])
204	return bi, nil
205}
206
207// BytesDataAvailability encodes a L1Tx into []byte for the Data Availability
208func (tx *L1Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
209	idxLen := nLevels / 8 //nolint:gomnd
210
211	b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
212
213	fromIdxBytes, err := tx.FromIdx.Bytes()
214	if err != nil {
215		return nil, tracerr.Wrap(err)
216	}
217	copy(b[0:idxLen], fromIdxBytes[6-idxLen:])
218	toIdxBytes, err := tx.ToIdx.Bytes()
219	if err != nil {
220		return nil, tracerr.Wrap(err)
221	}
222	copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
223
224	if tx.EffectiveAmount != nil {
225		amountFloat16, err := NewFloat16(tx.EffectiveAmount)
226		if err != nil {
227			return nil, tracerr.Wrap(err)
228		}
229		copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
230	}
231	// fee = 0 (as is L1Tx) b[10:11]
232	return b[:], nil
233}
234
235// L1TxFromDataAvailability decodes a L1Tx from []byte (Data Availability)
236func L1TxFromDataAvailability(b []byte, nLevels uint32) (*L1Tx, error) {
237	idxLen := nLevels / 8 //nolint:gomnd
238
239	fromIdxBytes := b[0:idxLen]
240	toIdxBytes := b[idxLen : idxLen*2]
241	amountBytes := b[idxLen*2 : idxLen*2+2]
242
243	l1tx := L1Tx{}
244	fromIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(fromIdxBytes, 6))
245	if err != nil {
246		return nil, tracerr.Wrap(err)
247	}
248	l1tx.FromIdx = fromIdx
249	toIdx, err := IdxFromBytes(ethCommon.LeftPadBytes(toIdxBytes, 6))
250	if err != nil {
251		return nil, tracerr.Wrap(err)
252	}
253	l1tx.ToIdx = toIdx
254	l1tx.EffectiveAmount = Float16FromBytes(amountBytes).BigInt()
255	return &l1tx, nil
256}
257
258// BytesGeneric returns the generic representation of a L1Tx. This method is
259// used to compute the []byte representation of a L1UserTx, and also to compute
260// the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
261// for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
262func (tx *L1Tx) BytesGeneric() ([]byte, error) {
263	var b [L1UserTxBytesLen]byte
264	copy(b[0:20], tx.FromEthAddr.Bytes())
265	if tx.FromBJJ != EmptyBJJComp {
266		pkCompL := tx.FromBJJ
267		pkCompB := SwapEndianness(pkCompL[:])
268		copy(b[20:52], pkCompB[:])
269	}
270	fromIdxBytes, err := tx.FromIdx.Bytes()
271	if err != nil {
272		return nil, tracerr.Wrap(err)
273	}
274	copy(b[52:58], fromIdxBytes[:])
275	depositAmountFloat16, err := NewFloat16(tx.DepositAmount)
276	if err != nil {
277		return nil, tracerr.Wrap(err)
278	}
279	copy(b[58:60], depositAmountFloat16.Bytes())
280	amountFloat16, err := NewFloat16(tx.Amount)
281	if err != nil {
282		return nil, tracerr.Wrap(err)
283	}
284	copy(b[60:62], amountFloat16.Bytes())
285	copy(b[62:66], tx.TokenID.Bytes())
286	toIdxBytes, err := tx.ToIdx.Bytes()
287	if err != nil {
288		return nil, tracerr.Wrap(err)
289	}
290	copy(b[66:72], toIdxBytes[:])
291	return b[:], nil
292}
293
294// BytesUser encodes a L1UserTx into []byte
295func (tx *L1Tx) BytesUser() ([]byte, error) {
296	if !tx.UserOrigin {
297		return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx"))
298	}
299	return tx.BytesGeneric()
300}
301
302// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
303func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
304	if tx.UserOrigin {
305		return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx"))
306	}
307	var b [L1CoordinatorTxBytesLen]byte
308	v := compressedSignatureBytes[64]
309	s := compressedSignatureBytes[32:64]
310	r := compressedSignatureBytes[0:32]
311	b[0] = v
312	copy(b[1:33], s)
313	copy(b[33:65], r)
314	pkCompL := tx.FromBJJ
315	pkCompB := SwapEndianness(pkCompL[:])
316	copy(b[65:97], pkCompB[:])
317	copy(b[97:101], tx.TokenID.Bytes())
318	return b[:], nil
319}
320
321// L1UserTxFromBytes decodes a L1Tx from []byte
322func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
323	if len(b) != L1UserTxBytesLen {
324		return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b)))
325	}
326
327	tx := &L1Tx{
328		UserOrigin: true,
329	}
330	var err error
331	tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
332
333	pkCompB := b[20:52]
334	pkCompL := SwapEndianness(pkCompB)
335	copy(tx.FromBJJ[:], pkCompL)
336	fromIdx, err := IdxFromBytes(b[52:58])
337	if err != nil {
338		return nil, tracerr.Wrap(err)
339	}
340	tx.FromIdx = fromIdx
341	tx.DepositAmount = Float16FromBytes(b[58:60]).BigInt()
342	tx.Amount = Float16FromBytes(b[60:62]).BigInt()
343	tx.TokenID, err = TokenIDFromBytes(b[62:66])
344	if err != nil {
345		return nil, tracerr.Wrap(err)
346	}
347	tx.ToIdx, err = IdxFromBytes(b[66:72])
348	if err != nil {
349		return nil, tracerr.Wrap(err)
350	}
351
352	return tx, nil
353}
354
355func signHash(data []byte) []byte {
356	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
357	return crypto.Keccak256([]byte(msg))
358}
359
360// L1CoordinatorTxFromBytes decodes a L1Tx from []byte
361func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) {
362	if len(b) != L1CoordinatorTxBytesLen {
363		return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b)))
364	}
365
366	bytesMessage := []byte("I authorize this babyjubjub key for hermez rollup account creation")
367
368	tx := &L1Tx{
369		UserOrigin: false,
370	}
371	var err error
372	v := b[0]
373	s := b[1:33]
374	r := b[33:65]
375	pkCompB := b[65:97]
376	pkCompL := SwapEndianness(pkCompB)
377	copy(tx.FromBJJ[:], pkCompL)
378	tx.TokenID, err = TokenIDFromBytes(b[97:101])
379	if err != nil {
380		return nil, tracerr.Wrap(err)
381	}
382	tx.Amount = big.NewInt(0)
383	tx.DepositAmount = big.NewInt(0)
384	if int(v) > 0 {
385		// L1CoordinatorTX ETH
386		// Ethereum adds 27 to v
387		v = b[0] - byte(27) //nolint:gomnd
388		chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
389		var data []byte
390		data = append(data, bytesMessage...)
391		data = append(data, pkCompB...)
392		data = append(data, chainIDBytes[:]...)
393		data = append(data, hermezAddress.Bytes()...)
394		var signature []byte
395		signature = append(signature, r[:]...)
396		signature = append(signature, s[:]...)
397		signature = append(signature, v)
398		hash := signHash(data)
399		pubKeyBytes, err := crypto.Ecrecover(hash, signature)
400		if err != nil {
401			return nil, tracerr.Wrap(err)
402		}
403		pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
404		if err != nil {
405			return nil, tracerr.Wrap(err)
406		}
407		tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
408	} else {
409		// L1Coordinator Babyjub
410		tx.FromEthAddr = RollupConstEthAddressInternalOnly
411	}
412	return tx, nil
413}