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.

189 lines
8.8 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.
3 years ago
  1. package common
  2. import (
  3. "math/big"
  4. ethCommon "github.com/ethereum/go-ethereum/common"
  5. "github.com/ethereum/go-ethereum/crypto"
  6. )
  7. // RollupVars contain the Rollup smart contract variables
  8. // type RollupVars struct {
  9. // EthBlockNum uint64
  10. // ForgeL1Timeout *big.Int
  11. // FeeL1UserTx *big.Int
  12. // FeeAddToken *big.Int
  13. // TokensHEZ eth.Address
  14. // Governance eth.Address
  15. // }
  16. // AuctionVars contain the Auction smart contract variables
  17. // type AuctionVars struct {
  18. // EthBlockNum uint64
  19. // SlotDeadline uint
  20. // CloseAuctionSlots uint
  21. // OpenAuctionSlots uint
  22. // Governance eth.Address
  23. // MinBidSlots MinBidSlots
  24. // Outbidding int
  25. // DonationAddress eth.Address
  26. // GovernanceAddress eth.Address
  27. // AllocationRatio AllocationRatio
  28. // }
  29. // WithdrawDelayerVars contains the Withdrawal Delayer smart contract variables
  30. // type WithdrawDelayerVars struct {
  31. // HermezRollupAddress eth.Address
  32. // HermezGovernanceAddress eth.Address
  33. // EmergencyCouncilAddress eth.Address
  34. // WithdrawalDelay uint
  35. // EmergencyModeStartingTime time.Time
  36. // EmergencyModeEnabled bool
  37. // }
  38. // MinBidSlots TODO
  39. // type MinBidSlots [6]uint
  40. //
  41. // // AllocationRatio TODO
  42. // type AllocationRatio struct {
  43. // Donation uint
  44. // Burn uint
  45. // Forger uint
  46. // }
  47. const (
  48. // RollupConstMaxFeeIdxCoordinator is the maximum number of tokens the
  49. // coordinator can use to collect fees (determines the number of tokens
  50. // that the coordinator can collect fees from). This value is
  51. // determined by the circuit.
  52. RollupConstMaxFeeIdxCoordinator = 64
  53. // RollupConstReservedIDx First 256 indexes reserved, first user index will be the 256
  54. RollupConstReservedIDx = 255
  55. // RollupConstExitIDx IDX 1 is reserved for exits
  56. RollupConstExitIDx = 1
  57. // RollupConstLimitTokens Max number of tokens allowed to be registered inside the rollup
  58. RollupConstLimitTokens = (1 << 32)
  59. // RollupConstL1CoordinatorTotalBytes [4 bytes] token + [32 bytes] babyjub + [65 bytes] compressedSignature
  60. RollupConstL1CoordinatorTotalBytes = 101
  61. // RollupConstL1UserTotalBytes [20 bytes] fromEthAddr + [32 bytes] fromBjj-compressed + [6 bytes] fromIdx +
  62. // [2 bytes] depositAmountFloat16 + [2 bytes] amountFloat16 + [4 bytes] tokenId + [6 bytes] toIdx
  63. RollupConstL1UserTotalBytes = 72
  64. // RollupConstMaxL1UserTx Maximum L1-user transactions allowed to be queued in a batch
  65. RollupConstMaxL1UserTx = 128
  66. // RollupConstMaxL1Tx Maximum L1 transactions allowed to be queued in a batch
  67. RollupConstMaxL1Tx = 256
  68. // RollupConstInputSHAConstantBytes [6 bytes] lastIdx + [6 bytes] newLastIdx + [32 bytes] stateRoot + [32 bytes] newStRoot + [32 bytes] newExitRoot +
  69. // [_MAX_L1_TX * _L1_USER_TOTALBYTES bytes] l1TxsData + totalL2TxsDataLength + feeIdxCoordinatorLength + [2 bytes] chainID =
  70. // 18542 bytes + totalL2TxsDataLength + feeIdxCoordinatorLength
  71. RollupConstInputSHAConstantBytes = 18542
  72. // RollupConstNumBuckets Number of buckets
  73. RollupConstNumBuckets = 5
  74. // RollupConstMaxWithdrawalDelay max withdrawal delay in seconds
  75. RollupConstMaxWithdrawalDelay = 2 * 7 * 24 * 60 * 60
  76. // RollupConstExchangeMultiplier exchange multiplier
  77. RollupConstExchangeMultiplier = 1e14
  78. // LenVerifiers number of Rollup Smart Contract Verifiers
  79. LenVerifiers = 1
  80. )
  81. var (
  82. // RollupConstLimitDepositAmount Max deposit amount allowed (depositAmount: L1 --> L2)
  83. RollupConstLimitDepositAmount, _ = new(big.Int).SetString("340282366920938463463374607431768211456", 10)
  84. // RollupConstLimitL2TransferAmount Max amount allowed (amount L2 --> L2)
  85. RollupConstLimitL2TransferAmount, _ = new(big.Int).SetString("6277101735386680763835789423207666416102355444464034512896", 10)
  86. // RollupConstEthAddressInternalOnly This ethereum address is used internally for rollup accounts that don't have ethereum address, only Babyjubjub
  87. // This non-ethereum accounts can be created by the coordinator and allow users to have a rollup
  88. // account without needing an ethereum address
  89. RollupConstEthAddressInternalOnly = ethCommon.HexToAddress("0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF")
  90. // RollupConstRfield Modulus zkSNARK
  91. RollupConstRfield, _ = new(big.Int).SetString(
  92. "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10)
  93. // RollupConstERC1820 ERC1820Registry address
  94. RollupConstERC1820 = ethCommon.HexToAddress("0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24")
  95. // ERC777 tokens signatures
  96. // RollupConstRecipientInterfaceHash ERC777 recipient interface hash
  97. RollupConstRecipientInterfaceHash = crypto.Keccak256([]byte("ERC777TokensRecipient"))
  98. // RollupConstPerformL1UserTxSignature the signature of the function that can be called thru an ERC777 `send`
  99. RollupConstPerformL1UserTxSignature = crypto.Keccak256([]byte("addL1Transaction(uint256,uint48,uint16,uint16,uint32,uint48)"))
  100. // RollupConstAddTokenSignature the signature of the function that can be called thru an ERC777 `send`
  101. RollupConstAddTokenSignature = crypto.Keccak256([]byte("addToken(address)"))
  102. // RollupConstSendSignature ERC777 Signature
  103. RollupConstSendSignature = crypto.Keccak256([]byte("send(address,uint256,bytes)"))
  104. // RollupConstERC777Granularity ERC777 Signature
  105. RollupConstERC777Granularity = crypto.Keccak256([]byte("granularity()"))
  106. // RollupConstWithdrawalDelayerDeposit This constant are used to deposit tokens from ERC77 tokens into withdrawal delayer
  107. RollupConstWithdrawalDelayerDeposit = crypto.Keccak256([]byte("deposit(address,address,uint192)"))
  108. // ERC20 signature
  109. // RollupConstTransferSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  110. RollupConstTransferSignature = crypto.Keccak256([]byte("transfer(address,uint256)"))
  111. // RollupConstTransferFromSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  112. RollupConstTransferFromSignature = crypto.Keccak256([]byte("transferFrom(address,address,uint256)"))
  113. // RollupConstApproveSignature This constant is used in the _safeTransfer internal method in order to safe GAS.
  114. RollupConstApproveSignature = crypto.Keccak256([]byte("approve(address,uint256)"))
  115. // RollupConstERC20Signature ERC20 decimals signature
  116. RollupConstERC20Signature = crypto.Keccak256([]byte("decimals()"))
  117. )
  118. // RollupVerifierStruct is the information about verifiers of the Rollup Smart Contract
  119. type RollupVerifierStruct struct {
  120. MaxTx int64 `json:"maxTx"`
  121. NLevels int64 `json:"nlevels"`
  122. }
  123. // RollupConstants are the constants of the Rollup Smart Contract
  124. type RollupConstants struct {
  125. AbsoluteMaxL1L2BatchTimeout int64 `json:"absoluteMaxL1L2BatchTimeout"`
  126. TokenHEZ ethCommon.Address `json:"tokenHEZ"`
  127. Verifiers []RollupVerifierStruct `json:"verifiers"`
  128. HermezAuctionContract ethCommon.Address `json:"hermezAuctionContract"`
  129. HermezGovernanceAddress ethCommon.Address `json:"hermezGovernanceAddress"`
  130. WithdrawDelayerContract ethCommon.Address `json:"withdrawDelayerContract"`
  131. }
  132. // BucketParams are the parameter variables of each Bucket of Rollup Smart
  133. // Contract
  134. type BucketParams struct {
  135. CeilUSD *big.Int `json:"ceilUSD"`
  136. Withdrawals *big.Int `json:"withdrawals"`
  137. BlockWithdrawalRate *big.Int `json:"blockWithdrawalRate"`
  138. MaxWithdrawals *big.Int `json:"maxWithdrawals"`
  139. }
  140. // BucketUpdate are the bucket updates (tracking the withdrawals value changes)
  141. // in Rollup Smart Contract
  142. type BucketUpdate struct {
  143. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  144. NumBucket int `json:"numBucket" meddler:"num_bucket"`
  145. BlockStamp int64 `json:"blockStamp" meddler:"block_stamp"`
  146. Withdrawals *big.Int `json:"withdrawals" meddler:"withdrawals,bigint"`
  147. }
  148. // TokenExchange are the exchange value for tokens registered in the Rollup
  149. // Smart Contract
  150. type TokenExchange struct {
  151. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  152. Address ethCommon.Address `json:"address" meddler:"eth_addr"`
  153. ValueUSD int64 `json:"valueUSD" meddler:"value_usd"`
  154. }
  155. // RollupVariables are the variables of the Rollup Smart Contract
  156. type RollupVariables struct {
  157. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  158. FeeAddToken *big.Int `json:"feeAddToken" meddler:"fee_add_token,bigint" validate:"required"`
  159. ForgeL1L2BatchTimeout int64 `json:"forgeL1L2BatchTimeout" meddler:"forge_l1_timeout" validate:"required"`
  160. WithdrawalDelay uint64 `json:"withdrawalDelay" meddler:"withdrawal_delay" validate:"required"`
  161. Buckets [RollupConstNumBuckets]BucketParams `json:"buckets" meddler:"buckets,json"`
  162. SafeMode bool `json:"safeMode" meddler:"safe_mode"`
  163. }
  164. // Copy returns a deep copy of the Variables
  165. func (v *RollupVariables) Copy() *RollupVariables {
  166. vCpy := *v
  167. return &vCpy
  168. }