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.

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