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.

330 lines
11 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
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
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
3 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
3 years ago
Update coordinator, call all api update functions - Common: - Rename Block.EthBlockNum to Block.Num to avoid unneeded repetition - API: - Add UpdateNetworkInfoBlock to update just block information, to be used when the node is not yet synchronized - Node: - Call API.UpdateMetrics and UpdateRecommendedFee in a loop, with configurable time intervals - Synchronizer: - When mapping events by TxHash, use an array to support the possibility of multiple calls of the same function happening in the same transaction (for example, a smart contract in a single transaction could call withdraw with delay twice, which would generate 2 withdraw events, and 2 deposit events). - In Stats, keep entire LastBlock instead of just the blockNum - In Stats, add lastL1BatchBlock - Test Stats and SCVars - Coordinator: - Enable writing the BatchInfo in every step of the pipeline to disk (with JSON text files) for debugging purposes. - Move the Pipeline functionality from the Coordinator to its own struct (Pipeline) - Implement shouldL1lL2Batch - In TxManager, implement logic to perform several attempts when doing ethereum node RPC calls before considering the error. (Both for calls to forgeBatch and transaction receipt) - In TxManager, reorganize the flow and note the specific points in which actions are made when err != nil - HistoryDB: - Implement GetLastL1BatchBlockNum: returns the blockNum of the latest forged l1Batch, to help the coordinator decide when to forge an L1Batch. - EthereumClient and test.Client: - Update EthBlockByNumber to return the last block when the passed number is -1.
3 years ago
  1. package eth
  2. import (
  3. "context"
  4. "fmt"
  5. "math/big"
  6. "time"
  7. "github.com/ethereum/go-ethereum/accounts"
  8. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  9. ethKeystore "github.com/ethereum/go-ethereum/accounts/keystore"
  10. ethCommon "github.com/ethereum/go-ethereum/common"
  11. "github.com/ethereum/go-ethereum/core/types"
  12. "github.com/ethereum/go-ethereum/ethclient"
  13. "github.com/hermeznetwork/hermez-node/common"
  14. HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ"
  15. "github.com/hermeznetwork/hermez-node/log"
  16. "github.com/hermeznetwork/tracerr"
  17. )
  18. // ERC20Consts are the constants defined in a particular ERC20 Token instance
  19. type ERC20Consts struct {
  20. Name string
  21. Symbol string
  22. Decimals uint64
  23. }
  24. // EthereumInterface is the interface to Ethereum
  25. type EthereumInterface interface {
  26. EthLastBlock() (int64, error)
  27. // EthHeaderByNumber(context.Context, *big.Int) (*types.Header, error)
  28. EthBlockByNumber(context.Context, int64) (*common.Block, error)
  29. EthAddress() (*ethCommon.Address, error)
  30. EthTransactionReceipt(context.Context, ethCommon.Hash) (*types.Receipt, error)
  31. EthERC20Consts(ethCommon.Address) (*ERC20Consts, error)
  32. }
  33. var (
  34. // ErrAccountNil is used when the calls can not be made because the account is nil
  35. ErrAccountNil = fmt.Errorf("Authorized calls can't be made when the account is nil")
  36. // ErrReceiptStatusFailed is used when receiving a failed transaction
  37. ErrReceiptStatusFailed = fmt.Errorf("receipt status is failed")
  38. // ErrReceiptNotReceived is used when unable to retrieve a transaction
  39. ErrReceiptNotReceived = fmt.Errorf("receipt not available")
  40. // ErrBlockHashMismatchEvent is used when there's a block hash mismatch
  41. // beetween different events of the same block
  42. ErrBlockHashMismatchEvent = fmt.Errorf("block hash mismatch in event log")
  43. )
  44. const (
  45. errStrDeploy = "deployment of %s failed: %w"
  46. errStrWaitReceipt = "wait receipt of %s deploy failed: %w"
  47. // default values
  48. defaultCallGasLimit = 300000
  49. defaultDeployGasLimit = 1000000
  50. defaultGasPriceDiv = 100
  51. defaultReceiptTimeout = 60
  52. defaultIntervalReceiptLoop = 200
  53. )
  54. // EthereumConfig defines the configuration parameters of the EthereumClient
  55. type EthereumConfig struct {
  56. CallGasLimit uint64
  57. DeployGasLimit uint64
  58. GasPriceDiv uint64
  59. ReceiptTimeout time.Duration // in seconds
  60. IntervalReceiptLoop time.Duration // in milliseconds
  61. }
  62. // EthereumClient is an ethereum client to call Smart Contract methods and check blockchain information.
  63. type EthereumClient struct {
  64. client *ethclient.Client
  65. account *accounts.Account
  66. ks *ethKeystore.KeyStore
  67. ReceiptTimeout time.Duration
  68. config *EthereumConfig
  69. opts *bind.CallOpts
  70. }
  71. // NewEthereumClient creates a EthereumClient instance. The account is not mandatory (it can
  72. // be nil). If the account is nil, CallAuth will fail with ErrAccountNil.
  73. func NewEthereumClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, config *EthereumConfig) *EthereumClient {
  74. if config == nil {
  75. config = &EthereumConfig{
  76. CallGasLimit: defaultCallGasLimit,
  77. DeployGasLimit: defaultDeployGasLimit,
  78. GasPriceDiv: defaultGasPriceDiv,
  79. ReceiptTimeout: defaultReceiptTimeout,
  80. IntervalReceiptLoop: defaultIntervalReceiptLoop,
  81. }
  82. }
  83. return &EthereumClient{
  84. client: client,
  85. account: account,
  86. ks: ks,
  87. ReceiptTimeout: config.ReceiptTimeout * time.Second,
  88. config: config,
  89. opts: newCallOpts(),
  90. }
  91. }
  92. // BalanceAt retieves information about the default account
  93. func (c *EthereumClient) BalanceAt(addr ethCommon.Address) (*big.Int, error) {
  94. return c.client.BalanceAt(context.TODO(), addr, nil)
  95. }
  96. // Account returns the underlying ethereum account
  97. func (c *EthereumClient) Account() *accounts.Account {
  98. return c.account
  99. }
  100. // EthAddress returns the ethereum address of the account loaded into the EthereumClient
  101. func (c *EthereumClient) EthAddress() (*ethCommon.Address, error) {
  102. if c.account == nil {
  103. return nil, tracerr.Wrap(ErrAccountNil)
  104. }
  105. return &c.account.Address, nil
  106. }
  107. // CallAuth performs a Smart Contract method call that requires authorization.
  108. // This call requires a valid account with Ether that can be spend during the
  109. // call.
  110. func (c *EthereumClient) CallAuth(gasLimit uint64,
  111. fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) {
  112. if c.account == nil {
  113. return nil, tracerr.Wrap(ErrAccountNil)
  114. }
  115. gasPrice, err := c.client.SuggestGasPrice(context.Background())
  116. if err != nil {
  117. return nil, tracerr.Wrap(err)
  118. }
  119. inc := new(big.Int).Set(gasPrice)
  120. inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
  121. gasPrice.Add(gasPrice, inc)
  122. log.Debugw("Transaction metadata", "gasPrice", gasPrice)
  123. auth, err := bind.NewKeyStoreTransactor(c.ks, *c.account)
  124. if err != nil {
  125. return nil, tracerr.Wrap(err)
  126. }
  127. auth.Value = big.NewInt(0) // in wei
  128. if gasLimit == 0 {
  129. auth.GasLimit = c.config.CallGasLimit // in units
  130. } else {
  131. auth.GasLimit = gasLimit // in units
  132. }
  133. auth.GasPrice = gasPrice
  134. tx, err := fn(c.client, auth)
  135. if tx != nil {
  136. log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
  137. }
  138. return tx, tracerr.Wrap(err)
  139. }
  140. // ContractData contains the contract data
  141. type ContractData struct {
  142. Address ethCommon.Address
  143. Tx *types.Transaction
  144. Receipt *types.Receipt
  145. }
  146. // Deploy a smart contract. `name` is used to log deployment information. fn
  147. // is a wrapper to the deploy function generated by abigen. In case of error,
  148. // the returned `ContractData` may have some parameters filled depending on the
  149. // kind of error that occurred.
  150. func (c *EthereumClient) Deploy(name string,
  151. fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
  152. var contractData ContractData
  153. log.Infow("Deploying", "contract", name)
  154. tx, err := c.CallAuth(
  155. c.config.DeployGasLimit,
  156. func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  157. addr, tx, _, err := fn(client, auth)
  158. if err != nil {
  159. return nil, tracerr.Wrap(err)
  160. }
  161. contractData.Address = addr
  162. return tx, nil
  163. },
  164. )
  165. if err != nil {
  166. return contractData, tracerr.Wrap(fmt.Errorf(errStrDeploy, name, err))
  167. }
  168. log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
  169. contractData.Tx = tx
  170. receipt, err := c.WaitReceipt(tx)
  171. if err != nil {
  172. return contractData, tracerr.Wrap(fmt.Errorf(errStrWaitReceipt, name, err))
  173. }
  174. contractData.Receipt = receipt
  175. return contractData, nil
  176. }
  177. // Call performs a read only Smart Contract method call.
  178. func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
  179. return fn(c.client)
  180. }
  181. // WaitReceipt will block until a transaction is confirmed. Internally it
  182. // polls the state every 200 milliseconds.
  183. func (c *EthereumClient) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
  184. return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
  185. }
  186. // GetReceipt will check if a transaction is confirmed and return
  187. // immediately, waiting at most 1 second and returning error if the transaction
  188. // is still pending.
  189. func (c *EthereumClient) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
  190. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  191. defer cancel()
  192. return c.waitReceipt(ctx, tx, 0)
  193. }
  194. // EthTransactionReceipt returns the transaction receipt of the given txHash
  195. func (c *EthereumClient) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  196. return c.client.TransactionReceipt(ctx, txHash)
  197. }
  198. func (c *EthereumClient) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
  199. var err error
  200. var receipt *types.Receipt
  201. txHash := tx.Hash()
  202. log.Debugw("Waiting for receipt", "tx", txHash.Hex())
  203. start := time.Now()
  204. for {
  205. receipt, err = c.client.TransactionReceipt(ctx, txHash)
  206. if receipt != nil || time.Since(start) >= timeout {
  207. break
  208. }
  209. time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
  210. }
  211. if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
  212. log.Errorw("Failed transaction", "tx", txHash.Hex())
  213. return receipt, tracerr.Wrap(ErrReceiptStatusFailed)
  214. }
  215. if receipt == nil {
  216. log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txHash.Hex(), "lasterr", err)
  217. return receipt, tracerr.Wrap(ErrReceiptNotReceived)
  218. }
  219. log.Debugw("Successful transaction", "tx", txHash.Hex())
  220. return receipt, tracerr.Wrap(err)
  221. }
  222. // EthLastBlock returns the last block number in the blockchain
  223. func (c *EthereumClient) EthLastBlock() (int64, error) {
  224. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  225. defer cancel()
  226. header, err := c.client.HeaderByNumber(ctx, nil)
  227. if err != nil {
  228. return 0, tracerr.Wrap(err)
  229. }
  230. return header.Number.Int64(), nil
  231. }
  232. // EthHeaderByNumber internally calls ethclient.Client HeaderByNumber
  233. // func (c *EthereumClient) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  234. // return c.client.HeaderByNumber(ctx, number)
  235. // }
  236. // EthBlockByNumber internally calls ethclient.Client BlockByNumber and returns
  237. // *common.Block. If number == -1, the latests known block is returned.
  238. func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
  239. blockNum := big.NewInt(number)
  240. if number == -1 {
  241. blockNum = nil
  242. }
  243. block, err := c.client.BlockByNumber(ctx, blockNum)
  244. if err != nil {
  245. return nil, tracerr.Wrap(err)
  246. }
  247. b := &common.Block{
  248. Num: block.Number().Int64(),
  249. Timestamp: time.Unix(int64(block.Time()), 0),
  250. ParentHash: block.ParentHash(),
  251. Hash: block.Hash(),
  252. }
  253. return b, nil
  254. }
  255. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  256. func (c *EthereumClient) EthERC20Consts(tokenAddress ethCommon.Address) (*ERC20Consts, error) {
  257. // We use the HEZ token smart contract interfacehere because it's an
  258. // ERC20, which allows us to access the standard ERC20 constants.
  259. instance, err := HEZ.NewHEZ(tokenAddress, c.client)
  260. if err != nil {
  261. return nil, tracerr.Wrap(err)
  262. }
  263. name, err := instance.Name(c.opts)
  264. if err != nil {
  265. return nil, tracerr.Wrap(err)
  266. }
  267. symbol, err := instance.Symbol(c.opts)
  268. if err != nil {
  269. return nil, tracerr.Wrap(err)
  270. }
  271. decimals, err := instance.Decimals(c.opts)
  272. if err != nil {
  273. return nil, tracerr.Wrap(err)
  274. }
  275. return &ERC20Consts{
  276. Name: name,
  277. Symbol: symbol,
  278. Decimals: uint64(decimals),
  279. }, nil
  280. }
  281. // Client returns the internal ethclient.Client
  282. func (c *EthereumClient) Client() *ethclient.Client {
  283. return c.client
  284. }
  285. // newCallOpts returns a CallOpts to be used in ethereum calls with a non-zero
  286. // From address. This is a workaround for a bug in ethereumjs-vm that shows up
  287. // in ganache: https://github.com/hermeznetwork/hermez-node/issues/317
  288. func newCallOpts() *bind.CallOpts {
  289. return &bind.CallOpts{
  290. From: ethCommon.HexToAddress("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"),
  291. }
  292. }