arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
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/common"
 23	"github.com/hermeznetwork/hermez-node/db"
 24	"github.com/hermeznetwork/hermez-node/db/historydb"
 25	"github.com/hermeznetwork/hermez-node/db/l2db"
 26	"github.com/hermeznetwork/hermez-node/log"
 27	"github.com/hermeznetwork/hermez-node/stateapiupdater"
 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 apiAddr = ":4010"
 44const apiURL = "http://localhost" + apiAddr + "/"
 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", apiAddr) //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:         &ethUSD,
317		USDUpdate:   &ethNow,
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 = stateapiupdater.NewUpdater(hdb, nodeConfig, &common.SCVariables{
526		Rollup:   rollupVars,
527		Auction:  auctionVars,
528		WDelayer: wdelayerVars,
529	}, constants)
530
531	// Generate test data, as expected to be received/sended from/to the API
532	testCoords := genTestCoordinators(commonCoords)
533	testBids := genTestBids(commonBlocks, testCoords, bids)
534	testExits := genTestExits(commonExitTree, testTokens, commonAccounts)
535	testTxs := genTestTxs(commonL1Txs, commonL2Txs, commonAccounts, testTokens, commonBlocks)
536	testBatches, testFullBatches := genTestBatches(commonBlocks, commonBatches, testTxs)
537	poolTxsToSend, poolTxsToReceive := genTestPoolTxs(commonPoolTxs, testTokens, commonAccounts)
538	// Add balance and nonce to historyDB
539	accounts := genTestAccounts(commonAccounts, testTokens)
540	accUpdates := []common.AccountUpdate{}
541	for i := 0; i < len(accounts); i++ {
542		balance := new(big.Int)
543		balance.SetString(string(*accounts[i].Balance), 10)
544		idx, err := stringToIdx(string(accounts[i].Idx), "foo")
545		if err != nil {
546			panic(err)
547		}
548		accUpdates = append(accUpdates, common.AccountUpdate{
549			EthBlockNum: 0,
550			BatchNum:    1,
551			Idx:         *idx,
552			Nonce:       0,
553			Balance:     balance,
554		})
555		accUpdates = append(accUpdates, common.AccountUpdate{
556			EthBlockNum: 0,
557			BatchNum:    1,
558			Idx:         *idx,
559			Nonce:       accounts[i].Nonce,
560			Balance:     balance,
561		})
562	}
563	if err := api.h.AddAccountUpdates(accUpdates); err != nil {
564		panic(err)
565	}
566	tc = testCommon{
567		blocks:           commonBlocks,
568		tokens:           testTokens,
569		batches:          testBatches,
570		fullBatches:      testFullBatches,
571		coordinators:     testCoords,
572		accounts:         accounts,
573		txs:              testTxs,
574		exits:            testExits,
575		poolTxsToSend:    poolTxsToSend,
576		poolTxsToReceive: poolTxsToReceive,
577		auths:            genTestAuths(test.GenAuths(5, _config.ChainID, _config.HermezAddress)),
578		router:           router,
579		bids:             testBids,
580		slots: api.genTestSlots(
581			20,
582			commonBlocks[len(commonBlocks)-1].Num,
583			testBids,
584			auctionVars,
585		),
586		auctionVars:  auctionVars,
587		rollupVars:   rollupVars,
588		wdelayerVars: wdelayerVars,
589		nextForgers:  nextForgers,
590	}
591
592	// Run tests
593	result := m.Run()
594	// Fake server
595	if os.Getenv("FAKE_SERVER") == "yes" {
596		for {
597			log.Info("Running fake server at " + apiURL + " until ^C is received")
598			time.Sleep(30 * time.Second)
599		}
600	}
601	// Stop server
602	if err := server.Shutdown(context.Background()); err != nil {
603		panic(err)
604	}
605	if err := database.Close(); err != nil {
606		panic(err)
607	}
608	os.Exit(result)
609}
610
611func TestTimeout(t *testing.T) {
612	pass := os.Getenv("POSTGRES_PASS")
613	databaseTO, err := db.ConnectSQLDB(5432, "localhost", "hermez", pass, "hermez")
614	require.NoError(t, err)
615	apiConnConTO := db.NewAPIConnectionController(1, 100*time.Millisecond)
616	hdbTO := historydb.NewHistoryDB(databaseTO, databaseTO, apiConnConTO)
617	require.NoError(t, err)
618	// L2DB
619	l2DBTO := l2db.NewL2DB(databaseTO, databaseTO, 10, 1000, 1.0, 1000.0, 24*time.Hour, apiConnConTO)
620
621	// API
622	apiGinTO := gin.Default()
623	finishWait := make(chan interface{})
624	startWait := make(chan interface{})
625	apiGinTO.GET("/wait", func(c *gin.Context) {
626		cancel, err := apiConnConTO.Acquire()
627		defer cancel()
628		require.NoError(t, err)
629		defer apiConnConTO.Release()
630		startWait <- nil
631		<-finishWait
632	})
633	// Start server
634	serverTO := &http.Server{Handler: apiGinTO}
635	listener, err := net.Listen("tcp", ":4444") //nolint:gosec
636	require.NoError(t, err)
637	go func() {
638		if err := serverTO.Serve(listener); err != nil &&
639			tracerr.Unwrap(err) != http.ErrServerClosed {
640			require.NoError(t, err)
641		}
642	}()
643	_, err = NewAPI(
644		true,
645		true,
646		apiGinTO,
647		hdbTO,
648		l2DBTO,
649	)
650	require.NoError(t, err)
651
652	client := &http.Client{}
653	httpReq, err := http.NewRequest("GET", "http://localhost:4444/tokens", nil)
654	require.NoError(t, err)
655	httpReqWait, err := http.NewRequest("GET", "http://localhost:4444/wait", nil)
656	require.NoError(t, err)
657	// Request that will get timed out
658	var wg sync.WaitGroup
659	wg.Add(1)
660	go func() {
661		// Request that will make the API busy
662		_, err = client.Do(httpReqWait)
663		require.NoError(t, err)
664		wg.Done()
665	}()
666	<-startWait
667	resp, err := client.Do(httpReq)
668	require.NoError(t, err)
669	require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode)
670	defer resp.Body.Close() //nolint
671	body, err := ioutil.ReadAll(resp.Body)
672	require.NoError(t, err)
673	// Unmarshal body into return struct
674	msg := &errorMsg{}
675	err = json.Unmarshal(body, msg)
676	require.NoError(t, err)
677	// Check that the error was the expected down
678	require.Equal(t, errSQLTimeout, msg.Message)
679	finishWait <- nil
680
681	// Stop server
682	wg.Wait()
683	require.NoError(t, serverTO.Shutdown(context.Background()))
684	require.NoError(t, databaseTO.Close())
685}
686
687func doGoodReqPaginated(
688	path, order string,
689	iterStruct Pendinger,
690	appendIter func(res interface{}),
691) error {
692	var next uint64
693	firstIte := true
694	expectedTotal := 0
695	totalReceived := 0
696	for {
697		// Calculate fromItem
698		iterPath := path
699		if !firstIte {
700			iterPath += "&fromItem=" + strconv.Itoa(int(next))
701		}
702		// Call API to get this iteration items
703		iterStruct = iterStruct.New()
704		if err := doGoodReq(
705			"GET", iterPath+"&order="+order, nil,
706			iterStruct,
707		); err != nil {
708			return tracerr.Wrap(err)
709		}
710		appendIter(iterStruct)
711		// Keep iterating?
712		remaining, lastID := iterStruct.GetPending()
713		if remaining == 0 {
714			break
715		}
716		if order == historydb.OrderDesc {
717			next = lastID - 1
718		} else {
719			next = lastID + 1
720		}
721		// Check that the expected amount of items is consistent across iterations
722		totalReceived += iterStruct.Len()
723		if firstIte {
724			firstIte = false
725			expectedTotal = totalReceived + int(remaining)
726		}
727		if expectedTotal != totalReceived+int(remaining) {
728			panic(fmt.Sprintf(
729				"pagination error, totalReceived + remaining should be %d, but is %d",
730				expectedTotal, totalReceived+int(remaining),
731			))
732		}
733	}
734	return nil
735}
736
737func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{}) error {
738	ctx := context.Background()
739	client := &http.Client{}
740	httpReq, err := http.NewRequest(method, path, reqBody)
741	if err != nil {
742		return tracerr.Wrap(err)
743	}
744	if reqBody != nil {
745		httpReq.Header.Add("Content-Type", "application/json")
746	}
747	route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
748	if err != nil {
749		return tracerr.Wrap(err)
750	}
751	// Validate request against swagger spec
752	requestValidationInput := &swagger.RequestValidationInput{
753		Request:    httpReq,
754		PathParams: pathParams,
755		Route:      route,
756	}
757	if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
758		return tracerr.Wrap(err)
759	}
760	// Do API call
761	resp, err := client.Do(httpReq)
762	if err != nil {
763		return tracerr.Wrap(err)
764	}
765	if resp.Body == nil && returnStruct != nil {
766		return tracerr.Wrap(errors.New("Nil body"))
767	}
768	//nolint
769	defer resp.Body.Close()
770	body, err := ioutil.ReadAll(resp.Body)
771	if err != nil {
772		return tracerr.Wrap(err)
773	}
774	if resp.StatusCode != 200 {
775		return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
776	}
777	if returnStruct == nil {
778		return nil
779	}
780	// Unmarshal body into return struct
781	if err := json.Unmarshal(body, returnStruct); err != nil {
782		log.Error("invalid json: " + string(body))
783		log.Error(err)
784		return tracerr.Wrap(err)
785	}
786	// log.Info(string(body))
787	// Validate response against swagger spec
788	responseValidationInput := &swagger.ResponseValidationInput{
789		RequestValidationInput: requestValidationInput,
790		Status:                 resp.StatusCode,
791		Header:                 resp.Header,
792	}
793	responseValidationInput = responseValidationInput.SetBodyBytes(body)
794	return swagger.ValidateResponse(ctx, responseValidationInput)
795}
796
797func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int) error {
798	ctx := context.Background()
799	client := &http.Client{}
800	httpReq, _ := http.NewRequest(method, path, reqBody)
801	route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
802	if err != nil {
803		return tracerr.Wrap(err)
804	}
805	// Validate request against swagger spec
806	requestValidationInput := &swagger.RequestValidationInput{
807		Request:    httpReq,
808		PathParams: pathParams,
809		Route:      route,
810	}
811	if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
812		if expectedResponseCode != 400 {
813			return tracerr.Wrap(err)
814		}
815		log.Warn("The request does not match the API spec")
816	}
817	// Do API call
818	resp, err := client.Do(httpReq)
819	if err != nil {
820		return tracerr.Wrap(err)
821	}
822	if resp.Body == nil {
823		return tracerr.Wrap(errors.New("Nil body"))
824	}
825	//nolint
826	defer resp.Body.Close()
827	body, err := ioutil.ReadAll(resp.Body)
828	if err != nil {
829		return tracerr.Wrap(err)
830	}
831	if resp.StatusCode != expectedResponseCode {
832		return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
833	}
834	// Validate response against swagger spec
835	responseValidationInput := &swagger.ResponseValidationInput{
836		RequestValidationInput: requestValidationInput,
837		Status:                 resp.StatusCode,
838		Header:                 resp.Header,
839	}
840	responseValidationInput = responseValidationInput.SetBodyBytes(body)
841	return swagger.ValidateResponse(ctx, responseValidationInput)
842}
843
844// test helpers
845
846func getTimestamp(blockNum int64, blocks []common.Block) time.Time {
847	for i := 0; i < len(blocks); i++ {
848		if blocks[i].Num == blockNum {
849			return blocks[i].Timestamp
850		}
851	}
852	panic("timesamp not found")
853}
854
855func getTokenByID(id common.TokenID, tokens []historydb.TokenWithUSD) historydb.TokenWithUSD {
856	for i := 0; i < len(tokens); i++ {
857		if tokens[i].TokenID == id {
858			return tokens[i]
859		}
860	}
861	panic("token not found")
862}
863
864func getTokenByIdx(idx common.Idx, tokens []historydb.TokenWithUSD, accs []common.Account) historydb.TokenWithUSD {
865	for _, acc := range accs {
866		if idx == acc.Idx {
867			return getTokenByID(acc.TokenID, tokens)
868		}
869	}
870	panic("token not found")
871}
872
873func getAccountByIdx(idx common.Idx, accs []common.Account) *common.Account {
874	for _, acc := range accs {
875		if acc.Idx == idx {
876			return &acc
877		}
878	}
879	panic("account not found")
880}
881
882func getBlockByNum(ethBlockNum int64, blocks []common.Block) common.Block {
883	for _, b := range blocks {
884		if b.Num == ethBlockNum {
885			return b
886		}
887	}
888	panic("block not found")
889}
890
891func getCoordinatorByBidder(bidder ethCommon.Address, coordinators []historydb.CoordinatorAPI) historydb.CoordinatorAPI {
892	var coordLastUpdate historydb.CoordinatorAPI
893	found := false
894	for _, c := range coordinators {
895		if c.Bidder == bidder {
896			coordLastUpdate = c
897			found = true
898		}
899	}
900	if !found {
901		panic("coordinator not found")
902	}
903	return coordLastUpdate
904}