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.

383 lines
11 KiB

  1. package common
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "fmt"
  6. "math/big"
  7. "time"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/tracerr"
  10. "github.com/iden3/go-iden3-crypto/babyjub"
  11. "github.com/iden3/go-iden3-crypto/poseidon"
  12. )
  13. // EmptyBJJComp contains the 32 byte array of a empty BabyJubJub PublicKey
  14. // Compressed. It is a valid point in the BabyJubJub curve, so does not give
  15. // errors when being decompressed.
  16. var EmptyBJJComp = babyjub.PublicKeyComp([32]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
  17. // PoolL2Tx is a struct that represents a L2Tx sent by an account to the
  18. // coordinator that is waiting to be forged
  19. type PoolL2Tx struct {
  20. // Stored in DB: mandatory fileds
  21. // TxID (12 bytes) for L2Tx is:
  22. // bytes: | 1 | 6 | 5 |
  23. // values: | type | FromIdx | Nonce |
  24. TxID TxID `meddler:"tx_id"`
  25. FromIdx Idx `meddler:"from_idx"`
  26. ToIdx Idx `meddler:"to_idx,zeroisnull"`
  27. // AuxToIdx is only used internally at the StateDB to avoid repeated
  28. // computation when processing transactions (from Synchronizer,
  29. // TxSelector, BatchBuilder)
  30. AuxToIdx Idx `meddler:"-"`
  31. ToEthAddr ethCommon.Address `meddler:"to_eth_addr,zeroisnull"`
  32. ToBJJ babyjub.PublicKeyComp `meddler:"to_bjj,zeroisnull"`
  33. TokenID TokenID `meddler:"token_id"`
  34. Amount *big.Int `meddler:"amount,bigint"` // TODO: change to float16
  35. Fee FeeSelector `meddler:"fee"`
  36. Nonce Nonce `meddler:"nonce"` // effective 40 bits used
  37. State PoolL2TxState `meddler:"state"`
  38. Signature babyjub.SignatureComp `meddler:"signature"` // tx signature
  39. Timestamp time.Time `meddler:"timestamp,utctime"` // time when added to the tx pool
  40. // Stored in DB: optional fileds, may be uninitialized
  41. RqFromIdx Idx `meddler:"rq_from_idx,zeroisnull"`
  42. RqToIdx Idx `meddler:"rq_to_idx,zeroisnull"`
  43. RqToEthAddr ethCommon.Address `meddler:"rq_to_eth_addr,zeroisnull"`
  44. RqToBJJ babyjub.PublicKeyComp `meddler:"rq_to_bjj,zeroisnull"`
  45. RqTokenID TokenID `meddler:"rq_token_id,zeroisnull"`
  46. RqAmount *big.Int `meddler:"rq_amount,bigintnull"` // TODO: change to float16
  47. RqFee FeeSelector `meddler:"rq_fee,zeroisnull"`
  48. RqNonce Nonce `meddler:"rq_nonce,zeroisnull"` // effective 48 bits used
  49. AbsoluteFee float64 `meddler:"fee_usd,zeroisnull"`
  50. AbsoluteFeeUpdate time.Time `meddler:"usd_update,utctimez"`
  51. Type TxType `meddler:"tx_type"`
  52. // Extra metadata, may be uninitialized
  53. RqTxCompressedData []byte `meddler:"-"` // 253 bits, optional for atomic txs
  54. }
  55. // NewPoolL2Tx returns the given L2Tx with the TxId & Type parameters calculated
  56. // from the L2Tx values
  57. func NewPoolL2Tx(tx *PoolL2Tx) (*PoolL2Tx, error) {
  58. txTypeOld := tx.Type
  59. if err := tx.SetType(); err != nil {
  60. return nil, tracerr.Wrap(err)
  61. }
  62. // If original Type doesn't match the correct one, return error
  63. if txTypeOld != "" && txTypeOld != tx.Type {
  64. return nil, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s",
  65. tx.Type, txTypeOld))
  66. }
  67. txIDOld := tx.TxID
  68. if err := tx.SetID(); err != nil {
  69. return nil, tracerr.Wrap(err)
  70. }
  71. // If original TxID doesn't match the correct one, return error
  72. if txIDOld != (TxID{}) && txIDOld != tx.TxID {
  73. return tx, tracerr.Wrap(fmt.Errorf("PoolL2Tx.TxID: %s, should be: %s",
  74. tx.TxID.String(), txIDOld.String()))
  75. }
  76. return tx, nil
  77. }
  78. // SetType sets the type of the transaction
  79. func (tx *PoolL2Tx) SetType() error {
  80. if tx.ToIdx >= IdxUserThreshold {
  81. tx.Type = TxTypeTransfer
  82. } else if tx.ToIdx == 1 {
  83. tx.Type = TxTypeExit
  84. } else if tx.ToIdx == 0 {
  85. if tx.ToBJJ != EmptyBJJComp && tx.ToEthAddr == FFAddr {
  86. tx.Type = TxTypeTransferToBJJ
  87. } else if tx.ToEthAddr != FFAddr && tx.ToEthAddr != EmptyAddr {
  88. tx.Type = TxTypeTransferToEthAddr
  89. }
  90. } else {
  91. return tracerr.Wrap(errors.New("malformed transaction"))
  92. }
  93. return nil
  94. }
  95. // SetID sets the ID of the transaction
  96. func (tx *PoolL2Tx) SetID() error {
  97. txID, err := tx.L2Tx().CalculateTxID()
  98. if err != nil {
  99. return tracerr.Wrap(err)
  100. }
  101. tx.TxID = txID
  102. return nil
  103. }
  104. // TxCompressedData spec:
  105. // [ 1 bits ] toBJJSign // 1 byte
  106. // [ 8 bits ] userFee // 1 byte
  107. // [ 40 bits ] nonce // 5 bytes
  108. // [ 32 bits ] tokenID // 4 bytes
  109. // [ 16 bits ] amountFloat16 // 2 bytes
  110. // [ 48 bits ] toIdx // 6 bytes
  111. // [ 48 bits ] fromIdx // 6 bytes
  112. // [ 16 bits ] chainId // 2 bytes
  113. // [ 32 bits ] signatureConstant // 4 bytes
  114. // Total bits compressed data: 241 bits // 31 bytes in *big.Int representation
  115. func (tx *PoolL2Tx) TxCompressedData(chainID uint16) (*big.Int, error) {
  116. amountFloat16, err := NewFloat16(tx.Amount)
  117. if err != nil {
  118. return nil, tracerr.Wrap(err)
  119. }
  120. var b [31]byte
  121. toBJJSign := byte(0)
  122. pkSign, _ := babyjub.UnpackSignY(tx.ToBJJ)
  123. if pkSign {
  124. toBJJSign = byte(1)
  125. }
  126. b[0] = toBJJSign
  127. b[1] = byte(tx.Fee)
  128. nonceBytes, err := tx.Nonce.Bytes()
  129. if err != nil {
  130. return nil, tracerr.Wrap(err)
  131. }
  132. copy(b[2:7], nonceBytes[:])
  133. copy(b[7:11], tx.TokenID.Bytes())
  134. copy(b[11:13], amountFloat16.Bytes())
  135. toIdxBytes, err := tx.ToIdx.Bytes()
  136. if err != nil {
  137. return nil, tracerr.Wrap(err)
  138. }
  139. copy(b[13:19], toIdxBytes[:])
  140. fromIdxBytes, err := tx.FromIdx.Bytes()
  141. if err != nil {
  142. return nil, tracerr.Wrap(err)
  143. }
  144. copy(b[19:25], fromIdxBytes[:])
  145. binary.BigEndian.PutUint16(b[25:27], chainID)
  146. copy(b[27:31], SignatureConstantBytes[:])
  147. bi := new(big.Int).SetBytes(b[:])
  148. return bi, nil
  149. }
  150. // TxCompressedDataEmpty calculates the TxCompressedData of an empty
  151. // transaction
  152. func TxCompressedDataEmpty(chainID uint16) *big.Int {
  153. var b [31]byte
  154. binary.BigEndian.PutUint16(b[25:27], chainID)
  155. copy(b[27:31], SignatureConstantBytes[:])
  156. bi := new(big.Int).SetBytes(b[:])
  157. return bi
  158. }
  159. // TxCompressedDataV2 spec:
  160. // [ 1 bits ] toBJJSign // 1 byte
  161. // [ 8 bits ] userFee // 1 byte
  162. // [ 40 bits ] nonce // 5 bytes
  163. // [ 32 bits ] tokenID // 4 bytes
  164. // [ 16 bits ] amountFloat16 // 2 bytes
  165. // [ 48 bits ] toIdx // 6 bytes
  166. // [ 48 bits ] fromIdx // 6 bytes
  167. // Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
  168. func (tx *PoolL2Tx) TxCompressedDataV2() (*big.Int, error) {
  169. if tx.Amount == nil {
  170. tx.Amount = big.NewInt(0)
  171. }
  172. amountFloat16, err := NewFloat16(tx.Amount)
  173. if err != nil {
  174. return nil, tracerr.Wrap(err)
  175. }
  176. var b [25]byte
  177. toBJJSign := byte(0)
  178. if tx.ToBJJ != EmptyBJJComp {
  179. sign, _ := babyjub.UnpackSignY(tx.ToBJJ)
  180. if sign {
  181. toBJJSign = byte(1)
  182. }
  183. }
  184. b[0] = toBJJSign
  185. b[1] = byte(tx.Fee)
  186. nonceBytes, err := tx.Nonce.Bytes()
  187. if err != nil {
  188. return nil, tracerr.Wrap(err)
  189. }
  190. copy(b[2:7], nonceBytes[:])
  191. copy(b[7:11], tx.TokenID.Bytes())
  192. copy(b[11:13], amountFloat16.Bytes())
  193. toIdxBytes, err := tx.ToIdx.Bytes()
  194. if err != nil {
  195. return nil, tracerr.Wrap(err)
  196. }
  197. copy(b[13:19], toIdxBytes[:])
  198. fromIdxBytes, err := tx.FromIdx.Bytes()
  199. if err != nil {
  200. return nil, tracerr.Wrap(err)
  201. }
  202. copy(b[19:25], fromIdxBytes[:])
  203. bi := new(big.Int).SetBytes(b[:])
  204. return bi, nil
  205. }
  206. // RqTxCompressedDataV2 is like the TxCompressedDataV2 but using the 'Rq'
  207. // parameters. In a future iteration of the hermez-node, the 'Rq' parameters
  208. // can be inside a struct, which contains the 'Rq' transaction grouped inside,
  209. // so then computing the 'RqTxCompressedDataV2' would be just calling
  210. // 'tx.Rq.TxCompressedDataV2()'.
  211. // RqTxCompressedDataV2 spec:
  212. // [ 1 bits ] rqToBJJSign // 1 byte
  213. // [ 8 bits ] rqUserFee // 1 byte
  214. // [ 40 bits ] rqNonce // 5 bytes
  215. // [ 32 bits ] rqTokenID // 4 bytes
  216. // [ 16 bits ] rqAmountFloat16 // 2 bytes
  217. // [ 48 bits ] rqToIdx // 6 bytes
  218. // [ 48 bits ] rqFromIdx // 6 bytes
  219. // Total bits compressed data: 193 bits // 25 bytes in *big.Int representation
  220. func (tx *PoolL2Tx) RqTxCompressedDataV2() (*big.Int, error) {
  221. if tx.RqAmount == nil {
  222. tx.RqAmount = big.NewInt(0)
  223. }
  224. amountFloat16, err := NewFloat16(tx.RqAmount)
  225. if err != nil {
  226. return nil, tracerr.Wrap(err)
  227. }
  228. var b [25]byte
  229. rqToBJJSign := byte(0)
  230. if tx.RqToBJJ != EmptyBJJComp {
  231. sign, _ := babyjub.UnpackSignY(tx.RqToBJJ)
  232. if sign {
  233. rqToBJJSign = byte(1)
  234. }
  235. }
  236. b[0] = rqToBJJSign
  237. b[1] = byte(tx.RqFee)
  238. nonceBytes, err := tx.RqNonce.Bytes()
  239. if err != nil {
  240. return nil, tracerr.Wrap(err)
  241. }
  242. copy(b[2:7], nonceBytes[:])
  243. copy(b[7:11], tx.RqTokenID.Bytes())
  244. copy(b[11:13], amountFloat16.Bytes())
  245. toIdxBytes, err := tx.RqToIdx.Bytes()
  246. if err != nil {
  247. return nil, tracerr.Wrap(err)
  248. }
  249. copy(b[13:19], toIdxBytes[:])
  250. fromIdxBytes, err := tx.RqFromIdx.Bytes()
  251. if err != nil {
  252. return nil, tracerr.Wrap(err)
  253. }
  254. copy(b[19:25], fromIdxBytes[:])
  255. bi := new(big.Int).SetBytes(b[:])
  256. return bi, nil
  257. }
  258. // HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will
  259. // be signed by the sender.
  260. func (tx *PoolL2Tx) HashToSign(chainID uint16) (*big.Int, error) {
  261. toCompressedData, err := tx.TxCompressedData(chainID)
  262. if err != nil {
  263. return nil, tracerr.Wrap(err)
  264. }
  265. toEthAddr := EthAddrToBigInt(tx.ToEthAddr)
  266. rqToEthAddr := EthAddrToBigInt(tx.RqToEthAddr)
  267. _, toBJJY := babyjub.UnpackSignY(tx.ToBJJ)
  268. rqTxCompressedDataV2, err := tx.RqTxCompressedDataV2()
  269. if err != nil {
  270. return nil, tracerr.Wrap(err)
  271. }
  272. _, rqToBJJY := babyjub.UnpackSignY(tx.RqToBJJ)
  273. return poseidon.Hash([]*big.Int{toCompressedData, toEthAddr, toBJJY, rqTxCompressedDataV2, rqToEthAddr, rqToBJJY})
  274. }
  275. // VerifySignature returns true if the signature verification is correct for the given PublicKeyComp
  276. func (tx *PoolL2Tx) VerifySignature(chainID uint16, pkComp babyjub.PublicKeyComp) bool {
  277. h, err := tx.HashToSign(chainID)
  278. if err != nil {
  279. return false
  280. }
  281. s, err := tx.Signature.Decompress()
  282. if err != nil {
  283. return false
  284. }
  285. pk, err := pkComp.Decompress()
  286. if err != nil {
  287. return false
  288. }
  289. return pk.VerifyPoseidon(h, s)
  290. }
  291. // L2Tx returns a *L2Tx from the PoolL2Tx
  292. func (tx PoolL2Tx) L2Tx() L2Tx {
  293. var toIdx Idx
  294. if tx.ToIdx == Idx(0) {
  295. toIdx = tx.AuxToIdx
  296. } else {
  297. toIdx = tx.ToIdx
  298. }
  299. return L2Tx{
  300. TxID: tx.TxID,
  301. FromIdx: tx.FromIdx,
  302. ToIdx: toIdx,
  303. TokenID: tx.TokenID,
  304. Amount: tx.Amount,
  305. Fee: tx.Fee,
  306. Nonce: tx.Nonce,
  307. Type: tx.Type,
  308. }
  309. }
  310. // Tx returns a *Tx from the PoolL2Tx
  311. func (tx PoolL2Tx) Tx() Tx {
  312. return Tx{
  313. TxID: tx.TxID,
  314. FromIdx: tx.FromIdx,
  315. ToIdx: tx.ToIdx,
  316. Amount: tx.Amount,
  317. TokenID: tx.TokenID,
  318. Nonce: &tx.Nonce,
  319. Fee: &tx.Fee,
  320. Type: tx.Type,
  321. }
  322. }
  323. // PoolL2TxsToL2Txs returns an array of []L2Tx from an array of []PoolL2Tx
  324. func PoolL2TxsToL2Txs(txs []PoolL2Tx) ([]L2Tx, error) {
  325. l2Txs := make([]L2Tx, len(txs))
  326. for i, poolTx := range txs {
  327. l2Txs[i] = poolTx.L2Tx()
  328. }
  329. return l2Txs, nil
  330. }
  331. // TxIDsFromPoolL2Txs returns an array of TxID from the []PoolL2Tx
  332. func TxIDsFromPoolL2Txs(txs []PoolL2Tx) []TxID {
  333. txIDs := make([]TxID, len(txs))
  334. for i, tx := range txs {
  335. txIDs[i] = tx.TxID
  336. }
  337. return txIDs
  338. }
  339. // PoolL2TxState is a string that represents the status of a L2 transaction
  340. type PoolL2TxState string
  341. const (
  342. // PoolL2TxStatePending represents a valid L2Tx that hasn't started the
  343. // forging process
  344. PoolL2TxStatePending PoolL2TxState = "pend"
  345. // PoolL2TxStateForging represents a valid L2Tx that has started the
  346. // forging process
  347. PoolL2TxStateForging PoolL2TxState = "fing"
  348. // PoolL2TxStateForged represents a L2Tx that has already been forged
  349. PoolL2TxStateForged PoolL2TxState = "fged"
  350. // PoolL2TxStateInvalid represents a L2Tx that has been invalidated
  351. PoolL2TxStateInvalid PoolL2TxState = "invl"
  352. )