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.

806 lines
30 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. // RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
  23. // coordinator can use to collect fees (determines the number of tokens
  24. // that the coordinator can collect fees from). This value is
  25. // determined by the circuit.
  26. RollupConstMaxFeeIdxCoordinator = 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. // RollupPublicConstants are the constants of the Rollup Smart Contract
  93. type RollupPublicConstants struct {
  94. AbsoluteMaxL1L2BatchTimeout int64
  95. TokenHEZ ethCommon.Address
  96. Verifiers []RollupVerifierStruct
  97. HermezAuctionContract ethCommon.Address
  98. HermezGovernanceDAOAddress ethCommon.Address
  99. SafetyAddress ethCommon.Address
  100. WithdrawDelayerContract ethCommon.Address
  101. }
  102. // RollupVariables are the variables of the Rollup Smart Contract
  103. type RollupVariables struct {
  104. FeeAddToken *big.Int
  105. ForgeL1L2BatchTimeout int64
  106. WithdrawalDelay uint64
  107. }
  108. // QueueStruct is the queue of L1Txs for a batch
  109. type QueueStruct struct {
  110. L1TxQueue []common.L1Tx
  111. TotalL1TxFee *big.Int
  112. }
  113. // NewQueueStruct creates a new clear QueueStruct.
  114. func NewQueueStruct() *QueueStruct {
  115. return &QueueStruct{
  116. L1TxQueue: make([]common.L1Tx, 0),
  117. TotalL1TxFee: big.NewInt(0),
  118. }
  119. }
  120. // RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
  121. type RollupVerifierStruct struct {
  122. MaxTx int64
  123. NLevels int64
  124. }
  125. // RollupState represents the state of the Rollup in the Smart Contract
  126. type RollupState struct {
  127. StateRoot *big.Int
  128. ExitRoots []*big.Int
  129. ExitNullifierMap map[[256 / 8]byte]bool
  130. TokenList []ethCommon.Address
  131. TokenMap map[ethCommon.Address]bool
  132. MapL1TxQueue map[int64]*QueueStruct
  133. LastL1L2Batch int64
  134. CurrentToForgeL1TxsNum int64
  135. LastToForgeL1TxsNum int64
  136. CurrentIdx int64
  137. }
  138. // RollupEventL1UserTx is an event of the Rollup Smart Contract
  139. type RollupEventL1UserTx struct {
  140. ToForgeL1TxsNum int64 // QueueIndex *big.Int
  141. Position int // TransactionIndex *big.Int
  142. L1UserTx common.L1Tx
  143. }
  144. // RollupEventL1UserTxAux is an event of the Rollup Smart Contract
  145. type RollupEventL1UserTxAux struct {
  146. ToForgeL1TxsNum uint64 // QueueIndex *big.Int
  147. Position uint8 // TransactionIndex *big.Int
  148. L1UserTx []byte
  149. }
  150. // RollupEventAddToken is an event of the Rollup Smart Contract
  151. type RollupEventAddToken struct {
  152. TokenAddress ethCommon.Address
  153. TokenID uint32
  154. }
  155. // RollupEventForgeBatch is an event of the Rollup Smart Contract
  156. type RollupEventForgeBatch struct {
  157. BatchNum int64
  158. EthTxHash ethCommon.Hash
  159. }
  160. // RollupEventUpdateForgeL1L2BatchTimeout is an event of the Rollup Smart Contract
  161. type RollupEventUpdateForgeL1L2BatchTimeout struct {
  162. NewForgeL1L2BatchTimeout int64
  163. }
  164. // RollupEventUpdateFeeAddToken is an event of the Rollup Smart Contract
  165. type RollupEventUpdateFeeAddToken struct {
  166. NewFeeAddToken *big.Int
  167. }
  168. // RollupEventWithdrawEvent is an event of the Rollup Smart Contract
  169. type RollupEventWithdrawEvent struct {
  170. Idx uint64
  171. NumExitRoot uint64
  172. InstantWithdraw bool
  173. }
  174. // RollupEvents is the list of events in a block of the Rollup Smart Contract
  175. type RollupEvents struct {
  176. L1UserTx []RollupEventL1UserTx
  177. AddToken []RollupEventAddToken
  178. ForgeBatch []RollupEventForgeBatch
  179. UpdateForgeL1L2BatchTimeout []RollupEventUpdateForgeL1L2BatchTimeout
  180. UpdateFeeAddToken []RollupEventUpdateFeeAddToken
  181. WithdrawEvent []RollupEventWithdrawEvent
  182. }
  183. // NewRollupEvents creates an empty RollupEvents with the slices initialized.
  184. func NewRollupEvents() RollupEvents {
  185. return RollupEvents{
  186. L1UserTx: make([]RollupEventL1UserTx, 0),
  187. AddToken: make([]RollupEventAddToken, 0),
  188. ForgeBatch: make([]RollupEventForgeBatch, 0),
  189. UpdateForgeL1L2BatchTimeout: make([]RollupEventUpdateForgeL1L2BatchTimeout, 0),
  190. UpdateFeeAddToken: make([]RollupEventUpdateFeeAddToken, 0),
  191. WithdrawEvent: make([]RollupEventWithdrawEvent, 0),
  192. }
  193. }
  194. // RollupForgeBatchArgs are the arguments to the ForgeBatch function in the Rollup Smart Contract
  195. type RollupForgeBatchArgs struct {
  196. NewLastIdx int64
  197. NewStRoot *big.Int
  198. NewExitRoot *big.Int
  199. L1CoordinatorTxs []common.L1Tx
  200. L1CoordinatorTxsAuths [][]byte // Authorization for accountCreations for each L1CoordinatorTx
  201. L2TxsData []common.L2Tx
  202. FeeIdxCoordinator []common.Idx
  203. // Circuit selector
  204. VerifierIdx uint8
  205. L1Batch bool
  206. ProofA [2]*big.Int
  207. ProofB [2][2]*big.Int
  208. ProofC [2]*big.Int
  209. }
  210. // RollupForgeBatchArgsAux are the arguments to the ForgeBatch function in the Rollup Smart Contract
  211. type RollupForgeBatchArgsAux struct {
  212. NewLastIdx *big.Int
  213. NewStRoot *big.Int
  214. NewExitRoot *big.Int
  215. EncodedL1CoordinatorTx []byte
  216. L2TxsData []byte
  217. FeeIdxCoordinator []byte
  218. // Circuit selector
  219. VerifierIdx uint8
  220. L1Batch bool
  221. ProofA [2]*big.Int
  222. ProofB [2][2]*big.Int
  223. ProofC [2]*big.Int
  224. }
  225. // RollupInterface is the inteface to to Rollup Smart Contract
  226. type RollupInterface interface {
  227. //
  228. // Smart Contract Methods
  229. //
  230. // Public Functions
  231. RollupForgeBatch(*RollupForgeBatchArgs) (*types.Transaction, error)
  232. RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int) (*types.Transaction, error)
  233. RollupWithdrawMerkleProof(babyPubKey *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction, error)
  234. RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error)
  235. RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
  236. RollupL1UserTxERC777(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error)
  237. // Governance Public Functions
  238. RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (*types.Transaction, error)
  239. RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error)
  240. // Viewers
  241. RollupRegisterTokensCount() (*big.Int, error)
  242. //
  243. // Smart Contract Status
  244. //
  245. RollupConstants() (*RollupPublicConstants, error)
  246. RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error)
  247. RollupForgeBatchArgs(ethCommon.Hash) (*RollupForgeBatchArgs, error)
  248. }
  249. //
  250. // Implementation
  251. //
  252. // RollupClient is the implementation of the interface to the Rollup Smart Contract in ethereum.
  253. type RollupClient struct {
  254. client *EthereumClient
  255. address ethCommon.Address
  256. tokenHEZAddress ethCommon.Address
  257. gasLimit uint64
  258. contractAbi abi.ABI
  259. }
  260. // NewRollupClient creates a new RollupClient
  261. func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZAddress ethCommon.Address) (*RollupClient, error) {
  262. contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
  263. if err != nil {
  264. return nil, err
  265. }
  266. return &RollupClient{
  267. client: client,
  268. address: address,
  269. tokenHEZAddress: tokenHEZAddress,
  270. gasLimit: 1000000, //nolint:gomnd
  271. contractAbi: contractAbi,
  272. }, nil
  273. }
  274. // RollupForgeBatch is the interface to call the smart contract function
  275. func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (*types.Transaction, error) {
  276. var tx *types.Transaction
  277. var err error
  278. if tx, err = c.client.CallAuth(
  279. c.gasLimit,
  280. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  281. hermez, err := Hermez.NewHermez(c.address, ec)
  282. if err != nil {
  283. return nil, err
  284. }
  285. rollupConst, err := c.RollupConstants()
  286. if err != nil {
  287. return nil, err
  288. }
  289. nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels
  290. lenBytes := nLevels / 8 //nolint:gomnd
  291. newLastIdx := big.NewInt(int64(args.NewLastIdx))
  292. var l1CoordinatorBytes []byte
  293. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  294. l1 := args.L1CoordinatorTxs[i]
  295. bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
  296. if err != nil {
  297. return nil, err
  298. }
  299. l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
  300. }
  301. var l2DataBytes []byte
  302. for i := 0; i < len(args.L2TxsData); i++ {
  303. l2 := args.L2TxsData[i]
  304. bytesl2, err := l2.Bytes(int(nLevels))
  305. if err != nil {
  306. return nil, err
  307. }
  308. l2DataBytes = append(l2DataBytes, bytesl2[:]...)
  309. }
  310. var feeIdxCoordinator []byte
  311. if len(args.FeeIdxCoordinator) > RollupConstMaxFeeIdxCoordinator {
  312. return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
  313. RollupConstMaxFeeIdxCoordinator)
  314. }
  315. for i := 0; i < RollupConstMaxFeeIdxCoordinator; i++ {
  316. feeIdx := common.Idx(0)
  317. if i < len(args.FeeIdxCoordinator) {
  318. feeIdx = args.FeeIdxCoordinator[i]
  319. }
  320. bytesFeeIdx, err := feeIdx.Bytes()
  321. if err != nil {
  322. return nil, err
  323. }
  324. feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
  325. }
  326. return hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC)
  327. },
  328. ); err != nil {
  329. return nil, fmt.Errorf("Failed forge batch: %w", err)
  330. }
  331. return tx, nil
  332. }
  333. // RollupAddToken is the interface to call the smart contract function.
  334. // `feeAddToken` is the amount of HEZ tokens that will be paid to add the
  335. // token. `feeAddToken` must match the public value of the smart contract.
  336. func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken *big.Int) (*types.Transaction, error) {
  337. var tx *types.Transaction
  338. var err error
  339. if tx, err = c.client.CallAuth(
  340. c.gasLimit,
  341. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  342. tokens, err := ERC777.NewERC777(c.tokenHEZAddress, ec)
  343. if err != nil {
  344. return nil, err
  345. }
  346. addTokenFnSignature := []byte("addToken(address)")
  347. hash := sha3.NewLegacyKeccak256()
  348. _, err = hash.Write(addTokenFnSignature)
  349. if err != nil {
  350. return nil, err
  351. }
  352. methodID := hash.Sum(nil)[:4]
  353. var data []byte
  354. data = append(data, methodID...)
  355. paddedAddress := ethCommon.LeftPadBytes(tokenAddress.Bytes(), 32)
  356. data = append(data, paddedAddress[:]...)
  357. return tokens.Send(auth, c.address, feeAddToken, data)
  358. },
  359. ); err != nil {
  360. return nil, fmt.Errorf("Failed add Token %w", err)
  361. }
  362. return tx, nil
  363. }
  364. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  365. func (c *RollupClient) RollupWithdrawMerkleProof(fromBJJ *babyjub.PublicKey, tokenID uint32, numExitRoot, idx int64, amount *big.Int, siblings []*big.Int, instantWithdraw bool) (*types.Transaction, error) {
  366. var tx *types.Transaction
  367. var err error
  368. if tx, err = c.client.CallAuth(
  369. c.gasLimit,
  370. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  371. hermez, err := Hermez.NewHermez(c.address, ec)
  372. if err != nil {
  373. return nil, err
  374. }
  375. pkCompL := fromBJJ.Compress()
  376. pkCompB := common.SwapEndianness(pkCompL[:])
  377. babyPubKey := new(big.Int).SetBytes(pkCompB)
  378. numExitRootB := big.NewInt(numExitRoot)
  379. idxBig := big.NewInt(idx)
  380. return hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey, numExitRootB, siblings, idxBig, instantWithdraw)
  381. },
  382. ); err != nil {
  383. return nil, fmt.Errorf("Failed update WithdrawMerkleProof: %w", err)
  384. }
  385. return tx, nil
  386. }
  387. // RollupWithdrawCircuit is the interface to call the smart contract function
  388. 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) {
  389. log.Error("TODO")
  390. return nil, errTODO
  391. }
  392. // RollupL1UserTxERC20ETH is the interface to call the smart contract function
  393. func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error) {
  394. var tx *types.Transaction
  395. var err error
  396. if tx, err = c.client.CallAuth(
  397. c.gasLimit,
  398. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  399. hermez, err := Hermez.NewHermez(c.address, ec)
  400. if err != nil {
  401. return nil, err
  402. }
  403. pkCompL := fromBJJ.Compress()
  404. pkCompB := common.SwapEndianness(pkCompL[:])
  405. babyPubKey := new(big.Int).SetBytes(pkCompB)
  406. fromIdxBig := big.NewInt(fromIdx)
  407. toIdxBig := big.NewInt(toIdx)
  408. tokenIDBig := uint32(tokenID)
  409. loadAmountF, err := common.NewFloat16(loadAmount)
  410. if err != nil {
  411. return nil, err
  412. }
  413. amountF, err := common.NewFloat16(amount)
  414. if err != nil {
  415. return nil, err
  416. }
  417. if tokenID == 0 {
  418. auth.Value = loadAmount
  419. }
  420. return hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF), uint16(amountF), tokenIDBig, toIdxBig)
  421. },
  422. ); err != nil {
  423. return nil, fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err)
  424. }
  425. return tx, nil
  426. }
  427. // RollupL1UserTxERC777 is the interface to call the smart contract function
  428. func (c *RollupClient) RollupL1UserTxERC777(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (*types.Transaction, error) {
  429. var tx *types.Transaction
  430. var err error
  431. if tx, err = c.client.CallAuth(
  432. c.gasLimit,
  433. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  434. tokens, err := ERC777.NewERC777(c.tokenHEZAddress, ec)
  435. if err != nil {
  436. return nil, err
  437. }
  438. addL1TxFnSignature := []byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)")
  439. hash := sha3.NewLegacyKeccak256()
  440. _, err = hash.Write(addL1TxFnSignature)
  441. if err != nil {
  442. return nil, err
  443. }
  444. methodID := hash.Sum(nil)[:4]
  445. pkCompL := fromBJJ.Compress()
  446. pkCompB := common.SwapEndianness(pkCompL[:])
  447. paddedAddress := ethCommon.LeftPadBytes(pkCompB, 32)
  448. fromIdxB, err := common.Idx(fromIdx).Bytes()
  449. if err != nil {
  450. return nil, err
  451. }
  452. paddedFromIdx := ethCommon.LeftPadBytes(fromIdxB[:], 32)
  453. loadAmountF, err := common.NewFloat16(loadAmount)
  454. if err != nil {
  455. return nil, err
  456. }
  457. paddedLoadAmount := ethCommon.LeftPadBytes(loadAmountF.Bytes(), 32)
  458. amountF, err := common.NewFloat16(amount)
  459. if err != nil {
  460. return nil, err
  461. }
  462. paddedAmount := ethCommon.LeftPadBytes(amountF.Bytes(), 32)
  463. tokenIDB := common.TokenID(tokenID).Bytes()
  464. paddedTokenID := ethCommon.LeftPadBytes(tokenIDB, 32)
  465. toIdxB, err := common.Idx(toIdx).Bytes()
  466. if err != nil {
  467. return nil, err
  468. }
  469. paddedToIdx := ethCommon.LeftPadBytes(toIdxB[:], 32)
  470. var data []byte
  471. data = append(data, methodID...)
  472. data = append(data, paddedAddress[:]...)
  473. data = append(data, paddedFromIdx[:]...)
  474. data = append(data, paddedLoadAmount[:]...)
  475. data = append(data, paddedAmount[:]...)
  476. data = append(data, paddedTokenID[:]...)
  477. data = append(data, paddedToIdx[:]...)
  478. return tokens.Send(auth, c.address, loadAmount, data)
  479. },
  480. ); err != nil {
  481. return nil, fmt.Errorf("Failed add L1 Tx ERC777: %w", err)
  482. }
  483. return tx, nil
  484. }
  485. // RollupRegisterTokensCount is the interface to call the smart contract function
  486. func (c *RollupClient) RollupRegisterTokensCount() (*big.Int, error) {
  487. var registerTokensCount *big.Int
  488. if err := c.client.Call(func(ec *ethclient.Client) error {
  489. hermez, err := Hermez.NewHermez(c.address, ec)
  490. if err != nil {
  491. return err
  492. }
  493. registerTokensCount, err = hermez.RegisterTokensCount(nil)
  494. return err
  495. }); err != nil {
  496. return nil, err
  497. }
  498. return registerTokensCount, nil
  499. }
  500. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  501. func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (*types.Transaction, error) {
  502. var tx *types.Transaction
  503. var err error
  504. if tx, err = c.client.CallAuth(
  505. c.gasLimit,
  506. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  507. hermez, err := Hermez.NewHermez(c.address, ec)
  508. if err != nil {
  509. return nil, err
  510. }
  511. return hermez.UpdateForgeL1L2BatchTimeout(auth, uint8(newForgeL1L2BatchTimeout))
  512. },
  513. ); err != nil {
  514. return nil, fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err)
  515. }
  516. return tx, nil
  517. }
  518. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  519. func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (*types.Transaction, error) {
  520. var tx *types.Transaction
  521. var err error
  522. if tx, err = c.client.CallAuth(
  523. c.gasLimit,
  524. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  525. hermez, err := Hermez.NewHermez(c.address, ec)
  526. if err != nil {
  527. return nil, err
  528. }
  529. return hermez.UpdateFeeAddToken(auth, newFeeAddToken)
  530. },
  531. ); err != nil {
  532. return nil, fmt.Errorf("Failed update FeeAddToken: %w", err)
  533. }
  534. return tx, nil
  535. }
  536. // RollupConstants returns the Constants of the Rollup Smart Contract
  537. func (c *RollupClient) RollupConstants() (*RollupPublicConstants, error) {
  538. rollupConstants := new(RollupPublicConstants)
  539. if err := c.client.Call(func(ec *ethclient.Client) error {
  540. hermez, err := Hermez.NewHermez(c.address, ec)
  541. if err != nil {
  542. return err
  543. }
  544. absoluteMaxL1L2BatchTimeout, err := hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
  545. if err != nil {
  546. return err
  547. }
  548. rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
  549. rollupConstants.TokenHEZ, err = hermez.TokenHEZ(nil)
  550. if err != nil {
  551. return err
  552. }
  553. for i := int64(0); i < int64(LenVerifiers); i++ {
  554. var newRollupVerifier RollupVerifierStruct
  555. rollupVerifier, err := hermez.RollupVerifiers(nil, big.NewInt(i))
  556. if err != nil {
  557. return err
  558. }
  559. newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
  560. newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
  561. rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)
  562. }
  563. rollupConstants.HermezAuctionContract, err = hermez.HermezAuctionContract(nil)
  564. if err != nil {
  565. return err
  566. }
  567. rollupConstants.HermezGovernanceDAOAddress, err = hermez.HermezGovernanceDAOAddress(nil)
  568. if err != nil {
  569. return err
  570. }
  571. rollupConstants.SafetyAddress, err = hermez.SafetyAddress(nil)
  572. if err != nil {
  573. return err
  574. }
  575. rollupConstants.WithdrawDelayerContract, err = hermez.WithdrawDelayerContract(nil)
  576. return err
  577. }); err != nil {
  578. return nil, err
  579. }
  580. return rollupConstants, nil
  581. }
  582. var (
  583. logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)"))
  584. logHermezAddToken = crypto.Keccak256Hash([]byte("AddToken(address,uint32)"))
  585. logHermezForgeBatch = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)"))
  586. logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)"))
  587. logHermezUpdateFeeAddToken = crypto.Keccak256Hash([]byte("UpdateFeeAddToken(uint256)"))
  588. logHermezWithdrawEvent = crypto.Keccak256Hash([]byte("WithdrawEvent(uint48,uint48,bool)"))
  589. )
  590. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  591. func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
  592. var rollupEvents RollupEvents
  593. var blockHash ethCommon.Hash
  594. query := ethereum.FilterQuery{
  595. FromBlock: big.NewInt(blockNum),
  596. ToBlock: big.NewInt(blockNum),
  597. Addresses: []ethCommon.Address{
  598. c.address,
  599. },
  600. BlockHash: nil,
  601. Topics: [][]ethCommon.Hash{},
  602. }
  603. logs, err := c.client.client.FilterLogs(context.Background(), query)
  604. if err != nil {
  605. return nil, nil, err
  606. }
  607. if len(logs) > 0 {
  608. blockHash = logs[0].BlockHash
  609. }
  610. for _, vLog := range logs {
  611. if vLog.BlockHash != blockHash {
  612. return nil, nil, ErrBlockHashMismatchEvent
  613. }
  614. switch vLog.Topics[0] {
  615. case logHermezL1UserTxEvent:
  616. var L1UserTxAux RollupEventL1UserTxAux
  617. var L1UserTx RollupEventL1UserTx
  618. err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
  619. if err != nil {
  620. return nil, nil, err
  621. }
  622. L1Tx, err := common.L1TxFromBytes(L1UserTxAux.L1UserTx)
  623. if err != nil {
  624. return nil, nil, err
  625. }
  626. L1UserTx.ToForgeL1TxsNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  627. L1UserTx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
  628. L1UserTx.L1UserTx = *L1Tx
  629. rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
  630. case logHermezAddToken:
  631. var addToken RollupEventAddToken
  632. err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data)
  633. if err != nil {
  634. return nil, nil, err
  635. }
  636. addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
  637. rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
  638. case logHermezForgeBatch:
  639. var forgeBatch RollupEventForgeBatch
  640. forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  641. forgeBatch.EthTxHash = vLog.TxHash
  642. rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
  643. case logHermezUpdateForgeL1L2BatchTimeout:
  644. var updateForgeL1L2BatchTimeout struct {
  645. NewForgeL1L2BatchTimeout uint8
  646. }
  647. err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data)
  648. if err != nil {
  649. return nil, nil, err
  650. }
  651. rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout,
  652. RollupEventUpdateForgeL1L2BatchTimeout{
  653. NewForgeL1L2BatchTimeout: int64(updateForgeL1L2BatchTimeout.NewForgeL1L2BatchTimeout),
  654. })
  655. case logHermezUpdateFeeAddToken:
  656. var updateFeeAddToken RollupEventUpdateFeeAddToken
  657. err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
  658. if err != nil {
  659. return nil, nil, err
  660. }
  661. rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
  662. case logHermezWithdrawEvent:
  663. var withdraw RollupEventWithdrawEvent
  664. withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
  665. withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
  666. instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
  667. if instantWithdraw == 1 {
  668. withdraw.InstantWithdraw = true
  669. }
  670. rollupEvents.WithdrawEvent = append(rollupEvents.WithdrawEvent, withdraw)
  671. }
  672. }
  673. return &rollupEvents, &blockHash, nil
  674. }
  675. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the Rollup Smart Contract in the given transaction
  676. func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, error) {
  677. tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
  678. if err != nil {
  679. return nil, err
  680. }
  681. txData := tx.Data()
  682. method, err := c.contractAbi.MethodById(txData[:4])
  683. if err != nil {
  684. return nil, err
  685. }
  686. var aux RollupForgeBatchArgsAux
  687. if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil {
  688. return nil, err
  689. }
  690. rollupForgeBatchArgs := RollupForgeBatchArgs{
  691. L1Batch: aux.L1Batch,
  692. NewExitRoot: aux.NewExitRoot,
  693. NewLastIdx: aux.NewLastIdx.Int64(),
  694. NewStRoot: aux.NewStRoot,
  695. ProofA: aux.ProofA,
  696. ProofB: aux.ProofB,
  697. ProofC: aux.ProofC,
  698. VerifierIdx: aux.VerifierIdx,
  699. L1CoordinatorTxs: []common.L1Tx{},
  700. L1CoordinatorTxsAuths: [][]byte{},
  701. L2TxsData: []common.L2Tx{},
  702. FeeIdxCoordinator: []common.Idx{},
  703. }
  704. numTxsL1 := len(aux.EncodedL1CoordinatorTx) / common.L1CoordinatorTxBytesLen
  705. for i := 0; i < numTxsL1; i++ {
  706. bytesL1Coordinator := aux.EncodedL1CoordinatorTx[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]
  707. var signature []byte
  708. v := bytesL1Coordinator[0]
  709. s := bytesL1Coordinator[1:33]
  710. r := bytesL1Coordinator[33:65]
  711. signature = append(signature, r[:]...)
  712. signature = append(signature, s[:]...)
  713. signature = append(signature, v)
  714. l1Tx, err := common.L1TxFromCoordinatorBytes(bytesL1Coordinator)
  715. if err != nil {
  716. return nil, err
  717. }
  718. rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx)
  719. rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
  720. }
  721. rollupConsts, err := c.RollupConstants()
  722. if err != nil {
  723. return nil, err
  724. }
  725. nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
  726. lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)
  727. numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes
  728. for i := 0; i < numTxsL2; i++ {
  729. l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels))
  730. if err != nil {
  731. return nil, err
  732. }
  733. rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx)
  734. }
  735. lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
  736. numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
  737. for i := 0; i < numFeeIdxCoordinator; i++ {
  738. var paddedFeeIdx [6]byte
  739. // TODO: This check is not necessary: the first case will always work. Test it before removing the if.
  740. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
  741. copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  742. } else {
  743. copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  744. }
  745. feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
  746. if err != nil {
  747. return nil, err
  748. }
  749. if feeIdxCoordinator != common.Idx(0) {
  750. rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
  751. }
  752. }
  753. return &rollupForgeBatchArgs, nil
  754. }