arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
Merge pull request #263 from hermeznetwork/feature/wrapped-in-struct

Put api DBs into struct
Eduard S eduard@iden3.io
Fri, 06 Nov 2020 15:05:53 +0100
commit

220fd992c5ede5b6bcdd38c51000509e1b6712b2

parent

4a29cafcb751ef50dcc55cdfd914f1065aa4563d

M api/account.go → api/account.go

@@ -9,21 +9,21 @@ "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/db/historydb" ) -func getAccount(c *gin.Context) { +func (a *API) getAccount(c *gin.Context) { // Get Addr idx, err := parseParamIdx(c) if err != nil { retBadReq(err, c) return } - apiAccount, err := h.GetAccountAPI(*idx) + apiAccount, err := a.h.GetAccountAPI(*idx) if err != nil { retSQLErr(err, c) return } // Get balance from stateDB - account, err := s.GetAccount(*idx) + account, err := a.s.GetAccount(*idx) if err != nil { retSQLErr(err, c) return

@@ -34,7 +34,7 @@

c.JSON(http.StatusOK, apiAccount) } -func getAccounts(c *gin.Context) { +func (a *API) getAccounts(c *gin.Context) { // Account filters tokenIDs, addr, bjj, err := parseAccountFilters(c) if err != nil {

@@ -49,7 +49,7 @@ return

} // Fetch Accounts from historyDB - apiAccounts, pagination, err := h.GetAccountsAPI(tokenIDs, addr, bjj, fromItem, limit, order) + apiAccounts, pagination, err := a.h.GetAccountsAPI(tokenIDs, addr, bjj, fromItem, limit, order) if err != nil { retSQLErr(err, c) return

@@ -62,7 +62,7 @@ if err != nil {

retSQLErr(err, c) return } - account, err := s.GetAccount(*idx) + account, err := a.s.GetAccount(*idx) if err != nil { retSQLErr(err, c) return
M api/accountcreationauths.go → api/accountcreationauths.go

@@ -12,7 +12,7 @@ "github.com/hermeznetwork/hermez-node/common"

"github.com/iden3/go-iden3-crypto/babyjub" ) -func postAccountCreationAuth(c *gin.Context) { +func (a *API) postAccountCreationAuth(c *gin.Context) { // Parse body var apiAuth receivedAuth if err := c.ShouldBindJSON(&apiAuth); err != nil {

@@ -26,7 +26,7 @@ retBadReq(errors.New("invalid signature"), c)

return } // Insert to DB - if err := l2.AddAccountCreationAuth(commonAuth); err != nil { + if err := a.l2.AddAccountCreationAuth(commonAuth); err != nil { retSQLErr(err, c) return }

@@ -34,7 +34,7 @@ // Return OK

c.Status(http.StatusOK) } -func getAccountCreationAuth(c *gin.Context) { +func (a *API) getAccountCreationAuth(c *gin.Context) { // Get hezEthereumAddress addr, err := parseParamHezEthAddr(c) if err != nil {

@@ -42,7 +42,7 @@ retBadReq(err, c)

return } // Fetch auth from l2DB - auth, err := l2.GetAccountCreationAuthAPI(*addr) + auth, err := a.l2.GetAccountCreationAuthAPI(*addr) if err != nil { retSQLErr(err, c) return
M api/api.go → api/api.go

@@ -4,75 +4,90 @@ import (

"errors" "github.com/gin-gonic/gin" + "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/db/historydb" "github.com/hermeznetwork/hermez-node/db/l2db" "github.com/hermeznetwork/hermez-node/db/statedb" ) -var h *historydb.HistoryDB -var cg *configAPI -var s *statedb.StateDB -var l2 *l2db.L2DB +// Status define status of the network +type Status struct { + Network historydb.Network `json:"network"` + Metrics historydb.Metrics `json:"metrics"` + Rollup common.RollupVariables `json:"rollup"` + Auction common.AuctionVariables `json:"auction"` + WithdrawalDelayer common.WDelayerVariables `json:"withdrawalDelayer"` + RecommendedFee common.RecommendedFee `json:"recommendedFee"` +} -// SetAPIEndpoints sets the endpoints and the appropriate handlers, but doesn't start the server -func SetAPIEndpoints( +// API serves HTTP requests to allow external interaction with the Hermez node +type API struct { + h *historydb.HistoryDB + cg *configAPI + s *statedb.StateDB + l2 *l2db.L2DB + status Status +} + +// NewAPI sets the endpoints and the appropriate handlers, but doesn't start the server +func NewAPI( coordinatorEndpoints, explorerEndpoints bool, server *gin.Engine, hdb *historydb.HistoryDB, sdb *statedb.StateDB, l2db *l2db.L2DB, config *configAPI, -) error { +) (*API, error) { // Check input // TODO: is stateDB only needed for explorer endpoints or for both? if coordinatorEndpoints && l2db == nil { - return errors.New("cannot serve Coordinator endpoints without L2DB") + return nil, errors.New("cannot serve Coordinator endpoints without L2DB") } if explorerEndpoints && hdb == nil { - return errors.New("cannot serve Explorer endpoints without HistoryDB") + return nil, errors.New("cannot serve Explorer endpoints without HistoryDB") } - h = hdb - cg = config - s = sdb - l2 = l2db + a := &API{ + h: hdb, + cg: config, + s: sdb, + l2: l2db, + } // Add coordinator endpoints if coordinatorEndpoints { // Account - server.POST("/account-creation-authorization", postAccountCreationAuth) - server.GET("/account-creation-authorization/:hermezEthereumAddress", getAccountCreationAuth) + server.POST("/account-creation-authorization", a.postAccountCreationAuth) + server.GET("/account-creation-authorization/:hermezEthereumAddress", a.getAccountCreationAuth) // Transaction - server.POST("/transactions-pool", postPoolTx) - server.GET("/transactions-pool/:id", getPoolTx) + server.POST("/transactions-pool", a.postPoolTx) + server.GET("/transactions-pool/:id", a.getPoolTx) } // Add explorer endpoints if explorerEndpoints { // Account - server.GET("/accounts", getAccounts) - server.GET("/accounts/:accountIndex", getAccount) - server.GET("/exits", getExits) - server.GET("/exits/:batchNum/:accountIndex", getExit) + server.GET("/accounts", a.getAccounts) + server.GET("/accounts/:accountIndex", a.getAccount) + server.GET("/exits", a.getExits) + server.GET("/exits/:batchNum/:accountIndex", a.getExit) // Transaction - server.GET("/transactions-history", getHistoryTxs) - server.GET("/transactions-history/:id", getHistoryTx) + server.GET("/transactions-history", a.getHistoryTxs) + server.GET("/transactions-history/:id", a.getHistoryTx) // Status - server.GET("/batches", getBatches) - server.GET("/batches/:batchNum", getBatch) - server.GET("/full-batches/:batchNum", getFullBatch) - server.GET("/slots", getSlots) - server.GET("/slots/:slotNum", getSlot) - server.GET("/bids", getBids) - server.GET("/next-forgers", getNextForgers) - server.GET("/state", getState) - server.GET("/config", getConfig) - server.GET("/tokens", getTokens) - server.GET("/tokens/:id", getToken) - server.GET("/recommendedFee", getRecommendedFee) - server.GET("/coordinators", getCoordinators) - server.GET("/coordinators/:bidderAddr", getCoordinator) + server.GET("/batches", a.getBatches) + server.GET("/batches/:batchNum", a.getBatch) + server.GET("/full-batches/:batchNum", a.getFullBatch) + server.GET("/slots", a.getSlots) + server.GET("/slots/:slotNum", a.getSlot) + server.GET("/bids", a.getBids) + server.GET("/state", a.getState) + server.GET("/config", a.getConfig) + server.GET("/tokens", a.getTokens) + server.GET("/tokens/:id", a.getToken) + server.GET("/coordinators", a.getCoordinators) + server.GET("/coordinators/:bidderAddr", a.getCoordinator) } - return nil + return a, nil }
M api/api_test.go → api/api_test.go

@@ -56,6 +56,7 @@ }

var tc testCommon var config configAPI +var api *API // TestMain initializes the API server, and fill HistoryDB and StateDB with fake data, // emulating the task of the synchronizer in order to have data to be returned

@@ -97,20 +98,21 @@ // Config (smart contract constants)

config = getConfigTest() // API - api := gin.Default() - if err := SetAPIEndpoints( + apiGin := gin.Default() + api, err = NewAPI( true, true, - api, + apiGin, hdb, sdb, l2DB, &config, - ); err != nil { + ) + if err != nil { panic(err) } // Start server - server := &http.Server{Addr: apiPort, Handler: api} + server := &http.Server{Addr: apiPort, Handler: apiGin} go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {

@@ -122,7 +124,7 @@ // Fill HistoryDB and StateDB with fake data

// Gen blocks and add them to DB const nBlocks = 5 blocks := test.GenBlocks(1, nBlocks+1) - err = h.AddBlocks(blocks) + err = api.h.AddBlocks(blocks) if err != nil { panic(err) }

@@ -131,7 +133,7 @@

// Gen tokens and add them to DB const nTokens = 10 tokens, ethToken := test.GenTokens(nTokens, blocks) - err = h.AddTokens(tokens) + err = api.h.AddTokens(tokens) if err != nil { panic(err) }

@@ -153,7 +155,7 @@ value := float64(i) * 1.234567

now := time.Now().UTC() token.USD = &value token.USDUpdate = &now - err = h.UpdateTokenValue(token.Symbol, value) + err = api.h.UpdateTokenValue(token.Symbol, value) if err != nil { panic(err) }

@@ -163,7 +165,7 @@ }

// Gen batches and add them to DB const nBatches = 10 batches := test.GenBatches(nBatches, blocks) - err = h.AddBatches(batches) + err = api.h.AddBatches(batches) if err != nil { panic(err) }

@@ -174,12 +176,12 @@ usrAddr := ethCommon.BigToAddress(big.NewInt(4896847))

privK := babyjub.NewRandPrivKey() usrBjj := privK.Public() accs := test.GenAccounts(totalAccounts, userAccounts, tokens, &usrAddr, usrBjj, batches) - err = h.AddAccounts(accs) + err = api.h.AddAccounts(accs) if err != nil { panic(err) } for i := 0; i < len(accs); i++ { - if _, err := s.CreateAccount(accs[i].Idx, &accs[i]); err != nil { + if _, err := api.s.CreateAccount(accs[i].Idx, &accs[i]); err != nil { panic(err) } }

@@ -197,7 +199,7 @@ }

// Gen exits and add them to DB const totalExits = 40 exits := test.GenExitTree(totalExits, batches, accs) - err = h.AddExitTree(exits) + err = api.h.AddExitTree(exits) if err != nil { panic(err) }

@@ -235,12 +237,12 @@ for _, genericTx := range sortedTxs {

l1 := genericTx.L1() l2 := genericTx.L2() if l1 != nil { - err = h.AddL1Txs([]common.L1Tx{*l1}) + err = api.h.AddL1Txs([]common.L1Tx{*l1}) if err != nil { panic(err) } } else if l2 != nil { - err = h.AddL2Txs([]common.L2Tx{*l2}) + err = api.h.AddL2Txs([]common.L2Tx{*l2}) if err != nil { panic(err) }

@@ -252,13 +254,13 @@

// Coordinators const nCoords = 10 coords := test.GenCoordinators(nCoords, blocks) - err = hdb.AddCoordinators(coords) + err = api.h.AddCoordinators(coords) if err != nil { panic(err) } fromItem := uint(0) limit := uint(99999) - coordinators, _, err := hdb.GetCoordinatorsAPI(&fromItem, &limit, historydb.OrderAsc) + coordinators, _, err := api.h.GetCoordinatorsAPI(&fromItem, &limit, historydb.OrderAsc) if err != nil { panic(err) }

@@ -266,7 +268,7 @@

// Bids const nBids = 20 bids := test.GenBids(nBids, blocks, coords) - err = hdb.AddBids(bids) + err = api.h.AddBids(bids) if err != nil { panic(err) }

@@ -278,7 +280,7 @@ BootCoordinator: ethCommon.HexToAddress("0x1111111111111111111111111111111111111111"),

ClosedAuctionSlots: uint16(2), OpenAuctionSlots: uint16(5), } - err = hdb.AddAuctionVars(&auctionVars) + err = api.h.AddAuctionVars(&auctionVars) if err != nil { panic(err) }

@@ -309,7 +311,7 @@ poolTxsToReceive: poolTxsToReceive,

auths: genTestAuths(test.GenAuths(5)), router: router, bids: testBids, - slots: genTestSlots(nSlots, lastBlockNum, testBids, auctionVars), + slots: api.genTestSlots(nSlots, lastBlockNum, testBids, auctionVars), auctionVars: auctionVars, }
M api/batch.go → api/batch.go

@@ -10,7 +10,7 @@ "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/db/historydb" ) -func getBatches(c *gin.Context) { +func (a *API) getBatches(c *gin.Context) { // Get query parameters // minBatchNum minBatchNum, err := parseQueryUint("minBatchNum", nil, 0, maxUint32, c)

@@ -43,7 +43,7 @@ retBadReq(err, c)

return } // Fetch batches from historyDB - batches, pagination, err := h.GetBatchesAPI( + batches, pagination, err := a.h.GetBatchesAPI( minBatchNum, maxBatchNum, slotNum, forgerAddr, fromItem, limit, order, ) if err != nil {

@@ -62,7 +62,7 @@ Pagination: pagination,

}) } -func getBatch(c *gin.Context) { +func (a *API) getBatch(c *gin.Context) { // Get batchNum batchNum, err := parseParamUint("batchNum", nil, 0, maxUint32, c) if err != nil {

@@ -74,7 +74,7 @@ retBadReq(errors.New("Invalid batchNum"), c)

return } // Fetch batch from historyDB - batch, err := h.GetBatchAPI(common.BatchNum(*batchNum)) + batch, err := a.h.GetBatchAPI(common.BatchNum(*batchNum)) if err != nil { retSQLErr(err, c) return

@@ -88,7 +88,7 @@ Batch *historydb.BatchAPI `json:"batch"`

Txs []historydb.TxAPI `json:"transactions"` } -func getFullBatch(c *gin.Context) { +func (a *API) getFullBatch(c *gin.Context) { // Get batchNum batchNum, err := parseParamUint("batchNum", nil, 0, maxUint32, c) if err != nil {

@@ -100,14 +100,14 @@ retBadReq(errors.New("Invalid batchNum"), c)

return } // Fetch batch from historyDB - batch, err := h.GetBatchAPI(common.BatchNum(*batchNum)) + batch, err := a.h.GetBatchAPI(common.BatchNum(*batchNum)) if err != nil { retSQLErr(err, c) return } // Fetch txs forged in the batch from historyDB maxTxsPerBatch := uint(2048) //nolint:gomnd - txs, _, err := h.GetHistoryTxs( + txs, _, err := a.h.GetHistoryTxs( nil, nil, nil, nil, batchNum, nil, nil, &maxTxsPerBatch, historydb.OrderAsc, ) if err != nil {
M api/bids.go → api/bids.go

@@ -9,7 +9,7 @@ "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/db/historydb" ) -func getBids(c *gin.Context) { +func (a *API) getBids(c *gin.Context) { slotNum, bidderAddr, err := parseBidFilters(c) if err != nil { retBadReq(err, c)

@@ -26,7 +26,7 @@ retBadReq(err, c)

return } - bids, pagination, err := h.GetBidsAPI( + bids, pagination, err := a.h.GetBidsAPI( slotNum, bidderAddr, fromItem, limit, order, )
M api/config.go → api/config.go

@@ -32,6 +32,6 @@ AuctionConstants common.AuctionConstants `json:"auction"`

WDelayerConstants common.WDelayerConstants `json:"withdrawalDelayer"` } -func getConfig(c *gin.Context) { - c.JSON(http.StatusOK, cg) +func (a *API) getConfig(c *gin.Context) { + c.JSON(http.StatusOK, a.cg) }
M api/config_test.go → api/config_test.go

@@ -62,5 +62,5 @@ endpoint := apiURL + "config"

var configTest configAPI assert.NoError(t, doGoodReq("GET", endpoint, nil, &configTest)) assert.Equal(t, config, configTest) - assert.Equal(t, cg, &configTest) + assert.Equal(t, api.cg, &configTest) }
M api/coordinator.go → api/coordinator.go

@@ -8,7 +8,7 @@ "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/db/historydb" ) -func getCoordinator(c *gin.Context) { +func (a *API) getCoordinator(c *gin.Context) { // Get bidderAddr const name = "bidderAddr" bidderAddr, err := parseParamEthAddr(name, c)

@@ -21,7 +21,7 @@ retBadReq(ErrNillBidderAddr, c)

return } - coordinator, err := h.GetCoordinatorAPI(*bidderAddr) + coordinator, err := a.h.GetCoordinatorAPI(*bidderAddr) if err != nil { retSQLErr(err, c) return

@@ -30,7 +30,7 @@

c.JSON(http.StatusOK, coordinator) } -func getCoordinators(c *gin.Context) { +func (a *API) getCoordinators(c *gin.Context) { // Pagination fromItem, order, limit, err := parsePagination(c) if err != nil {

@@ -39,7 +39,7 @@ return

} // Fetch coordinators from historyDB - coordinators, pagination, err := h.GetCoordinatorsAPI(fromItem, limit, order) + coordinators, pagination, err := a.h.GetCoordinatorsAPI(fromItem, limit, order) if err != nil { retSQLErr(err, c) return
M api/exits.go → api/exits.go

@@ -8,7 +8,7 @@ "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/db/historydb" ) -func getExits(c *gin.Context) { +func (a *API) getExits(c *gin.Context) { // Get query parameters // Account filters tokenID, addr, bjj, idx, err := parseExitFilters(c)

@@ -36,7 +36,7 @@ return

} // Fetch exits from historyDB - exits, pagination, err := h.GetExitsAPI( + exits, pagination, err := a.h.GetExitsAPI( addr, bjj, tokenID, idx, batchNum, onlyPendingWithdraws, fromItem, limit, order, ) if err != nil {

@@ -55,7 +55,7 @@ Pagination: pagination,

}) } -func getExit(c *gin.Context) { +func (a *API) getExit(c *gin.Context) { // Get batchNum and accountIndex batchNum, err := parseParamUint("batchNum", nil, 0, maxUint32, c) if err != nil {

@@ -68,7 +68,7 @@ retBadReq(err, c)

return } // Fetch tx from historyDB - exit, err := h.GetExitAPI(batchNum, idx) + exit, err := a.h.GetExitAPI(batchNum, idx) if err != nil { retSQLErr(err, c) return
M api/handlers.go → api/handlers.go

@@ -31,18 +31,6 @@ // ErrNillBidderAddr is used when a nil bidderAddr is received in the getCoordinator method

ErrNillBidderAddr = errors.New("biderAddr can not be nil") ) -func getNextForgers(c *gin.Context) { - -} - -func getState(c *gin.Context) { - -} - -func getRecommendedFee(c *gin.Context) { - -} - func retSQLErr(err error, c *gin.Context) { if err == sql.ErrNoRows { c.JSON(http.StatusNotFound, errorMsg{
M api/slots.go → api/slots.go

@@ -24,23 +24,23 @@ FirstItem uint64 `json:"-"`

LastItem uint64 `json:"-"` } -func getFirstLastBlock(slotNum int64) (int64, int64) { - genesisBlock := cg.AuctionConstants.GenesisBlockNum - blocksPerSlot := int64(cg.AuctionConstants.BlocksPerSlot) +func (a *API) getFirstLastBlock(slotNum int64) (int64, int64) { + genesisBlock := a.cg.AuctionConstants.GenesisBlockNum + blocksPerSlot := int64(a.cg.AuctionConstants.BlocksPerSlot) firstBlock := slotNum*blocksPerSlot + genesisBlock lastBlock := (slotNum+1)*blocksPerSlot + genesisBlock - 1 return firstBlock, lastBlock } -func getCurrentSlot(currentBlock int64) int64 { - genesisBlock := cg.AuctionConstants.GenesisBlockNum - blocksPerSlot := int64(cg.AuctionConstants.BlocksPerSlot) +func (a *API) getCurrentSlot(currentBlock int64) int64 { + genesisBlock := a.cg.AuctionConstants.GenesisBlockNum + blocksPerSlot := int64(a.cg.AuctionConstants.BlocksPerSlot) currentSlot := (currentBlock - genesisBlock) / blocksPerSlot return currentSlot } -func isOpenAuction(currentBlock, slotNum int64, auctionVars common.AuctionVariables) bool { - currentSlot := getCurrentSlot(currentBlock) +func (a *API) isOpenAuction(currentBlock, slotNum int64, auctionVars common.AuctionVariables) bool { + currentSlot := a.getCurrentSlot(currentBlock) closedAuctionSlots := currentSlot + int64(auctionVars.ClosedAuctionSlots) openAuctionSlots := int64(auctionVars.OpenAuctionSlots) if slotNum > closedAuctionSlots && slotNum <= (closedAuctionSlots+openAuctionSlots) {

@@ -61,9 +61,9 @@ }

return pagination } -func newSlotAPI(slotNum, currentBlockNum int64, bid *historydb.BidAPI, auctionVars *common.AuctionVariables) SlotAPI { - firstBlock, lastBlock := getFirstLastBlock(slotNum) - openAuction := isOpenAuction(currentBlockNum, slotNum, *auctionVars) +func (a *API) newSlotAPI(slotNum, currentBlockNum int64, bid *historydb.BidAPI, auctionVars *common.AuctionVariables) SlotAPI { + firstBlock, lastBlock := a.getFirstLastBlock(slotNum) + openAuction := a.isOpenAuction(currentBlockNum, slotNum, *auctionVars) slot := SlotAPI{ ItemID: uint64(slotNum), SlotNum: slotNum,

@@ -75,10 +75,10 @@ }

return slot } -func newSlotsAPIFromWinnerBids(fromItem *uint, order string, bids []historydb.BidAPI, currentBlockNum int64, auctionVars *common.AuctionVariables) (slots []SlotAPI) { +func (a *API) newSlotsAPIFromWinnerBids(fromItem *uint, order string, bids []historydb.BidAPI, currentBlockNum int64, auctionVars *common.AuctionVariables) (slots []SlotAPI) { for i := range bids { slotNum := bids[i].SlotNum - slot := newSlotAPI(slotNum, currentBlockNum, &bids[i], auctionVars) + slot := a.newSlotAPI(slotNum, currentBlockNum, &bids[i], auctionVars) if order == historydb.OrderAsc { if slot.ItemID >= uint64(*fromItem) { slots = append(slots, slot)

@@ -92,8 +92,8 @@ }

return slots } -func addEmptySlot(slots []SlotAPI, slotNum int64, currentBlockNum int64, auctionVars *common.AuctionVariables, fromItem *uint, order string) ([]SlotAPI, error) { - emptySlot := newSlotAPI(slotNum, currentBlockNum, nil, auctionVars) +func (a *API) addEmptySlot(slots []SlotAPI, slotNum int64, currentBlockNum int64, auctionVars *common.AuctionVariables, fromItem *uint, order string) ([]SlotAPI, error) { + emptySlot := a.newSlotAPI(slotNum, currentBlockNum, nil, auctionVars) if order == historydb.OrderAsc { if emptySlot.ItemID >= uint64(*fromItem) { slots = append(slots, emptySlot)

@@ -106,25 +106,25 @@ }

return slots, nil } -func getSlot(c *gin.Context) { +func (a *API) getSlot(c *gin.Context) { slotNumUint, err := parseParamUint("slotNum", nil, 0, maxUint32, c) if err != nil { retBadReq(err, c) return } - currentBlock, err := h.GetLastBlock() + currentBlock, err := a.h.GetLastBlock() if err != nil { retBadReq(err, c) return } - auctionVars, err := h.GetAuctionVars() + auctionVars, err := a.h.GetAuctionVars() if err != nil { retBadReq(err, c) return } slotNum := int64(*slotNumUint) - bid, err := h.GetBestBidAPI(&slotNum) + bid, err := a.h.GetBestBidAPI(&slotNum) if err != nil && err != sql.ErrNoRows { retSQLErr(err, c) return

@@ -132,9 +132,9 @@ }

var slot SlotAPI if err == sql.ErrNoRows { - slot = newSlotAPI(slotNum, currentBlock.EthBlockNum, nil, auctionVars) + slot = a.newSlotAPI(slotNum, currentBlock.EthBlockNum, nil, auctionVars) } else { - slot = newSlotAPI(bid.SlotNum, currentBlock.EthBlockNum, &bid, auctionVars) + slot = a.newSlotAPI(bid.SlotNum, currentBlock.EthBlockNum, &bid, auctionVars) } // JSON response

@@ -193,7 +193,7 @@ }

return minLim, maxLim } -func getSlots(c *gin.Context) { +func (a *API) getSlots(c *gin.Context) { var slots []SlotAPI minSlotNumDflt := int64(0)

@@ -211,12 +211,12 @@ retBadReq(err, c)

return } - currentBlock, err := h.GetLastBlock() + currentBlock, err := a.h.GetLastBlock() if err != nil { retBadReq(err, c) return } - auctionVars, err := h.GetAuctionVars() + auctionVars, err := a.h.GetAuctionVars() if err != nil { retBadReq(err, c) return

@@ -231,13 +231,13 @@ if maxSlotNum == nil && !*finishedAuction {

retBadReq(errors.New("It is necessary to add maxSlotNum filter"), c) return } else if *finishedAuction { - currentBlock, err := h.GetLastBlock() + currentBlock, err := a.h.GetLastBlock() if err != nil { retBadReq(err, c) return } - currentSlot := getCurrentSlot(currentBlock.EthBlockNum) - auctionVars, err := h.GetAuctionVars() + currentSlot := a.getCurrentSlot(currentBlock.EthBlockNum) + auctionVars, err := a.h.GetAuctionVars() if err != nil { retBadReq(err, c) return

@@ -267,7 +267,7 @@ totalItems := uint64(0)

if wonByEthereumAddress == nil { slotMinLim, slotMaxLim = getLimits(minSlotNum, maxSlotNum, fromItem, limit, order) // Get best bids in range maxSlotNum - minSlotNum - bids, _, err = h.GetBestBidsAPI(&slotMinLim, &slotMaxLim, wonByEthereumAddress, nil, order) + bids, _, err = a.h.GetBestBidsAPI(&slotMinLim, &slotMaxLim, wonByEthereumAddress, nil, order) if err != nil && err != sql.ErrNoRows { retSQLErr(err, c) return

@@ -275,7 +275,7 @@ }

totalItems = uint64(*maxSlotNum) - uint64(*minSlotNum) + 1 } else { slotMinLim, slotMaxLim = getLimitsWithAddr(minSlotNum, maxSlotNum, fromItem, limit, order) - bids, pag, err = h.GetBestBidsAPI(&slotMinLim, &slotMaxLim, wonByEthereumAddress, limit, order) + bids, pag, err = a.h.GetBestBidsAPI(&slotMinLim, &slotMaxLim, wonByEthereumAddress, limit, order) if err != nil && err != sql.ErrNoRows { retSQLErr(err, c) return

@@ -290,7 +290,7 @@

// Build the slot information with previous bids var slotsBids []SlotAPI if len(bids) > 0 { - slotsBids = newSlotsAPIFromWinnerBids(fromItem, order, bids, currentBlock.EthBlockNum, auctionVars) + slotsBids = a.newSlotsAPIFromWinnerBids(fromItem, order, bids, currentBlock.EthBlockNum, auctionVars) if err != nil { retBadReq(err, c) return

@@ -318,7 +318,7 @@ break

} } if !found { - slots, err = addEmptySlot(slots, i, currentBlock.EthBlockNum, auctionVars, fromItem, order) + slots, err = a.addEmptySlot(slots, i, currentBlock.EthBlockNum, auctionVars, fromItem, order) if err != nil { retBadReq(err, c) return
M api/slots_test.go → api/slots_test.go

@@ -41,7 +41,7 @@ func (t testSlotsResponse) Len() int {

return len(t.Slots) } -func genTestSlots(nSlots int, lastBlockNum int64, bids []testBid, auctionVars common.AuctionVariables) []testSlot { +func (a *API) genTestSlots(nSlots int, lastBlockNum int64, bids []testBid, auctionVars common.AuctionVariables) []testSlot { tSlots := []testSlot{} bestBids := make(map[int64]testBid) // It's assumed that bids for each slot will be received in increasing order

@@ -51,12 +51,12 @@ }

for i := int64(0); i < int64(nSlots); i++ { bid, ok := bestBids[i] - firstBlock, lastBlock := getFirstLastBlock(int64(i)) + firstBlock, lastBlock := a.getFirstLastBlock(int64(i)) tSlot := testSlot{ SlotNum: int64(i), FirstBlock: firstBlock, LastBlock: lastBlock, - OpenAuction: isOpenAuction(lastBlockNum, int64(i), auctionVars), + OpenAuction: a.isOpenAuction(lastBlockNum, int64(i), auctionVars), } if ok { tSlot.WinnerBid = &bid

@@ -66,8 +66,8 @@ }

return tSlots } -func getEmptyTestSlot(slotNum int64) testSlot { - firstBlock, lastBlock := getFirstLastBlock(slotNum) +func (a *API) getEmptyTestSlot(slotNum int64) testSlot { + firstBlock, lastBlock := a.getFirstLastBlock(slotNum) slot := testSlot{ SlotNum: slotNum, FirstBlock: firstBlock,

@@ -102,7 +102,7 @@ endpoint+strconv.Itoa(int(slotNum)),

nil, &fetchedSlot, ), ) - emptySlot := getEmptyTestSlot(slotNum) + emptySlot := api.getEmptyTestSlot(slotNum) assertSlot(t, emptySlot, fetchedSlot) // Invalid slotNum

@@ -131,7 +131,7 @@ err := doGoodReqPaginated(path, historydb.OrderAsc, &testSlotsResponse{}, appendIter)

assert.NoError(t, err) allSlots := tc.slots for i := tc.slots[len(tc.slots)-1].SlotNum; i < maxSlotNum; i++ { - emptySlot := getEmptyTestSlot(i + 1) + emptySlot := api.getEmptyTestSlot(i + 1) allSlots = append(allSlots, emptySlot) } assertSlots(t, allSlots, fetchedSlots)

@@ -185,7 +185,7 @@ path = fmt.Sprintf("%s?finishedAuction=%t&limit=%d&fromItem=", endpoint, true, limit)

err = doGoodReqPaginated(path, historydb.OrderAsc, &testSlotsResponse{}, appendIter) assert.NoError(t, err) - currentSlot := getCurrentSlot(tc.blocks[len(tc.blocks)-1].EthBlockNum) + currentSlot := api.getCurrentSlot(tc.blocks[len(tc.blocks)-1].EthBlockNum) finishedAuctionSlots := []testSlot{} for i := 0; i < len(tc.slots); i++ { finishAuction := currentSlot + int64(tc.auctionVars.ClosedAuctionSlots)
M api/state.go → api/state.go

@@ -1,16 +1,11 @@

package api import ( - "github.com/hermeznetwork/hermez-node/common" - "github.com/hermeznetwork/hermez-node/db/historydb" + "net/http" + + "github.com/gin-gonic/gin" ) -// Status define status of the network -type Status struct { - Network historydb.Network `json:"network"` - Metrics historydb.Metrics `json:"metrics"` - Rollup common.RollupVariables `json:"rollup"` - Auction common.AuctionVariables `json:"auction"` - WithdrawalDelayer common.WDelayerVariables `json:"withdrawalDelayer"` - RecommendedFee common.RecommendedFee `json:"recommendedFee"` +func (a *API) getState(c *gin.Context) { + c.JSON(http.StatusOK, a.status) }
M api/token.go → api/token.go

@@ -10,7 +10,7 @@ "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/db/historydb" ) -func getToken(c *gin.Context) { +func (a *API) getToken(c *gin.Context) { // Get TokenID tokenIDUint, err := parseParamUint("id", nil, 0, maxUint32, c) if err != nil {

@@ -23,7 +23,7 @@ return

} tokenID := common.TokenID(*tokenIDUint) // Fetch token from historyDB - token, err := h.GetToken(tokenID) + token, err := a.h.GetToken(tokenID) if err != nil { retSQLErr(err, c) return

@@ -31,7 +31,7 @@ }

c.JSON(http.StatusOK, token) } -func getTokens(c *gin.Context) { +func (a *API) getTokens(c *gin.Context) { // Account filters tokenIDs, symbols, name, err := parseTokenFilters(c) if err != nil {

@@ -46,7 +46,7 @@ retBadReq(err, c)

return } // Fetch exits from historyDB - tokens, pagination, err := h.GetTokens( + tokens, pagination, err := a.h.GetTokens( tokenIDs, symbols, name, fromItem, limit, order, ) if err != nil {
M api/txshistory.go → api/txshistory.go

@@ -8,7 +8,7 @@ "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/db/historydb" ) -func getHistoryTxs(c *gin.Context) { +func (a *API) getHistoryTxs(c *gin.Context) { // Get query parameters tokenID, addr, bjj, idx, err := parseExitFilters(c) if err != nil {

@@ -35,7 +35,7 @@ return

} // Fetch txs from historyDB - txs, pagination, err := h.GetHistoryTxs( + txs, pagination, err := a.h.GetHistoryTxs( addr, bjj, tokenID, idx, batchNum, txType, fromItem, limit, order, ) if err != nil {

@@ -54,7 +54,7 @@ Pagination: pagination,

}) } -func getHistoryTx(c *gin.Context) { +func (a *API) getHistoryTx(c *gin.Context) { // Get TxID txID, err := parseParamTxID(c) if err != nil {

@@ -62,7 +62,7 @@ retBadReq(err, c)

return } // Fetch tx from historyDB - tx, err := h.GetHistoryTx(txID) + tx, err := a.h.GetHistoryTx(txID) if err != nil { retSQLErr(err, c) return
M api/txspool.go → api/txspool.go

@@ -13,7 +13,7 @@ "github.com/hermeznetwork/hermez-node/db/l2db"

"github.com/iden3/go-iden3-crypto/babyjub" ) -func postPoolTx(c *gin.Context) { +func (a *API) postPoolTx(c *gin.Context) { // Parse body var receivedTx receivedPoolTx if err := c.ShouldBindJSON(&receivedTx); err != nil {

@@ -22,12 +22,12 @@ return

} // Transform from received to insert format and validate writeTx := receivedTx.toPoolL2TxWrite() - if err := verifyPoolL2TxWrite(writeTx); err != nil { + if err := a.verifyPoolL2TxWrite(writeTx); err != nil { retBadReq(err, c) return } // Insert to DB - if err := l2.AddTx(writeTx); err != nil { + if err := a.l2.AddTx(writeTx); err != nil { retSQLErr(err, c) return }

@@ -35,7 +35,7 @@ // Return TxID

c.JSON(http.StatusOK, writeTx.TxID.String()) } -func getPoolTx(c *gin.Context) { +func (a *API) getPoolTx(c *gin.Context) { // Get TxID txID, err := parseParamTxID(c) if err != nil {

@@ -43,7 +43,7 @@ retBadReq(err, c)

return } // Fetch tx from l2DB - tx, err := l2.GetTxAPI(txID) + tx, err := a.l2.GetTxAPI(txID) if err != nil { retSQLErr(err, c) return

@@ -102,7 +102,7 @@ Type: tx.Type,

} } -func verifyPoolL2TxWrite(txw *l2db.PoolL2TxWrite) error { +func (a *API) verifyPoolL2TxWrite(txw *l2db.PoolL2TxWrite) error { poolTx := common.PoolL2Tx{ TxID: txw.TxID, FromIdx: txw.FromIdx,

@@ -159,7 +159,7 @@ if err != nil {

return err } // Get public key - account, err := s.GetAccount(poolTx.FromIdx) + account, err := a.s.GetAccount(poolTx.FromIdx) if err != nil { return err }
M common/fee_test.go → common/fee_test.go

@@ -9,15 +9,15 @@ "github.com/stretchr/testify/assert"

) func TestFeePercentage(t *testing.T) { - assert.InEpsilon(t, 2.68E-18, FeeSelector(1).Percentage(), 0.002) - assert.InEpsilon(t, 6.76E-14, FeeSelector(10).Percentage(), 0.002) - assert.InEpsilon(t, 3.91E-03, FeeSelector(32).Percentage(), 0.002) - assert.InEpsilon(t, 7.29E-03, FeeSelector(50).Percentage(), 0.002) - assert.InEpsilon(t, 4.12E-02, FeeSelector(100).Percentage(), 0.002) - assert.InEpsilon(t, 2.33E-01, FeeSelector(150).Percentage(), 0.002) - assert.InEpsilon(t, 1.00E+00, FeeSelector(192).Percentage(), 0.002) - assert.InEpsilon(t, 2.56E+02, FeeSelector(200).Percentage(), 0.002) - assert.InEpsilon(t, 2.88E+17, FeeSelector(250).Percentage(), 0.002) + assert.InEpsilon(t, 2.68e-18, FeeSelector(1).Percentage(), 0.002) + assert.InEpsilon(t, 6.76e-14, FeeSelector(10).Percentage(), 0.002) + assert.InEpsilon(t, 3.91e-03, FeeSelector(32).Percentage(), 0.002) + assert.InEpsilon(t, 7.29e-03, FeeSelector(50).Percentage(), 0.002) + assert.InEpsilon(t, 4.12e-02, FeeSelector(100).Percentage(), 0.002) + assert.InEpsilon(t, 2.33e-01, FeeSelector(150).Percentage(), 0.002) + assert.InEpsilon(t, 1.00e+00, FeeSelector(192).Percentage(), 0.002) + assert.InEpsilon(t, 2.56e+02, FeeSelector(200).Percentage(), 0.002) + assert.InEpsilon(t, 2.88e+17, FeeSelector(250).Percentage(), 0.002) } func TestCalcFeeAmount(t *testing.T) {