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