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.

684 lines
25 KiB

4 years ago
  1. package eth
  2. import (
  3. "context"
  4. "fmt"
  5. "math/big"
  6. "strings"
  7. "github.com/ethereum/go-ethereum"
  8. "github.com/ethereum/go-ethereum/accounts/abi"
  9. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  10. ethCommon "github.com/ethereum/go-ethereum/common"
  11. "github.com/ethereum/go-ethereum/core/types"
  12. "github.com/ethereum/go-ethereum/crypto"
  13. "github.com/ethereum/go-ethereum/ethclient"
  14. "github.com/hermeznetwork/hermez-node/common"
  15. Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez"
  16. HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
  17. "github.com/hermeznetwork/hermez-node/log"
  18. "github.com/iden3/go-iden3-crypto/babyjub"
  19. )
  20. // QueueStruct is the queue of L1Txs for a batch
  21. type QueueStruct struct {
  22. L1TxQueue []common.L1Tx
  23. TotalL1TxFee *big.Int
  24. }
  25. // NewQueueStruct creates a new clear QueueStruct.
  26. func NewQueueStruct() *QueueStruct {
  27. return &QueueStruct{
  28. L1TxQueue: make([]common.L1Tx, 0),
  29. TotalL1TxFee: big.NewInt(0),
  30. }
  31. }
  32. // RollupState represents the state of the Rollup in the Smart Contract
  33. type RollupState struct {
  34. StateRoot *big.Int
  35. ExitRoots []*big.Int
  36. // ExitNullifierMap map[[256 / 8]byte]bool
  37. ExitNullifierMap map[int64]map[int64]bool // batchNum -> idx -> bool
  38. TokenList []ethCommon.Address
  39. TokenMap map[ethCommon.Address]bool
  40. MapL1TxQueue map[int64]*QueueStruct
  41. LastL1L2Batch int64
  42. CurrentToForgeL1TxsNum int64
  43. LastToForgeL1TxsNum int64
  44. CurrentIdx int64
  45. }
  46. // RollupEventL1UserTx is an event of the Rollup Smart Contract
  47. type RollupEventL1UserTx struct {
  48. // ToForgeL1TxsNum int64 // QueueIndex *big.Int
  49. // Position int // TransactionIndex *big.Int
  50. L1UserTx common.L1Tx
  51. }
  52. // RollupEventL1UserTxAux is an event of the Rollup Smart Contract
  53. type RollupEventL1UserTxAux struct {
  54. ToForgeL1TxsNum uint64 // QueueIndex *big.Int
  55. Position uint8 // TransactionIndex *big.Int
  56. L1UserTx []byte
  57. }
  58. // RollupEventAddToken is an event of the Rollup Smart Contract
  59. type RollupEventAddToken struct {
  60. TokenAddress ethCommon.Address
  61. TokenID uint32
  62. }
  63. // RollupEventForgeBatch is an event of the Rollup Smart Contract
  64. type RollupEventForgeBatch struct {
  65. BatchNum int64
  66. // Sender ethCommon.Address
  67. EthTxHash ethCommon.Hash
  68. }
  69. // RollupEventUpdateForgeL1L2BatchTimeout is an event of the Rollup Smart Contract
  70. type RollupEventUpdateForgeL1L2BatchTimeout struct {
  71. NewForgeL1L2BatchTimeout int64
  72. }
  73. // RollupEventUpdateFeeAddToken is an event of the Rollup Smart Contract
  74. type RollupEventUpdateFeeAddToken struct {
  75. NewFeeAddToken *big.Int
  76. }
  77. // RollupEventWithdraw is an event of the Rollup Smart Contract
  78. type RollupEventWithdraw struct {
  79. Idx uint64
  80. NumExitRoot uint64
  81. InstantWithdraw bool
  82. TxHash ethCommon.Hash // Hash of the transaction that generated this event
  83. }
  84. // RollupEvents is the list of events in a block of the Rollup Smart Contract
  85. type RollupEvents struct {
  86. L1UserTx []RollupEventL1UserTx
  87. AddToken []RollupEventAddToken
  88. ForgeBatch []RollupEventForgeBatch
  89. UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
  90. UpdateFeeAddToken []RollupEventUpdateFeeAddToken
  91. Withdraw []RollupEventWithdraw
  92. }
  93. // NewRollupEvents creates an empty RollupEvents with the slices initialized.
  94. func NewRollupEvents() RollupEvents {
  95. return RollupEvents{
  96. L1UserTx: make([]RollupEventL1UserTx, 0),
  97. AddToken: make([]RollupEventAddToken, 0),
  98. ForgeBatch: make([]RollupEventForgeBatch, 0),
  99. UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
  100. UpdateFeeAddToken: make([]RollupEventUpdateFeeAddToken, 0),
  101. Withdraw: make([]RollupEventWithdraw, 0),
  102. }
  103. }
  104. // RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract
  105. type RollupForgeBatchArgs struct {
  106. NewLastIdx int64
  107. NewStRoot *big.Int
  108. NewExitRoot *big.Int
  109. L1CoordinatorTxs []common.L1Tx
  110. L1CoordinatorTxsAuths [][]byte // Authorization for accountCreations for each L1CoordinatorTx
  111. L2TxsData []common.L2Tx
  112. FeeIdxCoordinator []common.Idx
  113. // Circuit selector
  114. VerifierIdx uint8
  115. L1Batch bool
  116. ProofA [2]*big.Int
  117. ProofB [2][2]*big.Int
  118. ProofC [2]*big.Int
  119. }
  120. // RollupForgeBatchArgsAux are the arguments to the ForgeBatch function in the Rollup Smart Contract
  121. type RollupForgeBatchArgsAux struct {
  122. NewLastIdx *big.Int
  123. NewStRoot *big.Int
  124. NewExitRoot *big.Int
  125. EncodedL1CoordinatorTx []byte
  126. L2TxsData []byte
  127. FeeIdxCoordinator []byte
  128. // Circuit selector
  129. VerifierIdx uint8
  130. L1Batch bool
  131. ProofA [2]*big.Int
  132. ProofB [2][2]*big.Int
  133. ProofC [2]*big.Int
  134. }
  135. // RollupInterface is the inteface to to Rollup Smart Contract
  136. type RollupInterface interface {
  137. //
  138. // Smart Contract Methods
  139. //
  140. // Public Functions
  141. RollupForgeBatch(*RollupForgeBatchArgs) (*types.Transaction, error)
  142. RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (*types.Transaction, error)
  143. RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction, error)
  144. RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error)
  145. RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
  146. RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error)
  147. // Governance Public Functions
  148. RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (*types.Transaction, error)
  149. RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error)
  150. // Viewers
  151. RollupRegisterTokensCount() (*big.Int, error)
  152. RollupLastForgedBatch() (int64, error)
  153. //
  154. // Smart Contract Status
  155. //
  156. RollupConstants() (*common.RollupConstants, error)
  157. RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
  158. RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error)
  159. }
  160. //
  161. // Implementation
  162. //
  163. // RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
  164. type RollupClient struct {
  165. client *EthereumClient
  166. address ethCommon.Address
  167. tokenHEZCfg TokenConfig
  168. hermez *Hermez.Hermez
  169. tokenHEZ *HEZ.HEZ
  170. contractAbi abi.ABI
  171. }
  172. // NewRollupClient creates a new RollupClient
  173. func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZCfg TokenConfig) (*RollupClient, error) {
  174. contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
  175. if err != nil {
  176. return nil, err
  177. }
  178. hermez, err := Hermez.NewHermez(address, client.Client())
  179. if err != nil {
  180. return nil, err
  181. }
  182. tokenHEZ, err := HEZ.NewHEZ(tokenHEZCfg.Address, client.Client())
  183. if err != nil {
  184. return nil, err
  185. }
  186. return &RollupClient{
  187. client: client,
  188. address: address,
  189. tokenHEZCfg: tokenHEZCfg,
  190. hermez: hermez,
  191. tokenHEZ: tokenHEZ,
  192. contractAbi: contractAbi,
  193. }, nil
  194. }
  195. // RollupForgeBatch is the interface to call the smart contract function
  196. func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  197. if tx, err = c.client.CallAuth(
  198. 1000000, //nolint:gomnd
  199. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  200. rollupConst, err := c.RollupConstants()
  201. if err != nil {
  202. return nil, err
  203. }
  204. nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels
  205. lenBytes := nLevels / 8 //nolint:gomnd
  206. newLastIdx := big.NewInt(int64(args.NewLastIdx))
  207. var l1CoordinatorBytes []byte
  208. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  209. l1 := args.L1CoordinatorTxs[i]
  210. bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
  211. if err != nil {
  212. return nil, err
  213. }
  214. l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
  215. }
  216. var l2DataBytes []byte
  217. for i := 0; i < len(args.L2TxsData); i++ {
  218. l2 := args.L2TxsData[i]
  219. bytesl2, err := l2.Bytes(int(nLevels))
  220. if err != nil {
  221. return nil, err
  222. }
  223. l2DataBytes = append(l2DataBytes, bytesl2[:]...)
  224. }
  225. var feeIdxCoordinator []byte
  226. if len(args.FeeIdxCoordinator) > common.RollupConstMaxFeeIdxCoordinator {
  227. return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
  228. common.RollupConstMaxFeeIdxCoordinator)
  229. }
  230. for i := 0; i < common.RollupConstMaxFeeIdxCoordinator; i++ {
  231. feeIdx := common.Idx(0)
  232. if i < len(args.FeeIdxCoordinator) {
  233. feeIdx = args.FeeIdxCoordinator[i]
  234. }
  235. bytesFeeIdx, err := feeIdx.Bytes()
  236. if err != nil {
  237. return nil, err
  238. }
  239. feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
  240. }
  241. return c.hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC)
  242. },
  243. ); err != nil {
  244. return nil, fmt.Errorf("Failed forge batch: %w", err)
  245. }
  246. return tx, nil
  247. }
  248. // RollupAddToken is the interface to call the smart contract function.
  249. // `feeAddToken` is the amount of HEZ tokens that will be paid to add the
  250. // token. `feeAddToken` must match the public value of the smart contract.
  251. func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (tx *types.Transaction, err error) {
  252. if tx, err = c.client.CallAuth(
  253. 0,
  254. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  255. owner := c.client.account.Address
  256. spender := c.address
  257. nonce, err := c.tokenHEZ.Nonces(nil, owner)
  258. if err != nil {
  259. return nil, err
  260. }
  261. tokenName := c.tokenHEZCfg.Name
  262. tokenAddr := c.tokenHEZCfg.Address
  263. chainid, _ := c.client.Client().ChainID(context.Background())
  264. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, feeAddToken, nonce, deadline, tokenName)
  265. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  266. permit := createPermit(owner, spender, feeAddToken, deadline, digest, signature)
  267. return c.hermez.AddToken(auth, tokenAddress, permit)
  268. },
  269. ); err != nil {
  270. return nil, fmt.Errorf("Failed add Token %w", err)
  271. }
  272. return tx, nil
  273. }
  274. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  275. func (c *RollupClient) RollupWithdrawMerkleProof(fromBJJ *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (tx *types.Transaction, err error) {
  276. if tx, err = c.client.CallAuth(
  277. 0,
  278. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  279. pkCompL := fromBJJ.Compress()
  280. pkCompB := common.SwapEndianness(pkCompL[:])
  281. babyPubKey := new(big.Int).SetBytes(pkCompB)
  282. numExitRootB := big.NewInt(numExitRoot)
  283. idxBig := big.NewInt(idx)
  284. return c.hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey, numExitRootB, siblings, idxBig, instantWithdraw)
  285. },
  286. ); err != nil {
  287. return nil, fmt.Errorf("Failed update WithdrawMerkleProof: %w", err)
  288. }
  289. return tx, nil
  290. }
  291. // RollupWithdrawCircuit is the interface to call the smart contract function
  292. func (c *RollupClient) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error) {
  293. log.Error("TODO")
  294. return nil, errTODO
  295. }
  296. // RollupL1UserTxERC20ETH is the interface to call the smart contract function
  297. func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction, err error) {
  298. if tx, err = c.client.CallAuth(
  299. 0,
  300. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  301. pkCompL := fromBJJ.Compress()
  302. pkCompB := common.SwapEndianness(pkCompL[:])
  303. babyPubKey := new(big.Int).SetBytes(pkCompB)
  304. fromIdxBig := big.NewInt(fromIdx)
  305. toIdxBig := big.NewInt(toIdx)
  306. loadAmountF, err := common.NewFloat16(loadAmount)
  307. if err != nil {
  308. return nil, err
  309. }
  310. amountF, err := common.NewFloat16(amount)
  311. if err != nil {
  312. return nil, err
  313. }
  314. if tokenID == 0 {
  315. auth.Value = loadAmount
  316. }
  317. var permit []byte
  318. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),
  319. uint16(amountF), tokenID, toIdxBig, permit)
  320. },
  321. ); err != nil {
  322. return nil, fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err)
  323. }
  324. return tx, nil
  325. }
  326. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  327. func (c *RollupClient) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) {
  328. if tx, err = c.client.CallAuth(
  329. 0,
  330. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  331. pkCompL := fromBJJ.Compress()
  332. pkCompB := common.SwapEndianness(pkCompL[:])
  333. babyPubKey := new(big.Int).SetBytes(pkCompB)
  334. fromIdxBig := big.NewInt(fromIdx)
  335. toIdxBig := big.NewInt(toIdx)
  336. loadAmountF, err := common.NewFloat16(loadAmount)
  337. if err != nil {
  338. return nil, err
  339. }
  340. amountF, err := common.NewFloat16(amount)
  341. if err != nil {
  342. return nil, err
  343. }
  344. if tokenID == 0 {
  345. auth.Value = loadAmount
  346. }
  347. owner := c.client.account.Address
  348. spender := c.address
  349. nonce, err := c.tokenHEZ.Nonces(nil, owner)
  350. if err != nil {
  351. return nil, err
  352. }
  353. tokenName := c.tokenHEZCfg.Name
  354. tokenAddr := c.tokenHEZCfg.Address
  355. chainid, _ := c.client.Client().ChainID(context.Background())
  356. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, amount, nonce, deadline, tokenName)
  357. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  358. permit := createPermit(owner, spender, amount, deadline, digest, signature)
  359. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),
  360. uint16(amountF), tokenID, toIdxBig, permit)
  361. },
  362. ); err != nil {
  363. return nil, fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err)
  364. }
  365. return tx, nil
  366. }
  367. // RollupRegisterTokensCount is the interface to call the smart contract function
  368. func (c *RollupClient) RollupRegisterTokensCount() (registerTokensCount *big.Int, err error) {
  369. if err := c.client.Call(func(ec *ethclient.Client) error {
  370. registerTokensCount, err = c.hermez.RegisterTokensCount(nil)
  371. return err
  372. }); err != nil {
  373. return nil, err
  374. }
  375. return registerTokensCount, nil
  376. }
  377. // RollupLastForgedBatch is the interface to call the smart contract function
  378. func (c *RollupClient) RollupLastForgedBatch() (lastForgedBatch int64, err error) {
  379. if err := c.client.Call(func(ec *ethclient.Client) error {
  380. _lastForgedBatch, err := c.hermez.LastForgedBatch(nil)
  381. lastForgedBatch = int64(_lastForgedBatch)
  382. return err
  383. }); err != nil {
  384. return 0, err
  385. }
  386. return lastForgedBatch, nil
  387. }
  388. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  389. func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (tx *types.Transaction, err error) {
  390. if tx, err = c.client.CallAuth(
  391. 0,
  392. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  393. return c.hermez.UpdateForgeL1L2BatchTimeout(auth, uint8(newForgeL1L2BatchTimeout))
  394. },
  395. ); err != nil {
  396. return nil, fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err)
  397. }
  398. return tx, nil
  399. }
  400. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  401. func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
  402. if tx, err = c.client.CallAuth(
  403. 0,
  404. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  405. return c.hermez.UpdateFeeAddToken(auth, newFeeAddToken)
  406. },
  407. ); err != nil {
  408. return nil, fmt.Errorf("Failed update FeeAddToken: %w", err)
  409. }
  410. return tx, nil
  411. }
  412. // RollupConstants returns the Constants of the Rollup Smart Contract
  413. func (c *RollupClient) RollupConstants() (rollupConstants *common.RollupConstants, err error) {
  414. rollupConstants = new(common.RollupConstants)
  415. if err := c.client.Call(func(ec *ethclient.Client) error {
  416. absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
  417. if err != nil {
  418. return err
  419. }
  420. rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
  421. rollupConstants.TokenHEZ, err = c.hermez.TokenHEZ(nil)
  422. if err != nil {
  423. return err
  424. }
  425. for i := int64(0); i < int64(common.LenVerifiers); i++ {
  426. var newRollupVerifier common.RollupVerifierStruct
  427. rollupVerifier, err := c.hermez.RollupVerifiers(nil, big.NewInt(i))
  428. if err != nil {
  429. return err
  430. }
  431. newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
  432. newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
  433. rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)
  434. }
  435. rollupConstants.HermezAuctionContract, err = c.hermez.HermezAuctionContract(nil)
  436. if err != nil {
  437. return err
  438. }
  439. rollupConstants.HermezGovernanceDAOAddress, err = c.hermez.HermezGovernanceDAOAddress(nil)
  440. if err != nil {
  441. return err
  442. }
  443. rollupConstants.SafetyAddress, err = c.hermez.SafetyAddress(nil)
  444. if err != nil {
  445. return err
  446. }
  447. rollupConstants.WithdrawDelayerContract, err = c.hermez.WithdrawDelayerContract(nil)
  448. return err
  449. }); err != nil {
  450. return nil, err
  451. }
  452. return rollupConstants, nil
  453. }
  454. var (
  455. logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)"))
  456. logHermezAddToken = crypto.Keccak256Hash([]byte("AddToken(address,uint32)"))
  457. logHermezForgeBatch = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)"))
  458. logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)"))
  459. logHermezUpdateFeeAddToken = crypto.Keccak256Hash([]byte("UpdateFeeAddToken(uint256)"))
  460. logHermezWithdrawEvent = crypto.Keccak256Hash([]byte("WithdrawEvent(uint48,uint48,bool)"))
  461. )
  462. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  463. func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
  464. var rollupEvents RollupEvents
  465. var blockHash *ethCommon.Hash
  466. query := ethereum.FilterQuery{
  467. FromBlock: big.NewInt(blockNum),
  468. ToBlock: big.NewInt(blockNum),
  469. Addresses: []ethCommon.Address{
  470. c.address,
  471. },
  472. BlockHash: nil,
  473. Topics: [][]ethCommon.Hash{},
  474. }
  475. logs, err := c.client.client.FilterLogs(context.Background(), query)
  476. if err != nil {
  477. return nil, nil, err
  478. }
  479. if len(logs) > 0 {
  480. blockHash = &logs[0].BlockHash
  481. }
  482. for _, vLog := range logs {
  483. if vLog.BlockHash != *blockHash {
  484. log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String())
  485. return nil, nil, ErrBlockHashMismatchEvent
  486. }
  487. switch vLog.Topics[0] {
  488. case logHermezL1UserTxEvent:
  489. var L1UserTxAux RollupEventL1UserTxAux
  490. var L1UserTx RollupEventL1UserTx
  491. err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
  492. if err != nil {
  493. return nil, nil, err
  494. }
  495. L1Tx, err := common.L1UserTxFromBytes(L1UserTxAux.L1UserTx)
  496. if err != nil {
  497. return nil, nil, err
  498. }
  499. toForgeL1TxsNum := new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  500. L1Tx.ToForgeL1TxsNum = &toForgeL1TxsNum
  501. L1Tx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
  502. L1Tx.UserOrigin = true
  503. L1UserTx.L1UserTx = *L1Tx
  504. rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
  505. case logHermezAddToken:
  506. var addToken RollupEventAddToken
  507. err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data)
  508. if err != nil {
  509. return nil, nil, err
  510. }
  511. addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
  512. rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
  513. case logHermezForgeBatch:
  514. var forgeBatch RollupEventForgeBatch
  515. forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  516. forgeBatch.EthTxHash = vLog.TxHash
  517. // forgeBatch.Sender = vLog.Address
  518. rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
  519. case logHermezUpdateForgeL1L2BatchTimeout:
  520. var updateForgeL1L2BatchTimeout struct {
  521. NewForgeL1L2BatchTimeout uint8
  522. }
  523. err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data)
  524. if err != nil {
  525. return nil, nil, err
  526. }
  527. rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout,
  528. RollupEventUpdateForgeL1L2BatchTimeout{
  529. NewForgeL1L2BatchTimeout: int64(updateForgeL1L2BatchTimeout.NewForgeL1L2BatchTimeout),
  530. })
  531. case logHermezUpdateFeeAddToken:
  532. var updateFeeAddToken RollupEventUpdateFeeAddToken
  533. err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
  534. if err != nil {
  535. return nil, nil, err
  536. }
  537. rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
  538. case logHermezWithdrawEvent:
  539. var withdraw RollupEventWithdraw
  540. withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
  541. withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
  542. instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
  543. if instantWithdraw == 1 {
  544. withdraw.InstantWithdraw = true
  545. }
  546. withdraw.TxHash = vLog.TxHash
  547. rollupEvents.Withdraw = append(rollupEvents.Withdraw, withdraw)
  548. }
  549. }
  550. return &rollupEvents, blockHash, nil
  551. }
  552. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the
  553. // Rollup Smart Contract in the given transaction, and the sender address.
  554. func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error) {
  555. tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
  556. if err != nil {
  557. return nil, nil, err
  558. }
  559. txData := tx.Data()
  560. method, err := c.contractAbi.MethodById(txData[:4])
  561. if err != nil {
  562. return nil, nil, err
  563. }
  564. receipt, err := c.client.client.TransactionReceipt(context.Background(), ethTxHash)
  565. if err != nil {
  566. return nil, nil, err
  567. }
  568. sender, err := c.client.client.TransactionSender(context.Background(), tx, receipt.Logs[0].BlockHash, receipt.Logs[0].Index)
  569. if err != nil {
  570. return nil, nil, err
  571. }
  572. var aux RollupForgeBatchArgsAux
  573. if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil {
  574. return nil, nil, err
  575. }
  576. rollupForgeBatchArgs := RollupForgeBatchArgs{
  577. L1Batch: aux.L1Batch,
  578. NewExitRoot: aux.NewExitRoot,
  579. NewLastIdx: aux.NewLastIdx.Int64(),
  580. NewStRoot: aux.NewStRoot,
  581. ProofA: aux.ProofA,
  582. ProofB: aux.ProofB,
  583. ProofC: aux.ProofC,
  584. VerifierIdx: aux.VerifierIdx,
  585. L1CoordinatorTxs: []common.L1Tx{},
  586. L1CoordinatorTxsAuths: [][]byte{},
  587. L2TxsData: []common.L2Tx{},
  588. FeeIdxCoordinator: []common.Idx{},
  589. }
  590. numTxsL1 := len(aux.EncodedL1CoordinatorTx) / common.L1CoordinatorTxBytesLen
  591. for i := 0; i < numTxsL1; i++ {
  592. bytesL1Coordinator := aux.EncodedL1CoordinatorTx[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]
  593. var signature []byte
  594. v := bytesL1Coordinator[0]
  595. s := bytesL1Coordinator[1:33]
  596. r := bytesL1Coordinator[33:65]
  597. signature = append(signature, r[:]...)
  598. signature = append(signature, s[:]...)
  599. signature = append(signature, v)
  600. l1Tx, err := common.L1CoordinatorTxFromBytes(bytesL1Coordinator)
  601. if err != nil {
  602. return nil, nil, err
  603. }
  604. rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx)
  605. rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
  606. }
  607. rollupConsts, err := c.RollupConstants()
  608. if err != nil {
  609. return nil, nil, err
  610. }
  611. nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
  612. lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)
  613. numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes
  614. for i := 0; i < numTxsL2; i++ {
  615. l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels))
  616. if err != nil {
  617. return nil, nil, err
  618. }
  619. rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx)
  620. }
  621. lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
  622. numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
  623. for i := 0; i < numFeeIdxCoordinator; i++ {
  624. var paddedFeeIdx [6]byte
  625. // TODO: This check is not necessary: the first case will always work. Test it before removing the if.
  626. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
  627. copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  628. } else {
  629. copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  630. }
  631. feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
  632. if err != nil {
  633. return nil, nil, err
  634. }
  635. if feeIdxCoordinator != common.Idx(0) {
  636. rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
  637. }
  638. }
  639. return &rollupForgeBatchArgs, &sender, nil
  640. }