You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

220 lines
7.7 KiB

  1. package common
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "math/big"
  6. "time"
  7. ethCommon "github.com/ethereum/go-ethereum/common"
  8. "github.com/hermeznetwork/hermez-node/utils"
  9. "github.com/iden3/go-iden3-crypto/babyjub"
  10. "github.com/iden3/go-iden3-crypto/poseidon"
  11. )
  12. // Nonce represents the nonce value in a uint64, which has the method Bytes that returns a byte array of length 5 (40 bits).
  13. type Nonce uint64
  14. // Bytes returns a byte array of length 5 representing the Nonce
  15. func (n Nonce) Bytes() ([5]byte, error) {
  16. if n >= 1099511627776 { // 2**40bits
  17. return [5]byte{}, ErrNonceOverflow
  18. }
  19. var nonceBytes [8]byte
  20. binary.LittleEndian.PutUint64(nonceBytes[:], uint64(n))
  21. var b [5]byte
  22. copy(b[:], nonceBytes[:5])
  23. return b, nil
  24. }
  25. // NonceFromBytes returns Nonce from a [5]byte
  26. func NonceFromBytes(b [5]byte) Nonce {
  27. var nonceBytes [8]byte
  28. copy(nonceBytes[:], b[:5])
  29. nonce := binary.LittleEndian.Uint64(nonceBytes[:])
  30. return Nonce(nonce)
  31. }
  32. // PoolL2Tx is a struct that represents a L2Tx sent by an account to the coordinator hat is waiting to be forged
  33. type PoolL2Tx struct {
  34. // Stored in DB: mandatory fileds
  35. TxID TxID `meddler:"tx_id"`
  36. FromIdx Idx `meddler:"from_idx"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
  37. ToIdx Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
  38. ToEthAddr ethCommon.Address `meddler:"to_eth_addr"`
  39. ToBJJ *babyjub.PublicKey `meddler:"to_bjj"` // TODO: stop using json, use scanner/valuer
  40. TokenID TokenID `meddler:"token_id"`
  41. Amount *big.Int `meddler:"amount,bigint"` // TODO: change to float16
  42. Fee FeeSelector `meddler:"fee"`
  43. Nonce Nonce `meddler:"nonce"` // effective 40 bits used
  44. State PoolL2TxState `meddler:"state"`
  45. Signature *babyjub.Signature `meddler:"signature"` // tx signature
  46. Timestamp time.Time `meddler:"timestamp,utctime"` // time when added to the tx pool
  47. // Stored in DB: optional fileds, may be uninitialized
  48. BatchNum BatchNum `meddler:"batch_num,zeroisnull"` // batchNum in which this tx was forged. Presence indicates "forged" state.
  49. RqFromIdx Idx `meddler:"rq_from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
  50. RqToIdx Idx `meddler:"rq_to_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
  51. RqToEthAddr ethCommon.Address `meddler:"rq_to_eth_addr"`
  52. RqToBJJ *babyjub.PublicKey `meddler:"rq_to_bjj"` // TODO: stop using json, use scanner/valuer
  53. RqTokenID TokenID `meddler:"rq_token_id,zeroisnull"`
  54. RqAmount *big.Int `meddler:"rq_amount,bigintnull"` // TODO: change to float16
  55. RqFee FeeSelector `meddler:"rq_fee,zeroisnull"`
  56. RqNonce uint64 `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
  57. AbsoluteFee float64 `meddler:"absolute_fee,zeroisnull"`
  58. AbsoluteFeeUpdate time.Time `meddler:"absolute_fee_update,utctimez"`
  59. // Extra metadata, may be uninitialized
  60. Type TxType `meddler:"-"` // optional, descrives which kind of tx it's
  61. RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
  62. }
  63. // TxCompressedData spec:
  64. // [ 32 bits ] signatureConstant // 4 bytes: [0:4]
  65. // [ 16 bits ] chainId // 2 bytes: [4:6]
  66. // [ 48 bits ] fromIdx // 6 bytes: [6:12]
  67. // [ 48 bits ] toIdx // 6 bytes: [12:18]
  68. // [ 16 bits ] amountFloat16 // 2 bytes: [18:20]
  69. // [ 32 bits ] tokenID // 4 bytes: [20:24]
  70. // [ 40 bits ] nonce // 5 bytes: [24:29]
  71. // [ 8 bits ] userFee // 1 byte: [29:30]
  72. // [ 1 bits ] toBjjSign // 1 byte: [30:31]
  73. // Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
  74. func (tx *PoolL2Tx) TxCompressedData() (*big.Int, error) {
  75. // sigconstant
  76. sc, ok := new(big.Int).SetString("3322668559", 10)
  77. if !ok {
  78. return nil, fmt.Errorf("error parsing SignatureConstant")
  79. }
  80. amountFloat16, err := utils.NewFloat16(tx.Amount)
  81. if err != nil {
  82. return nil, err
  83. }
  84. var b [31]byte
  85. copy(b[:4], SwapEndianness(sc.Bytes()))
  86. copy(b[4:6], []byte{1, 0, 0, 0}) // LittleEndian representation of uint32(1) for Ethereum
  87. copy(b[6:12], tx.FromIdx.Bytes())
  88. copy(b[12:18], tx.ToIdx.Bytes())
  89. copy(b[18:20], amountFloat16.Bytes())
  90. copy(b[20:24], tx.TokenID.Bytes())
  91. nonceBytes, err := tx.Nonce.Bytes()
  92. if err != nil {
  93. return nil, err
  94. }
  95. copy(b[24:29], nonceBytes[:])
  96. b[29] = byte(tx.Fee)
  97. toBjjSign := byte(0)
  98. if babyjub.PointCoordSign(tx.ToBJJ.X) {
  99. toBjjSign = byte(1)
  100. }
  101. b[30] = toBjjSign
  102. bi := new(big.Int).SetBytes(SwapEndianness(b[:]))
  103. return bi, nil
  104. }
  105. // TxCompressedDataV2 spec:
  106. // [ 48 bits ] fromIdx // 6 bytes: [0:6]
  107. // [ 48 bits ] toIdx // 6 bytes: [6:12]
  108. // [ 16 bits ] amountFloat16 // 2 bytes: [12:14]
  109. // [ 32 bits ] tokenID // 4 bytes: [14:18]
  110. // [ 40 bits ] nonce // 5 bytes: [18:23]
  111. // [ 8 bits ] userFee // 1 byte: [23:24]
  112. // [ 1 bits ] toBjjSign // 1 byte: [24:25]
  113. // Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
  114. func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
  115. amountFloat16, err := utils.NewFloat16(tx.Amount)
  116. if err != nil {
  117. return nil, err
  118. }
  119. var b [25]byte
  120. copy(b[0:6], tx.FromIdx.Bytes())
  121. copy(b[6:12], tx.ToIdx.Bytes())
  122. copy(b[12:14], amountFloat16.Bytes())
  123. copy(b[14:18], tx.TokenID.Bytes())
  124. nonceBytes, err := tx.Nonce.Bytes()
  125. if err != nil {
  126. return nil, err
  127. }
  128. copy(b[18:23], nonceBytes[:])
  129. b[23] = byte(tx.Fee)
  130. toBjjSign := byte(0)
  131. if babyjub.PointCoordSign(tx.ToBJJ.X) {
  132. toBjjSign = byte(1)
  133. }
  134. b[24] = toBjjSign
  135. bi := new(big.Int).SetBytes(SwapEndianness(b[:]))
  136. return bi, nil
  137. }
  138. // HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will be signed by the sender.
  139. func (tx *PoolL2Tx) HashToSign() (*big.Int, error) {
  140. toCompressedData, err := tx.TxCompressedData()
  141. if err != nil {
  142. return nil, err
  143. }
  144. toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
  145. toBjjAy := tx.ToBJJ.Y
  146. rqTxCompressedDataV2, err := tx.TxCompressedDataV2()
  147. if err != nil {
  148. return nil, err
  149. }
  150. return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBjjAy, rqTxCompressedDataV2, EthAddrToBigInt(tx.RqToEthAddr), tx.RqToBJJ.Y})
  151. }
  152. // VerifySignature returns true if the signature verification is correct for the given PublicKey
  153. func (tx *PoolL2Tx) VerifySignature(pk *babyjub.PublicKey) bool {
  154. h, err := tx.HashToSign()
  155. if err != nil {
  156. return false
  157. }
  158. return pk.VerifyPoseidon(h, tx.Signature)
  159. }
  160. func (tx *PoolL2Tx) L2Tx() *L2Tx {
  161. return &L2Tx{
  162. TxID: tx.TxID,
  163. BatchNum: tx.BatchNum,
  164. FromIdx: tx.FromIdx,
  165. ToIdx: tx.ToIdx,
  166. Amount: tx.Amount,
  167. Fee: tx.Fee,
  168. Nonce: tx.Nonce,
  169. Type: tx.Type,
  170. }
  171. }
  172. func (tx *PoolL2Tx) Tx() *Tx {
  173. return &Tx{
  174. TxID: tx.TxID,
  175. FromIdx: tx.FromIdx,
  176. ToIdx: tx.ToIdx,
  177. Amount: tx.Amount,
  178. Nonce: tx.Nonce,
  179. Fee: tx.Fee,
  180. Type: tx.Type,
  181. }
  182. }
  183. func PoolL2TxsToL2Txs(txs []*PoolL2Tx) []*L2Tx {
  184. var r []*L2Tx
  185. for _, tx := range txs {
  186. r = append(r, tx.L2Tx())
  187. }
  188. return r
  189. }
  190. // PoolL2TxState is a struct that represents the status of a L2 transaction
  191. type PoolL2TxState string
  192. const (
  193. // PoolL2TxStatePending represents a valid L2Tx that hasn't started the forging process
  194. PoolL2TxStatePending PoolL2TxState = "pend"
  195. // PoolL2TxStateForging represents a valid L2Tx that has started the forging process
  196. PoolL2TxStateForging PoolL2TxState = "fing"
  197. // PoolL2TxStateForged represents a L2Tx that has already been forged
  198. PoolL2TxStateForged PoolL2TxState = "fged"
  199. // PoolL2TxStateInvalid represents a L2Tx that has been invalidated
  200. PoolL2TxStateInvalid PoolL2TxState = "invl"
  201. )