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