arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/common/pooll2tx.go
common/pooll2tx.goRaw
  1package common
  2
  3import (
  4	"encoding/binary"
  5	"errors"
  6	"fmt"
  7	"math/big"
  8	"time"
  9
 10	ethCommon "github.com/ethereum/go-ethereum/common"
 11	"github.com/hermeznetwork/tracerr"
 12	"github.com/iden3/go-iden3-crypto/babyjub"
 13	"github.com/iden3/go-iden3-crypto/poseidon"
 14)
 15
 16// EmptyBJJComp contains the 32 byte array of a empty BabyJubJub PublicKey
 17// Compressed. It is a valid point in the BabyJubJub curve, so does not give
 18// errors when being decompressed.
 19var EmptyBJJComp = babyjub.PublicKeyComp([32]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
 20
 21// PoolL2Tx is a struct that represents a L2Tx sent by an account to the
 22// coordinator that is waiting to be forged
 23type PoolL2Tx struct {
 24	// Stored in DB: mandatory fileds
 25
 26	// TxID (12 bytes) for L2Tx is:
 27	// bytes:  |  1   |    6    |   5   |
 28	// values: | type | FromIdx | Nonce |
 29	TxID    TxID `meddler:"tx_id"`
 30	FromIdx Idx  `meddler:"from_idx"`
 31	ToIdx   Idx  `meddler:"to_idx,zeroisnull"`
 32	// AuxToIdx is only used internally at the StateDB to avoid repeated
 33	// computation when processing transactions (from Synchronizer,
 34	// TxSelector, BatchBuilder)
 35	AuxToIdx  Idx                   `meddler:"-"`
 36	ToEthAddr ethCommon.Address     `meddler:"to_eth_addr,zeroisnull"`
 37	ToBJJ     babyjub.PublicKeyComp `meddler:"to_bjj,zeroisnull"`
 38	TokenID   TokenID               `meddler:"token_id"`
 39	Amount    *big.Int              `meddler:"amount,bigint"` // TODO: change to float16
 40	Fee       FeeSelector           `meddler:"fee"`
 41	Nonce     Nonce                 `meddler:"nonce"` // effective 40 bits used
 42	State     PoolL2TxState         `meddler:"state"`
 43	// Info contains information about the status & State of the
 44	// transaction. As for example, if the Tx has not been selected in the
 45	// last batch due not enough Balance at the Sender account, this reason
 46	// would appear at this parameter.
 47	Info      string                `meddler:"info,zeroisnull"`
 48	Signature babyjub.SignatureComp `meddler:"signature"`         // tx signature
 49	Timestamp time.Time             `meddler:"timestamp,utctime"` // time when added to the tx pool
 50	// Stored in DB: optional fileds, may be uninitialized
 51	RqFromIdx         Idx                   `meddler:"rq_from_idx,zeroisnull"`
 52	RqToIdx           Idx                   `meddler:"rq_to_idx,zeroisnull"`
 53	RqToEthAddr       ethCommon.Address     `meddler:"rq_to_eth_addr,zeroisnull"`
 54	RqToBJJ           babyjub.PublicKeyComp `meddler:"rq_to_bjj,zeroisnull"`
 55	RqTokenID         TokenID               `meddler:"rq_token_id,zeroisnull"`
 56	RqAmount          *big.Int              `meddler:"rq_amount,bigintnull"` // TODO: change to float16
 57	RqFee             FeeSelector           `meddler:"rq_fee,zeroisnull"`
 58	RqNonce           Nonce                 `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
 59	AbsoluteFee       float64               `meddler:"fee_usd,zeroisnull"`
 60	AbsoluteFeeUpdate time.Time             `meddler:"usd_update,utctimez"`
 61	Type              TxType                `meddler:"tx_type"`
 62	// Extra metadata, may be uninitialized
 63	RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
 64}
 65
 66// NewPoolL2Tx returns the given L2Tx with the TxId & Type parameters calculated
 67// from the L2Tx values
 68func NewPoolL2Tx(tx *PoolL2Tx) (*PoolL2Tx, error) {
 69	txTypeOld := tx.Type
 70	if err := tx.SetType(); err != nil {
 71		return nil, tracerr.Wrap(err)
 72	}
 73	// If original Type doesn't match the correct one, return error
 74	if txTypeOld != "" && txTypeOld != tx.Type {
 75		return nil, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s",
 76			tx.Type, txTypeOld))
 77	}
 78
 79	txIDOld := tx.TxID
 80	if err := tx.SetID(); err != nil {
 81		return nil, tracerr.Wrap(err)
 82	}
 83	// If original TxID doesn't match the correct one, return error
 84	if txIDOld != (TxID{}) && txIDOld != tx.TxID {
 85		return tx, tracerr.Wrap(fmt.Errorf("PoolL2Tx.TxID: %s, should be: %s",
 86			tx.TxID.String(), txIDOld.String()))
 87	}
 88
 89	return tx, nil
 90}
 91
 92// SetType sets the type of the transaction
 93func (tx *PoolL2Tx) SetType() error {
 94	if tx.ToIdx >= IdxUserThreshold {
 95		tx.Type = TxTypeTransfer
 96	} else if tx.ToIdx == 1 {
 97		tx.Type = TxTypeExit
 98	} else if tx.ToIdx == 0 {
 99		if tx.ToBJJ != EmptyBJJComp && tx.ToEthAddr == FFAddr {
100			tx.Type = TxTypeTransferToBJJ
101		} else if tx.ToEthAddr != FFAddr && tx.ToEthAddr != EmptyAddr {
102			tx.Type = TxTypeTransferToEthAddr
103		}
104	} else {
105		return tracerr.Wrap(errors.New("malformed transaction"))
106	}
107	return nil
108}
109
110// SetID sets the ID of the transaction
111func (tx *PoolL2Tx) SetID() error {
112	txID, err := tx.L2Tx().CalculateTxID()
113	if err != nil {
114		return tracerr.Wrap(err)
115	}
116	tx.TxID = txID
117	return nil
118}
119
120// TxCompressedData spec:
121// [ 1 bits  ] toBJJSign // 1 byte
122// [ 8 bits  ] userFee // 1 byte
123// [ 40 bits ] nonce // 5 bytes
124// [ 32 bits ] tokenID // 4 bytes
125// [ 16 bits ] amountFloat16 // 2 bytes
126// [ 48 bits ] toIdx // 6 bytes
127// [ 48 bits ] fromIdx // 6 bytes
128// [ 16 bits ] chainId // 2 bytes
129// [ 32 bits ] signatureConstant // 4 bytes
130// Total bits compressed data:  241 bits // 31 bytes in *big.Int representation
131func (tx *PoolL2Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
132	amountFloat16, err := NewFloat16(tx.Amount)
133	if err != nil {
134		return nil, tracerr.Wrap(err)
135	}
136	var b [31]byte
137
138	toBJJSign := byte(0)
139	pkSign, _ := babyjub.UnpackSignY(tx.ToBJJ)
140	if pkSign {
141		toBJJSign = byte(1)
142	}
143
144	b[0] = toBJJSign
145	b[1] = byte(tx.Fee)
146	nonceBytes, err := tx.Nonce.Bytes()
147	if err != nil {
148		return nil, tracerr.Wrap(err)
149	}
150	copy(b[2:7], nonceBytes[:])
151	copy(b[7:11], tx.TokenID.Bytes())
152	copy(b[11:13], amountFloat16.Bytes())
153	toIdxBytes, err := tx.ToIdx.Bytes()
154	if err != nil {
155		return nil, tracerr.Wrap(err)
156	}
157	copy(b[13:19], toIdxBytes[:])
158	fromIdxBytes, err := tx.FromIdx.Bytes()
159	if err != nil {
160		return nil, tracerr.Wrap(err)
161	}
162	copy(b[19:25], fromIdxBytes[:])
163	binary.BigEndian.PutUint16(b[25:27], chainID)
164	copy(b[27:31], SignatureConstantBytes[:])
165
166	bi := new(big.Int).SetBytes(b[:])
167	return bi, nil
168}
169
170// TxCompressedDataEmpty calculates the TxCompressedData of an empty
171// transaction
172func TxCompressedDataEmpty(chainID uint16) *big.Int {
173	var b [31]byte
174	binary.BigEndian.PutUint16(b[25:27], chainID)
175	copy(b[27:31], SignatureConstantBytes[:])
176	bi := new(big.Int).SetBytes(b[:])
177	return bi
178}
179
180// TxCompressedDataV2 spec:
181// [ 1 bits  ] toBJJSign // 1 byte
182// [ 8 bits  ] userFee // 1 byte
183// [ 40 bits ] nonce // 5 bytes
184// [ 32 bits ] tokenID // 4 bytes
185// [ 16 bits ] amountFloat16 // 2 bytes
186// [ 48 bits ] toIdx // 6 bytes
187// [ 48 bits ] fromIdx // 6 bytes
188// Total bits compressed data:  193 bits // 25 bytes in *big.Int representation
189func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
190	if tx.Amount == nil {
191		tx.Amount = big.NewInt(0)
192	}
193	amountFloat16, err := NewFloat16(tx.Amount)
194	if err != nil {
195		return nil, tracerr.Wrap(err)
196	}
197	var b [25]byte
198	toBJJSign := byte(0)
199	if tx.ToBJJ != EmptyBJJComp {
200		sign, _ := babyjub.UnpackSignY(tx.ToBJJ)
201		if sign {
202			toBJJSign = byte(1)
203		}
204	}
205	b[0] = toBJJSign
206	b[1] = byte(tx.Fee)
207	nonceBytes, err := tx.Nonce.Bytes()
208	if err != nil {
209		return nil, tracerr.Wrap(err)
210	}
211	copy(b[2:7], nonceBytes[:])
212	copy(b[7:11], tx.TokenID.Bytes())
213	copy(b[11:13], amountFloat16.Bytes())
214	toIdxBytes, err := tx.ToIdx.Bytes()
215	if err != nil {
216		return nil, tracerr.Wrap(err)
217	}
218	copy(b[13:19], toIdxBytes[:])
219	fromIdxBytes, err := tx.FromIdx.Bytes()
220	if err != nil {
221		return nil, tracerr.Wrap(err)
222	}
223	copy(b[19:25], fromIdxBytes[:])
224
225	bi := new(big.Int).SetBytes(b[:])
226	return bi, nil
227}
228
229// RqTxCompressedDataV2 is like the TxCompressedDataV2 but using the 'Rq'
230// parameters. In a future iteration of the hermez-node, the 'Rq' parameters
231// can be inside a struct, which contains the 'Rq' transaction grouped inside,
232// so then computing the 'RqTxCompressedDataV2' would be just calling
233// 'tx.Rq.TxCompressedDataV2()'.
234// RqTxCompressedDataV2 spec:
235// [ 1 bits  ] rqToBJJSign // 1 byte
236// [ 8 bits  ] rqUserFee // 1 byte
237// [ 40 bits ] rqNonce // 5 bytes
238// [ 32 bits ] rqTokenID // 4 bytes
239// [ 16 bits ] rqAmountFloat16 // 2 bytes
240// [ 48 bits ] rqToIdx // 6 bytes
241// [ 48 bits ] rqFromIdx // 6 bytes
242// Total bits compressed data:  193 bits // 25 bytes in *big.Int representation
243func (tx *PoolL2Tx) RqTxCompressedDataV2() (*big.Int, error) {
244	if tx.RqAmount == nil {
245		tx.RqAmount = big.NewInt(0)
246	}
247	amountFloat16, err := NewFloat16(tx.RqAmount)
248	if err != nil {
249		return nil, tracerr.Wrap(err)
250	}
251	var b [25]byte
252	rqToBJJSign := byte(0)
253	if tx.RqToBJJ != EmptyBJJComp {
254		sign, _ := babyjub.UnpackSignY(tx.RqToBJJ)
255		if sign {
256			rqToBJJSign = byte(1)
257		}
258	}
259	b[0] = rqToBJJSign
260	b[1] = byte(tx.RqFee)
261	nonceBytes, err := tx.RqNonce.Bytes()
262	if err != nil {
263		return nil, tracerr.Wrap(err)
264	}
265	copy(b[2:7], nonceBytes[:])
266	copy(b[7:11], tx.RqTokenID.Bytes())
267	copy(b[11:13], amountFloat16.Bytes())
268	toIdxBytes, err := tx.RqToIdx.Bytes()
269	if err != nil {
270		return nil, tracerr.Wrap(err)
271	}
272	copy(b[13:19], toIdxBytes[:])
273	fromIdxBytes, err := tx.RqFromIdx.Bytes()
274	if err != nil {
275		return nil, tracerr.Wrap(err)
276	}
277	copy(b[19:25], fromIdxBytes[:])
278
279	bi := new(big.Int).SetBytes(b[:])
280	return bi, nil
281}
282
283// HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will
284// be signed by the sender.
285func (tx *PoolL2Tx) HashToSign(chainID uint16) (*big.Int, error) {
286	toCompressedData, err := tx.TxCompressedData(chainID)
287	if err != nil {
288		return nil, tracerr.Wrap(err)
289	}
290	toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
291	rqToEthAddr := EthAddrToBigInt(tx.RqToEthAddr)
292
293	_, toBJJY := babyjub.UnpackSignY(tx.ToBJJ)
294
295	rqTxCompressedDataV2, err := tx.RqTxCompressedDataV2()
296	if err != nil {
297		return nil, tracerr.Wrap(err)
298	}
299
300	_, rqToBJJY := babyjub.UnpackSignY(tx.RqToBJJ)
301
302	return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJY, rqTxCompressedDataV2, rqToEthAddr, rqToBJJY})
303}
304
305// VerifySignature returns true if the signature verification is correct for the given PublicKeyComp
306func (tx *PoolL2Tx) VerifySignature(chainID uint16, pkComp babyjub.PublicKeyComp) bool {
307	h, err := tx.HashToSign(chainID)
308	if err != nil {
309		return false
310	}
311	s, err := tx.Signature.Decompress()
312	if err != nil {
313		return false
314	}
315	pk, err := pkComp.Decompress()
316	if err != nil {
317		return false
318	}
319	return pk.VerifyPoseidon(h, s)
320}
321
322// L2Tx returns a *L2Tx from the PoolL2Tx
323func (tx PoolL2Tx) L2Tx() L2Tx {
324	var toIdx Idx
325	if tx.ToIdx == Idx(0) {
326		toIdx = tx.AuxToIdx
327	} else {
328		toIdx = tx.ToIdx
329	}
330	return L2Tx{
331		TxID:    tx.TxID,
332		FromIdx: tx.FromIdx,
333		ToIdx:   toIdx,
334		TokenID: tx.TokenID,
335		Amount:  tx.Amount,
336		Fee:     tx.Fee,
337		Nonce:   tx.Nonce,
338		Type:    tx.Type,
339	}
340}
341
342// Tx returns a *Tx from the PoolL2Tx
343func (tx PoolL2Tx) Tx() Tx {
344	return Tx{
345		TxID:    tx.TxID,
346		FromIdx: tx.FromIdx,
347		ToIdx:   tx.ToIdx,
348		Amount:  tx.Amount,
349		TokenID: tx.TokenID,
350		Nonce:   &tx.Nonce,
351		Fee:     &tx.Fee,
352		Type:    tx.Type,
353	}
354}
355
356// PoolL2TxsToL2Txs returns an array of []L2Tx from an array of []PoolL2Tx
357func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error) {
358	l2Txs := make([]L2Tx, len(txs))
359	for i, poolTx := range txs {
360		l2Txs[i] = poolTx.L2Tx()
361	}
362	return l2Txs, nil
363}
364
365// TxIDsFromPoolL2Txs returns an array of TxID from the []PoolL2Tx
366func TxIDsFromPoolL2Txs(txs []PoolL2Tx) []TxID {
367	txIDs := make([]TxID, len(txs))
368	for i, tx := range txs {
369		txIDs[i] = tx.TxID
370	}
371	return txIDs
372}
373
374// PoolL2TxState is a string that represents the status of a L2 transaction
375type PoolL2TxState string
376
377const (
378	// PoolL2TxStatePending represents a valid L2Tx that hasn't started the
379	// forging process
380	PoolL2TxStatePending PoolL2TxState = "pend"
381	// PoolL2TxStateForging represents a valid L2Tx that has started the
382	// forging process
383	PoolL2TxStateForging PoolL2TxState = "fing"
384	// PoolL2TxStateForged represents a L2Tx that has already been forged
385	PoolL2TxStateForged PoolL2TxState = "fged"
386	// PoolL2TxStateInvalid represents a L2Tx that has been invalidated
387	PoolL2TxStateInvalid PoolL2TxState = "invl"
388)