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.

216 lines
7.4 KiB

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