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.

863 lines
24 KiB

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