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.

313 lines
10 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
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
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.
4 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.
4 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.
4 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. }
  70. // NewEthereumClient creates a EthereumClient instance. The account is not mandatory (it can
  71. // be nil). If the account is nil, CallAuth will fail with ErrAccountNil.
  72. func NewEthereumClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, config *EthereumConfig) *EthereumClient {
  73. if config == nil {
  74. config = &EthereumConfig{
  75. CallGasLimit: defaultCallGasLimit,
  76. DeployGasLimit: defaultDeployGasLimit,
  77. GasPriceDiv: defaultGasPriceDiv,
  78. ReceiptTimeout: defaultReceiptTimeout,
  79. IntervalReceiptLoop: defaultIntervalReceiptLoop,
  80. }
  81. }
  82. return &EthereumClient{client: client, account: account, ks: ks, ReceiptTimeout: config.ReceiptTimeout * time.Second, config: config}
  83. }
  84. // BalanceAt retieves information about the default account
  85. func (c *EthereumClient) BalanceAt(addr ethCommon.Address) (*big.Int, error) {
  86. return c.client.BalanceAt(context.TODO(), addr, nil)
  87. }
  88. // Account returns the underlying ethereum account
  89. func (c *EthereumClient) Account() *accounts.Account {
  90. return c.account
  91. }
  92. // EthAddress returns the ethereum address of the account loaded into the EthereumClient
  93. func (c *EthereumClient) EthAddress() (*ethCommon.Address, error) {
  94. if c.account == nil {
  95. return nil, tracerr.Wrap(ErrAccountNil)
  96. }
  97. return &c.account.Address, nil
  98. }
  99. // CallAuth performs a Smart Contract method call that requires authorization.
  100. // This call requires a valid account with Ether that can be spend during the
  101. // call.
  102. func (c *EthereumClient) CallAuth(gasLimit uint64,
  103. fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) {
  104. if c.account == nil {
  105. return nil, tracerr.Wrap(ErrAccountNil)
  106. }
  107. gasPrice, err := c.client.SuggestGasPrice(context.Background())
  108. if err != nil {
  109. return nil, tracerr.Wrap(err)
  110. }
  111. inc := new(big.Int).Set(gasPrice)
  112. inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
  113. gasPrice.Add(gasPrice, inc)
  114. log.Debugw("Transaction metadata", "gasPrice", gasPrice)
  115. auth, err := bind.NewKeyStoreTransactor(c.ks, *c.account)
  116. if err != nil {
  117. return nil, tracerr.Wrap(err)
  118. }
  119. auth.Value = big.NewInt(0) // in wei
  120. if gasLimit == 0 {
  121. auth.GasLimit = c.config.CallGasLimit // in units
  122. } else {
  123. auth.GasLimit = gasLimit // in units
  124. }
  125. auth.GasPrice = gasPrice
  126. tx, err := fn(c.client, auth)
  127. if tx != nil {
  128. log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
  129. }
  130. return tx, tracerr.Wrap(err)
  131. }
  132. // ContractData contains the contract data
  133. type ContractData struct {
  134. Address ethCommon.Address
  135. Tx *types.Transaction
  136. Receipt *types.Receipt
  137. }
  138. // Deploy a smart contract. `name` is used to log deployment information. fn
  139. // is a wrapper to the deploy function generated by abigen. In case of error,
  140. // the returned `ContractData` may have some parameters filled depending on the
  141. // kind of error that occurred.
  142. func (c *EthereumClient) Deploy(name string,
  143. fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
  144. var contractData ContractData
  145. log.Infow("Deploying", "contract", name)
  146. tx, err := c.CallAuth(
  147. c.config.DeployGasLimit,
  148. func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  149. addr, tx, _, err := fn(client, auth)
  150. if err != nil {
  151. return nil, tracerr.Wrap(err)
  152. }
  153. contractData.Address = addr
  154. return tx, nil
  155. },
  156. )
  157. if err != nil {
  158. return contractData, tracerr.Wrap(fmt.Errorf(errStrDeploy, name, err))
  159. }
  160. log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
  161. contractData.Tx = tx
  162. receipt, err := c.WaitReceipt(tx)
  163. if err != nil {
  164. return contractData, tracerr.Wrap(fmt.Errorf(errStrWaitReceipt, name, err))
  165. }
  166. contractData.Receipt = receipt
  167. return contractData, nil
  168. }
  169. // Call performs a read only Smart Contract method call.
  170. func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
  171. return fn(c.client)
  172. }
  173. // WaitReceipt will block until a transaction is confirmed. Internally it
  174. // polls the state every 200 milliseconds.
  175. func (c *EthereumClient) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
  176. return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
  177. }
  178. // GetReceipt will check if a transaction is confirmed and return
  179. // immediately, waiting at most 1 second and returning error if the transaction
  180. // is still pending.
  181. func (c *EthereumClient) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
  182. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  183. defer cancel()
  184. return c.waitReceipt(ctx, tx, 0)
  185. }
  186. // EthTransactionReceipt returns the transaction receipt of the given txHash
  187. func (c *EthereumClient) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  188. return c.client.TransactionReceipt(ctx, txHash)
  189. }
  190. func (c *EthereumClient) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
  191. var err error
  192. var receipt *types.Receipt
  193. txHash := tx.Hash()
  194. log.Debugw("Waiting for receipt", "tx", txHash.Hex())
  195. start := time.Now()
  196. for {
  197. receipt, err = c.client.TransactionReceipt(ctx, txHash)
  198. if receipt != nil || time.Since(start) >= timeout {
  199. break
  200. }
  201. time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
  202. }
  203. if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
  204. log.Errorw("Failed transaction", "tx", txHash.Hex())
  205. return receipt, tracerr.Wrap(ErrReceiptStatusFailed)
  206. }
  207. if receipt == nil {
  208. log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txHash.Hex(), "lasterr", err)
  209. return receipt, tracerr.Wrap(ErrReceiptNotReceived)
  210. }
  211. log.Debugw("Successful transaction", "tx", txHash.Hex())
  212. return receipt, tracerr.Wrap(err)
  213. }
  214. // EthLastBlock returns the last block number in the blockchain
  215. func (c *EthereumClient) EthLastBlock() (int64, error) {
  216. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  217. defer cancel()
  218. header, err := c.client.HeaderByNumber(ctx, nil)
  219. if err != nil {
  220. return 0, tracerr.Wrap(err)
  221. }
  222. return header.Number.Int64(), nil
  223. }
  224. // EthHeaderByNumber internally calls ethclient.Client HeaderByNumber
  225. // func (c *EthereumClient) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  226. // return c.client.HeaderByNumber(ctx, number)
  227. // }
  228. // EthBlockByNumber internally calls ethclient.Client BlockByNumber and returns
  229. // *common.Block. If number == -1, the latests known block is returned.
  230. func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
  231. blockNum := big.NewInt(number)
  232. if number == -1 {
  233. blockNum = nil
  234. }
  235. block, err := c.client.BlockByNumber(ctx, blockNum)
  236. if err != nil {
  237. return nil, tracerr.Wrap(err)
  238. }
  239. b := &common.Block{
  240. Num: block.Number().Int64(),
  241. Timestamp: time.Unix(int64(block.Time()), 0),
  242. ParentHash: block.ParentHash(),
  243. Hash: block.Hash(),
  244. }
  245. return b, nil
  246. }
  247. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  248. func (c *EthereumClient) EthERC20Consts(tokenAddress ethCommon.Address) (*ERC20Consts, error) {
  249. // We use the HEZ token smart contract interfacehere because it's an
  250. // ERC20, which allows us to access the standard ERC20 constants.
  251. instance, err := HEZ.NewHEZ(tokenAddress, c.client)
  252. if err != nil {
  253. return nil, tracerr.Wrap(err)
  254. }
  255. name, err := instance.Name(nil)
  256. if err != nil {
  257. return nil, tracerr.Wrap(err)
  258. }
  259. symbol, err := instance.Symbol(nil)
  260. if err != nil {
  261. return nil, tracerr.Wrap(err)
  262. }
  263. decimals, err := instance.Decimals(nil)
  264. if err != nil {
  265. return nil, tracerr.Wrap(err)
  266. }
  267. return &ERC20Consts{
  268. Name: name,
  269. Symbol: symbol,
  270. Decimals: uint64(decimals),
  271. }, nil
  272. }
  273. // Client returns the internal ethclient.Client
  274. func (c *EthereumClient) Client() *ethclient.Client {
  275. return c.client
  276. }