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.

266 lines
8.5 KiB

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