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.

173 lines
7.7 KiB

Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
  1. package common
  2. import (
  3. "fmt"
  4. "math/big"
  5. ethCommon "github.com/ethereum/go-ethereum/common"
  6. "github.com/ethereum/go-ethereum/crypto"
  7. "github.com/hermeznetwork/tracerr"
  8. )
  9. const (
  10. // RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
  11. // coordinator can use to collect fees (determines the number of tokens
  12. // that the coordinator can collect fees from). This value is
  13. // determined by the circuit.
  14. RollupConstMaxFeeIdxCoordinator = 64
  15. // RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
  16. RollupConstReservedIDx = 255
  17. // RollupConstExitIDx IDX 1 is reserved for exits
  18. RollupConstExitIDx = 1
  19. // RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
  20. RollupConstLimitTokens = (1 << 32) //nolint:gomnd
  21. // RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes]
  22. // compressedSignature
  23. RollupConstL1CoordinatorTotalBytes = 101
  24. // RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6
  25. // bytes] fromIdx + [5 bytes] depositAmountFloat40 + [5 bytes] amountFloat40 + [4 bytes]
  26. // tokenId + [6 bytes] toIdx
  27. RollupConstL1UserTotalBytes = 78
  28. // RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
  29. RollupConstMaxL1UserTx = 128
  30. // RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch
  31. RollupConstMaxL1Tx = 256
  32. // RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx + [32 bytes]
  33. // stateRoot + [32 bytes] newStRoot + [32 bytes] newExitRoot + [_MAX_L1_TX *
  34. // _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength +
  35. // [2 bytes] chainID = 18542 bytes + totalL2TxsDataLength + feeIdxCoordinatorLength
  36. RollupConstInputSHAConstantBytes = 18546
  37. // RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
  38. RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
  39. // RollupConstExchangeMultiplier exchange multiplier
  40. RollupConstExchangeMultiplier = 1e14
  41. )
  42. var (
  43. // RollupConstLimitDepositAmount Max deposit amount allowed (depositAmount: L1 --> L2)
  44. RollupConstLimitDepositAmount, _ = new(big.Int).SetString(
  45. "340282366920938463463374607431768211456", 10)
  46. // RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
  47. RollupConstLimitL2TransferAmount, _ = new(big.Int).SetString(
  48. "6277101735386680763835789423207666416102355444464034512896", 10)
  49. // RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup
  50. // accounts that don't have ethereum address, only Babyjubjub.
  51. // This non-ethereum accounts can be created by the coordinator and allow users to have a
  52. // rollup account without needing an ethereum address
  53. RollupConstEthAddressInternalOnly = ethCommon.HexToAddress(
  54. "0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF")
  55. // RollupConstRfield Modulus zkSNARK
  56. RollupConstRfield, _ = new(big.Int).SetString(
  57. "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
  58. // RollupConstERC1820 ERC1820Registry address
  59. RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24")
  60. // ERC777 tokens signatures
  61. // RollupConstRecipientInterfaceHash ERC777 recipient interface hash
  62. RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient"))
  63. // RollupConstPerformL1UserTxSignature the signature of the function that can be called thru
  64. // an ERC777 `send`
  65. RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte(
  66. "addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)"))
  67. // RollupConstAddTokenSignature the signature of the function that can be called thru an
  68. // ERC777 `send`
  69. RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
  70. // RollupConstSendSignature ERC777 Signature
  71. RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
  72. // RollupConstERC777Granularity ERC777 Signature
  73. RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
  74. // RollupConstWithdrawalDelayerDeposit This constant are used to deposit tokens from ERC77
  75. // tokens into withdrawal delayer
  76. RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))
  77. // ERC20 signature
  78. // RollupConstTransferSignature This constant is used in the _safeTransfer internal method
  79. // in order to safe GAS.
  80. RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
  81. // RollupConstTransferFromSignature This constant is used in the _safeTransfer internal
  82. // method in order to safe GAS.
  83. RollupConstTransferFromSignature = crypto.Keccak256([]byte(
  84. "transferFrom(address,address,uint256)"))
  85. // RollupConstApproveSignature This constant is used in the _safeTransfer internal method in
  86. // 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. // RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
  92. type RollupVerifierStruct struct {
  93. MaxTx int64 `json:"maxTx"`
  94. NLevels int64 `json:"nlevels"`
  95. }
  96. // RollupConstants are the constants of the Rollup Smart Contract
  97. type RollupConstants struct {
  98. AbsoluteMaxL1L2BatchTimeout int64 `json:"absoluteMaxL1L2BatchTimeout"`
  99. TokenHEZ ethCommon.Address `json:"tokenHEZ"`
  100. Verifiers []RollupVerifierStruct `json:"verifiers"`
  101. HermezAuctionContract ethCommon.Address `json:"hermezAuctionContract"`
  102. HermezGovernanceAddress ethCommon.Address `json:"hermezGovernanceAddress"`
  103. WithdrawDelayerContract ethCommon.Address `json:"withdrawDelayerContract"`
  104. }
  105. // FindVerifierIdx tries to find a matching verifier in the RollupConstants and
  106. // returns its index
  107. func (c *RollupConstants) FindVerifierIdx(MaxTx, NLevels int64) (int, error) {
  108. for i, verifier := range c.Verifiers {
  109. if verifier.MaxTx == MaxTx && verifier.NLevels == NLevels {
  110. return i, nil
  111. }
  112. }
  113. return 0, tracerr.Wrap(fmt.Errorf("verifier not found for MaxTx: %v, NLevels: %v",
  114. MaxTx, NLevels))
  115. }
  116. // BucketParams are the parameter variables of each Bucket of Rollup Smart
  117. // Contract
  118. type BucketParams struct {
  119. CeilUSD *big.Int
  120. BlockStamp *big.Int
  121. Withdrawals *big.Int
  122. RateBlocks *big.Int
  123. RateWithdrawals *big.Int
  124. MaxWithdrawals *big.Int
  125. }
  126. // BucketUpdate are the bucket updates (tracking the withdrawals value changes)
  127. // in Rollup Smart Contract
  128. type BucketUpdate struct {
  129. EthBlockNum int64 `meddler:"eth_block_num"`
  130. NumBucket int `meddler:"num_bucket"`
  131. BlockStamp int64 `meddler:"block_stamp"`
  132. Withdrawals *big.Int `meddler:"withdrawals,bigint"`
  133. }
  134. // TokenExchange are the exchange value for tokens registered in the Rollup
  135. // Smart Contract
  136. type TokenExchange struct {
  137. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  138. Address ethCommon.Address `json:"address" meddler:"eth_addr"`
  139. ValueUSD int64 `json:"valueUSD" meddler:"value_usd"`
  140. }
  141. // RollupVariables are the variables of the Rollup Smart Contract
  142. //nolint:lll
  143. type RollupVariables struct {
  144. EthBlockNum int64 `meddler:"eth_block_num"`
  145. FeeAddToken *big.Int `meddler:"fee_add_token,bigint" validate:"required"`
  146. ForgeL1L2BatchTimeout int64 `meddler:"forge_l1_timeout" validate:"required"`
  147. WithdrawalDelay uint64 `meddler:"withdrawal_delay" validate:"required"`
  148. Buckets []BucketParams `meddler:"buckets,json"`
  149. SafeMode bool `meddler:"safe_mode"`
  150. }
  151. // Copy returns a deep copy of the Variables
  152. func (v *RollupVariables) Copy() *RollupVariables {
  153. vCpy := *v
  154. return &vCpy
  155. }