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.

341 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.
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. EthChainID() (*big.Int, error)
  33. }
  34. var (
  35. // ErrAccountNil is used when the calls can not be made because the account is nil
  36. ErrAccountNil = fmt.Errorf("Authorized calls can't be made when the account is nil")
  37. // ErrReceiptStatusFailed is used when receiving a failed transaction
  38. ErrReceiptStatusFailed = fmt.Errorf("receipt status is failed")
  39. // ErrReceiptNotReceived is used when unable to retrieve a transaction
  40. ErrReceiptNotReceived = fmt.Errorf("receipt not available")
  41. // ErrBlockHashMismatchEvent is used when there's a block hash mismatch
  42. // beetween different events of the same block
  43. ErrBlockHashMismatchEvent = fmt.Errorf("block hash mismatch in event log")
  44. )
  45. const (
  46. errStrDeploy = "deployment of %s failed: %w"
  47. errStrWaitReceipt = "wait receipt of %s deploy failed: %w"
  48. // default values
  49. defaultCallGasLimit = 300000
  50. defaultDeployGasLimit = 1000000
  51. defaultGasPriceDiv = 100
  52. defaultReceiptTimeout = 60
  53. defaultIntervalReceiptLoop = 200
  54. )
  55. // EthereumConfig defines the configuration parameters of the EthereumClient
  56. type EthereumConfig struct {
  57. CallGasLimit uint64
  58. DeployGasLimit uint64
  59. GasPriceDiv uint64
  60. ReceiptTimeout time.Duration
  61. IntervalReceiptLoop time.Duration
  62. }
  63. // EthereumClient is an ethereum client to call Smart Contract methods and check blockchain information.
  64. type EthereumClient struct {
  65. client *ethclient.Client
  66. account *accounts.Account
  67. ks *ethKeystore.KeyStore
  68. ReceiptTimeout time.Duration
  69. config *EthereumConfig
  70. opts *bind.CallOpts
  71. }
  72. // NewEthereumClient creates a EthereumClient instance. The account is not mandatory (it can
  73. // be nil). If the account is nil, CallAuth will fail with ErrAccountNil.
  74. func NewEthereumClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, config *EthereumConfig) *EthereumClient {
  75. if config == nil {
  76. config = &EthereumConfig{
  77. CallGasLimit: defaultCallGasLimit,
  78. DeployGasLimit: defaultDeployGasLimit,
  79. GasPriceDiv: defaultGasPriceDiv,
  80. ReceiptTimeout: defaultReceiptTimeout,
  81. IntervalReceiptLoop: defaultIntervalReceiptLoop,
  82. }
  83. }
  84. return &EthereumClient{
  85. client: client,
  86. account: account,
  87. ks: ks,
  88. ReceiptTimeout: config.ReceiptTimeout * time.Second,
  89. config: config,
  90. opts: newCallOpts(),
  91. }
  92. }
  93. // EthChainID returns the ChainID of the ethereum network
  94. func (c *EthereumClient) EthChainID() (*big.Int, error) {
  95. chainID, err := c.client.ChainID(context.Background())
  96. if err != nil {
  97. return nil, tracerr.Wrap(err)
  98. }
  99. return chainID, nil
  100. }
  101. // BalanceAt retieves information about the default account
  102. func (c *EthereumClient) BalanceAt(addr ethCommon.Address) (*big.Int, error) {
  103. return c.client.BalanceAt(context.TODO(), addr, nil)
  104. }
  105. // Account returns the underlying ethereum account
  106. func (c *EthereumClient) Account() *accounts.Account {
  107. return c.account
  108. }
  109. // EthAddress returns the ethereum address of the account loaded into the EthereumClient
  110. func (c *EthereumClient) EthAddress() (*ethCommon.Address, error) {
  111. if c.account == nil {
  112. return nil, tracerr.Wrap(ErrAccountNil)
  113. }
  114. return &c.account.Address, nil
  115. }
  116. // CallAuth performs a Smart Contract method call that requires authorization.
  117. // This call requires a valid account with Ether that can be spend during the
  118. // call.
  119. func (c *EthereumClient) CallAuth(gasLimit uint64,
  120. fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) {
  121. if c.account == nil {
  122. return nil, tracerr.Wrap(ErrAccountNil)
  123. }
  124. gasPrice, err := c.client.SuggestGasPrice(context.Background())
  125. if err != nil {
  126. return nil, tracerr.Wrap(err)
  127. }
  128. inc := new(big.Int).Set(gasPrice)
  129. inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))
  130. gasPrice.Add(gasPrice, inc)
  131. log.Debugw("Transaction metadata", "gasPrice", gasPrice)
  132. // TODO: Set the correct chainID
  133. auth, err := bind.NewKeyStoreTransactorWithChainID(c.ks, *c.account, big.NewInt(0))
  134. if err != nil {
  135. return nil, tracerr.Wrap(err)
  136. }
  137. auth.Value = big.NewInt(0) // in wei
  138. if gasLimit == 0 {
  139. auth.GasLimit = c.config.CallGasLimit // in units
  140. } else {
  141. auth.GasLimit = gasLimit // in units
  142. }
  143. auth.GasPrice = gasPrice
  144. tx, err := fn(c.client, auth)
  145. if tx != nil {
  146. log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
  147. }
  148. return tx, tracerr.Wrap(err)
  149. }
  150. // ContractData contains the contract data
  151. type ContractData struct {
  152. Address ethCommon.Address
  153. Tx *types.Transaction
  154. Receipt *types.Receipt
  155. }
  156. // Deploy a smart contract. `name` is used to log deployment information. fn
  157. // is a wrapper to the deploy function generated by abigen. In case of error,
  158. // the returned `ContractData` may have some parameters filled depending on the
  159. // kind of error that occurred.
  160. func (c *EthereumClient) Deploy(name string,
  161. fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
  162. var contractData ContractData
  163. log.Infow("Deploying", "contract", name)
  164. tx, err := c.CallAuth(
  165. c.config.DeployGasLimit,
  166. func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  167. addr, tx, _, err := fn(client, auth)
  168. if err != nil {
  169. return nil, tracerr.Wrap(err)
  170. }
  171. contractData.Address = addr
  172. return tx, nil
  173. },
  174. )
  175. if err != nil {
  176. return contractData, tracerr.Wrap(fmt.Errorf(errStrDeploy, name, err))
  177. }
  178. log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
  179. contractData.Tx = tx
  180. receipt, err := c.WaitReceipt(tx)
  181. if err != nil {
  182. return contractData, tracerr.Wrap(fmt.Errorf(errStrWaitReceipt, name, err))
  183. }
  184. contractData.Receipt = receipt
  185. return contractData, nil
  186. }
  187. // Call performs a read only Smart Contract method call.
  188. func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
  189. return fn(c.client)
  190. }
  191. // WaitReceipt will block until a transaction is confirmed. Internally it
  192. // polls the state every 200 milliseconds.
  193. func (c *EthereumClient) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
  194. return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
  195. }
  196. // GetReceipt will check if a transaction is confirmed and return
  197. // immediately, waiting at most 1 second and returning error if the transaction
  198. // is still pending.
  199. func (c *EthereumClient) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
  200. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  201. defer cancel()
  202. return c.waitReceipt(ctx, tx, 0)
  203. }
  204. // EthTransactionReceipt returns the transaction receipt of the given txHash
  205. func (c *EthereumClient) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  206. return c.client.TransactionReceipt(ctx, txHash)
  207. }
  208. func (c *EthereumClient) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
  209. var err error
  210. var receipt *types.Receipt
  211. txHash := tx.Hash()
  212. log.Debugw("Waiting for receipt", "tx", txHash.Hex())
  213. start := time.Now()
  214. for {
  215. receipt, err = c.client.TransactionReceipt(ctx, txHash)
  216. if receipt != nil || time.Since(start) >= timeout {
  217. break
  218. }
  219. time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
  220. }
  221. if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
  222. log.Errorw("Failed transaction", "tx", txHash.Hex())
  223. return receipt, tracerr.Wrap(ErrReceiptStatusFailed)
  224. }
  225. if receipt == nil {
  226. log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txHash.Hex(), "lasterr", err)
  227. return receipt, tracerr.Wrap(ErrReceiptNotReceived)
  228. }
  229. log.Debugw("Successful transaction", "tx", txHash.Hex())
  230. return receipt, tracerr.Wrap(err)
  231. }
  232. // EthLastBlock returns the last block number in the blockchain
  233. func (c *EthereumClient) EthLastBlock() (int64, error) {
  234. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  235. defer cancel()
  236. header, err := c.client.HeaderByNumber(ctx, nil)
  237. if err != nil {
  238. return 0, tracerr.Wrap(err)
  239. }
  240. return header.Number.Int64(), nil
  241. }
  242. // EthHeaderByNumber internally calls ethclient.Client HeaderByNumber
  243. // func (c *EthereumClient) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  244. // return c.client.HeaderByNumber(ctx, number)
  245. // }
  246. // EthBlockByNumber internally calls ethclient.Client BlockByNumber and returns
  247. // *common.Block. If number == -1, the latests known block is returned.
  248. func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
  249. blockNum := big.NewInt(number)
  250. if number == -1 {
  251. blockNum = nil
  252. }
  253. block, err := c.client.BlockByNumber(ctx, blockNum)
  254. if err != nil {
  255. return nil, tracerr.Wrap(err)
  256. }
  257. b := &common.Block{
  258. Num: block.Number().Int64(),
  259. Timestamp: time.Unix(int64(block.Time()), 0),
  260. ParentHash: block.ParentHash(),
  261. Hash: block.Hash(),
  262. }
  263. return b, nil
  264. }
  265. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  266. func (c *EthereumClient) EthERC20Consts(tokenAddress ethCommon.Address) (*ERC20Consts, error) {
  267. // We use the HEZ token smart contract interfacehere because it's an
  268. // ERC20, which allows us to access the standard ERC20 constants.
  269. instance, err := HEZ.NewHEZ(tokenAddress, c.client)
  270. if err != nil {
  271. return nil, tracerr.Wrap(err)
  272. }
  273. name, err := instance.Name(c.opts)
  274. if err != nil {
  275. return nil, tracerr.Wrap(err)
  276. }
  277. symbol, err := instance.Symbol(c.opts)
  278. if err != nil {
  279. return nil, tracerr.Wrap(err)
  280. }
  281. decimals, err := instance.Decimals(c.opts)
  282. if err != nil {
  283. return nil, tracerr.Wrap(err)
  284. }
  285. return &ERC20Consts{
  286. Name: name,
  287. Symbol: symbol,
  288. Decimals: uint64(decimals),
  289. }, nil
  290. }
  291. // Client returns the internal ethclient.Client
  292. func (c *EthereumClient) Client() *ethclient.Client {
  293. return c.client
  294. }
  295. // newCallOpts returns a CallOpts to be used in ethereum calls with a non-zero
  296. // From address. This is a workaround for a bug in ethereumjs-vm that shows up
  297. // in ganache: https://github.com/hermeznetwork/hermez-node/issues/317
  298. func newCallOpts() *bind.CallOpts {
  299. return &bind.CallOpts{
  300. From: ethCommon.HexToAddress("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"),
  301. }
  302. }