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.

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