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