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.

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