arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/common/pooll2tx.go
common/pooll2tx.goRaw
  1package common
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"math/big"
  7	"time"
  8
  9	ethCommon "github.com/ethereum/go-ethereum/common"
 10	"github.com/iden3/go-iden3-crypto/babyjub"
 11	"github.com/iden3/go-iden3-crypto/poseidon"
 12)
 13
 14// PoolL2Tx is a struct that represents a L2Tx sent by an account to the coordinator hat is waiting to be forged
 15type PoolL2Tx struct {
 16	// Stored in DB: mandatory fileds
 17
 18	// TxID (12 bytes) for L2Tx is:
 19	// bytes:  |  1   |    6    |   5   |
 20	// values: | type | FromIdx | Nonce |
 21	TxID        TxID               `meddler:"tx_id"`
 22	FromIdx     Idx                `meddler:"from_idx"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
 23	ToIdx       *Idx               `meddler:"to_idx"`   // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
 24	ToEthAddr   *ethCommon.Address `meddler:"to_eth_addr"`
 25	ToBJJ       *babyjub.PublicKey `meddler:"to_bjj"` // TODO: stop using json, use scanner/valuer
 26	TokenID     TokenID            `meddler:"token_id"`
 27	Amount      *big.Int           `meddler:"amount,bigint"` // TODO: change to float16
 28	AmountFloat float64            `meddler:"amount_f"`      // TODO: change to float16
 29	USD         *float64           `meddler:"value_usd"`     // TODO: change to float16
 30	Fee         FeeSelector        `meddler:"fee"`
 31	Nonce       Nonce              `meddler:"nonce"` // effective 40 bits used
 32	State       PoolL2TxState      `meddler:"state"`
 33	Signature   *babyjub.Signature `meddler:"signature"`         // tx signature
 34	Timestamp   time.Time          `meddler:"timestamp,utctime"` // time when added to the tx pool
 35	// Stored in DB: optional fileds, may be uninitialized
 36	BatchNum          *BatchNum          `meddler:"batch_num"`   // batchNum in which this tx was forged. Presence indicates "forged" state.
 37	RqFromIdx         *Idx               `meddler:"rq_from_idx"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
 38	RqToIdx           *Idx               `meddler:"rq_to_idx"`   // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
 39	RqToEthAddr       *ethCommon.Address `meddler:"rq_to_eth_addr"`
 40	RqToBJJ           *babyjub.PublicKey `meddler:"rq_to_bjj"` // TODO: stop using json, use scanner/valuer
 41	RqTokenID         *TokenID           `meddler:"rq_token_id"`
 42	RqAmount          *big.Int           `meddler:"rq_amount,bigintnull"` // TODO: change to float16
 43	RqFee             *FeeSelector       `meddler:"rq_fee"`
 44	RqNonce           *uint64            `meddler:"rq_nonce"` // effective 48 bits used
 45	AbsoluteFee       *float64           `meddler:"fee_usd"`
 46	AbsoluteFeeUpdate *time.Time         `meddler:"usd_update,utctime"`
 47	Type              TxType             `meddler:"tx_type"`
 48	// Extra metadata, may be uninitialized
 49	RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
 50}
 51
 52// NewPoolL2Tx returns the given L2Tx with the TxId & Type parameters calculated
 53// from the L2Tx values
 54func NewPoolL2Tx(poolL2Tx *PoolL2Tx) (*PoolL2Tx, error) {
 55	// calculate TxType
 56	var txType TxType
 57	if poolL2Tx.ToIdx == nil || *poolL2Tx.ToIdx == Idx(0) {
 58		txType = TxTypeTransfer
 59	} else if *poolL2Tx.ToIdx == Idx(1) {
 60		txType = TxTypeExit
 61	} else if *poolL2Tx.ToIdx >= IdxUserThreshold {
 62		txType = TxTypeTransfer
 63	} else {
 64		return poolL2Tx, fmt.Errorf("Can not determine type of PoolL2Tx, invalid ToIdx value: %d", poolL2Tx.ToIdx)
 65	}
 66
 67	// if TxType!=poolL2Tx.TxType return error
 68	if poolL2Tx.Type != "" && poolL2Tx.Type != txType {
 69		return poolL2Tx, fmt.Errorf("PoolL2Tx.Type: %s, should be: %s", poolL2Tx.Type, txType)
 70	}
 71	poolL2Tx.Type = txType
 72
 73	var txid [TxIDLen]byte
 74	txid[0] = TxIDPrefixL2Tx
 75	fromIdxBytes, err := poolL2Tx.FromIdx.Bytes()
 76	if err != nil {
 77		return poolL2Tx, err
 78	}
 79	copy(txid[1:7], fromIdxBytes[:])
 80	nonceBytes, err := poolL2Tx.Nonce.Bytes()
 81	if err != nil {
 82		return poolL2Tx, err
 83	}
 84	copy(txid[7:12], nonceBytes[:])
 85	poolL2Tx.TxID = TxID(txid)
 86
 87	return poolL2Tx, nil
 88}
 89
 90// TxCompressedData spec:
 91// [ 1 bits  ] toBJJSign // 1 byte
 92// [ 8 bits  ] userFee // 1 byte
 93// [ 40 bits ] nonce // 5 bytes
 94// [ 32 bits ] tokenID // 4 bytes
 95// [ 16 bits ] amountFloat16 // 2 bytes
 96// [ 48 bits ] toIdx // 6 bytes
 97// [ 48 bits ] fromIdx // 6 bytes
 98// [ 16 bits ] chainId // 2 bytes
 99// [ 32 bits ] signatureConstant // 4 bytes
