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.

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