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.

770 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. 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. const (
  21. // RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
  22. // coordinator can use to collect fees (determines the number of tokens
  23. // that the coordinator can collect fees from). This value is
  24. // determined by the circuit.
  25. RollupConstMaxFeeIdxCoordinator = 64
  26. // RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
  27. RollupConstReservedIDx = 255
  28. // RollupConstExitIDx IDX 1 is reserved for exits
  29. RollupConstExitIDx = 1
  30. // RollupConstLimitLoadAmount Max load amount allowed (loadAmount: L1 --> L2)
  31. RollupConstLimitLoadAmount = (1 << 128)
  32. // RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
  33. RollupConstLimitL2TransferAmount = (1 << 192)
  34. // RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
  35. RollupConstLimitTokens = (1 << 32)
  36. // RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes] compressedSignature
  37. RollupConstL1CoordinatorTotalBytes = 101
  38. // RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6 bytes] fromIdx +
  39. // [2 bytes] loadAmountFloat16 + [2 bytes] amountFloat16 + [4 bytes] tokenId + [6 bytes] toIdx
  40. RollupConstL1UserTotalBytes = 72
  41. // RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
  42. RollupConstMaxL1UserTx = 128
  43. // RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch
  44. RollupConstMaxL1Tx = 256
  45. // RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx + [32 bytes] stateRoot + [32 bytes] newStRoot + [32 bytes] newExitRoot +
  46. // [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength + [2 bytes] chainID =
  47. // 18542 bytes + totalL2TxsDataLength + feeIdxCoordinatorLength
  48. RollupConstInputSHAConstantBytes = 18542
  49. // RollupConstNumBuckets Number of buckets
  50. RollupConstNumBuckets = 5
  51. // RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
  52. RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
  53. // RollupConstExchangeMultiplier exchange multiplier
  54. RollupConstExchangeMultiplier = 1e14
  55. // LenVerifiers number of Rollup Smart Contract Verifiers
  56. LenVerifiers = 1
  57. )
  58. var (
  59. // RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup accounts that don't have ethereum address, only Babyjubjub
  60. // This non-ethereum accounts can be created by the coordinator and allow users to have a rollup
  61. // account without needing an ethereum address
  62. RollupConstEthAddressInternalOnly = ethCommon.HexToAddress("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF")
  63. // RollupConstRfield Modulus zkSNARK
  64. RollupConstRfield, _ = new(big.Int).SetString(
  65. "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
  66. // RollupConstERC1820 ERC1820Registry address
  67. RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24")
  68. // ERC777 tokens signatures
  69. // RollupConstRecipientInterfaceHash ERC777 recipient interface hash
  70. RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient"))
  71. // RollupConstPerformL1UserTxSignature the signature of the function that can be called thru an ERC777 `send`
  72. RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)"))
  73. // RollupConstAddTokenSignature the signature of the function that can be called thru an ERC777 `send`
  74. RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
  75. // RollupConstSendSignature ERC777 Signature
  76. RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
  77. // RollupConstERC777Granularity ERC777 Signature
  78. RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
  79. // RollupConstWithdrawalDelayerDeposit This constant are used to deposit tokens from ERC77 tokens into withdrawal delayer
  80. RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))
  81. // ERC20 signature
  82. // RollupConstTransferSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  83. RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
  84. // RollupConstTransferFromSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  85. RollupConstTransferFromSignature = crypto.Keccak256([]byte("transferFrom(address,address,uint256)"))
  86. // RollupConstApproveSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  87. RollupConstApproveSignature = crypto.Keccak256([]byte("approve(address,uint256)"))
  88. // RollupConstERC20Signature ERC20 decimals signature
  89. RollupConstERC20Signature = crypto.Keccak256([]byte("decimals()"))
  90. )
  91. // RollupPublicConstants are the constants of the Rollup Smart Contract
  92. type RollupPublicConstants struct {
  93. AbsoluteMaxL1L2BatchTimeout int64 `json:"absoluteMaxL1L2BatchTimeout"`
  94. TokenHEZ ethCommon.Address `json:"tokenHEZ"`
  95. Verifiers []RollupVerifierStruct `json:"verifiers"`
  96. HermezAuctionContract ethCommon.Address `json:"hermezAuctionContract"`
  97. HermezGovernanceDAOAddress ethCommon.Address `json:"hermezGovernanceDAOAddress"`
  98. SafetyAddress ethCommon.Address `json:"safetyAddress"`
  99. WithdrawDelayerContract ethCommon.Address `json:"withdrawDelayerContract"`
  100. }
  101. // RollupVariables are the variables of the Rollup Smart Contract
  102. type RollupVariables struct {
  103. FeeAddToken *big.Int
  104. ForgeL1L2BatchTimeout int64
  105. WithdrawalDelay uint64
  106. }
  107. // QueueStruct is the queue of L1Txs for a batch
  108. type QueueStruct struct {
  109. L1TxQueue []common.L1Tx
  110. TotalL1TxFee *big.Int
  111. }
  112. // NewQueueStruct creates a new clear QueueStruct.
  113. func NewQueueStruct() *QueueStruct {
  114. return &QueueStruct{
  115. L1TxQueue: make([]common.L1Tx, 0),
  116. TotalL1TxFee: big.NewInt(0),
  117. }
  118. }
  119. // RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
  120. type RollupVerifierStruct struct {
  121. MaxTx int64 `json:"maxTx"`
  122. NLevels int64 `json:"nlevels"`
  123. }
  124. // RollupState represents the state of the Rollup in the Smart Contract
  125. type RollupState struct {
  126. StateRoot *big.Int
  127. ExitRoots []*big.Int
  128. ExitNullifierMap map[[256 / 8]byte]bool
  129. TokenList []ethCommon.Address
  130. TokenMap map[ethCommon.Address]bool
  131. MapL1TxQueue map[int64]*QueueStruct
  132. LastL1L2Batch int64
  133. CurrentToForgeL1TxsNum int64
  134. LastToForgeL1TxsNum int64
  135. CurrentIdx int64
  136. }
  137. // RollupEventL1UserTx is an event of the Rollup Smart Contract
  138. type RollupEventL1UserTx struct {
  139. // ToForgeL1TxsNum int64 // QueueIndex *big.Int
  140. // Position int // TransactionIndex *big.Int
  141. L1UserTx common.L1Tx
  142. }
  143. // RollupEventL1UserTxAux is an event of the Rollup Smart Contract
  144. type RollupEventL1UserTxAux struct {
  145. ToForgeL1TxsNum uint64 // QueueIndex *big.Int
  146. Position uint8 // TransactionIndex *big.Int
  147. L1UserTx []byte
  148. }
  149. // RollupEventAddToken is an event of the Rollup Smart Contract
  150. type RollupEventAddToken struct {
  151. TokenAddress ethCommon.Address
  152. TokenID uint32
  153. }
  154. // RollupEventForgeBatch is an event of the Rollup Smart Contract
  155. type RollupEventForgeBatch struct {
  156. BatchNum int64
  157. // Sender ethCommon.Address
  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, deadline *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. RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err 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, *ethCommon.Address, 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. tokenHEZ TokenConfig
  257. hermez *Hermez.Hermez
  258. contractAbi abi.ABI
  259. }
  260. // NewRollupClient creates a new RollupClient
  261. func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZ TokenConfig) (*RollupClient, error) {
  262. contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI)))
  263. if err != nil {
  264. return nil, err
  265. }
  266. hermez, err := Hermez.NewHermez(address, client.Client())
  267. if err != nil {
  268. return nil, err
  269. }
  270. return &RollupClient{
  271. client: client,
  272. address: address,
  273. tokenHEZ: tokenHEZ,
  274. hermez: hermez,
  275. contractAbi: contractAbi,
  276. }, nil
  277. }
  278. // RollupForgeBatch is the interface to call the smart contract function
  279. func (c *RollupClient) RollupForgeBatch(args *RollupForgeBatchArgs) (tx *types.Transaction, err error) {
  280. if tx, err = c.client.CallAuth(
  281. 1000000, //nolint:gomnd
  282. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  283. rollupConst, err := c.RollupConstants()
  284. if err != nil {
  285. return nil, err
  286. }
  287. nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels
  288. lenBytes := nLevels / 8 //nolint:gomnd
  289. newLastIdx := big.NewInt(int64(args.NewLastIdx))
  290. var l1CoordinatorBytes []byte
  291. for i := 0; i < len(args.L1CoordinatorTxs); i++ {
  292. l1 := args.L1CoordinatorTxs[i]
  293. bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i])
  294. if err != nil {
  295. return nil, err
  296. }
  297. l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...)
  298. }
  299. var l2DataBytes []byte
  300. for i := 0; i < len(args.L2TxsData); i++ {
  301. l2 := args.L2TxsData[i]
  302. bytesl2, err := l2.Bytes(int(nLevels))
  303. if err != nil {
  304. return nil, err
  305. }
  306. l2DataBytes = append(l2DataBytes, bytesl2[:]...)
  307. }
  308. var feeIdxCoordinator []byte
  309. if len(args.FeeIdxCoordinator) > RollupConstMaxFeeIdxCoordinator {
  310. return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v",
  311. RollupConstMaxFeeIdxCoordinator)
  312. }
  313. for i := 0; i < RollupConstMaxFeeIdxCoordinator; i++ {
  314. feeIdx := common.Idx(0)
  315. if i < len(args.FeeIdxCoordinator) {
  316. feeIdx = args.FeeIdxCoordinator[i]
  317. }
  318. bytesFeeIdx, err := feeIdx.Bytes()
  319. if err != nil {
  320. return nil, err
  321. }
  322. feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...)
  323. }
  324. return c.hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC)
  325. },
  326. ); err != nil {
  327. return nil, fmt.Errorf("Failed forge batch: %w", err)
  328. }
  329. return tx, nil
  330. }
  331. // RollupAddToken is the interface to call the smart contract function.
  332. // `feeAddToken` is the amount of HEZ tokens that will be paid to add the
  333. // token. `feeAddToken` must match the public value of the smart contract.
  334. func (c *RollupClient) RollupAddToken(tokenAddress ethCommon.Address, feeAddToken, deadline *big.Int) (tx *types.Transaction, err error) {
  335. if tx, err = c.client.CallAuth(
  336. 0,
  337. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  338. tokenHEZcontract, err := HEZ.NewHEZ(c.tokenHEZ.Address, ec)
  339. if err != nil {
  340. return nil, err
  341. }
  342. owner := c.client.account.Address
  343. spender := c.address
  344. nonce, err := tokenHEZcontract.Nonces(nil, owner)
  345. tokenname := c.tokenHEZ.Name
  346. tokenAddr := c.tokenHEZ.Address
  347. chainid, _ := c.client.client.ChainID(context.Background())
  348. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, feeAddToken, nonce, deadline, tokenname)
  349. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  350. permit := createPermit(owner, spender, feeAddToken, deadline, digest, signature)
  351. return c.hermez.AddToken(auth, tokenAddress, permit)
  352. },
  353. ); err != nil {
  354. return nil, fmt.Errorf("Failed add Token %w", err)
  355. }
  356. return tx, nil
  357. }
  358. // RollupWithdrawMerkleProof is the interface to call the smart contract function
  359. 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) {
  360. if tx, err = c.client.CallAuth(
  361. 0,
  362. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  363. pkCompL := fromBJJ.Compress()
  364. pkCompB := common.SwapEndianness(pkCompL[:])
  365. babyPubKey := new(big.Int).SetBytes(pkCompB)
  366. numExitRootB := big.NewInt(numExitRoot)
  367. idxBig := big.NewInt(idx)
  368. return c.hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey, numExitRootB, siblings, idxBig, instantWithdraw)
  369. },
  370. ); err != nil {
  371. return nil, fmt.Errorf("Failed update WithdrawMerkleProof: %w", err)
  372. }
  373. return tx, nil
  374. }
  375. // RollupWithdrawCircuit is the interface to call the smart contract function
  376. 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) {
  377. log.Error("TODO")
  378. return nil, errTODO
  379. }
  380. // RollupL1UserTxERC20ETH is the interface to call the smart contract function
  381. func (c *RollupClient) RollupL1UserTxERC20ETH(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64) (tx *types.Transaction, err error) {
  382. if tx, err = c.client.CallAuth(
  383. 0,
  384. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  385. pkCompL := fromBJJ.Compress()
  386. pkCompB := common.SwapEndianness(pkCompL[:])
  387. babyPubKey := new(big.Int).SetBytes(pkCompB)
  388. fromIdxBig := big.NewInt(fromIdx)
  389. toIdxBig := big.NewInt(toIdx)
  390. tokenIDBig := uint32(tokenID)
  391. loadAmountF, err := common.NewFloat16(loadAmount)
  392. if err != nil {
  393. return nil, err
  394. }
  395. amountF, err := common.NewFloat16(amount)
  396. if err != nil {
  397. return nil, err
  398. }
  399. if tokenID == 0 {
  400. auth.Value = loadAmount
  401. }
  402. var permit []byte
  403. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF), uint16(amountF), tokenIDBig, toIdxBig, permit)
  404. },
  405. ); err != nil {
  406. return nil, fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err)
  407. }
  408. return tx, nil
  409. }
  410. // RollupL1UserTxERC20Permit is the interface to call the smart contract function
  411. 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) {
  412. if tx, err = c.client.CallAuth(
  413. 0,
  414. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  415. pkCompL := fromBJJ.Compress()
  416. pkCompB := common.SwapEndianness(pkCompL[:])
  417. babyPubKey := new(big.Int).SetBytes(pkCompB)
  418. fromIdxBig := big.NewInt(fromIdx)
  419. toIdxBig := big.NewInt(toIdx)
  420. tokenIDBig := uint32(tokenID)
  421. loadAmountF, err := common.NewFloat16(loadAmount)
  422. if err != nil {
  423. return nil, err
  424. }
  425. amountF, err := common.NewFloat16(amount)
  426. if err != nil {
  427. return nil, err
  428. }
  429. if tokenID == 0 {
  430. auth.Value = loadAmount
  431. }
  432. tokenHEZcontract, err := HEZ.NewHEZ(c.tokenHEZ.Address, ec)
  433. if err != nil {
  434. return nil, err
  435. }
  436. owner := c.client.account.Address
  437. spender := c.address
  438. nonce, err := tokenHEZcontract.Nonces(nil, owner)
  439. tokenname := c.tokenHEZ.Name
  440. tokenAddr := c.tokenHEZ.Address
  441. chainid, _ := c.client.client.ChainID(context.Background())
  442. digest, _ := createPermitDigest(tokenAddr, owner, spender, chainid, amount, nonce, deadline, tokenname)
  443. signature, _ := c.client.ks.SignHash(*c.client.account, digest)
  444. permit := createPermit(owner, spender, amount, deadline, digest, signature)
  445. return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF), uint16(amountF), tokenIDBig, toIdxBig, permit)
  446. },
  447. ); err != nil {
  448. return nil, fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err)
  449. }
  450. return tx, nil
  451. }
  452. // RollupRegisterTokensCount is the interface to call the smart contract function
  453. func (c *RollupClient) RollupRegisterTokensCount() (*big.Int, error) {
  454. var registerTokensCount *big.Int
  455. if err := c.client.Call(func(ec *ethclient.Client) error {
  456. hermez, err := Hermez.NewHermez(c.address, ec)
  457. if err != nil {
  458. return err
  459. }
  460. registerTokensCount, err = hermez.RegisterTokensCount(nil)
  461. return err
  462. }); err != nil {
  463. return nil, err
  464. }
  465. return registerTokensCount, nil
  466. }
  467. // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function
  468. func (c *RollupClient) RollupUpdateForgeL1L2BatchTimeout(newForgeL1L2BatchTimeout int64) (tx *types.Transaction, err error) {
  469. if tx, err = c.client.CallAuth(
  470. 0,
  471. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  472. return c.hermez.UpdateForgeL1L2BatchTimeout(auth, uint8(newForgeL1L2BatchTimeout))
  473. },
  474. ); err != nil {
  475. return nil, fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err)
  476. }
  477. return tx, nil
  478. }
  479. // RollupUpdateFeeAddToken is the interface to call the smart contract function
  480. func (c *RollupClient) RollupUpdateFeeAddToken(newFeeAddToken *big.Int) (tx *types.Transaction, err error) {
  481. if tx, err = c.client.CallAuth(
  482. 0,
  483. func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  484. return c.hermez.UpdateFeeAddToken(auth, newFeeAddToken)
  485. },
  486. ); err != nil {
  487. return nil, fmt.Errorf("Failed update FeeAddToken: %w", err)
  488. }
  489. return tx, nil
  490. }
  491. // RollupConstants returns the Constants of the Rollup Smart Contract
  492. func (c *RollupClient) RollupConstants() (rollupConstants *RollupPublicConstants, err error) {
  493. rollupConstants = new(RollupPublicConstants)
  494. if err := c.client.Call(func(ec *ethclient.Client) error {
  495. absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil)
  496. if err != nil {
  497. return err
  498. }
  499. rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout)
  500. rollupConstants.TokenHEZ, err = c.hermez.TokenHEZ(nil)
  501. if err != nil {
  502. return err
  503. }
  504. for i := int64(0); i < int64(LenVerifiers); i++ {
  505. var newRollupVerifier RollupVerifierStruct
  506. rollupVerifier, err := c.hermez.RollupVerifiers(nil, big.NewInt(i))
  507. if err != nil {
  508. return err
  509. }
  510. newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64()
  511. newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()
  512. rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)
  513. }
  514. rollupConstants.HermezAuctionContract, err = c.hermez.HermezAuctionContract(nil)
  515. if err != nil {
  516. return err
  517. }
  518. rollupConstants.HermezGovernanceDAOAddress, err = c.hermez.HermezGovernanceDAOAddress(nil)
  519. if err != nil {
  520. return err
  521. }
  522. rollupConstants.SafetyAddress, err = c.hermez.SafetyAddress(nil)
  523. if err != nil {
  524. return err
  525. }
  526. rollupConstants.WithdrawDelayerContract, err = c.hermez.WithdrawDelayerContract(nil)
  527. return err
  528. }); err != nil {
  529. return nil, err
  530. }
  531. return rollupConstants, nil
  532. }
  533. var (
  534. logHermezL1UserTxEvent = crypto.Keccak256Hash([]byte("L1UserTxEvent(uint64,uint8,bytes)"))
  535. logHermezAddToken = crypto.Keccak256Hash([]byte("AddToken(address,uint32)"))
  536. logHermezForgeBatch = crypto.Keccak256Hash([]byte("ForgeBatch(uint64)"))
  537. logHermezUpdateForgeL1L2BatchTimeout = crypto.Keccak256Hash([]byte("UpdateForgeL1L2BatchTimeout(uint8)"))
  538. logHermezUpdateFeeAddToken = crypto.Keccak256Hash([]byte("UpdateFeeAddToken(uint256)"))
  539. logHermezWithdrawEvent = crypto.Keccak256Hash([]byte("WithdrawEvent(uint48,uint48,bool)"))
  540. )
  541. // RollupEventsByBlock returns the events in a block that happened in the Rollup Smart Contract
  542. func (c *RollupClient) RollupEventsByBlock(blockNum int64) (*RollupEvents, *ethCommon.Hash, error) {
  543. var rollupEvents RollupEvents
  544. var blockHash ethCommon.Hash
  545. query := ethereum.FilterQuery{
  546. FromBlock: big.NewInt(blockNum),
  547. ToBlock: big.NewInt(blockNum),
  548. Addresses: []ethCommon.Address{
  549. c.address,
  550. },
  551. BlockHash: nil,
  552. Topics: [][]ethCommon.Hash{},
  553. }
  554. logs, err := c.client.client.FilterLogs(context.Background(), query)
  555. if err != nil {
  556. return nil, nil, err
  557. }
  558. if len(logs) > 0 {
  559. blockHash = logs[0].BlockHash
  560. }
  561. for _, vLog := range logs {
  562. if vLog.BlockHash != blockHash {
  563. return nil, nil, ErrBlockHashMismatchEvent
  564. }
  565. switch vLog.Topics[0] {
  566. case logHermezL1UserTxEvent:
  567. var L1UserTxAux RollupEventL1UserTxAux
  568. var L1UserTx RollupEventL1UserTx
  569. err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data)
  570. if err != nil {
  571. return nil, nil, err
  572. }
  573. L1Tx, err := common.L1UserTxFromBytes(L1UserTxAux.L1UserTx)
  574. if err != nil {
  575. return nil, nil, err
  576. }
  577. toForgeL1TxsNum := new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  578. L1Tx.ToForgeL1TxsNum = &toForgeL1TxsNum
  579. L1Tx.Position = int(new(big.Int).SetBytes(vLog.Topics[2][:]).Int64())
  580. L1Tx.UserOrigin = true
  581. L1UserTx.L1UserTx = *L1Tx
  582. rollupEvents.L1UserTx = append(rollupEvents.L1UserTx, L1UserTx)
  583. case logHermezAddToken:
  584. var addToken RollupEventAddToken
  585. err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data)
  586. if err != nil {
  587. return nil, nil, err
  588. }
  589. addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes())
  590. rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)
  591. case logHermezForgeBatch:
  592. var forgeBatch RollupEventForgeBatch
  593. forgeBatch.BatchNum = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()
  594. forgeBatch.EthTxHash = vLog.TxHash
  595. // forgeBatch.Sender = vLog.Address
  596. rollupEvents.ForgeBatch = append(rollupEvents.ForgeBatch, forgeBatch)
  597. case logHermezUpdateForgeL1L2BatchTimeout:
  598. var updateForgeL1L2BatchTimeout struct {
  599. NewForgeL1L2BatchTimeout uint8
  600. }
  601. err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data)
  602. if err != nil {
  603. return nil, nil, err
  604. }
  605. rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout,
  606. RollupEventUpdateForgeL1L2BatchTimeout{
  607. NewForgeL1L2BatchTimeout: int64(updateForgeL1L2BatchTimeout.NewForgeL1L2BatchTimeout),
  608. })
  609. case logHermezUpdateFeeAddToken:
  610. var updateFeeAddToken RollupEventUpdateFeeAddToken
  611. err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data)
  612. if err != nil {
  613. return nil, nil, err
  614. }
  615. rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken)
  616. case logHermezWithdrawEvent:
  617. var withdraw RollupEventWithdrawEvent
  618. withdraw.Idx = new(big.Int).SetBytes(vLog.Topics[1][:]).Uint64()
  619. withdraw.NumExitRoot = new(big.Int).SetBytes(vLog.Topics[2][:]).Uint64()
  620. instantWithdraw := new(big.Int).SetBytes(vLog.Topics[3][:]).Uint64()
  621. if instantWithdraw == 1 {
  622. withdraw.InstantWithdraw = true
  623. }
  624. rollupEvents.WithdrawEvent = append(rollupEvents.WithdrawEvent, withdraw)
  625. }
  626. }
  627. return &rollupEvents, &blockHash, nil
  628. }
  629. // RollupForgeBatchArgs returns the arguments used in a ForgeBatch call in the
  630. // Rollup Smart Contract in the given transaction, and the sender address.
  631. func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error) {
  632. tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash)
  633. if err != nil {
  634. return nil, nil, err
  635. }
  636. txData := tx.Data()
  637. method, err := c.contractAbi.MethodById(txData[:4])
  638. if err != nil {
  639. return nil, nil, err
  640. }
  641. receipt, err := c.client.client.TransactionReceipt(context.Background(), ethTxHash)
  642. if err != nil {
  643. return nil, nil, err
  644. }
  645. sender, err := c.client.client.TransactionSender(context.Background(), tx, receipt.Logs[0].BlockHash, receipt.Logs[0].Index)
  646. if err != nil {
  647. return nil, nil, err
  648. }
  649. var aux RollupForgeBatchArgsAux
  650. if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil {
  651. return nil, nil, err
  652. }
  653. rollupForgeBatchArgs := RollupForgeBatchArgs{
  654. L1Batch: aux.L1Batch,
  655. NewExitRoot: aux.NewExitRoot,
  656. NewLastIdx: aux.NewLastIdx.Int64(),
  657. NewStRoot: aux.NewStRoot,
  658. ProofA: aux.ProofA,
  659. ProofB: aux.ProofB,
  660. ProofC: aux.ProofC,
  661. VerifierIdx: aux.VerifierIdx,
  662. L1CoordinatorTxs: []common.L1Tx{},
  663. L1CoordinatorTxsAuths: [][]byte{},
  664. L2TxsData: []common.L2Tx{},
  665. FeeIdxCoordinator: []common.Idx{},
  666. }
  667. numTxsL1 := len(aux.EncodedL1CoordinatorTx) / common.L1CoordinatorTxBytesLen
  668. for i := 0; i < numTxsL1; i++ {
  669. bytesL1Coordinator := aux.EncodedL1CoordinatorTx[i*common.L1CoordinatorTxBytesLen : (i+1)*common.L1CoordinatorTxBytesLen]
  670. var signature []byte
  671. v := bytesL1Coordinator[0]
  672. s := bytesL1Coordinator[1:33]
  673. r := bytesL1Coordinator[33:65]
  674. signature = append(signature, r[:]...)
  675. signature = append(signature, s[:]...)
  676. signature = append(signature, v)
  677. l1Tx, err := common.L1CoordinatorTxFromBytes(bytesL1Coordinator)
  678. if err != nil {
  679. return nil, nil, err
  680. }
  681. rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx)
  682. rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature)
  683. }
  684. rollupConsts, err := c.RollupConstants()
  685. if err != nil {
  686. return nil, nil, err
  687. }
  688. nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels
  689. lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)
  690. numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes
  691. for i := 0; i < numTxsL2; i++ {
  692. l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels))
  693. if err != nil {
  694. return nil, nil, err
  695. }
  696. rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx)
  697. }
  698. lenFeeIdxCoordinatorBytes := int(nLevels / 8) //nolint:gomnd
  699. numFeeIdxCoordinator := len(aux.FeeIdxCoordinator) / lenFeeIdxCoordinatorBytes
  700. for i := 0; i < numFeeIdxCoordinator; i++ {
  701. var paddedFeeIdx [6]byte
  702. // TODO: This check is not necessary: the first case will always work. Test it before removing the if.
  703. if lenFeeIdxCoordinatorBytes < common.IdxBytesLen {
  704. copy(paddedFeeIdx[6-lenFeeIdxCoordinatorBytes:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  705. } else {
  706. copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])
  707. }
  708. feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:])
  709. if err != nil {
  710. return nil, nil, err
  711. }
  712. if feeIdxCoordinator != common.Idx(0) {
  713. rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
  714. }
  715. }
  716. return &rollupForgeBatchArgs, &sender, nil
  717. }