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