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