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.

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