Browse Source

Put api DBs into struct

feature/sql-semaphore1
Arnau B 3 years ago
parent
commit
1112ded933
18 changed files with 172 additions and 172 deletions
  1. +6
    -6
      api/account.go
  2. +4
    -4
      api/accountcreationauths.go
  3. +53
    -38
      api/api.go
  4. +21
    -19
      api/api_test.go
  5. +7
    -7
      api/batch.go
  6. +2
    -2
      api/bids.go
  7. +2
    -2
      api/config.go
  8. +1
    -1
      api/config_test.go
  9. +4
    -4
      api/coordinator.go
  10. +4
    -4
      api/exits.go
  11. +0
    -12
      api/handlers.go
  12. +31
    -31
      api/slots.go
  13. +8
    -8
      api/slots_test.go
  14. +5
    -10
      api/state.go
  15. +4
    -4
      api/token.go
  16. +4
    -4
      api/txshistory.go
  17. +7
    -7
      api/txspool.go
  18. +9
    -9
      common/fee_test.go

+ 6
- 6
api/account.go

@ -9,21 +9,21 @@ import (
"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 @@ func getAccount(c *gin.Context) {
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 @@ func getAccounts(c *gin.Context) {
}
// 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 @@ func getAccounts(c *gin.Context) {
retSQLErr(err, c)
return
}
account, err := s.GetAccount(*idx)
account, err := a.s.GetAccount(*idx)
if err != nil {
retSQLErr(err, c)
return

+ 4
- 4
api/accountcreationauths.go

@ -12,7 +12,7 @@ import (
"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 @@ func postAccountCreationAuth(c *gin.Context) {
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 @@ func postAccountCreationAuth(c *gin.Context) {
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 @@ func getAccountCreationAuth(c *gin.Context) {
return
}
// Fetch auth from l2DB
auth, err := l2.GetAccountCreationAuthAPI(*addr)
auth, err := a.l2.GetAccountCreationAuthAPI(*addr)
if err != nil {
retSQLErr(err, c)
return

+ 53
- 38
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"`
}
// 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
}
// SetAPIEndpoints sets the endpoints and the appropriate handlers, but doesn't start the server
func SetAPIEndpoints(
// 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
}

+ 21
- 19
api/api_test.go

@ -56,6 +56,7 @@ type testCommon struct {
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 @@ func TestMain(m *testing.M) {
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 @@ func TestMain(m *testing.M) {
// 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 @@ func TestMain(m *testing.M) {
// 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 @@ func TestMain(m *testing.M) {
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 @@ func TestMain(m *testing.M) {
// 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 @@ func TestMain(m *testing.M) {
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 @@ func TestMain(m *testing.M) {
// 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 @@ func TestMain(m *testing.M) {
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 @@ func TestMain(m *testing.M) {
// 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 @@ func TestMain(m *testing.M) {
// 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 @@ func TestMain(m *testing.M) {
ClosedAuctionSlots: uint16(2),
OpenAuctionSlots: uint16(5),
}
err = hdb.AddAuctionVars(&auctionVars)
err = api.h.AddAuctionVars(&auctionVars)
if err != nil {
panic(err)
}
@ -309,7 +311,7 @@ func TestMain(m *testing.M) {
auths: genTestAuths(test.GenAuths(5)),
router: router,
bids: testBids,
slots: genTestSlots(nSlots, lastBlockNum, testBids, auctionVars),
slots: api.genTestSlots(nSlots, lastBlockNum, testBids, auctionVars),
auctionVars: auctionVars,
}

+ 7
- 7
api/batch.go

@ -10,7 +10,7 @@ import (
"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 @@ func getBatches(c *gin.Context) {
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 @@ func getBatches(c *gin.Context) {
})
}
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 @@ func getBatch(c *gin.Context) {
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 @@ type fullBatch struct {
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 @@ func getFullBatch(c *gin.Context) {
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 {

+ 2
- 2
api/bids.go

@ -9,7 +9,7 @@ import (
"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 @@ func getBids(c *gin.Context) {
return
}
bids, pagination, err := h.GetBidsAPI(
bids, pagination, err := a.h.GetBidsAPI(
slotNum, bidderAddr, fromItem, limit, order,
)

+ 2
- 2
api/config.go

@ -32,6 +32,6 @@ type configAPI struct {
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)
}

+ 1
- 1
api/config_test.go

@ -62,5 +62,5 @@ func TestGetConfig(t *testing.T) {
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)
}

+ 4
- 4
api/coordinator.go

@ -8,7 +8,7 @@ import (
"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 @@ func getCoordinator(c *gin.Context) {
return
}
coordinator, err := h.GetCoordinatorAPI(*bidderAddr)
coordinator, err := a.h.GetCoordinatorAPI(*bidderAddr)
if err != nil {
retSQLErr(err, c)
return
@ -30,7 +30,7 @@ func getCoordinator(c *gin.Context) {
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 @@ func getCoordinators(c *gin.Context) {
}
// 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

+ 4
- 4
api/exits.go

@ -8,7 +8,7 @@ import (
"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 @@ func getExits(c *gin.Context) {
}
// 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 @@ func getExits(c *gin.Context) {
})
}
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 @@ func getExit(c *gin.Context) {
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

+ 0
- 12
api/handlers.go

@ -31,18 +31,6 @@ var (
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{

+ 31
- 31
api/slots.go

@ -24,23 +24,23 @@ type SlotAPI struct {
LastItem int `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 @@ func getPagination(totalItems int, minSlotNum, maxSlotNum *int64) *db.Pagination
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: int(slotNum),
SlotNum: slotNum,
@ -75,10 +75,10 @@ func newSlotAPI(slotNum, currentBlockNum int64, bid *historydb.BidAPI, auctionVa
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 >= int(*fromItem) {
slots = append(slots, slot)
@ -92,8 +92,8 @@ func newSlotsAPIFromWinnerBids(fromItem *uint, order string, bids []historydb.Bi
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 >= int(*fromItem) {
slots = append(slots, emptySlot)
@ -106,25 +106,25 @@ func addEmptySlot(slots []SlotAPI, slotNum int64, currentBlockNum int64, auction
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 @@ func getSlot(c *gin.Context) {
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 @@ func getLimitsWithAddr(minSlotNum, maxSlotNum *int64, fromItem, limit *uint, ord
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 @@ func getSlots(c *gin.Context) {
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 @@ func getSlots(c *gin.Context) {
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 @@ func getSlots(c *gin.Context) {
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 @@ func getSlots(c *gin.Context) {
totalItems = int(*maxSlotNum) - int(*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 @@ func getSlots(c *gin.Context) {
// 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 @@ func getSlots(c *gin.Context) {
}
}
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

+ 8
- 8
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 @@ func genTestSlots(nSlots int, lastBlockNum int64, bids []testBid, auctionVars co
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 @@ func genTestSlots(nSlots int, lastBlockNum int64, bids []testBid, auctionVars co
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 @@ func TestGetSlot(t *testing.T) {
nil, &fetchedSlot,
),
)
emptySlot := getEmptyTestSlot(slotNum)
emptySlot := api.getEmptyTestSlot(slotNum)
assertSlot(t, emptySlot, fetchedSlot)
// Invalid slotNum
@ -131,7 +131,7 @@ func TestGetSlots(t *testing.T) {
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 @@ func TestGetSlots(t *testing.T) {
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)

+ 5
- 10
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)
}

+ 4
- 4
api/token.go

@ -10,7 +10,7 @@ import (
"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 @@ func getToken(c *gin.Context) {
}
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 @@ func getToken(c *gin.Context) {
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 @@ func getTokens(c *gin.Context) {
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 {

+ 4
- 4
api/txshistory.go

@ -8,7 +8,7 @@ import (
"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 @@ func getHistoryTxs(c *gin.Context) {
}
// 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 @@ func getHistoryTxs(c *gin.Context) {
})
}
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 @@ func getHistoryTx(c *gin.Context) {
return
}
// Fetch tx from historyDB
tx, err := h.GetHistoryTx(txID)
tx, err := a.h.GetHistoryTx(txID)
if err != nil {
retSQLErr(err, c)
return

+ 7
- 7
api/txspool.go

@ -13,7 +13,7 @@ import (
"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 @@ func postPoolTx(c *gin.Context) {
}
// 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 @@ func postPoolTx(c *gin.Context) {
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 @@ func getPoolTx(c *gin.Context) {
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 @@ func (tx *receivedPoolTx) toPoolL2TxWrite() *l2db.PoolL2TxWrite {
}
}
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 @@ func verifyPoolL2TxWrite(txw *l2db.PoolL2TxWrite) error {
return err
}
// Get public key
account, err := s.GetAccount(poolTx.FromIdx)
account, err := a.s.GetAccount(poolTx.FromIdx)
if err != nil {
return err
}

+ 9
- 9
common/fee_test.go

@ -9,15 +9,15 @@ import (
)
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) {

Loading…
Cancel
Save