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.

910 lines
26 KiB

4 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
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
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
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
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.
4 years ago
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
3 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
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.
4 years ago
Allow serving API only via new cli command - Add new command to the cli/node: `serveapi` that alows serving the API just by connecting to the PostgreSQL database. The mode flag should me passed in order to select whether we are connecting to a synchronizer database or a coordinator database. If `coord` is chosen as mode, the coordinator endpoints can be activated in order to allow inserting l2txs and authorizations into the L2DB. Summary of the implementation details - New SQL table with 3 columns (plus `item_id` pk). The table only contains a single row with `item_id` = 1. Columns: - state: historydb.StateAPI in JSON. This is the struct that is served via the `/state` API endpoint. The node will periodically update this struct and store it int he DB. The api server will query it from the DB to serve it. - config: historydb.NodeConfig in JSON. This struct contains node configuration parameters that the API needs to be aware of. It's updated once every time the node starts. - constants: historydb.Constants in JSON. This struct contains all the hermez network constants gathered via the ethereum client by the node. It's written once every time the node starts. - The HistoryDB contains methods to get and update each one of these columns individually. - The HistoryDB contains all methods that query the DB and prepare objects that will appear in the StateAPI endpoint. - The configuration used in for the `serveapi` cli/node command is defined in `config.APIServer`, and is a subset of `node.Config` in order to allow reusing the same configuration file of the node if desired. - A new object is introduced in the api: `StateAPIUpdater`, which contains all the necessary information to update the StateAPI in the DB periodically by the node. - Moved the types `SCConsts`, `SCVariables` and `SCVariablesPtr` from `syncrhonizer` to `common` for convenience.
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.
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 api
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "math/big"
  10. "net"
  11. "net/http"
  12. "os"
  13. "strconv"
  14. "sync"
  15. "testing"
  16. "time"
  17. ethCommon "github.com/ethereum/go-ethereum/common"
  18. swagger "github.com/getkin/kin-openapi/openapi3filter"
  19. "github.com/gin-gonic/gin"
  20. "github.com/hermeznetwork/hermez-node/api/stateapiupdater"
  21. "github.com/hermeznetwork/hermez-node/common"
  22. "github.com/hermeznetwork/hermez-node/db"
  23. "github.com/hermeznetwork/hermez-node/db/historydb"
  24. "github.com/hermeznetwork/hermez-node/db/l2db"
  25. "github.com/hermeznetwork/hermez-node/log"
  26. "github.com/hermeznetwork/hermez-node/test"
  27. "github.com/hermeznetwork/hermez-node/test/til"
  28. "github.com/hermeznetwork/hermez-node/test/txsets"
  29. "github.com/hermeznetwork/tracerr"
  30. "github.com/stretchr/testify/require"
  31. )
  32. // Pendinger is an interface that allows getting last returned item ID and PendingItems to be used for building fromItem
  33. // when testing paginated endpoints.
  34. type Pendinger interface {
  35. GetPending() (pendingItems, lastItemID uint64)
  36. Len() int
  37. New() Pendinger
  38. }
  39. const apiPort = "4010"
  40. const apiURL = "http://localhost:" + apiPort + "/v1/"
  41. var SetBlockchain = `
  42. Type: Blockchain
  43. AddToken(1)
  44. AddToken(2)
  45. AddToken(3)
  46. AddToken(4)
  47. AddToken(5)
  48. AddToken(6)
  49. AddToken(7)
  50. AddToken(8)
  51. > block
  52. // Coordinator accounts, Idxs: 256, 257
  53. CreateAccountCoordinator(0) Coord
  54. CreateAccountCoordinator(1) Coord
  55. // close Block:0, Batch:1
  56. > batch
  57. CreateAccountDeposit(0) A: 11100000000000000
  58. CreateAccountDeposit(1) C: 22222222200000000000
  59. CreateAccountCoordinator(0) C
  60. // close Block:0, Batch:2
  61. > batchL1
  62. // Expected balances:
  63. // Coord(0): 0, Coord(1): 0
  64. // C(0): 0
  65. CreateAccountDeposit(1) A: 33333333300000000000
  66. // close Block:0, Batch:3
  67. > batchL1
  68. // close Block:0, Batch:4
  69. > batchL1
  70. CreateAccountDepositTransfer(0) B-A: 44444444400000000000, 123444444400000000000
  71. // close Block:0, Batch:5
  72. > batchL1
  73. CreateAccountDeposit(0) D: 55555555500000000000
  74. // close Block:0, Batch:6
  75. > batchL1
  76. CreateAccountCoordinator(1) B
  77. Transfer(1) A-B: 11100000000000000 (2)
  78. Transfer(0) B-C: 22200000000000000 (3)
  79. // close Block:0, Batch:7
  80. > batchL1 // forge L1User{1}, forge L1Coord{2}, forge L2{2}
  81. Deposit(0) C: 66666666600000000000
  82. DepositTransfer(0) C-D: 77777777700000000000, 12377777700000000000
  83. Transfer(0) A-B: 33350000000000000 (111)
  84. Transfer(0) C-A: 44450000000000000 (222)
  85. Transfer(1) B-C: 55550000000000000 (123)
  86. Exit(0) A: 66650000000000000 (44)
  87. ForceTransfer(0) D-B: 77777700000000000
  88. ForceExit(0) B: 88888800000000000
  89. // close Block:0, Batch:8
  90. > batchL1
  91. > block
  92. Transfer(0) D-A: 99950000000000000 (77)
  93. Transfer(0) B-D: 12300000000000000 (55)
  94. // close Block:1, Batch:1
  95. > batchL1
  96. CreateAccountCoordinator(0) F
  97. CreateAccountCoordinator(0) G
  98. CreateAccountCoordinator(0) H
  99. CreateAccountCoordinator(0) I
  100. CreateAccountCoordinator(0) J
  101. CreateAccountCoordinator(0) K
  102. CreateAccountCoordinator(0) L
  103. CreateAccountCoordinator(0) M
  104. CreateAccountCoordinator(0) N
  105. CreateAccountCoordinator(0) O
  106. CreateAccountCoordinator(0) P
  107. CreateAccountCoordinator(5) G
  108. CreateAccountCoordinator(5) H
  109. CreateAccountCoordinator(5) I
  110. CreateAccountCoordinator(5) J
  111. CreateAccountCoordinator(5) K
  112. CreateAccountCoordinator(5) L
  113. CreateAccountCoordinator(5) M
  114. CreateAccountCoordinator(5) N
  115. CreateAccountCoordinator(5) O
  116. CreateAccountCoordinator(5) P
  117. CreateAccountCoordinator(2) G
  118. CreateAccountCoordinator(2) H
  119. CreateAccountCoordinator(2) I
  120. CreateAccountCoordinator(2) J
  121. CreateAccountCoordinator(2) K
  122. CreateAccountCoordinator(2) L
  123. CreateAccountCoordinator(2) M
  124. CreateAccountCoordinator(2) N
  125. CreateAccountCoordinator(2) O
  126. CreateAccountCoordinator(2) P
  127. > batch
  128. > block
  129. > batch
  130. > block
  131. > batch
  132. > block
  133. `
  134. type testCommon struct {
  135. blocks []common.Block
  136. tokens []historydb.TokenWithUSD
  137. batches []testBatch
  138. fullBatches []testFullBatch
  139. coordinators []historydb.CoordinatorAPI
  140. accounts []testAccount
  141. txs []testTx
  142. exits []testExit
  143. poolTxsToSend []testPoolTxSend
  144. poolTxsToReceive []testPoolTxReceive
  145. auths []testAuth
  146. router *swagger.Router
  147. bids []testBid
  148. slots []testSlot
  149. auctionVars common.AuctionVariables
  150. rollupVars common.RollupVariables
  151. wdelayerVars common.WDelayerVariables
  152. nextForgers []historydb.NextForgerAPI
  153. }
  154. var tc testCommon
  155. var config configAPI
  156. var api *API
  157. var stateAPIUpdater *stateapiupdater.Updater
  158. // TestMain initializes the API server, and fill HistoryDB and StateDB with fake data,
  159. // emulating the task of the synchronizer in order to have data to be returned
  160. // by the API endpoints that will be tested
  161. func TestMain(m *testing.M) {
  162. // Initializations
  163. // Swagger
  164. router := swagger.NewRouter().WithSwaggerFromFile("./swagger.yml")
  165. // HistoryDB
  166. pass := os.Getenv("POSTGRES_PASS")
  167. database, err := db.InitSQLDB(5432, "localhost", "hermez", pass, "hermez")
  168. if err != nil {
  169. panic(err)
  170. }
  171. apiConnCon := db.NewAPIConnectionController(1, time.Second)
  172. hdb := historydb.NewHistoryDB(database, database, apiConnCon)
  173. if err != nil {
  174. panic(err)
  175. }
  176. // L2DB
  177. l2DB := l2db.NewL2DB(database, database, 10, 1000, 0.0, 1000.0, 24*time.Hour, apiConnCon)
  178. test.WipeDB(l2DB.DB()) // this will clean HistoryDB and L2DB
  179. // Config (smart contract constants)
  180. chainID := uint16(0)
  181. _config := getConfigTest(chainID)
  182. config = configAPI{
  183. ChainID: chainID,
  184. RollupConstants: *newRollupConstants(_config.RollupConstants),
  185. AuctionConstants: _config.AuctionConstants,
  186. WDelayerConstants: _config.WDelayerConstants,
  187. }
  188. // API
  189. apiGin := gin.Default()
  190. // Reset DB
  191. test.WipeDB(hdb.DB())
  192. constants := &historydb.Constants{
  193. SCConsts: common.SCConsts{
  194. Rollup: _config.RollupConstants,
  195. Auction: _config.AuctionConstants,
  196. WDelayer: _config.WDelayerConstants,
  197. },
  198. ChainID: chainID,
  199. HermezAddress: _config.HermezAddress,
  200. }
  201. if err := hdb.SetConstants(constants); err != nil {
  202. panic(err)
  203. }
  204. nodeConfig := &historydb.NodeConfig{
  205. MaxPoolTxs: 10,
  206. MinFeeUSD: 0,
  207. MaxFeeUSD: 10000000000,
  208. }
  209. if err := hdb.SetNodeConfig(nodeConfig); err != nil {
  210. panic(err)
  211. }
  212. api, err = NewAPI(
  213. true,
  214. true,
  215. apiGin,
  216. hdb,
  217. l2DB,
  218. )
  219. if err != nil {
  220. log.Error(err)
  221. panic(err)
  222. }
  223. // Start server
  224. listener, err := net.Listen("tcp", ":"+apiPort) //nolint:gosec
  225. if err != nil {
  226. panic(err)
  227. }
  228. server := &http.Server{Handler: apiGin}
  229. go func() {
  230. if err := server.Serve(listener); err != nil &&
  231. tracerr.Unwrap(err) != http.ErrServerClosed {
  232. panic(err)
  233. }
  234. }()
  235. // Generate blockchain data with til
  236. tcc := til.NewContext(chainID, common.RollupConstMaxL1UserTx)
  237. tilCfgExtra := til.ConfigExtra{
  238. BootCoordAddr: ethCommon.HexToAddress("0xE39fEc6224708f0772D2A74fd3f9055A90E0A9f2"),
  239. CoordUser: "Coord",
  240. }
  241. blocksData, err := tcc.GenerateBlocks(SetBlockchain)
  242. if err != nil {
  243. panic(err)
  244. }
  245. err = tcc.FillBlocksExtra(blocksData, &tilCfgExtra)
  246. if err != nil {
  247. panic(err)
  248. }
  249. err = tcc.FillBlocksForgedL1UserTxs(blocksData)
  250. if err != nil {
  251. panic(err)
  252. }
  253. AddAditionalInformation(blocksData)
  254. // Generate L2 Txs with til
  255. commonPoolTxs, err := tcc.GeneratePoolL2Txs(txsets.SetPoolL2MinimumFlow0)
  256. if err != nil {
  257. panic(err)
  258. }
  259. // Extract til generated data, and add it to HistoryDB
  260. var commonBlocks []common.Block
  261. var commonBatches []common.Batch
  262. var commonAccounts []common.Account
  263. var commonExitTree []common.ExitInfo
  264. var commonL1Txs []common.L1Tx
  265. var commonL2Txs []common.L2Tx
  266. // Add ETH token at the beginning of the array
  267. testTokens := []historydb.TokenWithUSD{}
  268. ethUSD := float64(500)
  269. ethNow := time.Now()
  270. testTokens = append(testTokens, historydb.TokenWithUSD{
  271. TokenID: test.EthToken.TokenID,
  272. EthBlockNum: test.EthToken.EthBlockNum,
  273. EthAddr: test.EthToken.EthAddr,
  274. Name: test.EthToken.Name,
  275. Symbol: test.EthToken.Symbol,
  276. Decimals: test.EthToken.Decimals,
  277. USD: &ethUSD,
  278. USDUpdate: &ethNow,
  279. })
  280. err = api.h.UpdateTokenValue(common.EmptyAddr, ethUSD)
  281. if err != nil {
  282. panic(err)
  283. }
  284. for _, block := range blocksData {
  285. // Insert block into HistoryDB
  286. // nolint reason: block is used as read only in the function
  287. if err := api.h.AddBlockSCData(&block); err != nil { //nolint:gosec
  288. log.Error(err)
  289. panic(err)
  290. }
  291. // Extract data
  292. commonBlocks = append(commonBlocks, block.Block)
  293. for i, tkn := range block.Rollup.AddedTokens {
  294. token := historydb.TokenWithUSD{
  295. TokenID: tkn.TokenID,
  296. EthBlockNum: tkn.EthBlockNum,
  297. EthAddr: tkn.EthAddr,
  298. Name: tkn.Name,
  299. Symbol: tkn.Symbol,
  300. Decimals: tkn.Decimals,
  301. }
  302. value := float64(i + 423)
  303. now := time.Now().UTC()
  304. token.USD = &value
  305. token.USDUpdate = &now
  306. // Set value in DB
  307. err = api.h.UpdateTokenValue(token.EthAddr, value)
  308. if err != nil {
  309. panic(err)
  310. }
  311. testTokens = append(testTokens, token)
  312. }
  313. // Set USD value for tokens in DB
  314. for _, batch := range block.Rollup.Batches {
  315. commonL2Txs = append(commonL2Txs, batch.L2Txs...)
  316. for i := range batch.CreatedAccounts {
  317. batch.CreatedAccounts[i].Nonce = common.Nonce(i)
  318. commonAccounts = append(commonAccounts, batch.CreatedAccounts[i])
  319. }
  320. commonBatches = append(commonBatches, batch.Batch)
  321. commonExitTree = append(commonExitTree, batch.ExitTree...)
  322. commonL1Txs = append(commonL1Txs, batch.L1UserTxs...)
  323. commonL1Txs = append(commonL1Txs, batch.L1CoordinatorTxs...)
  324. }
  325. }
  326. // Generate Coordinators and add them to HistoryDB
  327. const nCoords = 10
  328. commonCoords := test.GenCoordinators(nCoords, commonBlocks)
  329. // Update one coordinator to test behaviour when bidder address is repeated
  330. updatedCoordBlock := commonCoords[len(commonCoords)-1].EthBlockNum
  331. commonCoords = append(commonCoords, common.Coordinator{
  332. Bidder: commonCoords[0].Bidder,
  333. Forger: commonCoords[0].Forger,
  334. EthBlockNum: updatedCoordBlock,
  335. URL: commonCoords[0].URL + ".new",
  336. })
  337. if err := api.h.AddCoordinators(commonCoords); err != nil {
  338. panic(err)
  339. }
  340. // Test next forgers
  341. // Set auction vars
  342. // Slots 3 and 6 will have bids that will be invalidated because of minBid update
  343. // Slots 4 and 7 will have valid bids, the rest will be cordinator slots
  344. var slot3MinBid int64 = 3
  345. var slot4MinBid int64 = 4
  346. var slot6MinBid int64 = 6
  347. var slot7MinBid int64 = 7
  348. // First update will indicate how things behave from slot 0
  349. var defaultSlotSetBid [6]*big.Int = [6]*big.Int{
  350. big.NewInt(10), // Slot 0 min bid
  351. big.NewInt(10), // Slot 1 min bid
  352. big.NewInt(10), // Slot 2 min bid
  353. big.NewInt(slot3MinBid), // Slot 3 min bid
  354. big.NewInt(slot4MinBid), // Slot 4 min bid
  355. big.NewInt(10), // Slot 5 min bid
  356. }
  357. auctionVars := common.AuctionVariables{
  358. EthBlockNum: int64(2),
  359. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  360. DefaultSlotSetBid: defaultSlotSetBid,
  361. DefaultSlotSetBidSlotNum: 0,
  362. Outbidding: uint16(1),
  363. SlotDeadline: uint8(20),
  364. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  365. BootCoordinatorURL: "https://boot.coordinator.io",
  366. ClosedAuctionSlots: uint16(10),
  367. OpenAuctionSlots: uint16(20),
  368. }
  369. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  370. panic(err)
  371. }
  372. // Last update in auction vars will indicate how things will behave from slot 5
  373. defaultSlotSetBid = [6]*big.Int{
  374. big.NewInt(10), // Slot 5 min bid
  375. big.NewInt(slot6MinBid), // Slot 6 min bid
  376. big.NewInt(slot7MinBid), // Slot 7 min bid
  377. big.NewInt(10), // Slot 8 min bid
  378. big.NewInt(10), // Slot 9 min bid
  379. big.NewInt(10), // Slot 10 min bid
  380. }
  381. auctionVars = common.AuctionVariables{
  382. EthBlockNum: int64(3),
  383. DonationAddress: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  384. DefaultSlotSetBid: defaultSlotSetBid,
  385. DefaultSlotSetBidSlotNum: 5,
  386. Outbidding: uint16(1),
  387. SlotDeadline: uint8(20),
  388. BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),
  389. BootCoordinatorURL: "https://boot.coordinator.io",
  390. ClosedAuctionSlots: uint16(10),
  391. OpenAuctionSlots: uint16(20),
  392. }
  393. if err := api.h.AddAuctionVars(&auctionVars); err != nil {
  394. panic(err)
  395. }
  396. // Generate Bids and add them to HistoryDB
  397. bids := []common.Bid{}
  398. // Slot 1 and 2, no bids, wins boot coordinator
  399. // Slot 3, below what's going to be the minimum (wins boot coordinator)
  400. bids = append(bids, common.Bid{
  401. SlotNum: 3,
  402. BidValue: big.NewInt(slot3MinBid - 1),
  403. EthBlockNum: commonBlocks[0].Num,
  404. Bidder: commonCoords[0].Bidder,
  405. })
  406. // Slot 4, valid bid (wins bidder)
  407. bids = append(bids, common.Bid{
  408. SlotNum: 4,
  409. BidValue: big.NewInt(slot4MinBid),
  410. EthBlockNum: commonBlocks[0].Num,
  411. Bidder: commonCoords[0].Bidder,
  412. })
  413. // Slot 5 no bids, wins boot coordinator
  414. // Slot 6, below what's going to be the minimum (wins boot coordinator)
  415. bids = append(bids, common.Bid{
  416. SlotNum: 6,
  417. BidValue: big.NewInt(slot6MinBid - 1),
  418. EthBlockNum: commonBlocks[0].Num,
  419. Bidder: commonCoords[0].Bidder,
  420. })
  421. // Slot 7, valid bid (wins bidder)
  422. bids = append(bids, common.Bid{
  423. SlotNum: 7,
  424. BidValue: big.NewInt(slot7MinBid),
  425. EthBlockNum: commonBlocks[0].Num,
  426. Bidder: commonCoords[0].Bidder,
  427. })
  428. if err = api.h.AddBids(bids); err != nil {
  429. panic(err)
  430. }
  431. bootForger := historydb.NextForgerAPI{
  432. Coordinator: historydb.CoordinatorAPI{
  433. Forger: auctionVars.BootCoordinator,
  434. URL: auctionVars.BootCoordinatorURL,
  435. },
  436. }
  437. // Set next forgers: set all as boot coordinator then replace the non boot coordinators
  438. nextForgers := []historydb.NextForgerAPI{}
  439. var initBlock int64 = 140
  440. var deltaBlocks int64 = 40
  441. for i := 1; i < int(auctionVars.ClosedAuctionSlots)+2; i++ {
  442. fromBlock := initBlock + deltaBlocks*int64(i-1)
  443. bootForger.Period = historydb.Period{
  444. SlotNum: int64(i),
  445. FromBlock: fromBlock,
  446. ToBlock: fromBlock + deltaBlocks - 1,
  447. }
  448. nextForgers = append(nextForgers, bootForger)
  449. }
  450. // Set next forgers that aren't the boot coordinator
  451. nonBootForger := historydb.CoordinatorAPI{
  452. Bidder: commonCoords[0].Bidder,
  453. Forger: commonCoords[0].Forger,
  454. URL: commonCoords[0].URL + ".new",
  455. }
  456. // Slot 4
  457. nextForgers[3].Coordinator = nonBootForger
  458. // Slot 7
  459. nextForgers[6].Coordinator = nonBootForger
  460. var buckets [common.RollupConstNumBuckets]common.BucketParams
  461. for i := range buckets {
  462. buckets[i].CeilUSD = big.NewInt(int64(i) * 10)
  463. buckets[i].Withdrawals = big.NewInt(int64(i) * 100)
  464. buckets[i].BlockWithdrawalRate = big.NewInt(int64(i) * 1000)
  465. buckets[i].MaxWithdrawals = big.NewInt(int64(i) * 10000)
  466. }
  467. // Generate SC vars and add them to HistoryDB (if needed)
  468. rollupVars := common.RollupVariables{
  469. EthBlockNum: int64(3),
  470. FeeAddToken: big.NewInt(100),
  471. ForgeL1L2BatchTimeout: int64(44),
  472. WithdrawalDelay: uint64(3000),
  473. Buckets: buckets,
  474. SafeMode: false,
  475. }
  476. wdelayerVars := common.WDelayerVariables{
  477. WithdrawalDelay: uint64(3000),
  478. }
  479. stateAPIUpdater, err = stateapiupdater.NewUpdater(hdb, nodeConfig, &common.SCVariables{
  480. Rollup: rollupVars,
  481. Auction: auctionVars,
  482. WDelayer: wdelayerVars,
  483. }, constants, &stateapiupdater.RecommendedFeePolicy{
  484. PolicyType: stateapiupdater.RecommendedFeePolicyTypeAvgLastHour,
  485. })
  486. if err != nil {
  487. panic(err)
  488. }
  489. // Generate test data, as expected to be received/sended from/to the API
  490. testCoords := genTestCoordinators(commonCoords)
  491. testBids := genTestBids(commonBlocks, testCoords, bids)
  492. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  493. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  494. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  495. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  496. // Add balance and nonce to historyDB
  497. accounts := genTestAccounts(commonAccounts, testTokens)
  498. accUpdates := []common.AccountUpdate{}
  499. for i := 0; i < len(accounts); i++ {
  500. balance := new(big.Int)
  501. balance.SetString(string(*accounts[i].Balance), 10)
  502. idx, err := stringToIdx(string(accounts[i].Idx), "foo")
  503. if err != nil {
  504. panic(err)
  505. }
  506. accUpdates = append(accUpdates, common.AccountUpdate{
  507. EthBlockNum: 0,
  508. BatchNum: 1,
  509. Idx: *idx,
  510. Nonce: 0,
  511. Balance: balance,
  512. })
  513. accUpdates = append(accUpdates, common.AccountUpdate{
  514. EthBlockNum: 0,
  515. BatchNum: 1,
  516. Idx: *idx,
  517. Nonce: accounts[i].Nonce,
  518. Balance: balance,
  519. })
  520. }
  521. if err := api.h.AddAccountUpdates(accUpdates); err != nil {
  522. panic(err)
  523. }
  524. tc = testCommon{
  525. blocks: commonBlocks,
  526. tokens: testTokens,
  527. batches: testBatches,
  528. fullBatches: testFullBatches,
  529. coordinators: testCoords,
  530. accounts: accounts,
  531. txs: testTxs,
  532. exits: testExits,
  533. poolTxsToSend: poolTxsToSend,
  534. poolTxsToReceive: poolTxsToReceive,
  535. auths: genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
  536. router: router,
  537. bids: testBids,
  538. slots: api.genTestSlots(
  539. 20,
  540. commonBlocks[len(commonBlocks)-1].Num,
  541. testBids,
  542. auctionVars,
  543. ),
  544. auctionVars: auctionVars,
  545. rollupVars: rollupVars,
  546. wdelayerVars: wdelayerVars,
  547. nextForgers: nextForgers,
  548. }
  549. // Run tests
  550. result := m.Run()
  551. // Fake server
  552. if os.Getenv("FAKE_SERVER") == "yes" {
  553. for {
  554. log.Info("Running fake server at " + apiURL + " until ^C is received")
  555. time.Sleep(30 * time.Second)
  556. }
  557. }
  558. // Stop server
  559. if err := server.Shutdown(context.Background()); err != nil {
  560. panic(err)
  561. }
  562. if err := database.Close(); err != nil {
  563. panic(err)
  564. }
  565. os.Exit(result)
  566. }
  567. func TestTimeout(t *testing.T) {
  568. pass := os.Getenv("POSTGRES_PASS")
  569. databaseTO, err := db.ConnectSQLDB(5432, "localhost", "hermez", pass, "hermez")
  570. require.NoError(t, err)
  571. apiConnConTO := db.NewAPIConnectionController(1, 100*time.Millisecond)
  572. hdbTO := historydb.NewHistoryDB(databaseTO, databaseTO, apiConnConTO)
  573. require.NoError(t, err)
  574. // L2DB
  575. l2DBTO := l2db.NewL2DB(databaseTO, databaseTO, 10, 1000, 1.0, 1000.0, 24*time.Hour, apiConnConTO)
  576. // API
  577. apiGinTO := gin.Default()
  578. finishWait := make(chan interface{})
  579. startWait := make(chan interface{})
  580. apiGinTO.GET("/v1/wait", func(c *gin.Context) {
  581. cancel, err := apiConnConTO.Acquire()
  582. defer cancel()
  583. require.NoError(t, err)
  584. defer apiConnConTO.Release()
  585. startWait <- nil
  586. <-finishWait
  587. })
  588. // Start server
  589. serverTO := &http.Server{Handler: apiGinTO}
  590. listener, err := net.Listen("tcp", ":4444") //nolint:gosec
  591. require.NoError(t, err)
  592. go func() {
  593. if err := serverTO.Serve(listener); err != nil &&
  594. tracerr.Unwrap(err) != http.ErrServerClosed {
  595. require.NoError(t, err)
  596. }
  597. }()
  598. _, err = NewAPI(
  599. true,
  600. true,
  601. apiGinTO,
  602. hdbTO,
  603. l2DBTO,
  604. )
  605. require.NoError(t, err)
  606. client := &http.Client{}
  607. httpReq, err := http.NewRequest("GET", "http://localhost:4444/v1/tokens", nil)
  608. require.NoError(t, err)
  609. httpReqWait, err := http.NewRequest("GET", "http://localhost:4444/v1/wait", nil)
  610. require.NoError(t, err)
  611. // Request that will get timed out
  612. var wg sync.WaitGroup
  613. wg.Add(1)
  614. go func() {
  615. // Request that will make the API busy
  616. _, err = client.Do(httpReqWait)
  617. require.NoError(t, err)
  618. wg.Done()
  619. }()
  620. <-startWait
  621. resp, err := client.Do(httpReq)
  622. require.NoError(t, err)
  623. require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
  624. defer resp.Body.Close() //nolint
  625. body, err := ioutil.ReadAll(resp.Body)
  626. require.NoError(t, err)
  627. // Unmarshal body into return struct
  628. msg := &errorMsg{}
  629. err = json.Unmarshal(body, msg)
  630. require.NoError(t, err)
  631. // Check that the error was the expected down
  632. require.Equal(t, errSQLTimeout, msg.Message)
  633. finishWait <- nil
  634. // Stop server
  635. wg.Wait()
  636. require.NoError(t, serverTO.Shutdown(context.Background()))
  637. require.NoError(t, databaseTO.Close())
  638. }
  639. func doGoodReqPaginated(
  640. path, order string,
  641. iterStruct Pendinger,
  642. appendIter func(res interface{}),
  643. ) error {
  644. var next uint64
  645. firstIte := true
  646. expectedTotal := 0
  647. totalReceived := 0
  648. for {
  649. // Calculate fromItem
  650. iterPath := path
  651. if !firstIte {
  652. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  653. }
  654. // Call API to get this iteration items
  655. iterStruct = iterStruct.New()
  656. if err := doGoodReq(
  657. "GET", iterPath+"&order="+order, nil,
  658. iterStruct,
  659. ); err != nil {
  660. return tracerr.Wrap(err)
  661. }
  662. appendIter(iterStruct)
  663. // Keep iterating?
  664. remaining, lastID := iterStruct.GetPending()
  665. if remaining == 0 {
  666. break
  667. }
  668. if order == historydb.OrderDesc {
  669. next = lastID - 1
  670. } else {
  671. next = lastID + 1
  672. }
  673. // Check that the expected amount of items is consistent across iterations
  674. totalReceived += iterStruct.Len()
  675. if firstIte {
  676. firstIte = false
  677. expectedTotal = totalReceived + int(remaining)
  678. }
  679. if expectedTotal != totalReceived+int(remaining) {
  680. panic(fmt.Sprintf(
  681. "pagination error, totalReceived + remaining should be %d, but is %d",
  682. expectedTotal, totalReceived+int(remaining),
  683. ))
  684. }
  685. }
  686. return nil
  687. }
  688. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  689. ctx := context.Background()
  690. client := &http.Client{}
  691. httpReq, err := http.NewRequest(method, path, reqBody)
  692. if err != nil {
  693. return tracerr.Wrap(err)
  694. }
  695. if reqBody != nil {
  696. httpReq.Header.Add("Content-Type", "application/json")
  697. }
  698. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  699. if err != nil {
  700. return tracerr.Wrap(err)
  701. }
  702. // Validate request against swagger spec
  703. requestValidationInput := &swagger.RequestValidationInput{
  704. Request: httpReq,
  705. PathParams: pathParams,
  706. Route: route,
  707. }
  708. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  709. return tracerr.Wrap(err)
  710. }
  711. // Do API call
  712. resp, err := client.Do(httpReq)
  713. if err != nil {
  714. return tracerr.Wrap(err)
  715. }
  716. if resp.Body == nil && returnStruct != nil {
  717. return tracerr.Wrap(errors.New("Nil body"))
  718. }
  719. //nolint
  720. defer resp.Body.Close()
  721. body, err := ioutil.ReadAll(resp.Body)
  722. if err != nil {
  723. return tracerr.Wrap(err)
  724. }
  725. if resp.StatusCode != 200 {
  726. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  727. }
  728. if returnStruct == nil {
  729. return nil
  730. }
  731. // Unmarshal body into return struct
  732. if err := json.Unmarshal(body, returnStruct); err != nil {
  733. log.Error("invalid json: " + string(body))
  734. log.Error(err)
  735. return tracerr.Wrap(err)
  736. }
  737. // log.Info(string(body))
  738. // Validate response against swagger spec
  739. responseValidationInput := &swagger.ResponseValidationInput{
  740. RequestValidationInput: requestValidationInput,
  741. Status: resp.StatusCode,
  742. Header: resp.Header,
  743. }
  744. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  745. return swagger.ValidateResponse(ctx, responseValidationInput)
  746. }
  747. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  748. ctx := context.Background()
  749. client := &http.Client{}
  750. httpReq, _ := http.NewRequest(method, path, reqBody)
  751. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  752. if err != nil {
  753. return tracerr.Wrap(err)
  754. }
  755. // Validate request against swagger spec
  756. requestValidationInput := &swagger.RequestValidationInput{
  757. Request: httpReq,
  758. PathParams: pathParams,
  759. Route: route,
  760. }
  761. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  762. if expectedResponseCode != 400 {
  763. return tracerr.Wrap(err)
  764. }
  765. log.Warn("The request does not match the API spec")
  766. }
  767. // Do API call
  768. resp, err := client.Do(httpReq)
  769. if err != nil {
  770. return tracerr.Wrap(err)
  771. }
  772. if resp.Body == nil {
  773. return tracerr.Wrap(errors.New("Nil body"))
  774. }
  775. //nolint
  776. defer resp.Body.Close()
  777. body, err := ioutil.ReadAll(resp.Body)
  778. if err != nil {
  779. return tracerr.Wrap(err)
  780. }
  781. if resp.StatusCode != expectedResponseCode {
  782. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  783. }
  784. // Validate response against swagger spec
  785. responseValidationInput := &swagger.ResponseValidationInput{
  786. RequestValidationInput: requestValidationInput,
  787. Status: resp.StatusCode,
  788. Header: resp.Header,
  789. }
  790. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  791. return swagger.ValidateResponse(ctx, responseValidationInput)
  792. }
  793. // test helpers
  794. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  795. for i := 0; i < len(blocks); i++ {
  796. if blocks[i].Num == blockNum {
  797. return blocks[i].Timestamp
  798. }
  799. }
  800. panic("timesamp not found")
  801. }
  802. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  803. for i := 0; i < len(tokens); i++ {
  804. if tokens[i].TokenID == id {
  805. return tokens[i]
  806. }
  807. }
  808. panic("token not found")
  809. }
  810. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  811. for _, acc := range accs {
  812. if idx == acc.Idx {
  813. return getTokenByID(acc.TokenID, tokens)
  814. }
  815. }
  816. panic("token not found")
  817. }
  818. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  819. for _, acc := range accs {
  820. if acc.Idx == idx {
  821. return &acc
  822. }
  823. }
  824. panic("account not found")
  825. }
  826. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  827. for _, b := range blocks {
  828. if b.Num == ethBlockNum {
  829. return b
  830. }
  831. }
  832. panic("block not found")
  833. }
  834. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  835. var coordLastUpdate historydb.CoordinatorAPI
  836. found := false
  837. for _, c := range coordinators {
  838. if c.Bidder == bidder {
  839. coordLastUpdate = c
  840. found = true
  841. }
  842. }
  843. if !found {
  844. panic("coordinator not found")
  845. }
  846. return coordLastUpdate
  847. }