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.

331 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. }
  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
  60. IntervalReceiptLoop time.Duration
  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. // TODO: Set the correct chainID
  124. auth, err := bind.NewKeyStoreTransactorWithChainID(c.ks, *c.account, big.NewInt(0))
  125. if err != nil {
  126. return nil, tracerr.Wrap(err)
  127. }
  128. auth.Value = big.NewInt(0) // in wei
  129. if gasLimit == 0 {
  130. auth.GasLimit = c.config.CallGasLimit // in units
  131. } else {
  132. auth.GasLimit = gasLimit // in units
  133. }
  134. auth.GasPrice = gasPrice
  135. tx, err := fn(c.client, auth)
  136. if tx != nil {
  137. log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce())
  138. }
  139. return tx, tracerr.Wrap(err)
  140. }
  141. // ContractData contains the contract data
  142. type ContractData struct {
  143. Address ethCommon.Address
  144. Tx *types.Transaction
  145. Receipt *types.Receipt
  146. }
  147. // Deploy a smart contract. `name` is used to log deployment information. fn
  148. // is a wrapper to the deploy function generated by abigen. In case of error,
  149. // the returned `ContractData` may have some parameters filled depending on the
  150. // kind of error that occurred.
  151. func (c *EthereumClient) Deploy(name string,
  152. fn func(c *ethclient.Client, auth *bind.TransactOpts) (ethCommon.Address, *types.Transaction, interface{}, error)) (ContractData, error) {
  153. var contractData ContractData
  154. log.Infow("Deploying", "contract", name)
  155. tx, err := c.CallAuth(
  156. c.config.DeployGasLimit,
  157. func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {
  158. addr, tx, _, err := fn(client, auth)
  159. if err != nil {
  160. return nil, tracerr.Wrap(err)
  161. }
  162. contractData.Address = addr
  163. return tx, nil
  164. },
  165. )
  166. if err != nil {
  167. return contractData, tracerr.Wrap(fmt.Errorf(errStrDeploy, name, err))
  168. }
  169. log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name)
  170. contractData.Tx = tx
  171. receipt, err := c.WaitReceipt(tx)
  172. if err != nil {
  173. return contractData, tracerr.Wrap(fmt.Errorf(errStrWaitReceipt, name, err))
  174. }
  175. contractData.Receipt = receipt
  176. return contractData, nil
  177. }
  178. // Call performs a read only Smart Contract method call.
  179. func (c *EthereumClient) Call(fn func(*ethclient.Client) error) error {
  180. return fn(c.client)
  181. }
  182. // WaitReceipt will block until a transaction is confirmed. Internally it
  183. // polls the state every 200 milliseconds.
  184. func (c *EthereumClient) WaitReceipt(tx *types.Transaction) (*types.Receipt, error) {
  185. return c.waitReceipt(context.TODO(), tx, c.ReceiptTimeout)
  186. }
  187. // GetReceipt will check if a transaction is confirmed and return
  188. // immediately, waiting at most 1 second and returning error if the transaction
  189. // is still pending.
  190. func (c *EthereumClient) GetReceipt(tx *types.Transaction) (*types.Receipt, error) {
  191. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  192. defer cancel()
  193. return c.waitReceipt(ctx, tx, 0)
  194. }
  195. // EthTransactionReceipt returns the transaction receipt of the given txHash
  196. func (c *EthereumClient) EthTransactionReceipt(ctx context.Context, txHash ethCommon.Hash) (*types.Receipt, error) {
  197. return c.client.TransactionReceipt(ctx, txHash)
  198. }
  199. func (c *EthereumClient) waitReceipt(ctx context.Context, tx *types.Transaction, timeout time.Duration) (*types.Receipt, error) {
  200. var err error
  201. var receipt *types.Receipt
  202. txHash := tx.Hash()
  203. log.Debugw("Waiting for receipt", "tx", txHash.Hex())
  204. start := time.Now()
  205. for {
  206. receipt, err = c.client.TransactionReceipt(ctx, txHash)
  207. if receipt != nil || time.Since(start) >= timeout {
  208. break
  209. }
  210. time.Sleep(c.config.IntervalReceiptLoop * time.Millisecond)
  211. }
  212. if receipt != nil && receipt.Status == types.ReceiptStatusFailed {
  213. log.Errorw("Failed transaction", "tx", txHash.Hex())
  214. return receipt, tracerr.Wrap(ErrReceiptStatusFailed)
  215. }
  216. if receipt == nil {
  217. log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txHash.Hex(), "lasterr", err)
  218. return receipt, tracerr.Wrap(ErrReceiptNotReceived)
  219. }
  220. log.Debugw("Successful transaction", "tx", txHash.Hex())
  221. return receipt, tracerr.Wrap(err)
  222. }
  223. // EthLastBlock returns the last block number in the blockchain
  224. func (c *EthereumClient) EthLastBlock() (int64, error) {
  225. ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)
  226. defer cancel()
  227. header, err := c.client.HeaderByNumber(ctx, nil)
  228. if err != nil {
  229. return 0, tracerr.Wrap(err)
  230. }
  231. return header.Number.Int64(), nil
  232. }
  233. // EthHeaderByNumber internally calls ethclient.Client HeaderByNumber
  234. // func (c *EthereumClient) EthHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
  235. // return c.client.HeaderByNumber(ctx, number)
  236. // }
  237. // EthBlockByNumber internally calls ethclient.Client BlockByNumber and returns
  238. // *common.Block. If number == -1, the latests known block is returned.
  239. func (c *EthereumClient) EthBlockByNumber(ctx context.Context, number int64) (*common.Block, error) {
  240. blockNum := big.NewInt(number)
  241. if number == -1 {
  242. blockNum = nil
  243. }
  244. block, err := c.client.BlockByNumber(ctx, blockNum)
  245. if err != nil {
  246. return nil, tracerr.Wrap(err)
  247. }
  248. b := &common.Block{
  249. Num: block.Number().Int64(),
  250. Timestamp: time.Unix(int64(block.Time()), 0),
  251. ParentHash: block.ParentHash(),
  252. Hash: block.Hash(),
  253. }
  254. return b, nil
  255. }
  256. // EthERC20Consts returns the constants defined for a particular ERC20 Token instance.
  257. func (c *EthereumClient) EthERC20Consts(tokenAddress ethCommon.Address) (*ERC20Consts, error) {
  258. // We use the HEZ token smart contract interfacehere because it's an
  259. // ERC20, which allows us to access the standard ERC20 constants.
  260. instance, err := HEZ.NewHEZ(tokenAddress, c.client)
  261. if err != nil {
  262. return nil, tracerr.Wrap(err)
  263. }
  264. name, err := instance.Name(c.opts)
  265. if err != nil {
  266. return nil, tracerr.Wrap(err)
  267. }
  268. symbol, err := instance.Symbol(c.opts)
  269. if err != nil {
  270. return nil, tracerr.Wrap(err)
  271. }
  272. decimals, err := instance.Decimals(c.opts)
  273. if err != nil {
  274. return nil, tracerr.Wrap(err)
  275. }
  276. return &ERC20Consts{
  277. Name: name,
  278. Symbol: symbol,
  279. Decimals: uint64(decimals),
  280. }, nil
  281. }
  282. // Client returns the internal ethclient.Client
  283. func (c *EthereumClient) Client() *ethclient.Client {
  284. return c.client
  285. }
  286. // newCallOpts returns a CallOpts to be used in ethereum calls with a non-zero
  287. // From address. This is a workaround for a bug in ethereumjs-vm that shows up
  288. // in ganache: https://github.com/hermeznetwork/hermez-node/issues/317
  289. func newCallOpts() *bind.CallOpts {
  290. return &bind.CallOpts{
  291. From: ethCommon.HexToAddress("0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f"),
  292. }
  293. }