Wrap all errors with tracerr

This commit is contained in:
Eduard S
2020-11-30 12:58:36 +01:00
parent 879af66a2a
commit ced42634da
59 changed files with 1324 additions and 1268 deletions

View File

@@ -9,6 +9,7 @@ import (
"github.com/hermeznetwork/hermez-node/db/historydb"
"github.com/hermeznetwork/hermez-node/db/l2db"
"github.com/hermeznetwork/hermez-node/db/statedb"
"github.com/hermeznetwork/tracerr"
)
// TODO: Add correct values to constants
@@ -49,10 +50,10 @@ func NewAPI(
// Check input
// TODO: is stateDB only needed for explorer endpoints or for both?
if coordinatorEndpoints && l2db == nil {
return nil, errors.New("cannot serve Coordinator endpoints without L2DB")
return nil, tracerr.Wrap(errors.New("cannot serve Coordinator endpoints without L2DB"))
}
if explorerEndpoints && hdb == nil {
return nil, errors.New("cannot serve Explorer endpoints without HistoryDB")
return nil, tracerr.Wrap(errors.New("cannot serve Explorer endpoints without HistoryDB"))
}
a := &API{

View File

@@ -25,6 +25,7 @@ import (
"github.com/hermeznetwork/hermez-node/log"
"github.com/hermeznetwork/hermez-node/test"
"github.com/hermeznetwork/hermez-node/test/til"
"github.com/hermeznetwork/tracerr"
)
// Pendinger is an interface that allows getting last returned item ID and PendingItems to be used for building fromItem
@@ -243,8 +244,7 @@ func TestMain(m *testing.M) {
// Start server
server := &http.Server{Addr: apiPort, Handler: apiGin}
go func() {
if err := server.ListenAndServe(); err != nil &&
err != http.ErrServerClosed {
if err := server.ListenAndServe(); err != nil && tracerr.Unwrap(err) != http.ErrServerClosed {
panic(err)
}
}()
@@ -471,7 +471,7 @@ func doGoodReqPaginated(
"GET", iterPath+"&order="+order, nil,
iterStruct,
); err != nil {
return err
return tracerr.Wrap(err)
}
appendIter(iterStruct)
// Keep iterating?
@@ -505,14 +505,14 @@ func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{})
client := &http.Client{}
httpReq, err := http.NewRequest(method, path, reqBody)
if err != nil {
return err
return tracerr.Wrap(err)
}
if reqBody != nil {
httpReq.Header.Add("Content-Type", "application/json")
}
route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
if err != nil {
return err
return tracerr.Wrap(err)
}
// Validate request against swagger spec
requestValidationInput := &swagger.RequestValidationInput{
@@ -521,24 +521,24 @@ func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{})
Route: route,
}
if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
return err
return tracerr.Wrap(err)
}
// Do API call
resp, err := client.Do(httpReq)
if err != nil {
return err
return tracerr.Wrap(err)
}
if resp.Body == nil && returnStruct != nil {
return errors.New("Nil body")
return tracerr.Wrap(errors.New("Nil body"))
}
//nolint
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
return tracerr.Wrap(err)
}
if resp.StatusCode != 200 {
return fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body))
return tracerr.Wrap(fmt.Errorf("%d response. Body: %s", resp.StatusCode, string(body)))
}
if returnStruct == nil {
return nil
@@ -547,7 +547,7 @@ func doGoodReq(method, path string, reqBody io.Reader, returnStruct interface{})
if err := json.Unmarshal(body, returnStruct); err != nil {
log.Error("invalid json: " + string(body))
log.Error(err)
return err
return tracerr.Wrap(err)
}
// log.Info(string(body))
// Validate response against swagger spec
@@ -566,7 +566,7 @@ func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int)
httpReq, _ := http.NewRequest(method, path, reqBody)
route, pathParams, err := tc.router.FindRoute(httpReq.Method, httpReq.URL)
if err != nil {
return err
return tracerr.Wrap(err)
}
// Validate request against swagger spec
requestValidationInput := &swagger.RequestValidationInput{
@@ -576,26 +576,26 @@ func doBadReq(method, path string, reqBody io.Reader, expectedResponseCode int)
}
if err := swagger.ValidateRequest(ctx, requestValidationInput); err != nil {
if expectedResponseCode != 400 {
return err
return tracerr.Wrap(err)
}
log.Warn("The request does not match the API spec")
}
// Do API call
resp, err := client.Do(httpReq)
if err != nil {
return err
return tracerr.Wrap(err)
}
if resp.Body == nil {
return errors.New("Nil body")
return tracerr.Wrap(errors.New("Nil body"))
}
//nolint
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
return tracerr.Wrap(err)
}
if resp.StatusCode != expectedResponseCode {
return fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body))
return tracerr.Wrap(fmt.Errorf("Unexpected response code: %d. Body: %s", resp.StatusCode, string(body)))
}
// Validate response against swagger spec
responseValidationInput := &swagger.ResponseValidationInput{

View File

@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/hermeznetwork/hermez-node/common"
"github.com/hermeznetwork/hermez-node/db/historydb"
"github.com/hermeznetwork/tracerr"
)
func (a *API) getBatches(c *gin.Context) {
@@ -110,7 +111,7 @@ func (a *API) getFullBatch(c *gin.Context) {
txs, _, err := a.h.GetHistoryTxs(
nil, nil, nil, nil, batchNum, nil, nil, &maxTxsPerBatch, historydb.OrderAsc,
)
if err != nil && err != sql.ErrNoRows {
if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows {
retSQLErr(err, c)
return
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/hermeznetwork/hermez-node/db/historydb"
"github.com/hermeznetwork/tracerr"
)
const (
@@ -32,7 +33,7 @@ var (
)
func retSQLErr(err error, c *gin.Context) {
if err == sql.ErrNoRows {
if tracerr.Unwrap(err) == sql.ErrNoRows {
c.JSON(http.StatusNotFound, errorMsg{
Message: err.Error(),
})

View File

@@ -10,6 +10,7 @@ import (
ethCommon "github.com/ethereum/go-ethereum/common"
"github.com/hermeznetwork/hermez-node/common"
"github.com/hermeznetwork/hermez-node/db/historydb"
"github.com/hermeznetwork/tracerr"
"github.com/iden3/go-iden3-crypto/babyjub"
)
@@ -25,16 +26,16 @@ func parsePagination(c querier) (fromItem *uint, order string, limit *uint, err
// FromItem
fromItem, err = parseQueryUint("fromItem", nil, 0, maxUint32, c)
if err != nil {
return nil, "", nil, err
return nil, "", nil, tracerr.Wrap(err)
}
// Order
order = dfltOrder
const orderName = "order"
orderStr := c.Query(orderName)
if orderStr != "" && !(orderStr == historydb.OrderAsc || historydb.OrderDesc == orderStr) {
return nil, "", nil, errors.New(
return nil, "", nil, tracerr.Wrap(errors.New(
"order must have the value " + historydb.OrderAsc + " or " + historydb.OrderDesc,
)
))
}
if orderStr == historydb.OrderAsc {
order = historydb.OrderAsc
@@ -46,7 +47,7 @@ func parsePagination(c querier) (fromItem *uint, order string, limit *uint, err
*limit = dfltLimit
limit, err = parseQueryUint("limit", limit, 1, maxLimit, c)
if err != nil {
return nil, "", nil, err
return nil, "", nil, tracerr.Wrap(err)
}
return fromItem, order, limit, nil
}
@@ -79,7 +80,7 @@ func parseQueryBool(name string, dflt *bool, c querier) (*bool, error) { //nolin
*res = false
return res, nil
}
return nil, fmt.Errorf("Invalid %s. Must be eithe true or false", name)
return nil, tracerr.Wrap(fmt.Errorf("Invalid %s. Must be eithe true or false", name))
}
func parseQueryHezEthAddr(c querier) (*ethCommon.Address, error) {
@@ -135,10 +136,10 @@ func parseQueryTxType(c querier) (*common.TxType, error) {
ret := common.TxTypeTransferToBJJ
return &ret, nil
}
return nil, fmt.Errorf(
return nil, tracerr.Wrap(fmt.Errorf(
"invalid %s, %s is not a valid option. Check the valid options in the docmentation",
name, typeStr,
)
))
}
func parseIdx(c querier) (*common.Idx, error) {
@@ -151,7 +152,7 @@ func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.
// TokenID
tid, err := parseQueryUint("tokenId", nil, 0, maxUint32, c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
var tokenID *common.TokenID
if tid != nil {
@@ -161,25 +162,23 @@ func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.
// Hez Eth addr
addr, err := parseQueryHezEthAddr(c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
// BJJ
bjj, err := parseQueryBJJ(c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
if addr != nil && bjj != nil {
return nil, nil, nil, nil,
errors.New("bjj and hermezEthereumAddress params are incompatible")
return nil, nil, nil, nil, tracerr.Wrap(errors.New("bjj and hermezEthereumAddress params are incompatible"))
}
// Idx
idx, err := parseIdx(c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
if idx != nil && (addr != nil || bjj != nil || tokenID != nil) {
return nil, nil, nil, nil,
errors.New("accountIndex is incompatible with BJJ, hermezEthereumAddress and tokenId")
return nil, nil, nil, nil, tracerr.Wrap(errors.New("accountIndex is incompatible with BJJ, hermezEthereumAddress and tokenId"))
}
return tokenID, addr, bjj, idx, nil
}
@@ -195,7 +194,7 @@ func parseTokenFilters(c querier) ([]common.TokenID, []string, string, error) {
for _, id := range ids {
idUint, err := strconv.Atoi(id)
if err != nil {
return nil, nil, "", err
return nil, nil, "", tracerr.Wrap(err)
}
tokenID := common.TokenID(idUint)
tokensIDs = append(tokensIDs, tokenID)
@@ -211,11 +210,11 @@ func parseTokenFilters(c querier) ([]common.TokenID, []string, string, error) {
func parseBidFilters(c querier) (*int64, *ethCommon.Address, error) {
slotNum, err := parseQueryInt64("slotNum", nil, 0, maxInt64, c)
if err != nil {
return nil, nil, err
return nil, nil, tracerr.Wrap(err)
}
bidderAddr, err := parseQueryEthAddr("bidderAddr", c)
if err != nil {
return nil, nil, err
return nil, nil, tracerr.Wrap(err)
}
return slotNum, bidderAddr, nil
}
@@ -223,19 +222,19 @@ func parseBidFilters(c querier) (*int64, *ethCommon.Address, error) {
func parseSlotFilters(c querier) (*int64, *int64, *ethCommon.Address, *bool, error) {
minSlotNum, err := parseQueryInt64("minSlotNum", nil, 0, maxInt64, c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
maxSlotNum, err := parseQueryInt64("maxSlotNum", nil, 0, maxInt64, c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
wonByEthereumAddress, err := parseQueryEthAddr("wonByEthereumAddress", c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
finishedAuction, err := parseQueryBool("finishedAuction", nil, c)
if err != nil {
return nil, nil, nil, nil, err
return nil, nil, nil, nil, tracerr.Wrap(err)
}
return minSlotNum, maxSlotNum, wonByEthereumAddress, finishedAuction, nil
}
@@ -250,7 +249,7 @@ func parseAccountFilters(c querier) ([]common.TokenID, *ethCommon.Address, *baby
for _, id := range ids {
idUint, err := strconv.Atoi(id)
if err != nil {
return nil, nil, nil, err
return nil, nil, nil, tracerr.Wrap(err)
}
tokenID := common.TokenID(idUint)
tokenIDs = append(tokenIDs, tokenID)
@@ -259,16 +258,15 @@ func parseAccountFilters(c querier) ([]common.TokenID, *ethCommon.Address, *baby
// Hez Eth addr
addr, err := parseQueryHezEthAddr(c)
if err != nil {
return nil, nil, nil, err
return nil, nil, nil, tracerr.Wrap(err)
}
// BJJ
bjj, err := parseQueryBJJ(c)
if err != nil {
return nil, nil, nil, err
return nil, nil, nil, tracerr.Wrap(err)
}
if addr != nil && bjj != nil {
return nil, nil, nil,
errors.New("bjj and hermezEthereumAddress params are incompatible")
return nil, nil, nil, tracerr.Wrap(errors.New("bjj and hermezEthereumAddress params are incompatible"))
}
return tokenIDs, addr, bjj, nil
@@ -284,11 +282,11 @@ func parseParamTxID(c paramer) (common.TxID, error) {
const name = "id"
txIDStr := c.Param(name)
if txIDStr == "" {
return common.TxID{}, fmt.Errorf("%s is required", name)
return common.TxID{}, tracerr.Wrap(fmt.Errorf("%s is required", name))
}
txID, err := common.NewTxIDFromString(txIDStr)
if err != nil {
return common.TxID{}, fmt.Errorf("invalid %s", name)
return common.TxID{}, tracerr.Wrap(fmt.Errorf("invalid %s", name))
}
return txID, nil
}
@@ -318,22 +316,22 @@ func stringToIdx(idxStr, name string) (*common.Idx, error) {
splitted := strings.Split(idxStr, ":")
const expectedLen = 3
if len(splitted) != expectedLen || splitted[0] != "hez" {
return nil, fmt.Errorf(
"invalid %s, must follow this: hez:<tokenSymbol>:index", name)
return nil, tracerr.Wrap(fmt.Errorf(
"invalid %s, must follow this: hez:<tokenSymbol>:index", name))
}
// TODO: check that the tokenSymbol match the token related to the account index
idxInt, err := strconv.Atoi(splitted[2])
idx := common.Idx(idxInt)
return &idx, err
return &idx, tracerr.Wrap(err)
}
func stringToUint(uintStr, name string, dflt *uint, min, max uint) (*uint, error) {
if uintStr != "" {
resInt, err := strconv.Atoi(uintStr)
if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
return nil, fmt.Errorf(
return nil, tracerr.Wrap(fmt.Errorf(
"Invalid %s. Must be an integer within the range [%d, %d]",
name, min, max)
name, min, max))
}
res := uint(resInt)
return &res, nil
@@ -345,9 +343,9 @@ func stringToInt64(uintStr, name string, dflt *int64, min, max int64) (*int64, e
if uintStr != "" {
resInt, err := strconv.Atoi(uintStr)
if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
return nil, fmt.Errorf(
return nil, tracerr.Wrap(fmt.Errorf(
"Invalid %s. Must be an integer within the range [%d, %d]",
name, min, max)
name, min, max))
}
res := int64(resInt)
return &res, nil
@@ -361,32 +359,32 @@ func hezStringToEthAddr(addrStr, name string) (*ethCommon.Address, error) {
}
splitted := strings.Split(addrStr, "hez:")
if len(splitted) != 2 || len(splitted[1]) != 42 {
return nil, fmt.Errorf(
"Invalid %s, must follow this regex: ^hez:0x[a-fA-F0-9]{40}$", name)
return nil, tracerr.Wrap(fmt.Errorf(
"Invalid %s, must follow this regex: ^hez:0x[a-fA-F0-9]{40}$", name))
}
var addr ethCommon.Address
err := addr.UnmarshalText([]byte(splitted[1]))
return &addr, err
return &addr, tracerr.Wrap(err)
}
func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKey, error) {
const decodedLen = 33
splitted := strings.Split(bjjStr, "hez:")
if len(splitted) != 2 || len(splitted[1]) != 44 {
return nil, fmt.Errorf(
return nil, tracerr.Wrap(fmt.Errorf(
"Invalid %s, must follow this regex: ^hez:[A-Za-z0-9+/=]{44}$",
name)
name))
}
decoded, err := base64.RawURLEncoding.DecodeString(splitted[1])
if err != nil {
return nil, fmt.Errorf(
return nil, tracerr.Wrap(fmt.Errorf(
"Invalid %s, error decoding base64 string: %s",
name, err.Error())
name, err.Error()))
}
if len(decoded) != decodedLen {
return nil, fmt.Errorf(
return nil, tracerr.Wrap(fmt.Errorf(
"invalid %s, error decoding base64 string: unexpected byte array length",
name)
name))
}
bjjBytes := [decodedLen - 1]byte{}
copy(bjjBytes[:decodedLen-1], decoded[:decodedLen-1])
@@ -395,15 +393,15 @@ func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKey, error) {
sum += bjjBytes[i]
}
if decoded[decodedLen-1] != sum {
return nil, fmt.Errorf("invalid %s, checksum failed",
name)
return nil, tracerr.Wrap(fmt.Errorf("invalid %s, checksum failed",
name))
}
bjjComp := babyjub.PublicKeyComp(bjjBytes)
bjj, err := bjjComp.Decompress()
if err != nil {
return nil, fmt.Errorf(
return nil, tracerr.Wrap(fmt.Errorf(
"invalid %s, error decompressing public key: %s",
name, err.Error())
name, err.Error()))
}
return bjj, nil
}
@@ -427,7 +425,7 @@ func parseParamEthAddr(name string, c paramer) (*ethCommon.Address, error) {
func parseEthAddr(ethAddrStr string) (*ethCommon.Address, error) {
var addr ethCommon.Address
err := addr.UnmarshalText([]byte(ethAddrStr))
return &addr, err
return &addr, tracerr.Wrap(err)
}
func parseParamHezEthAddr(c paramer) (*ethCommon.Address, error) {

View File

@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/hermeznetwork/hermez-node/common"
"github.com/hermeznetwork/hermez-node/db/historydb"
"github.com/hermeznetwork/tracerr"
)
// SlotAPI is a repesentation of a slot information
@@ -109,13 +110,13 @@ func (a *API) getSlot(c *gin.Context) {
slotNum := int64(*slotNumUint)
bid, err := a.h.GetBestBidAPI(&slotNum)
if err != nil && err != sql.ErrNoRows {
if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows {
retSQLErr(err, c)
return
}
var slot SlotAPI
if err == sql.ErrNoRows {
if tracerr.Unwrap(err) == sql.ErrNoRows {
slot = a.newSlotAPI(slotNum, currentBlock.Num, nil, auctionVars)
} else {
slot = a.newSlotAPI(bid.SlotNum, currentBlock.Num, &bid, auctionVars)
@@ -252,14 +253,14 @@ func (a *API) getSlots(c *gin.Context) {
slotMinLim, slotMaxLim, pendingItems = getLimits(*minSlotNum, *maxSlotNum, fromItem, limit, order)
// Get best bids in range maxSlotNum - minSlotNum
bids, _, err = a.h.GetBestBidsAPI(&slotMinLim, &slotMaxLim, wonByEthereumAddress, nil, order)
if err != nil && err != sql.ErrNoRows {
if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows {
retSQLErr(err, c)
return
}
} else {
slotMinLim, slotMaxLim = getLimitsWithAddr(minSlotNum, maxSlotNum, fromItem, limit, order)
bids, pendingItems, err = a.h.GetBestBidsAPI(&slotMinLim, &slotMaxLim, wonByEthereumAddress, limit, order)
if err != nil && err != sql.ErrNoRows {
if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows {
retSQLErr(err, c)
return
}

View File

@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/hermeznetwork/hermez-node/common"
"github.com/hermeznetwork/hermez-node/db/historydb"
"github.com/hermeznetwork/tracerr"
)
// Network define status of the network
@@ -89,12 +90,12 @@ func (a *API) UpdateNetworkInfo(
) error {
lastBatch, err := a.h.GetBatchAPI(lastBatchNum)
if err != nil {
return err
return tracerr.Wrap(err)
}
lastClosedSlot := currentSlot + int64(a.status.Auction.ClosedAuctionSlots)
nextForgers, err := a.getNextForgers(lastSyncBlock, currentSlot, lastClosedSlot)
if err != nil {
return err
return tracerr.Wrap(err)
}
a.status.Lock()
a.status.Network.LastSyncBlock = lastSyncBlock.Num
@@ -113,7 +114,7 @@ func (a *API) getNextForgers(lastBlock common.Block, currentSlot, lastClosedSlot
limit := uint(lastClosedSlot - currentSlot + 1)
bids, _, err := a.h.GetBestBidsAPI(&currentSlot, &lastClosedSlot, nil, &limit, "ASC")
if err != nil {
return nil, err
return nil, tracerr.Wrap(err)
}
nextForgers := []NextForger{}
// Create nextForger for each slot
@@ -136,7 +137,7 @@ func (a *API) getNextForgers(lastBlock common.Block, currentSlot, lastClosedSlot
foundBid = true
coordinator, err := a.h.GetCoordinatorAPI(bids[j].Bidder)
if err != nil {
return nil, err
return nil, tracerr.Wrap(err)
}
nextForger.Coordinator = *coordinator
break
@@ -160,7 +161,7 @@ func (a *API) UpdateMetrics() error {
a.status.RUnlock()
metrics, err := a.h.GetMetrics(batchNum)
if err != nil {
return err
return tracerr.Wrap(err)
}
a.status.Lock()
a.status.Metrics = *metrics
@@ -174,7 +175,7 @@ func (a *API) UpdateMetrics() error {
func (a *API) UpdateRecommendedFee() error {
feeExistingAccount, err := a.h.GetAvgTxFee()
if err != nil {
return err
return tracerr.Wrap(err)
}
a.status.Lock()
a.status.RecommendedFee.ExistingAccount = feeExistingAccount

View File

@@ -10,6 +10,7 @@ import (
"github.com/hermeznetwork/hermez-node/apitypes"
"github.com/hermeznetwork/hermez-node/common"
"github.com/hermeznetwork/hermez-node/db/l2db"
"github.com/hermeznetwork/tracerr"
"github.com/iden3/go-iden3-crypto/babyjub"
)
@@ -156,21 +157,21 @@ func (a *API) verifyPoolL2TxWrite(txw *l2db.PoolL2TxWrite) error {
// Check type and id
_, err := common.NewPoolL2Tx(&poolTx)
if err != nil {
return err
return tracerr.Wrap(err)
}
// Get public key
account, err := a.s.GetAccount(poolTx.FromIdx)
if err != nil {
return err
return tracerr.Wrap(err)
}
// Validate feeAmount
_, err = common.CalcFeeAmount(poolTx.Amount, poolTx.Fee)
if err != nil {
return err
return tracerr.Wrap(err)
}
// Check signature
if !poolTx.VerifySignature(account.PublicKey) {
return errors.New("wrong signature")
return tracerr.Wrap(errors.New("wrong signature"))
}
return nil
}