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.

883 lines
25 KiB

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