arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/common/l2tx.go
common/l2tx.goRaw
  1package common
  2
  3import (
  4	"fmt"
  5	"math/big"
  6
  7	"github.com/hermeznetwork/tracerr"
  8)
  9
 10// L2Tx is a struct that represents an already forged L2 tx
 11type L2Tx struct {
 12	// Stored in DB: mandatory fileds
 13	TxID     TxID     `meddler:"id"`
 14	BatchNum BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged.
 15	Position int      `meddler:"position"`
 16	FromIdx  Idx      `meddler:"from_idx"`
 17	ToIdx    Idx      `meddler:"to_idx"`
 18	// TokenID is filled by the TxProcessor
 19	TokenID TokenID     `meddler:"token_id"`
 20	Amount  *big.Int    `meddler:"amount,bigint"`
 21	Fee     FeeSelector `meddler:"fee"`
 22	// Nonce is filled by the TxProcessor
 23	Nonce       Nonce  `meddler:"nonce"`
 24	Type        TxType `meddler:"type"`
 25	EthBlockNum int64  `meddler:"eth_block_num"` // Ethereum Block Number in which this L2Tx was added to the queue
 26}
 27
 28// NewL2Tx returns the given L2Tx with the TxId & Type parameters calculated
 29// from the L2Tx values
 30func NewL2Tx(tx *L2Tx) (*L2Tx, error) {
 31	txTypeOld := tx.Type
 32	if err := tx.SetType(); err != nil {
 33		return nil, tracerr.Wrap(err)
 34	}
 35	// If original Type doesn't match the correct one, return error
 36	if txTypeOld != "" && txTypeOld != tx.Type {
 37		return nil, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s",
 38			tx.Type, txTypeOld))
 39	}
 40
 41	txIDOld := tx.TxID
 42	if err := tx.SetID(); err != nil {
 43		return nil, tracerr.Wrap(err)
 44	}
 45	// If original TxID doesn't match the correct one, return error
 46	if txIDOld != (TxID{}) && txIDOld != tx.TxID {
 47		return tx, tracerr.Wrap(fmt.Errorf("L2Tx.TxID: %s, should be: %s",
 48			tx.TxID.String(), txIDOld.String()))
 49	}
 50
 51	return tx, nil
 52}
 53
 54// SetType sets the type of the transaction.  Uses (FromIdx, Nonce).
 55func (tx *L2Tx) SetType() error {
 56	if tx.ToIdx == Idx(1) {
 57		tx.Type = TxTypeExit
 58	} else if tx.ToIdx >= IdxUserThreshold {
 59		tx.Type = TxTypeTransfer
 60	} else {
 61		return tracerr.Wrap(fmt.Errorf(
 62			"cannot determine type of L2Tx, invalid ToIdx value: %d", tx.ToIdx))
 63	}
 64	return nil
 65}
 66
 67// SetID sets the ID of the transaction
 68func (tx *L2Tx) SetID() error {
 69	tx.TxID[0] = TxIDPrefixL2Tx
 70	fromIdxBytes, err := tx.FromIdx.Bytes()
 71	if err != nil {
 72		return tracerr.Wrap(err)
 73	}
 74	copy(tx.TxID[1:7], fromIdxBytes[:])
 75	nonceBytes, err := tx.Nonce.Bytes()
 76	if err != nil {
 77		return tracerr.Wrap(err)
 78	}
 79	copy(tx.TxID[7:12], nonceBytes[:])
 80	return nil
 81}
 82
 83// Tx returns a *Tx from the L2Tx
 84func (tx *L2Tx) Tx() *Tx {
 85	batchNum := new(BatchNum)
 86	*batchNum = tx.BatchNum
 87	fee := new(FeeSelector)
 88	*fee = tx.Fee
 89	nonce := new(Nonce)
 90	*nonce = tx.Nonce
 91	return &Tx{
 92		IsL1:        false,
 93		TxID:        tx.TxID,
 94		Type:        tx.Type,
 95		Position:    tx.Position,
 96		FromIdx:     tx.FromIdx,
 97		ToIdx:       tx.ToIdx,
 98		TokenID:     tx.TokenID,
 99		Amount:      tx.Amount,
100		BatchNum:    batchNum,
101		EthBlockNum: tx.EthBlockNum,
102		Fee:         fee,
103		Nonce:       nonce,
104	}
105}
106
107// PoolL2Tx returns the data structure of PoolL2Tx with the parameters of a
108// L2Tx filled
109func (tx L2Tx) PoolL2Tx() *PoolL2Tx {
110	return &PoolL2Tx{
111		TxID:    tx.TxID,
112		FromIdx: tx.FromIdx,
113		ToIdx:   tx.ToIdx,
114		TokenID: tx.TokenID,
115		Amount:  tx.Amount,
116		Fee:     tx.Fee,
117		Nonce:   tx.Nonce,
118		Type:    tx.Type,
119	}
120}
121
122// L2TxsToPoolL2Txs returns an array of []*PoolL2Tx from an array of []*L2Tx,
123// where the PoolL2Tx only have the parameters of a L2Tx filled.
124func L2TxsToPoolL2Txs(txs []L2Tx) []PoolL2Tx {
125	var r []PoolL2Tx
126	for _, tx := range txs {
127		r = append(r, *tx.PoolL2Tx())
128	}
129	return r
130}
131
132// TxIDsFromL2Txs returns an array of TxID from the []L2Tx
133func TxIDsFromL2Txs(txs []L2Tx) []TxID {
134	txIDs := make([]TxID, len(txs))
135	for i, tx := range txs {
136		txIDs[i] = tx.TxID
137	}
138	return txIDs
139}
140
141// BytesDataAvailability encodes a L2Tx into []byte for the Data Availability
142// [ fromIdx | toIdx | amountFloat16 | Fee ]
143func (tx L2Tx) BytesDataAvailability(nLevels uint32) ([]byte, error) {
144	idxLen := nLevels / 8 //nolint:gomnd
145
146	b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd
147
148	fromIdxBytes, err := tx.FromIdx.Bytes()
149	if err != nil {
150		return nil, tracerr.Wrap(err)
151	}
152	copy(b[0:idxLen], fromIdxBytes[6-idxLen:]) // [6-idxLen:] as is BigEndian
153
154	toIdxBytes, err := tx.ToIdx.Bytes()
155	if err != nil {
156		return nil, tracerr.Wrap(err)
157	}
158	copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:])
159
160	amountFloat16, err := NewFloat16(tx.Amount)
161	if err != nil {
162		return nil, tracerr.Wrap(err)
163	}
164
165	copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())
166	b[idxLen*2+2] = byte(tx.Fee)
167
168	return b[:], nil
169}
170
171// L2TxFromBytesDataAvailability decodes a L2Tx from []byte (Data Availability)
172func L2TxFromBytesDataAvailability(b []byte, nLevels int) (*L2Tx, error) {
173	idxLen := nLevels / 8 //nolint:gomnd
174	tx := &L2Tx{}
175	var err error
176
177	var paddedFromIdxBytes [6]byte
178	copy(paddedFromIdxBytes[6-idxLen:], b[0:idxLen])
179	tx.FromIdx, err = IdxFromBytes(paddedFromIdxBytes[:])
180	if err != nil {
181		return nil, tracerr.Wrap(err)
182	}
183
184	var paddedToIdxBytes [6]byte
185	copy(paddedToIdxBytes[6-idxLen:6], b[idxLen:idxLen*2])
186	tx.ToIdx, err = IdxFromBytes(paddedToIdxBytes[:])
187	if err != nil {
188		return nil, tracerr.Wrap(err)
189	}
190
191	tx.Amount = Float16FromBytes(b[idxLen*2 : idxLen*2+2]).BigInt()
192	tx.Fee = FeeSelector(b[idxLen*2+2])
193	return tx, nil
194}