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.

904 lines
25 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
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 = stateapiupdater.NewUpdater(hdb, nodeConfig, &common.SCVariables{
  479. Rollup: rollupVars,
  480. Auction: auctionVars,
  481. WDelayer: wdelayerVars,
  482. }, constants)
  483. // Generate test data, as expected to be received/sended from/to the API
  484. testCoords := genTestCoordinators(commonCoords)
  485. testBids := genTestBids(commonBlocks, testCoords, bids)
  486. testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
  487. testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
  488. testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
  489. poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
  490. // Add balance and nonce to historyDB
  491. accounts := genTestAccounts(commonAccounts, testTokens)
  492. accUpdates := []common.AccountUpdate{}
  493. for i := 0; i < len(accounts); i++ {
  494. balance := new(big.Int)
  495. balance.SetString(string(*accounts[i].Balance), 10)
  496. idx, err := stringToIdx(string(accounts[i].Idx), "foo")
  497. if err != nil {
  498. panic(err)
  499. }
  500. accUpdates = append(accUpdates, common.AccountUpdate{
  501. EthBlockNum: 0,
  502. BatchNum: 1,
  503. Idx: *idx,
  504. Nonce: 0,
  505. Balance: balance,
  506. })
  507. accUpdates = append(accUpdates, common.AccountUpdate{
  508. EthBlockNum: 0,
  509. BatchNum: 1,
  510. Idx: *idx,
  511. Nonce: accounts[i].Nonce,
  512. Balance: balance,
  513. })
  514. }
  515. if err := api.h.AddAccountUpdates(accUpdates); err != nil {
  516. panic(err)
  517. }
  518. tc = testCommon{
  519. blocks: commonBlocks,
  520. tokens: testTokens,
  521. batches: testBatches,
  522. fullBatches: testFullBatches,
  523. coordinators: testCoords,
  524. accounts: accounts,
  525. txs: testTxs,
  526. exits: testExits,
  527. poolTxsToSend: poolTxsToSend,
  528. poolTxsToReceive: poolTxsToReceive,
  529. auths: genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
  530. router: router,
  531. bids: testBids,
  532. slots: api.genTestSlots(
  533. 20,
  534. commonBlocks[len(commonBlocks)-1].Num,
  535. testBids,
  536. auctionVars,
  537. ),
  538. auctionVars: auctionVars,
  539. rollupVars: rollupVars,
  540. wdelayerVars: wdelayerVars,
  541. nextForgers: nextForgers,
  542. }
  543. // Run tests
  544. result := m.Run()
  545. // Fake server
  546. if os.Getenv("FAKE_SERVER") == "yes" {
  547. for {
  548. log.Info("Running fake server at " + apiURL + " until ^C is received")
  549. time.Sleep(30 * time.Second)
  550. }
  551. }
  552. // Stop server
  553. if err := server.Shutdown(context.Background()); err != nil {
  554. panic(err)
  555. }
  556. if err := database.Close(); err != nil {
  557. panic(err)
  558. }
  559. os.Exit(result)
  560. }
  561. func TestTimeout(t *testing.T) {
  562. pass := os.Getenv("POSTGRES_PASS")
  563. databaseTO, err := db.ConnectSQLDB(5432, "localhost", "hermez", pass, "hermez")
  564. require.NoError(t, err)
  565. apiConnConTO := db.NewAPIConnectionController(1, 100*time.Millisecond)
  566. hdbTO := historydb.NewHistoryDB(databaseTO, databaseTO, apiConnConTO)
  567. require.NoError(t, err)
  568. // L2DB
  569. l2DBTO := l2db.NewL2DB(databaseTO, databaseTO, 10, 1000, 1.0, 1000.0, 24*time.Hour, apiConnConTO)
  570. // API
  571. apiGinTO := gin.Default()
  572. finishWait := make(chan interface{})
  573. startWait := make(chan interface{})
  574. apiGinTO.GET("/v1/wait", func(c *gin.Context) {
  575. cancel, err := apiConnConTO.Acquire()
  576. defer cancel()
  577. require.NoError(t, err)
  578. defer apiConnConTO.Release()
  579. startWait <- nil
  580. <-finishWait
  581. })
  582. // Start server
  583. serverTO := &http.Server{Handler: apiGinTO}
  584. listener, err := net.Listen("tcp", ":4444") //nolint:gosec
  585. require.NoError(t, err)
  586. go func() {
  587. if err := serverTO.Serve(listener); err != nil &&
  588. tracerr.Unwrap(err) != http.ErrServerClosed {
  589. require.NoError(t, err)
  590. }
  591. }()
  592. _, err = NewAPI(
  593. true,
  594. true,
  595. apiGinTO,
  596. hdbTO,
  597. l2DBTO,
  598. )
  599. require.NoError(t, err)
  600. client := &http.Client{}
  601. httpReq, err := http.NewRequest("GET", "http://localhost:4444/v1/tokens", nil)
  602. require.NoError(t, err)
  603. httpReqWait, err := http.NewRequest("GET", "http://localhost:4444/v1/wait", nil)
  604. require.NoError(t, err)
  605. // Request that will get timed out
  606. var wg sync.WaitGroup
  607. wg.Add(1)
  608. go func() {
  609. // Request that will make the API busy
  610. _, err = client.Do(httpReqWait)
  611. require.NoError(t, err)
  612. wg.Done()
  613. }()
  614. <-startWait
  615. resp, err := client.Do(httpReq)
  616. require.NoError(t, err)
  617. require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
  618. defer resp.Body.Close() //nolint
  619. body, err := ioutil.ReadAll(resp.Body)
  620. require.NoError(t, err)
  621. // Unmarshal body into return struct
  622. msg := &errorMsg{}
  623. err = json.Unmarshal(body, msg)
  624. require.NoError(t, err)
  625. // Check that the error was the expected down
  626. require.Equal(t, errSQLTimeout, msg.Message)
  627. finishWait <- nil
  628. // Stop server
  629. wg.Wait()
  630. require.NoError(t, serverTO.Shutdown(context.Background()))
  631. require.NoError(t, databaseTO.Close())
  632. }
  633. func doGoodReqPaginated(
  634. path, order string,
  635. iterStruct Pendinger,
  636. appendIter func(res interface{}),
  637. ) error {
  638. var next uint64
  639. firstIte := true
  640. expectedTotal := 0
  641. totalReceived := 0
  642. for {
  643. // Calculate fromItem
  644. iterPath := path
  645. if !firstIte {
  646. iterPath += "&fromItem=" + strconv.Itoa(int(next))
  647. }
  648. // Call API to get this iteration items
  649. iterStruct = iterStruct.New()
  650. if err := doGoodReq(
  651. "GET", iterPath+"&order="+order, nil,
  652. iterStruct,
  653. ); err != nil {
  654. return tracerr.Wrap(err)
  655. }
  656. appendIter(iterStruct)
  657. // Keep iterating?
  658. remaining, lastID := iterStruct.GetPending()
  659. if remaining == 0 {
  660. break
  661. }
  662. if order == historydb.OrderDesc {
  663. next = lastID - 1
  664. } else {
  665. next = lastID + 1
  666. }
  667. // Check that the expected amount of items is consistent across iterations
  668. totalReceived += iterStruct.Len()
  669. if firstIte {
  670. firstIte = false
  671. expectedTotal = totalReceived + int(remaining)
  672. }
  673. if expectedTotal != totalReceived+int(remaining) {
  674. panic(fmt.Sprintf(
  675. "pagination error, totalReceived + remaining should be %d, but is %d",
  676. expectedTotal, totalReceived+int(remaining),
  677. ))
  678. }
  679. }
  680. return nil
  681. }
  682. func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
  683. ctx := context.Background()
  684. client := &http.Client{}
  685. httpReq, err := http.NewRequest(method, path, reqBody)
  686. if err != nil {
  687. return tracerr.Wrap(err)
  688. }
  689. if reqBody != nil {
  690. httpReq.Header.Add("Content-Type", "application/json")
  691. }
  692. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  693. if err != nil {
  694. return tracerr.Wrap(err)
  695. }
  696. // Validate request against swagger spec
  697. requestValidationInput := &swagger.RequestValidationInput{
  698. Request: httpReq,
  699. PathParams: pathParams,
  700. Route: route,
  701. }
  702. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  703. return tracerr.Wrap(err)
  704. }
  705. // Do API call
  706. resp, err := client.Do(httpReq)
  707. if err != nil {
  708. return tracerr.Wrap(err)
  709. }
  710. if resp.Body == nil && returnStruct != nil {
  711. return tracerr.Wrap(errors.New("Nil body"))
  712. }
  713. //nolint
  714. defer resp.Body.Close()
  715. body, err := ioutil.ReadAll(resp.Body)
  716. if err != nil {
  717. return tracerr.Wrap(err)
  718. }
  719. if resp.StatusCode != 200 {
  720. return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
  721. }
  722. if returnStruct == nil {
  723. return nil
  724. }
  725. // Unmarshal body into return struct
  726. if err := json.Unmarshal(body, returnStruct); err != nil {
  727. log.Error("invalid json: " + string(body))
  728. log.Error(err)
  729. return tracerr.Wrap(err)
  730. }
  731. // log.Info(string(body))
  732. // Validate response against swagger spec
  733. responseValidationInput := &swagger.ResponseValidationInput{
  734. RequestValidationInput: requestValidationInput,
  735. Status: resp.StatusCode,
  736. Header: resp.Header,
  737. }
  738. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  739. return swagger.ValidateResponse(ctx, responseValidationInput)
  740. }
  741. func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
  742. ctx := context.Background()
  743. client := &http.Client{}
  744. httpReq, _ := http.NewRequest(method, path, reqBody)
  745. route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
  746. if err != nil {
  747. return tracerr.Wrap(err)
  748. }
  749. // Validate request against swagger spec
  750. requestValidationInput := &swagger.RequestValidationInput{
  751. Request: httpReq,
  752. PathParams: pathParams,
  753. Route: route,
  754. }
  755. if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
  756. if expectedResponseCode != 400 {
  757. return tracerr.Wrap(err)
  758. }
  759. log.Warn("The request does not match the API spec")
  760. }
  761. // Do API call
  762. resp, err := client.Do(httpReq)
  763. if err != nil {
  764. return tracerr.Wrap(err)
  765. }
  766. if resp.Body == nil {
  767. return tracerr.Wrap(errors.New("Nil body"))
  768. }
  769. //nolint
  770. defer resp.Body.Close()
  771. body, err := ioutil.ReadAll(resp.Body)
  772. if err != nil {
  773. return tracerr.Wrap(err)
  774. }
  775. if resp.StatusCode != expectedResponseCode {
  776. return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
  777. }
  778. // Validate response against swagger spec
  779. responseValidationInput := &swagger.ResponseValidationInput{
  780. RequestValidationInput: requestValidationInput,
  781. Status: resp.StatusCode,
  782. Header: resp.Header,
  783. }
  784. responseValidationInput = responseValidationInput.SetBodyBytes(body)
  785. return swagger.ValidateResponse(ctx, responseValidationInput)
  786. }
  787. // test helpers
  788. func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
  789. for i := 0; i < len(blocks); i++ {
  790. if blocks[i].Num == blockNum {
  791. return blocks[i].Timestamp
  792. }
  793. }
  794. panic("timesamp not found")
  795. }
  796. func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
  797. for i := 0; i < len(tokens); i++ {
  798. if tokens[i].TokenID == id {
  799. return tokens[i]
  800. }
  801. }
  802. panic("token not found")
  803. }
  804. func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
  805. for _, acc := range accs {
  806. if idx == acc.Idx {
  807. return getTokenByID(acc.TokenID, tokens)
  808. }
  809. }
  810. panic("token not found")
  811. }
  812. func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
  813. for _, acc := range accs {
  814. if acc.Idx == idx {
  815. return &acc
  816. }
  817. }
  818. panic("account not found")
  819. }
  820. func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
  821. for _, b := range blocks {
  822. if b.Num == ethBlockNum {
  823. return b
  824. }
  825. }
  826. panic("block not found")
  827. }
  828. func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
  829. var coordLastUpdate historydb.CoordinatorAPI
  830. found := false
  831. for _, c := range coordinators {
  832. if c.Bidder == bidder {
  833. coordLastUpdate = c
  834. found = true
  835. }
  836. }
  837. if !found {
  838. panic("coordinator not found")
  839. }
  840. return coordLastUpdate
  841. }