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.

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