100// Total bits compressed data:  241 bits // 31 bytes in *big.Int representation
101func (tx *PoolL2Tx) TxCompressedData() (*big.Int, error) {
102	// sigconstant
103	sc, ok := new(big.Int).SetString("3322668559", 10)
104	if !ok {
105		return nil, fmt.Errorf("error parsing SignatureConstant")
106	}
107
108	amountFloat16, err := NewFloat16(tx.Amount)
109	if err != nil {
110		return nil, err
111	}
112	var b [31]byte
113	toBJJSign := byte(0)
114	if babyjub.PointCoordSign(tx.ToBJJ.X) {
115		toBJJSign = byte(1)
116	}
117	b[0] = toBJJSign
118	b[1] = byte(tx.Fee)
119	nonceBytes, err := tx.Nonce.Bytes()
120	if err != nil {
121		return nil, err
122	}
123	copy(b[2:7], nonceBytes[:])
124	copy(b[7:11], tx.TokenID.Bytes())
125	copy(b[11:13], amountFloat16.Bytes())
126	toIdxBytes, err := tx.ToIdx.Bytes()
127	if err != nil {
128		return nil, err
129	}
130	copy(b[13:19], toIdxBytes[:])
131	fromIdxBytes, err := tx.FromIdx.Bytes()
132	if err != nil {
133		return nil, err
134	}
135	copy(b[19:25], fromIdxBytes[:])
136	copy(b[25:27], []byte{0, 1, 0, 0}) // TODO check js implementation (unexpected behaviour from test vector generated from js)
137	copy(b[27:31], sc.Bytes())
138
139	bi := new(big.Int).SetBytes(b[:])
140	return bi, nil
141}
142
143// TxCompressedDataV2 spec:
144// [ 1 bits  ] toBJJSign // 1 byte
145// [ 8 bits  ] userFee // 1 byte
146// [ 40 bits ] nonce // 5 bytes
147// [ 32 bits ] tokenID // 4 bytes
148// [ 16 bits ] amountFloat16 // 2 bytes
149// [ 48 bits ] toIdx // 6 bytes
150// [ 48 bits ] fromIdx // 6 bytes
151// Total bits compressed data:  193 bits // 25 bytes in *big.Int representation
152func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
153	amountFloat16, err := NewFloat16(tx.Amount)
154	if err != nil {
155		return nil, err
156	}
157	var b [25]byte
158	toBJJSign := byte(0)
159	if babyjub.PointCoordSign(tx.ToBJJ.X) {
160		toBJJSign = byte(1)
161	}
162	b[0] = toBJJSign
163	b[1] = byte(tx.Fee)
164	nonceBytes, err := tx.Nonce.Bytes()
165	if err != nil {
166		return nil, err
167	}
168	copy(b[2:7], nonceBytes[:])
169	copy(b[7:11], tx.TokenID.Bytes())
170	copy(b[11:13], amountFloat16.Bytes())
171	toIdxBytes, err := tx.ToIdx.Bytes()
172	if err != nil {
173		return nil, err
174	}
175	copy(b[13:19], toIdxBytes[:])
176	fromIdxBytes, err := tx.FromIdx.Bytes()
177	if err != nil {
178		return nil, err
179	}
180	copy(b[19:25], fromIdxBytes[:])
181
182	bi := new(big.Int).SetBytes(b[:])
183	return bi, nil
184}
185
186// HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will be signed by the sender.
187func (tx *PoolL2Tx) HashToSign() (*big.Int, error) {
188	toCompressedData, err := tx.TxCompressedData()
189	if err != nil {
190		return nil, err
191	}
192	toEthAddr := big.NewInt(0)
193	if tx.ToEthAddr != nil {
194		toEthAddr = EthAddrToBigInt(*tx.ToEthAddr)
195	}
196	rqToEthAddr := big.NewInt(0)
197	if tx.RqToEthAddr != nil {
198		rqToEthAddr = EthAddrToBigInt(*tx.RqToEthAddr)
199	}
200	toBJJAy := tx.ToBJJ.Y
201	rqTxCompressedDataV2, err := tx.TxCompressedDataV2()
202	if err != nil {
203		return nil, err
204	}
205
206	return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJAy, rqTxCompressedDataV2, rqToEthAddr, tx.RqToBJJ.Y})
207}
208
209// VerifySignature returns true if the signature verification is correct for the given PublicKey
210func (tx *PoolL2Tx) VerifySignature(pk *babyjub.PublicKey) bool {
211	h, err := tx.HashToSign()
212	if err != nil {
213		return false
214	}
215	return pk.VerifyPoseidon(h, tx.Signature)
216}
217
218// L2Tx returns a *L2Tx from the PoolL2Tx
219func (tx *PoolL2Tx) L2Tx() (*L2Tx, error) {
220	if tx.ToIdx == nil || tx.BatchNum == nil {
221		return nil, errors.New("PoolL2Tx must have ToIdx != nil and BatchNum != nil in order to be able to transform to Tx")
222	}
223	return &L2Tx{
224		TxID:     tx.TxID,
225		BatchNum: *tx.BatchNum,
226		FromIdx:  tx.FromIdx,
227		ToIdx:    *tx.ToIdx,
228		Amount:   tx.Amount,
229		Fee:      tx.Fee,
230		Nonce:    tx.Nonce,
231		Type:     tx.Type,
232	}, nil
233}
234
235// Tx returns a *Tx from the PoolL2Tx
236func (tx *PoolL2Tx) Tx() (*Tx, error) {
237	if tx.ToIdx == nil {
238		return nil, errors.New("PoolL2Tx must have ToIdx != nil in order to be able to transform to Tx")
239	}
240	fromIdx := new(Idx)
241	*fromIdx = tx.FromIdx
242	return &Tx{
243		TxID:    tx.TxID,
244		FromIdx: fromIdx,
245		ToIdx:   tx.ToIdx,
246		Amount:  tx.Amount,
247		Nonce:   &tx.Nonce,
248		Fee:     &tx.Fee,
249		Type:    tx.Type,
250	}, nil
251}
252
253// PoolL2TxsToL2Txs returns an array of []L2Tx from an array of []PoolL2Tx
254func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error) {
255	var r []L2Tx
256	for _, poolTx := range txs {
257		tx, err := poolTx.L2Tx()
258		if err != nil {
259			return nil, err
260		}
261		r = append(r, *tx)
262	}
263	return r, nil
264}
265
266// PoolL2TxState is a struct that represents the status of a L2 transaction
267type PoolL2TxState string
268
269const (
270	// PoolL2TxStatePending represents a valid L2Tx that hasn't started the forging process
271	PoolL2TxStatePending PoolL2TxState = "pend"
272	// PoolL2TxStateForging represents a valid L2Tx that has started the forging process
273	PoolL2TxStateForging PoolL2TxState = "fing"
274	// PoolL2TxStateForged represents a L2Tx that has already been forged
275	PoolL2TxStateForged PoolL2TxState = "fged"
276	// PoolL2TxStateInvalid represents a L2Tx that has been invalidated
277	PoolL2TxStateInvalid PoolL2TxState = "invl"
278)