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.

676 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. //
  153. // Smart Contract Status
  154. //
  155. RollupConstants() (*common.RollupConstants, error)
  156. RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
  157. RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error)
  158. }
  159. //
  160. // Implementation
  161. //
  162. // RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
  163. type RollupClient struct {
  164. client *EthereumClient
  165. address ethCommon.Address
  166. tokenHEZCfg TokenConfig
  167. hermez *Hermez.Hermez
  168. tokenHEZ *HEZ.HEZ
  169. contractAbi abi.ABI
  170. }
  171. // NewRollupClient creates a new RollupClient
  172. func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZCfg TokenConfig) (*RollupClient, error) {
  173. contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
  174. if err != nil {
  175. return nil, err
  176. }
  177. hermez, err := Hermez.NewHermez(address, client.Client())
  178. if err != nil {
  179. return nil, err
  180. }
  181. tokenHEZ, err := HEZ.NewHEZ(tokenHEZCfg.Address, client.Client())
  182. if err != nil {
  183. return nil, err
  184. }
  185. return &RollupClient{
  186. client: client,
  187. address: address,
  188. tokenHEZCfg: tokenHEZCfg,
  189. hermez: hermez,
  190. tokenHEZ: tokenHEZ,
  191. contractAbi: contractAbi,
  192. }, nil
  193. }
  194. // RollupForgeBatch is the interface to call the smart contract function
  195. func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  196. if tx, err = c.client.CallAuth(
  197. 1000000, //nolint:gomnd
  198. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  199. rollupConst, err := c.RollupConstants()
  200. if err != nil {
  201. return nil, err
  202. }
  203. nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels
  204. lenBytes := nLevels / 8 //nolint:gomnd
  205. newLastIdx := big.NewInt(int64(args.NewLastIdx))
  206. var l1CoordinatorBytes []byte
  207. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  208. l1 := args.L1CoordinatorTxs[i]
  209. bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
  210. if err != nil {
  211. return nil, err
  212. }
  213. l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
  214. }
  215. var l2DataBytes []byte
  216. for i := 0; i < len(args.L2TxsData); i++ {
  217. l2 := args.L2TxsData[i]
  218. bytesl2, err := l2.Bytes(int(nLevels))
  219. if err != nil {
  220. return nil, err
  221. }
  222. l2DataBytes = append(l2DataBytes, bytesl2[:]...)
  223. }
  224. var feeIdxCoordinator []byte
  225. if len(args.FeeIdxCoordinator) > common.RollupConstMaxFeeIdxCoordinator {
  226. return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
  227. common.RollupConstMaxFeeIdxCoordinator)
  228. }
  229. for i := 0; i < common.RollupConstMaxFeeIdxCoordinator; i++ {
  230. feeIdx := common.Idx(0)
  231. if i < len(args.FeeIdxCoordinator) {
  232. feeIdx = args.FeeIdxCoordinator[i]
  233. }
  234. bytesFeeIdx, err := feeIdx.Bytes()
  235. if err != nil {
  236. return nil, err
  237. }
  238. feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
  239. }
  240. return c.hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC)
  241. },
  242. ); err != nil {
  243. return nil, fmt.Errorf("Failed forge batch: %w", err)
  244. }
  245. return tx, nil
  246. }
  247. // RollupAddToken is the interface to call the smart contract function.
  248. // `feeAddToken` is the amount of HEZ tokens that will be paid to add the
  249. // token. `feeAddToken` must match the public value of the smart contract.
  250. func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (tx *types.Transaction, err error) {
  251. if tx, err = c.client.CallAuth(
  252. 0,
  253. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  254. owner := c.client.account.Address
  255. spender := c.address
  256. nonce, err := c.tokenHEZ.Nonces(nil, owner)
  257. if err != nil {
  258. return nil, err
  259. }
  260. tokenName := c.tokenHEZCfg.Name
  261. tokenAddr := c.tokenHEZCfg.Address
  262. chainid, _ := c.client.Client().ChainID(context.Background())
  263. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, feeAddToken, nonce, deadline, tokenName)
  264. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  265. permit := createPermit(owner, spender, feeAddToken, deadline, digest, signature)
  266. return c.hermez.AddToken(auth, tokenAddress, permit)
  267. },
  268. ); err != nil {
  269. return nil, fmt.Errorf("Failed add Token %w", err)
  270. }
  271. return tx, nil
  272. }
  273. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  274. 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) {
  275. if tx, err = c.client.CallAuth(
  276. 0,
  277. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  278. pkCompL := fromBJJ.Compress()
  279. pkCompB := common.SwapEndianness(pkCompL[:])
  280. babyPubKey := new(big.Int).SetBytes(pkCompB)
  281. numExitRootB := big.NewInt(numExitRoot)
  282. idxBig := big.NewInt(idx)
  283. return c.hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey, numExitRootB, siblings, idxBig, instantWithdraw)
  284. },
  285. ); err != nil {
  286. return nil, fmt.Errorf("Failed update WithdrawMerkleProof: %w", err)
  287. }
  288. return tx, nil
  289. }
  290. // RollupWithdrawCircuit is the interface to call the smart contract function
  291. 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) {
  292. log.Error("TODO")
  293. return nil, errTODO
  294. }
  295. // RollupL1UserTxERC20ETH is the interface to call the smart contract function
  296. func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction, err error) {
  297. if tx, err = c.client.CallAuth(
  298. 0,
  299. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  300. pkCompL := fromBJJ.Compress()
  301. pkCompB := common.SwapEndianness(pkCompL[:])
  302. babyPubKey := new(big.Int).SetBytes(pkCompB)
  303. fromIdxBig := big.NewInt(fromIdx)
  304. toIdxBig := big.NewInt(toIdx)
  305. loadAmountF, err := common.NewFloat16(loadAmount)
  306. if err != nil {
  307. return nil, err
  308. }
  309. amountF, err := common.NewFloat16(amount)
  310. if err != nil {
  311. return nil, err
  312. }
  313. if tokenID == 0 {
  314. auth.Value = loadAmount
  315. }
  316. var permit []byte
  317. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),
  318. uint16(amountF), tokenID, toIdxBig, permit)
  319. },
  320. ); err != nil {
  321. return nil, fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err)
  322. }
  323. return tx, nil
  324. }
  325. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  326. 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) {
  327. if tx, err = c.client.CallAuth(
  328. 0,
  329. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  330. pkCompL := fromBJJ.Compress()
  331. pkCompB := common.SwapEndianness(pkCompL[:])
  332. babyPubKey := new(big.Int).SetBytes(pkCompB)
  333. fromIdxBig := big.NewInt(fromIdx)
  334. toIdxBig := big.NewInt(toIdx)
  335. loadAmountF, err := common.NewFloat16(loadAmount)
  336. if err != nil {
  337. return nil, err
  338. }
  339. amountF, err := common.NewFloat16(amount)
  340. if err != nil {
  341. return nil, err
  342. }
  343. if tokenID == 0 {
  344. auth.Value = loadAmount
  345. }
  346. owner := c.client.account.Address
  347. spender := c.address
  348. nonce, err := c.tokenHEZ.Nonces(nil, owner)
  349. if err != nil {
  350. return nil, err
  351. }
  352. tokenName := c.tokenHEZCfg.Name
  353. tokenAddr := c.tokenHEZCfg.Address
  354. chainid, _ := c.client.Client().ChainID(context.Background())
  355. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, amount, nonce, deadline, tokenName)
  356. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  357. permit := createPermit(owner, spender, amount, deadline, digest, signature)
  358. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),
  359. uint16(amountF), tokenID, toIdxBig, permit)
  360. },
  361. ); err != nil {
  362. return nil, fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err)
  363. }
  364. return tx, nil
  365. }
  366. // RollupRegisterTokensCount is the interface to call the smart contract function
  367. func (c *RollupClient) RollupRegisterTokensCount() (*big.Int, error) {
  368. var registerTokensCount *big.Int
  369. if err := c.client.Call(func(ec *ethclient.Client) error {
  370. hermez, err := Hermez.NewHermez(c.address, ec)
  371. if err != nil {
  372. return err
  373. }
  374. registerTokensCount, err = hermez.RegisterTokensCount(nil)
  375. return err
  376. }); err != nil {
  377. return nil, err
  378. }
  379. return registerTokensCount, nil
  380. }
  381. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  382. func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (tx *types.Transaction, err error) {
  383. if tx, err = c.client.CallAuth(
  384. 0,
  385. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  386. return c.hermez.UpdateForgeL1L2BatchTimeout(auth, uint8(newForgeL1L2BatchTimeout))
  387. },
  388. ); err != nil {
  389. return nil, fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err)
  390. }
  391. return tx, nil
  392. }
  393. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  394. func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
  395. if tx, err = c.client.CallAuth(
  396. 0,
  397. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  398. return c.hermez.UpdateFeeAddToken(auth, newFeeAddToken)
  399. },
  400. ); err != nil {
  401. return nil, fmt.Errorf("Failed update FeeAddToken: %w", err)
  402. }
  403. return tx, nil
  404. }
  405. // RollupConstants returns the Constants of the Rollup Smart Contract
  406. func (c *RollupClient) RollupConstants() (rollupConstants *common.RollupConstants, err error) {
  407. rollupConstants = new(common.RollupConstants)
  408. if err := c.client.Call(func(ec *ethclient.Client) error {
  409. absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
  410. if err != nil {
  411. return err
  412. }
  413. rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
  414. rollupConstants.TokenHEZ, err = c.hermez.TokenHEZ(nil)
  415. if err != nil {
  416. return err
  417. }
  418. for i := int64(0); i < int64(common.LenVerifiers); i++ {
  419. var newRollupVerifier common.RollupVerifierStruct
  420. rollupVerifier, err := c.hermez.RollupVerifiers(nil, big.NewInt(i))
  421. if err != nil {
  422. return err
  423. }
  424. newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
  425. newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
  426. rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)
  427. }
  428. rollupConstants.HermezAuctionContract, err = c.hermez.HermezAuctionContract(nil)
  429. if err != nil {
  430. return err
  431. }
  432. rollupConstants.HermezGovernanceDAOAddress, err = c.hermez.HermezGovernanceDAOAddress(nil)
  433. if err != nil {
  434. return err
  435. }
  436. rollupConstants.SafetyAddress, err = c.hermez.SafetyAddress(nil)
  437. if err != nil {
  438. return err
  439. }
  440. rollupConstants.WithdrawDelayerContract, err = c.hermez.WithdrawDelayerContract(nil)
  441. return err
  442. }); err != nil {
  443. return nil, err
  444. }
  445. return rollupConstants, nil
  446. }
  447. var (
  448. logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)"))
  449. logHermezAddToken = crypto.Keccak256Hash([]byte("AddToken(address,uint32)"))
  450. logHermezForgeBatch = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)"))
  451. logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)"))
  452. logHermezUpdateFeeAddToken = crypto.Keccak256Hash([]byte("UpdateFeeAddToken(uint256)"))
  453. logHermezWithdrawEvent = crypto.Keccak256Hash([]byte("WithdrawEvent(uint48,uint48,bool)"))
  454. )
  455. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  456. func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
  457. var rollupEvents RollupEvents
  458. var blockHash *ethCommon.Hash
  459. query := ethereum.FilterQuery{
  460. FromBlock: big.NewInt(blockNum),
  461. ToBlock: big.NewInt(blockNum),
  462. Addresses: []ethCommon.Address{
  463. c.address,
  464. },
  465. BlockHash: nil,
  466. Topics: [][]ethCommon.Hash{},
  467. }
  468. logs, err := c.client.client.FilterLogs(context.Background(), query)
  469. if err != nil {
  470. return nil, nil, err
  471. }
  472. if len(logs) > 0 {
  473. blockHash = &logs[0].BlockHash
  474. }
  475. for _, vLog := range logs {
  476. if vLog.BlockHash != *blockHash {
  477. log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String())
  478. return nil, nil, ErrBlockHashMismatchEvent
  479. }
  480. switch vLog.Topics[0] {
  481. case logHermezL1UserTxEvent:
  482. var L1UserTxAux RollupEventL1UserTxAux
  483. var L1UserTx RollupEventL1UserTx
  484. err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
  485. if err != nil {
  486. return nil, nil, err
  487. }
  488. L1Tx, err := common.L1UserTxFromBytes(L1UserTxAux.L1UserTx)
  489. if err != nil {
  490. return nil, nil, err
  491. }
  492. toForgeL1TxsNum := new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  493. L1Tx.ToForgeL1TxsNum = &toForgeL1TxsNum
  494. L1Tx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
  495. L1Tx.UserOrigin = true
  496. L1UserTx.L1UserTx = *L1Tx
  497. rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
  498. case logHermezAddToken:
  499. var addToken RollupEventAddToken
  500. err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data)
  501. if err != nil {
  502. return nil, nil, err
  503. }
  504. addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
  505. rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
  506. case logHermezForgeBatch:
  507. var forgeBatch RollupEventForgeBatch
  508. forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  509. forgeBatch.EthTxHash = vLog.TxHash
  510. // forgeBatch.Sender = vLog.Address
  511. rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
  512. case logHermezUpdateForgeL1L2BatchTimeout:
  513. var updateForgeL1L2BatchTimeout struct {
  514. NewForgeL1L2BatchTimeout uint8
  515. }
  516. err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data)
  517. if err != nil {
  518. return nil, nil, err
  519. }
  520. rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout,
  521. RollupEventUpdateForgeL1L2BatchTimeout{
  522. NewForgeL1L2BatchTimeout: int64(updateForgeL1L2BatchTimeout.NewForgeL1L2BatchTimeout),
  523. })
  524. case logHermezUpdateFeeAddToken:
  525. var updateFeeAddToken RollupEventUpdateFeeAddToken
  526. err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
  527. if err != nil {
  528. return nil, nil, err
  529. }
  530. rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
  531. case logHermezWithdrawEvent:
  532. var withdraw RollupEventWithdraw
  533. withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
  534. withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
  535. instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
  536. if instantWithdraw == 1 {
  537. withdraw.InstantWithdraw = true
  538. }
  539. withdraw.TxHash = vLog.TxHash
  540. rollupEvents.Withdraw = append(rollupEvents.Withdraw, withdraw)
  541. }
  542. }
  543. return &rollupEvents, blockHash, nil
  544. }
  545. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the
  546. // Rollup Smart Contract in the given transaction, and the sender address.
  547. func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error) {
  548. tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
  549. if err != nil {
  550. return nil, nil, err
  551. }
  552. txData := tx.Data()
  553. method, err := c.contractAbi.MethodById(txData[:4])
  554. if err != nil {
  555. return nil, nil, err
  556. }
  557. receipt, err := c.client.client.TransactionReceipt(context.Background(), ethTxHash)
  558. if err != nil {
  559. return nil, nil, err
  560. }
  561. sender, err := c.client.client.TransactionSender(context.Background(), tx, receipt.Logs[0].BlockHash, receipt.Logs[0].Index)
  562. if err != nil {
  563. return nil, nil, err
  564. }
  565. var aux RollupForgeBatchArgsAux
  566. if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil {
  567. return nil, nil, err
  568. }
  569. rollupForgeBatchArgs := RollupForgeBatchArgs{
  570. L1Batch: aux.L1Batch,
  571. NewExitRoot: aux.NewExitRoot,
  572. NewLastIdx: aux.NewLastIdx.Int64(),
  573. NewStRoot: aux.NewStRoot,
  574. ProofA: aux.ProofA,
  575. ProofB: aux.ProofB,
  576. ProofC: aux.ProofC,
  577. VerifierIdx: aux.VerifierIdx,
  578. L1CoordinatorTxs: []common.L1Tx{},
  579. L1CoordinatorTxsAuths: [][]byte{},
  580. L2TxsData: []common.L2Tx{},
  581. FeeIdxCoordinator: []common.Idx{},
  582. }
  583. numTxsL1 := len(aux.EncodedL1CoordinatorTx) / common.L1CoordinatorTxBytesLen
  584. for i := 0; i < numTxsL1; i++ {
  585. bytesL1Coordinator := aux.EncodedL1CoordinatorTx[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]
  586. var signature []byte
  587. v := bytesL1Coordinator[0]
  588. s := bytesL1Coordinator[1:33]
  589. r := bytesL1Coordinator[33:65]
  590. signature = append(signature, r[:]...)
  591. signature = append(signature, s[:]...)
  592. signature = append(signature, v)
  593. l1Tx, err := common.L1CoordinatorTxFromBytes(bytesL1Coordinator)
  594. if err != nil {
  595. return nil, nil, err
  596. }
  597. rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx)
  598. rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
  599. }
  600. rollupConsts, err := c.RollupConstants()
  601. if err != nil {
  602. return nil, nil, err
  603. }
  604. nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
  605. lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)
  606. numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes
  607. for i := 0; i < numTxsL2; i++ {
  608. l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels))
  609. if err != nil {
  610. return nil, nil, err
  611. }
  612. rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx)
  613. }
  614. lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
  615. numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
  616. for i := 0; i < numFeeIdxCoordinator; i++ {
  617. var paddedFeeIdx [6]byte
  618. // TODO: This check is not necessary: the first case will always work. Test it before removing the if.
  619. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
  620. copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  621. } else {
  622. copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  623. }
  624. feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
  625. if err != nil {
  626. return nil, nil, err
  627. }
  628. if feeIdxCoordinator != common.Idx(0) {
  629. rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
  630. }
  631. }
  632. return &rollupForgeBatchArgs, &sender, nil
  633. }