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.

172 lines
8.1 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. "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. // HermezGovernanceDAOAddress eth.Address
  33. // WhiteHackGroupAddress 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] loadAmountFloat16 + [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. // RollupConstLimitLoadAmount Max load amount allowed (loadAmount: L1 --> L2)
  83. RollupConstLimitLoadAmount, _ = 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. HermezGovernanceDAOAddress ethCommon.Address `json:"hermezGovernanceDAOAddress"`
  130. SafetyAddress ethCommon.Address `json:"safetyAddress"`
  131. WithdrawDelayerContract ethCommon.Address `json:"withdrawDelayerContract"`
  132. }
  133. // Bucket are the variables of each Bucket of Rollup Smart Contract
  134. type Bucket struct {
  135. CeilUSD uint64 `json:"ceilUSD"`
  136. BlockStamp uint64 `json:"blockStamp"`
  137. Withdrawals uint64 `json:"withdrawals"`
  138. BlockWithdrawalRate uint64 `json:"blockWithdrawalRate"`
  139. MaxWithdrawals uint64 `json:"maxWithdrawals"`
  140. }
  141. // RollupVariables are the variables of the Rollup Smart Contract
  142. type RollupVariables struct {
  143. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  144. FeeAddToken *big.Int `json:"feeAddToken" meddler:"fee_add_token,bigint" validate:"required"`
  145. ForgeL1L2BatchTimeout int64 `json:"forgeL1L2BatchTimeout" meddler:"forge_l1_timeout" validate:"required"`
  146. WithdrawalDelay uint64 `json:"withdrawalDelay" meddler:"withdrawal_delay" validate:"required"`
  147. Buckets [RollupConstNumBuckets]Bucket `json:"buckets" meddler:"buckets,json"`
  148. }
  149. // Copy returns a deep copy of the Variables
  150. func (v *RollupVariables) Copy() *RollupVariables {
  151. vCpy := *v
  152. return &vCpy
  153. }