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.

735 lines
29 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. ERC777 "github.com/hermeznetwork/hermez-node/eth/contracts/erc777"
  16. Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez"
  17. "github.com/hermeznetwork/hermez-node/log"
  18. "github.com/iden3/go-iden3-crypto/babyjub"
  19. "golang.org/x/crypto/sha3"
  20. )
  21. const (
  22. // RollupConstFeeIdxCoordinatorLen is the number of tokens the coordinator can use
  23. // to collect fees (determines the number of tokens that the
  24. // coordinator can collect fees from). This value is determined by the
  25. // circuit.
  26. RollupConstFeeIdxCoordinatorLen = 64
  27. // RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
  28. RollupConstReservedIDx = 255
  29. // RollupConstExitIDx IDX 1 is reserved for exits
  30. RollupConstExitIDx = 1
  31. // RollupConstLimitLoadAmount Max load amount allowed (loadAmount: L1 --> L2)
  32. RollupConstLimitLoadAmount = (1 << 128)
  33. // RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
  34. RollupConstLimitL2TransferAmount = (1 << 192)
  35. // RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
  36. RollupConstLimitTokens = (1 << 32)
  37. // RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes] compressedSignature
  38. RollupConstL1CoordinatorTotalBytes = 101
  39. // RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6 bytes] fromIdx +
  40. // [2 bytes] loadAmountFloat16 + [2 bytes] amountFloat16 + [4 bytes] tokenId + [6 bytes] toIdx
  41. RollupConstL1UserTotalBytes = 72
  42. // RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
  43. RollupConstMaxL1UserTx = 128
  44. // RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch
  45. RollupConstMaxL1Tx = 256
  46. // RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx + [32 bytes] stateRoot + [32 bytes] newStRoot + [32 bytes] newExitRoot +
  47. // [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength + [2 bytes] chainID =
  48. // 18542 bytes + totalL2TxsDataLength + feeIdxCoordinatorLength
  49. RollupConstInputSHAConstantBytes = 18542
  50. // RollupConstNumBuckets Number of buckets
  51. RollupConstNumBuckets = 5
  52. // RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
  53. RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
  54. // RollupConstExchangeMultiplier exchange multiplier
  55. RollupConstExchangeMultiplier = 1e14
  56. // LenVerifiers number of Rollup Smart Contract Verifiers
  57. LenVerifiers = 1
  58. )
  59. var (
  60. // RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup accounts that don't have ethereum address, only Babyjubjub
  61. // This non-ethereum accounts can be created by the coordinator and allow users to have a rollup
  62. // account without needing an ethereum address
  63. RollupConstEthAddressInternalOnly = ethCommon.HexToAddress("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF")
  64. // RollupConstRfield Modulus zkSNARK
  65. RollupConstRfield, _ = new(big.Int).SetString(
  66. "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
  67. // RollupConstERC1820 ERC1820Registry address
  68. RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24")
  69. // ERC777 tokens signatures
  70. // RollupConstRecipientInterfaceHash ERC777 recipient interface hash
  71. RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient"))
  72. // RollupConstPerformL1UserTxSignature the signature of the function that can be called thru an ERC777 `send`
  73. RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)"))
  74. // RollupConstAddTokenSignature the signature of the function that can be called thru an ERC777 `send`
  75. RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
  76. // RollupConstSendSignature ERC777 Signature
  77. RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
  78. // RollupConstERC777Granularity ERC777 Signature
  79. RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
  80. // RollupConstWithdrawalDelayerDeposit This constant are used to deposit tokens from ERC77 tokens into withdrawal delayer
  81. RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))
  82. // ERC20 signature
  83. // RollupConstTransferSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  84. RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
  85. // RollupConstTransferFromSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  86. RollupConstTransferFromSignature = crypto.Keccak256([]byte("transferFrom(address,address,uint256)"))
  87. // RollupConstApproveSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  88. RollupConstApproveSignature = crypto.Keccak256([]byte("approve(address,uint256)"))
  89. // RollupConstERC20Signature ERC20 decimals signature
  90. RollupConstERC20Signature = crypto.Keccak256([]byte("decimals()"))
  91. )
  92. // RollupConstants are the constants of the Rollup Smart Contract
  93. /* type RollupConstants struct {
  94. // Maxim Deposit allowed
  95. MaxAmountDeposit *big.Int
  96. MaxAmountL2 *big.Int
  97. MaxTokens int64
  98. // maximum L1 transactions allowed to be queued for a batch
  99. MaxL1Tx int
  100. // maximum L1 user transactions allowed to be queued for a batch
  101. MaxL1UserTx int
  102. Rfield *big.Int
  103. L1CoordinatorBytes int
  104. L1UserBytes int
  105. L2Bytes int
  106. MaxTxVerifiers []int
  107. TokenHEZ ethCommon.Address
  108. // Only test
  109. GovernanceAddress ethCommon.Address
  110. // Only test
  111. SafetyBot ethCommon.Address
  112. // Only test
  113. ConsensusContract ethCommon.Address
  114. // Only test
  115. WithdrawalContract ethCommon.Address
  116. ReservedIDx uint32
  117. LastIDx uint32
  118. ExitIDx uint32
  119. NoLimitToken int
  120. NumBuckets int
  121. MaxWDelay int64
  122. }*/
  123. // RollupPublicConstants are the constants of the Rollup Smart Contract
  124. type RollupPublicConstants struct {
  125. AbsoluteMaxL1L2BatchTimeout int64
  126. TokenHEZ ethCommon.Address
  127. Verifiers []RollupVerifierStruct
  128. HermezAuctionContract ethCommon.Address
  129. HermezGovernanceDAOAddress ethCommon.Address
  130. SafetyAddress ethCommon.Address
  131. WithdrawDelayerContract ethCommon.Address
  132. }
  133. // RollupVariables are the variables of the Rollup Smart Contract
  134. type RollupVariables struct {
  135. FeeAddToken *big.Int
  136. ForgeL1L2BatchTimeout int64
  137. WithdrawalDelay uint64
  138. }
  139. // QueueStruct is the queue of L1Txs for a batch
  140. type QueueStruct struct {
  141. L1TxQueue []common.L1Tx
  142. TotalL1TxFee *big.Int
  143. }
  144. // NewQueueStruct creates a new clear QueueStruct.
  145. func NewQueueStruct() *QueueStruct {
  146. return &QueueStruct{
  147. L1TxQueue: make([]common.L1Tx, 0),
  148. TotalL1TxFee: big.NewInt(0),
  149. }
  150. }
  151. // RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
  152. type RollupVerifierStruct struct {
  153. MaxTx int64
  154. NLevels int64
  155. }
  156. // RollupState represents the state of the Rollup in the Smart Contract
  157. type RollupState struct {
  158. StateRoot *big.Int
  159. ExitRoots []*big.Int
  160. ExitNullifierMap map[[256 / 8]byte]bool
  161. TokenList []ethCommon.Address
  162. TokenMap map[ethCommon.Address]bool
  163. MapL1TxQueue map[int64]*QueueStruct
  164. LastL1L2Batch int64
  165. CurrentToForgeL1TxsNum int64
  166. LastToForgeL1TxsNum int64
  167. CurrentIdx int64
  168. }
  169. // RollupEventL1UserTx is an event of the Rollup Smart Contract
  170. type RollupEventL1UserTx struct {
  171. ToForgeL1TxsNum int64 // QueueIndex *big.Int
  172. Position int // TransactionIndex *big.Int
  173. L1Tx common.L1Tx
  174. }
  175. // RollupEventL1UserTxAux is an event of the Rollup Smart Contract
  176. type RollupEventL1UserTxAux struct {
  177. ToForgeL1TxsNum uint64 // QueueIndex *big.Int
  178. Position uint8 // TransactionIndex *big.Int
  179. L1Tx []byte
  180. }
  181. // RollupEventAddToken is an event of the Rollup Smart Contract
  182. type RollupEventAddToken struct {
  183. Address ethCommon.Address
  184. TokenID uint32
  185. }
  186. // RollupEventForgeBatch is an event of the Rollup Smart Contract
  187. type RollupEventForgeBatch struct {
  188. BatchNum int64
  189. EthTxHash ethCommon.Hash
  190. }
  191. // RollupEventUpdateForgeL1L2BatchTimeout is an event of the Rollup Smart Contract
  192. type RollupEventUpdateForgeL1L2BatchTimeout struct {
  193. ForgeL1L2BatchTimeout uint8
  194. }
  195. // RollupEventUpdateFeeAddToken is an event of the Rollup Smart Contract
  196. type RollupEventUpdateFeeAddToken struct {
  197. FeeAddToken *big.Int
  198. }
  199. // RollupEventWithdrawEvent is an event of the Rollup Smart Contract
  200. type RollupEventWithdrawEvent struct {
  201. Idx uint64
  202. NumExitRoot uint64
  203. InstantWithdraw bool
  204. }
  205. // RollupEvents is the list of events in a block of the Rollup Smart Contract
  206. type RollupEvents struct {
  207. L1UserTx []RollupEventL1UserTx
  208. AddToken []RollupEventAddToken
  209. ForgeBatch []RollupEventForgeBatch
  210. UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
  211. UpdateFeeAddToken []RollupEventUpdateFeeAddToken
  212. WithdrawEvent []RollupEventWithdrawEvent
  213. }
  214. // NewRollupEvents creates an empty RollupEvents with the slices initialized.
  215. func NewRollupEvents() RollupEvents {
  216. return RollupEvents{
  217. L1UserTx: make([]RollupEventL1UserTx, 0),
  218. AddToken: make([]RollupEventAddToken, 0),
  219. ForgeBatch: make([]RollupEventForgeBatch, 0),
  220. UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
  221. UpdateFeeAddToken: make([]RollupEventUpdateFeeAddToken, 0),
  222. WithdrawEvent: make([]RollupEventWithdrawEvent, 0),
  223. }
  224. }
  225. // RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract
  226. type RollupForgeBatchArgs struct {
  227. NewLastIdx int64
  228. NewStRoot *big.Int
  229. NewExitRoot *big.Int
  230. L1CoordinatorTxs []*common.L1Tx
  231. L1CoordinatorTxsAuths [][]byte // Authorization for accountCreations for each L1CoordinatorTx
  232. L2TxsData []*common.L2Tx
  233. FeeIdxCoordinator []common.Idx
  234. // Circuit selector
  235. VerifierIdx uint8
  236. L1Batch bool
  237. ProofA [2]*big.Int
  238. ProofB [2][2]*big.Int
  239. ProofC [2]*big.Int
  240. }
  241. // RollupForgeBatchArgsAux are the arguments to the ForgeBatch function in the Rollup Smart Contract
  242. type RollupForgeBatchArgsAux struct {
  243. NewLastIdx *big.Int
  244. NewStRoot *big.Int
  245. NewExitRoot *big.Int
  246. EncodedL1CoordinatorTx []byte
  247. L2TxsData []byte
  248. FeeIdxCoordinator []byte
  249. // Circuit selector
  250. VerifierIdx uint8
  251. L1Batch bool
  252. ProofA [2]*big.Int
  253. ProofB [2][2]*big.Int
  254. ProofC [2]*big.Int
  255. }
  256. // RollupInterface is the inteface to to Rollup Smart Contract
  257. type RollupInterface interface {
  258. //
  259. // Smart Contract Methods
  260. //
  261. // Public Functions
  262. RollupForgeBatch(*RollupForgeBatchArgs) (*types.Transaction, error)
  263. RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int) (*types.Transaction, error)
  264. RollupWithdraw(tokenID int64, balance *big.Int, babyPubKey *babyjub.PublicKey,
  265. numExitRoot int64, siblings []*big.Int, idx int64, instantWithdraw bool) (*types.Transaction, error)
  266. RollupForceExit(fromIdx int64, amountF common.Float16, tokenID int64) (*types.Transaction, error)
  267. RollupForceTransfer(fromIdx int64, amountF common.Float16, tokenID, toIdx int64) (*types.Transaction, error)
  268. RollupCreateAccountDepositTransfer(babyPubKey babyjub.PublicKey,
  269. loadAmountF, amountF common.Float16, tokenID int64, toIdx int64) (*types.Transaction, error)
  270. RollupDepositTransfer(fromIdx int64, loadAmountF, amountF common.Float16,
  271. tokenID int64, toIdx int64) (*types.Transaction, error)
  272. RollupDeposit(fromIdx int64, loadAmountF common.Float16, tokenID int64) (*types.Transaction, error)
  273. RollupCreateAccountDepositFromRelayer(accountCreationAuthSig []byte,
  274. babyPubKey babyjub.PublicKey, loadAmountF common.Float16) (*types.Transaction, error)
  275. RollupCreateAccountDeposit(babyPubKey babyjub.PublicKey, loadAmountF common.Float16,
  276. tokenID int64) (*types.Transaction, error)
  277. RollupGetCurrentTokens() (*big.Int, error)
  278. // RollupGetTokenAddress(tokenID int64) (*ethCommon.Address, error)
  279. // RollupGetL1TxFromQueue(queue int64, position int64) ([]byte, error)
  280. // RollupGetQueue(queue int64) ([]byte, error)
  281. // Governance Public Functions
  282. RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (*types.Transaction, error)
  283. RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error)
  284. //
  285. // Smart Contract Status
  286. //
  287. RollupConstants() (*RollupPublicConstants, error)
  288. RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
  289. RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, error)
  290. }
  291. //
  292. // Implementation
  293. //
  294. // RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
  295. type RollupClient struct {
  296. client *EthereumClient
  297. address ethCommon.Address
  298. tokenHEZAddress ethCommon.Address
  299. gasLimit uint64
  300. contractAbi abi.ABI
  301. }
  302. // NewRollupClient creates a new RollupClient
  303. func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZAddress ethCommon.Address) (*RollupClient, error) {
  304. contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
  305. if err != nil {
  306. return nil, err
  307. }
  308. return &RollupClient{
  309. client: client,
  310. address: address,
  311. tokenHEZAddress: tokenHEZAddress,
  312. gasLimit: 1000000, //nolint:gomnd
  313. contractAbi: contractAbi,
  314. }, nil
  315. }
  316. // RollupForgeBatch is the interface to call the smart contract function
  317. func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (*types.Transaction, error) {
  318. var tx *types.Transaction
  319. var err error
  320. if tx, err = c.client.CallAuth(
  321. c.gasLimit,
  322. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  323. hermez, err := Hermez.NewHermez(c.address, ec)
  324. if err != nil {
  325. return nil, err
  326. }
  327. rollupConst, err := c.RollupConstants()
  328. if err != nil {
  329. return nil, err
  330. }
  331. nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels
  332. lenBytes := nLevels / 8 //nolint:gomnd
  333. newLastIdx := big.NewInt(int64(args.NewLastIdx))
  334. var l1CoordinatorBytes []byte
  335. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  336. l1 := args.L1CoordinatorTxs[i]
  337. bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
  338. if err != nil {
  339. return nil, err
  340. }
  341. l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
  342. }
  343. var l2DataBytes []byte
  344. for i := 0; i < len(args.L2TxsData); i++ {
  345. l2 := args.L2TxsData[i]
  346. bytesl2, err := l2.Bytes(int(nLevels))
  347. if err != nil {
  348. return nil, err
  349. }
  350. l2DataBytes = append(l2DataBytes, bytesl2[:]...)
  351. }
  352. var feeIdxCoordinator []byte
  353. for i := 0; i < len(args.FeeIdxCoordinator); i++ {
  354. feeIdx := args.FeeIdxCoordinator[i]
  355. bytesFeeIdx, err := feeIdx.Bytes()
  356. if err != nil {
  357. return nil, err
  358. }
  359. feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
  360. }
  361. return hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC)
  362. },
  363. ); err != nil {
  364. return nil, fmt.Errorf("Failed forge batch: %w", err)
  365. }
  366. return tx, nil
  367. }
  368. // RollupAddToken is the interface to call the smart contract function.
  369. // `feeAddToken` is the amount of HEZ tokens that will be paid to add the
  370. // token. `feeAddToken` must match the public value of the smart contract.
  371. func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int) (*types.Transaction, error) {
  372. var tx *types.Transaction
  373. var err error
  374. if tx, err = c.client.CallAuth(
  375. c.gasLimit,
  376. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  377. tokens, err := ERC777.NewERC777(c.tokenHEZAddress, ec)
  378. if err != nil {
  379. return nil, err
  380. }
  381. addTokenFnSignature := []byte("addToken(address)")
  382. hash := sha3.NewLegacyKeccak256()
  383. _, err = hash.Write(addTokenFnSignature)
  384. if err != nil {
  385. return nil, err
  386. }
  387. methodID := hash.Sum(nil)[:4]
  388. var data []byte
  389. data = append(data, methodID...)
  390. paddedAddress := ethCommon.LeftPadBytes(tokenAddress.Bytes(), 32)
  391. data = append(data, paddedAddress[:]...)
  392. return tokens.Send(auth, c.address, feeAddToken, data)
  393. },
  394. ); err != nil {
  395. return nil, fmt.Errorf("Failed add Token %w", err)
  396. }
  397. return tx, nil
  398. }
  399. // RollupWithdrawSNARK is the interface to call the smart contract function
  400. // func (c *RollupClient) RollupWithdrawSNARK() (*types.Transaction, error) { // TODO (Not defined in Hermez.sol)
  401. // return nil, errTODO
  402. // }
  403. // RollupWithdraw is the interface to call the smart contract function
  404. func (c *RollupClient) RollupWithdraw(tokenID int64, balance *big.Int, babyPubKey *babyjub.PublicKey, numExitRoot int64, siblings []*big.Int, idx int64, instantWithdraw bool) (*types.Transaction, error) {
  405. log.Error("TODO")
  406. return nil, errTODO
  407. }
  408. // RollupForceExit is the interface to call the smart contract function
  409. func (c *RollupClient) RollupForceExit(fromIdx int64, amountF common.Float16, tokenID int64) (*types.Transaction, error) {
  410. log.Error("TODO")
  411. return nil, errTODO
  412. }
  413. // RollupForceTransfer is the interface to call the smart contract function
  414. func (c *RollupClient) RollupForceTransfer(fromIdx int64, amountF common.Float16, tokenID, toIdx int64) (*types.Transaction, error) {
  415. log.Error("TODO")
  416. return nil, errTODO
  417. }
  418. // RollupCreateAccountDepositTransfer is the interface to call the smart contract function
  419. func (c *RollupClient) RollupCreateAccountDepositTransfer(babyPubKey babyjub.PublicKey, loadAmountF, amountF common.Float16, tokenID int64, toIdx int64) (*types.Transaction, error) {
  420. log.Error("TODO")
  421. return nil, errTODO
  422. }
  423. // RollupDepositTransfer is the interface to call the smart contract function
  424. func (c *RollupClient) RollupDepositTransfer(fromIdx int64, loadAmountF, amountF common.Float16, tokenID int64, toIdx int64) (*types.Transaction, error) {
  425. log.Error("TODO")
  426. return nil, errTODO
  427. }
  428. // RollupDeposit is the interface to call the smart contract function
  429. func (c *RollupClient) RollupDeposit(fromIdx int64, loadAmountF common.Float16, tokenID int64) (*types.Transaction, error) {
  430. log.Error("TODO")
  431. return nil, errTODO
  432. }
  433. // RollupCreateAccountDepositFromRelayer is the interface to call the smart contract function
  434. func (c *RollupClient) RollupCreateAccountDepositFromRelayer(accountCreationAuthSig []byte, babyPubKey babyjub.PublicKey, loadAmountF common.Float16) (*types.Transaction, error) {
  435. log.Error("TODO")
  436. return nil, errTODO
  437. }
  438. // RollupCreateAccountDeposit is the interface to call the smart contract function
  439. func (c *RollupClient) RollupCreateAccountDeposit(babyPubKey babyjub.PublicKey, loadAmountF common.Float16, tokenID int64) (*types.Transaction, error) {
  440. log.Error("TODO")
  441. return nil, errTODO
  442. }
  443. // RollupGetTokenAddress is the interface to call the smart contract function
  444. /* func (c *RollupClient) RollupGetTokenAddress(tokenID int64) (*ethCommon.Address, error) {
  445. return nil, errTODO
  446. } */
  447. // RollupGetCurrentTokens is the interface to call the smart contract function
  448. func (c *RollupClient) RollupGetCurrentTokens() (*big.Int, error) {
  449. log.Error("TODO")
  450. return nil, errTODO
  451. }
  452. // RollupGetL1TxFromQueue is the interface to call the smart contract function
  453. /* func (c *RollupClient) RollupGetL1TxFromQueue(queue int64, position int64) ([]byte, error) {
  454. return nil, errTODO
  455. } */
  456. // RollupGetQueue is the interface to call the smart contract function
  457. /* func (c *RollupClient) RollupGetQueue(queue int64) ([]byte, error) {
  458. return nil, errTODO
  459. }*/
  460. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  461. func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1Timeout int64) (*types.Transaction, error) {
  462. log.Error("TODO")
  463. return nil, errTODO
  464. }
  465. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  466. func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error) {
  467. log.Error("TODO")
  468. return nil, errTODO
  469. }
  470. // RollupConstants returns the Constants of the Rollup Smart Contract
  471. func (c *RollupClient) RollupConstants() (*RollupPublicConstants, error) {
  472. rollupConstants := new(RollupPublicConstants)
  473. if err := c.client.Call(func(ec *ethclient.Client) error {
  474. hermez, err := Hermez.NewHermez(c.address, ec)
  475. if err != nil {
  476. return err
  477. }
  478. absoluteMaxL1L2BatchTimeout, err := hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
  479. if err != nil {
  480. return err
  481. }
  482. rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
  483. rollupConstants.TokenHEZ, err = hermez.TokenHEZ(nil)
  484. if err != nil {
  485. return err
  486. }
  487. for i := int64(0); i < int64(LenVerifiers); i++ {
  488. var newRollupVerifier RollupVerifierStruct
  489. rollupVerifier, err := hermez.RollupVerifiers(nil, big.NewInt(i))
  490. if err != nil {
  491. return err
  492. }
  493. newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
  494. newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
  495. rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)
  496. }
  497. rollupConstants.HermezAuctionContract, err = hermez.HermezAuctionContract(nil)
  498. if err != nil {
  499. return err
  500. }
  501. rollupConstants.HermezGovernanceDAOAddress, err = hermez.HermezGovernanceDAOAddress(nil)
  502. if err != nil {
  503. return err
  504. }
  505. rollupConstants.SafetyAddress, err = hermez.SafetyAddress(nil)
  506. if err != nil {
  507. return err
  508. }
  509. rollupConstants.WithdrawDelayerContract, err = hermez.WithdrawDelayerContract(nil)
  510. return err
  511. }); err != nil {
  512. return nil, err
  513. }
  514. return rollupConstants, nil
  515. }
  516. var (
  517. logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)"))
  518. logHermezAddToken = crypto.Keccak256Hash([]byte("AddToken(address,uint32)"))
  519. logHermezForgeBatch = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)"))
  520. logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)"))
  521. logHermezUpdateFeeAddToken = crypto.Keccak256Hash([]byte("UpdateFeeAddToken(uint256)"))
  522. logHermezWithdrawEvent = crypto.Keccak256Hash([]byte("WithdrawEvent(uint48,uint48,bool)"))
  523. )
  524. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  525. func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
  526. var rollupEvents RollupEvents
  527. var blockHash ethCommon.Hash
  528. query := ethereum.FilterQuery{
  529. FromBlock: big.NewInt(blockNum),
  530. ToBlock: big.NewInt(blockNum),
  531. Addresses: []ethCommon.Address{
  532. c.address,
  533. },
  534. BlockHash: nil,
  535. Topics: [][]ethCommon.Hash{},
  536. }
  537. logs, err := c.client.client.FilterLogs(context.Background(), query)
  538. if err != nil {
  539. return nil, nil, err
  540. }
  541. if len(logs) > 0 {
  542. blockHash = logs[0].BlockHash
  543. }
  544. for _, vLog := range logs {
  545. if vLog.BlockHash != blockHash {
  546. return nil, nil, ErrBlockHashMismatchEvent
  547. }
  548. switch vLog.Topics[0] {
  549. case logHermezL1UserTxEvent:
  550. var L1UserTxAux RollupEventL1UserTxAux
  551. var L1UserTx RollupEventL1UserTx
  552. err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
  553. if err != nil {
  554. return nil, nil, err
  555. }
  556. L1Tx, err := common.L1TxFromBytes(L1UserTxAux.L1Tx)
  557. if err != nil {
  558. return nil, nil, err
  559. }
  560. L1UserTx.ToForgeL1TxsNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  561. L1UserTx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
  562. L1UserTx.L1Tx = *L1Tx
  563. rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
  564. case logHermezAddToken:
  565. var addToken RollupEventAddToken
  566. err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data)
  567. if err != nil {
  568. return nil, nil, err
  569. }
  570. addToken.Address = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
  571. rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
  572. case logHermezForgeBatch:
  573. var forgeBatch RollupEventForgeBatch
  574. forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  575. forgeBatch.EthTxHash = vLog.TxHash
  576. rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
  577. case logHermezUpdateForgeL1L2BatchTimeout:
  578. var updateForgeL1L2BatchTimeout RollupEventUpdateForgeL1L2BatchTimeout
  579. err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data)
  580. if err != nil {
  581. return nil, nil, err
  582. }
  583. rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout, updateForgeL1L2BatchTimeout)
  584. case logHermezUpdateFeeAddToken:
  585. var updateFeeAddToken RollupEventUpdateFeeAddToken
  586. err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
  587. if err != nil {
  588. return nil, nil, err
  589. }
  590. rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
  591. case logHermezWithdrawEvent:
  592. var withdraw RollupEventWithdrawEvent
  593. err := c.contractAbi.Unpack(&withdraw, "WithdrawEvent", vLog.Data)
  594. if err != nil {
  595. return nil, nil, err
  596. }
  597. withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
  598. withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
  599. rollupEvents.WithdrawEvent = append(rollupEvents.WithdrawEvent, withdraw)
  600. }
  601. }
  602. return &rollupEvents, &blockHash, nil
  603. }
  604. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the Rollup Smart Contract in the given transaction
  605. func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, error) {
  606. tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
  607. if err != nil {
  608. return nil, err
  609. }
  610. txData := tx.Data()
  611. method, err := c.contractAbi.MethodById(txData[:4])
  612. if err != nil {
  613. return nil, err
  614. }
  615. var aux RollupForgeBatchArgsAux
  616. if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil {
  617. return nil, err
  618. }
  619. var rollupForgeBatchArgs RollupForgeBatchArgs
  620. rollupForgeBatchArgs.L1Batch = aux.L1Batch
  621. rollupForgeBatchArgs.NewExitRoot = aux.NewExitRoot
  622. rollupForgeBatchArgs.NewLastIdx = aux.NewLastIdx.Int64()
  623. rollupForgeBatchArgs.NewStRoot = aux.NewStRoot
  624. rollupForgeBatchArgs.ProofA = aux.ProofA
  625. rollupForgeBatchArgs.ProofB = aux.ProofB
  626. rollupForgeBatchArgs.ProofC = aux.ProofC
  627. rollupForgeBatchArgs.VerifierIdx = aux.VerifierIdx
  628. numTxsL1 := len(aux.EncodedL1CoordinatorTx) / common.L1CoordinatorTxBytesLen
  629. for i := 0; i < numTxsL1; i++ {
  630. bytesL1Coordinator := aux.EncodedL1CoordinatorTx[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]
  631. var signature []byte
  632. v := bytesL1Coordinator[0]
  633. s := bytesL1Coordinator[1:33]
  634. r := bytesL1Coordinator[33:65]
  635. signature = append(signature, r[:]...)
  636. signature = append(signature, s[:]...)
  637. signature = append(signature, v)
  638. l1Tx, err := common.L1TxFromCoordinatorBytes(bytesL1Coordinator)
  639. if err != nil {
  640. return nil, err
  641. }
  642. rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, l1Tx)
  643. rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
  644. }
  645. rollupConsts, err := c.RollupConstants()
  646. if err != nil {
  647. return nil, err
  648. }
  649. nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
  650. lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)
  651. numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes
  652. for i := 0; i < numTxsL2; i++ {
  653. l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels))
  654. if err != nil {
  655. return nil, err
  656. }
  657. rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, l2Tx)
  658. }
  659. lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
  660. numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
  661. for i := 0; i < numFeeIdxCoordinator; i++ {
  662. var paddedFeeIdx [6]byte
  663. // TODO: This check is not necessary: the first case will always work. Test it before removing the if.
  664. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
  665. copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  666. } else {
  667. copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  668. }
  669. FeeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
  670. if err != nil {
  671. return nil, err
  672. }
  673. rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, FeeIdxCoordinator)
  674. }
  675. return &rollupForgeBatchArgs, nil
  676. }