arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
Merge pull request #304 from hermeznetwork/feature/tracerr1

Wrap all errors with tracerr
a_bennassar arnaubennassar5@gmail.com
Mon, 30 Nov 2020 13:08:42 +0100
commit

a8c9b7a6044b0d015a09422ea6f3c5840ee21118

parent

aaeec881499ab572261c4f55be4b5862689e9774

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

@@ -9,6 +9,7 @@ "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" + "github.com/hermeznetwork/tracerr" ) // TODO: Add correct values to constants

@@ -49,10 +50,10 @@ ) (*API, error) {

// 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{
M api/api_test.go → api/api_test.go

@@ -25,6 +25,7 @@ "github.com/hermeznetwork/hermez-node/db/statedb"

"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 @@ }

// 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 @@ if err := doGoodReq(

"GET", iterPath+"&order="+order, nil, iterStruct, ); err != nil { - return err + return tracerr.Wrap(err) } appendIter(iterStruct) // Keep iterating?

@@ -505,14 +505,14 @@ ctx := context.Background()

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 @@ PathParams: pathParams,

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 @@ // Unmarshal body into return struct

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 @@ client := &http.Client{}

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 @@ Route: route,

} 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{
M api/batch.go → api/batch.go

@@ -8,6 +8,7 @@

"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 @@ maxTxsPerBatch := uint(2048) //nolint:gomnd

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 }
M api/handlers.go → api/handlers.go

@@ -7,6 +7,7 @@ "net/http"

"github.com/gin-gonic/gin" "github.com/hermeznetwork/hermez-node/db/historydb" + "github.com/hermeznetwork/tracerr" ) const (

@@ -32,7 +33,7 @@ ErrNillBidderAddr = errors.New("biderAddr can not be nil")

) 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(), })
M api/parsers.go → api/parsers.go

@@ -10,6 +10,7 @@

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 error) {

// 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 @@ limit = new(uint)

*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 @@ res := new(bool)

*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 @@ case common.TxTypeTransferToBJJ:

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.PublicKey, *common.Idx, error) {

// 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 @@ }

// 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 @@

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 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 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 @@

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 @@ }

// 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 @@ }

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, 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 := int64(resInt) return &res, nil

@@ -361,32 +359,32 @@ return nil, nil

} 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 @@ for i := 1; i < len(bjjBytes); i++ {

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 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) {
M api/slots.go → api/slots.go

@@ -8,6 +8,7 @@

"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 @@ }

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 @@ if wonByEthereumAddress == nil {

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 }
M api/state.go → api/state.go

@@ -8,6 +8,7 @@ ethCommon "github.com/ethereum/go-ethereum/common"

"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 @@ lastBatchNum common.BatchNum, currentSlot int64,

) 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 @@ // currentSlot and lastClosedSlot included

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 @@ if bids[j].SlotNum == i {

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 @@ batchNum := a.status.Network.LastBatch.BatchNum

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 @@ // UpdateRecommendedFee update Status.RecommendedFee information

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
M api/txspool.go → api/txspool.go

@@ -10,6 +10,7 @@ "github.com/gin-gonic/gin"

"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 @@ }

// 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 }
M apitypes/apitypes.go → apitypes/apitypes.go

@@ -13,6 +13,7 @@ "strings"

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -35,7 +36,7 @@ // Scan implements Scanner for database/sql

func (b *BigIntStr) Scan(src interface{}) error { srcBytes, ok := src.([]byte) if !ok { - return fmt.Errorf("can't scan %T into apitypes.BigIntStr", src) + return tracerr.Wrap(fmt.Errorf("can't scan %T into apitypes.BigIntStr", src)) } // bytes to *big.Int bigInt := new(big.Int).SetBytes(srcBytes)

@@ -53,7 +54,7 @@ func (b BigIntStr) Value() (driver.Value, error) {

// string to *big.Int bigInt, ok := new(big.Int).SetString(string(b), 10) if !ok || bigInt == nil { - return nil, errors.New("invalid representation of a *big.Int") + return nil, tracerr.Wrap(errors.New("invalid representation of a *big.Int")) } // *big.Int to bytes return bigInt.Bytes(), nil

@@ -66,7 +67,7 @@ // UnmarshalText unmarshals a StrBigInt

func (s *StrBigInt) UnmarshalText(text []byte) error { bi, ok := (*big.Int)(s).SetString(string(text), 10) if !ok { - return fmt.Errorf("could not unmarshal %s into a StrBigInt", text) + return tracerr.Wrap(fmt.Errorf("could not unmarshal %s into a StrBigInt", text)) } *s = StrBigInt(*bi) return nil

@@ -79,7 +80,7 @@ // UnmarshalJSON unmarshals a json representation of map[common.TokenID]*big.Int

func (c *CollectedFees) UnmarshalJSON(text []byte) error { bigIntMap := make(map[common.TokenID]*big.Int) if err := json.Unmarshal(text, &bigIntMap); err != nil { - return err + return tracerr.Wrap(err) } *c = CollectedFees(make(map[common.TokenID]BigIntStr)) for k, v := range bigIntMap {

@@ -110,7 +111,7 @@ // Scan implements Scanner for database/sql

func (a *HezEthAddr) Scan(src interface{}) error { ethAddr := &ethCommon.Address{} if err := ethAddr.Scan(src); err != nil { - return err + return tracerr.Wrap(err) } if ethAddr == nil { return nil

@@ -123,7 +124,7 @@ // Value implements valuer for database/sql

func (a HezEthAddr) Value() (driver.Value, error) { ethAddr, err := a.ToEthAddr() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return ethAddr.Value() }

@@ -136,7 +137,7 @@ func (s *StrHezEthAddr) UnmarshalText(text []byte) error {

withoutHez := strings.TrimPrefix(string(text), "hez:") var addr ethCommon.Address if err := addr.UnmarshalText([]byte(withoutHez)); err != nil { - return err + return tracerr.Wrap(err) } *s = StrHezEthAddr(addr) return nil

@@ -180,7 +181,7 @@ for i := 1; i < len(bjjBytes); i++ {

sum += bjjBytes[i] } if decoded[decodedLen-1] != sum { - return nil, errors.New("checksum verification failed") + return nil, tracerr.Wrap(errors.New("checksum verification failed")) } bjjComp := babyjub.PublicKeyComp(bjjBytes) return bjjComp.Decompress()

@@ -195,7 +196,7 @@ // Scan implements Scanner for database/sql

func (b *HezBJJ) Scan(src interface{}) error { bjj := &babyjub.PublicKey{} if err := bjj.Scan(src); err != nil { - return err + return tracerr.Wrap(err) } if bjj == nil { return nil

@@ -208,7 +209,7 @@ // Value implements valuer for database/sql

func (b HezBJJ) Value() (driver.Value, error) { bjj, err := b.ToBJJ() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return bjj.Value() }

@@ -220,7 +221,7 @@ // UnmarshalText unmarshals a StrHezBJJ

func (s *StrHezBJJ) UnmarshalText(text []byte) error { bjj, err := hezStrToBJJ(string(text)) if err != nil { - return err + return tracerr.Wrap(err) } *s = StrHezBJJ(*bjj) return nil

@@ -239,11 +240,11 @@ withoutHez := strings.TrimPrefix(string(text), "hez:")

splitted := strings.Split(withoutHez, ":") const expectedLen = 2 if len(splitted) != expectedLen { - return fmt.Errorf("can not unmarshal %s into StrHezIdx", text) + return tracerr.Wrap(fmt.Errorf("can not unmarshal %s into StrHezIdx", text)) } idxInt, err := strconv.Atoi(splitted[1]) if err != nil { - return err + return tracerr.Wrap(err) } *s = StrHezIdx(common.Idx(idxInt)) return nil

@@ -274,7 +275,7 @@ *e = *(NewEthSignature(srcBytes))

return nil } else { // unexpected src - return fmt.Errorf("can't scan %T into apitypes.EthSignature", src) + return tracerr.Wrap(fmt.Errorf("can't scan %T into apitypes.EthSignature", src)) } }

@@ -289,7 +290,7 @@ func (e *EthSignature) UnmarshalText(text []byte) error {

without0x := strings.TrimPrefix(string(text), "0x") signature, err := hex.DecodeString(without0x) if err != nil { - return err + return tracerr.Wrap(err) } *e = EthSignature([]byte(signature)) return nil
M apitypes/apitypes_test.go → apitypes/apitypes_test.go

@@ -12,7 +12,9 @@ ethCommon "github.com/ethereum/go-ethereum/common"

"github.com/hermeznetwork/hermez-node/common" dbUtils "github.com/hermeznetwork/hermez-node/db" "github.com/iden3/go-iden3-crypto/babyjub" - _ "github.com/mattn/go-sqlite3" //nolint sqlite driver + + // nolint sqlite driver + _ "github.com/mattn/go-sqlite3" "github.com/russross/meddler" "github.com/stretchr/testify/assert" )
M batchbuilder/batchbuilder.go → batchbuilder/batchbuilder.go

@@ -4,6 +4,7 @@ import (

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/db/statedb" + "github.com/hermeznetwork/tracerr" ) // ConfigCircuit contains the circuit configuration

@@ -30,7 +31,7 @@ // method

func NewBatchBuilder(dbpath string, synchronizerStateDB *statedb.StateDB, configCircuits []ConfigCircuit, batchNum common.BatchNum, nLevels uint64) (*BatchBuilder, error) { localStateDB, err := statedb.NewLocalStateDB(dbpath, synchronizerStateDB, statedb.TypeBatchBuilder, int(nLevels)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } bb := BatchBuilder{

@@ -39,7 +40,7 @@ configCircuits: configCircuits,

} err = bb.Reset(batchNum, true) - return &bb, err + return &bb, tracerr.Wrap(err) } // Reset tells the BatchBuilder to reset it's internal state to the required

@@ -61,8 +62,8 @@ MaxL1Tx: 64,

} ptOut, err := bb.localStateDB.ProcessTxs(ptc, coordIdxs, l1usertxs, l1coordinatortxs, pooll2txs) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } err = bb.localStateDB.MakeCheckpoint() - return ptOut.ZKInputs, err + return ptOut.ZKInputs, tracerr.Wrap(err) }
M cli/node/main.go → cli/node/main.go

@@ -8,6 +8,7 @@

"github.com/hermeznetwork/hermez-node/config" "github.com/hermeznetwork/hermez-node/log" "github.com/hermeznetwork/hermez-node/node" + "github.com/hermeznetwork/tracerr" "github.com/urfave/cli/v2" )

@@ -23,20 +24,20 @@ func cmdInit(c *cli.Context) error {

log.Info("Init") cfg, err := parseCli(c) if err != nil { - return err + return tracerr.Wrap(err) } fmt.Println("TODO", cfg) - return err + return tracerr.Wrap(err) } func cmdRun(c *cli.Context) error { cfg, err := parseCli(c) if err != nil { - return fmt.Errorf("error parsing flags and config: %w", err) + return tracerr.Wrap(fmt.Errorf("error parsing flags and config: %w", err)) } node, err := node.NewNode(cfg.mode, cfg.node, cfg.coord) if err != nil { - return fmt.Errorf("error starting node: %w", err) + return tracerr.Wrap(fmt.Errorf("error starting node: %w", err)) } node.Start()

@@ -71,7 +72,7 @@ if err != nil {

if err := cli.ShowAppHelp(c); err != nil { panic(err) } - return nil, err + return nil, tracerr.Wrap(err) } return cfg, nil }

@@ -85,27 +86,27 @@ cfg.mode = node.ModeSynchronizer

case modeCoord: cfg.mode = node.ModeCoordinator default: - return nil, fmt.Errorf("invalid mode \"%v\"", mode) + return nil, tracerr.Wrap(fmt.Errorf("invalid mode \"%v\"", mode)) } if cfg.mode == node.ModeCoordinator { coordCfgPath := c.String(flagCoordCfg) if coordCfgPath == "" { - return nil, fmt.Errorf("required flag \"%v\" not set", flagCoordCfg) + return nil, tracerr.Wrap(fmt.Errorf("required flag \"%v\" not set", flagCoordCfg)) } coordCfg, err := config.LoadCoordinator(coordCfgPath) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } cfg.coord = coordCfg } nodeCfgPath := c.String(flagCfg) if nodeCfgPath == "" { - return nil, fmt.Errorf("required flag \"%v\" not set", flagCfg) + return nil, tracerr.Wrap(fmt.Errorf("required flag \"%v\" not set", flagCfg)) } nodeCfg, err := config.LoadNode(nodeCfgPath) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // nodeCfg.Synchronizer.InitialVariables.WDelayer.HermezRollupAddress = nodeCfg.SmartContracts.Rollup cfg.node = nodeCfg

@@ -151,7 +152,7 @@ }

err := app.Run(os.Args) if err != nil { - fmt.Printf("\nError: %v\n", err) + fmt.Printf("\nError: %v\n", tracerr.Sprint(err)) os.Exit(1) } }
M common/account.go → common/account.go

@@ -8,6 +8,7 @@ "math/big"

"strconv" ethCommon "github.com/ethereum/go-ethereum/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-iden3-crypto/poseidon" cryptoUtils "github.com/iden3/go-iden3-crypto/utils"

@@ -51,7 +52,7 @@

// Bytes returns a byte array representing the Idx func (idx Idx) Bytes() ([6]byte, error) { if idx > maxIdxValue { - return [6]byte{}, ErrIdxOverflow + return [6]byte{}, tracerr.Wrap(ErrIdxOverflow) } var idxBytes [8]byte binary.BigEndian.PutUint64(idxBytes[:], uint64(idx))

@@ -68,7 +69,7 @@

// IdxFromBytes returns Idx from a byte array func IdxFromBytes(b []byte) (Idx, error) { if len(b) != IdxBytesLen { - return 0, fmt.Errorf("can not parse Idx, bytes len %d, expected %d", len(b), IdxBytesLen) + return 0, tracerr.Wrap(fmt.Errorf("can not parse Idx, bytes len %d, expected %d", len(b), IdxBytesLen)) } var idxBytes [8]byte copy(idxBytes[2:], b[:])

@@ -79,7 +80,7 @@

// IdxFromBigInt converts a *big.Int to Idx type func IdxFromBigInt(b *big.Int) (Idx, error) { if b.Int64() > maxIdxValue { - return 0, ErrNumOverflow + return 0, tracerr.Wrap(ErrNumOverflow) } return Idx(uint64(b.Int64())), nil }

@@ -90,7 +91,7 @@

// Bytes returns a byte array of length 5 representing the Nonce func (n Nonce) Bytes() ([5]byte, error) { if n > maxNonceValue { - return [5]byte{}, ErrNonceOverflow + return [5]byte{}, tracerr.Wrap(ErrNonceOverflow) } var nonceBytes [8]byte binary.BigEndian.PutUint64(nonceBytes[:], uint64(n))

@@ -143,22 +144,22 @@ func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {

var b [32 * NLeafElems]byte if a.Nonce > maxNonceValue { - return b, fmt.Errorf("%s Nonce", ErrNumOverflow) + return b, tracerr.Wrap(fmt.Errorf("%s Nonce", ErrNumOverflow)) } if len(a.Balance.Bytes()) > maxBalanceBytes { - return b, fmt.Errorf("%s Balance", ErrNumOverflow) + return b, tracerr.Wrap(fmt.Errorf("%s Balance", ErrNumOverflow)) } nonceBytes, err := a.Nonce.Bytes() if err != nil { - return b, err + return b, tracerr.Wrap(err) } copy(b[28:32], a.TokenID.Bytes()) copy(b[23:28], nonceBytes[:]) if a.PublicKey == nil { - return b, fmt.Errorf("Account.PublicKey can not be nil") + return b, tracerr.Wrap(fmt.Errorf("Account.PublicKey can not be nil")) } if babyjub.PointCoordSign(a.PublicKey.X) { b[22] = 1

@@ -178,7 +179,7 @@ e := [NLeafElems]*big.Int{}

b, err := a.Bytes() if err != nil { - return e, err + return e, tracerr.Wrap(err) } e[0] = new(big.Int).SetBytes(b[0:32])

@@ -193,7 +194,7 @@ // HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation

func (a *Account) HashValue() (*big.Int, error) { bi, err := a.BigInts() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return poseidon.Hash(bi[:]) }

@@ -201,7 +202,7 @@

// AccountFromBigInts returns a Account from a [5]*big.Int func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) { if !cryptoUtils.CheckBigIntArrayInField(e[:]) { - return nil, ErrNotInFF + return nil, tracerr.Wrap(ErrNotInFF) } e0B := e[0].Bytes() e1B := e[1].Bytes()

@@ -220,7 +221,7 @@ // AccountFromBytes returns a Account from a byte array

func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) { tokenID, err := TokenIDFromBytes(b[28:32]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var nonceBytes5 [5]byte copy(nonceBytes5[:], b[23:28])

@@ -230,21 +231,21 @@

balance := new(big.Int).SetBytes(b[40:64]) // Balance is max of 192 bits (24 bytes) if !bytes.Equal(b[32:40], []byte{0, 0, 0, 0, 0, 0, 0, 0}) { - return nil, fmt.Errorf("%s Balance", ErrNumOverflow) + return nil, tracerr.Wrap(fmt.Errorf("%s Balance", ErrNumOverflow)) } ay := new(big.Int).SetBytes(b[64:96]) pkPoint, err := babyjub.PointFromSignAndY(sign, ay) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } publicKey := babyjub.PublicKey(*pkPoint) ethAddr := ethCommon.BytesToAddress(b[108:128]) if !cryptoUtils.CheckBigIntInField(balance) { - return nil, ErrNotInFF + return nil, tracerr.Wrap(ErrNotInFF) } if !cryptoUtils.CheckBigIntInField(ay) { - return nil, ErrNotInFF + return nil, tracerr.Wrap(ErrNotInFF) } a := Account{
M common/account_test.go → common/account_test.go

@@ -10,6 +10,7 @@ "testing"

ethCommon "github.com/ethereum/go-ethereum/common" ethCrypto "github.com/ethereum/go-ethereum/crypto" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" cryptoConstants "github.com/iden3/go-iden3-crypto/constants" "github.com/iden3/go-iden3-crypto/poseidon"

@@ -45,7 +46,7 @@ // expect value overflow

i = Idx(281474976710656) iBytes, err = i.Bytes() assert.NotNil(t, err) - assert.Equal(t, ErrIdxOverflow, err) + assert.Equal(t, ErrIdxOverflow, tracerr.Unwrap(err)) } func TestNonceParser(t *testing.T) {

@@ -70,7 +71,7 @@ // expect value overflow

n = Nonce(1099511627776) nBytes, err = n.Bytes() assert.NotNil(t, err) - assert.Equal(t, ErrNonceOverflow, err) + assert.Equal(t, ErrNonceOverflow, tracerr.Unwrap(err)) } func TestAccount(t *testing.T) {

@@ -296,14 +297,14 @@ r = cryptoConstants.Q

e = [NLeafElems]*big.Int{z, z, r, r} _, err = AccountFromBigInts(e) assert.NotNil(t, err) - assert.Equal(t, ErrNotInFF, err) + assert.Equal(t, ErrNotInFF, tracerr.Unwrap(err)) // Q+1 should give error r = new(big.Int).Add(cryptoConstants.Q, big.NewInt(1)) e = [NLeafElems]*big.Int{z, z, r, r} _, err = AccountFromBigInts(e) assert.NotNil(t, err) - assert.Equal(t, ErrNotInFF, err) + assert.Equal(t, ErrNotInFF, tracerr.Unwrap(err)) } func TestAccountErrNumOverflowNonce(t *testing.T) {

@@ -327,7 +328,7 @@ // force value overflow

account.Nonce = Nonce(math.Pow(2, 40)) b, err := account.Bytes() assert.NotNil(t, err) - assert.Equal(t, fmt.Errorf("%s Nonce", ErrNumOverflow), err) + assert.Equal(t, fmt.Errorf("%s Nonce", ErrNumOverflow), tracerr.Unwrap(err)) _, err = AccountFromBytes(b) assert.Nil(t, err)

@@ -357,7 +358,7 @@ account.Balance = new(big.Int).Exp(big.NewInt(2), big.NewInt(192), nil)

assert.Equal(t, "6277101735386680763835789423207666416102355444464034512896", account.Balance.String()) b, err := account.Bytes() assert.NotNil(t, err) - assert.Equal(t, fmt.Errorf("%s Balance", ErrNumOverflow), err) + assert.Equal(t, fmt.Errorf("%s Balance", ErrNumOverflow), tracerr.Unwrap(err)) _, err = AccountFromBytes(b) assert.Nil(t, err)

@@ -365,5 +366,5 @@

b[39] = 1 _, err = AccountFromBytes(b) assert.NotNil(t, err) - assert.Equal(t, fmt.Errorf("%s Balance", ErrNumOverflow), err) + assert.Equal(t, fmt.Errorf("%s Balance", ErrNumOverflow), tracerr.Unwrap(err)) }
M common/accountcreationauths.go → common/accountcreationauths.go

@@ -5,6 +5,7 @@ "time"

ethCommon "github.com/ethereum/go-ethereum/common" ethCrypto "github.com/ethereum/go-ethereum/crypto" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -22,7 +23,7 @@ // Calculate message to be signed

const msg = "I authorize this babyjubjub key for hermez rollup account creation" comp, err := a.BJJ.Compress().MarshalText() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // Hash message (msg || compressed-bjj) return ethCrypto.Keccak256Hash([]byte(msg), comp).Bytes(), nil
M common/batch.go → common/batch.go

@@ -6,6 +6,7 @@ "fmt"

"math/big" ethCommon "github.com/ethereum/go-ethereum/common" + "github.com/hermeznetwork/tracerr" ) const batchNumBytesLen = 8

@@ -44,7 +45,7 @@

// BatchNumFromBytes returns BatchNum from a []byte func BatchNumFromBytes(b []byte) (BatchNum, error) { if len(b) != batchNumBytesLen { - return 0, fmt.Errorf("can not parse BatchNumFromBytes, bytes len %d, expected %d", len(b), batchNumBytesLen) + return 0, tracerr.Wrap(fmt.Errorf("can not parse BatchNumFromBytes, bytes len %d, expected %d", len(b), batchNumBytesLen)) } batchNum := binary.BigEndian.Uint64(b[:batchNumBytesLen]) return BatchNum(batchNum), nil
M common/fee.go → common/fee.go

@@ -4,6 +4,8 @@ import (

"fmt" "math" "math/big" + + "github.com/hermeznetwork/tracerr" ) // MaxFeePlan is the maximum value of the FeePlan

@@ -49,7 +51,7 @@ if feeSel < 192 { //nolint:gomnd

feeAmount.Rsh(feeAmount, 60) } if feeAmount.BitLen() > 128 { //nolint:gomnd - return nil, fmt.Errorf("FeeAmount overflow (feeAmount doesn't fit in 128 bits)") + return nil, tracerr.Wrap(fmt.Errorf("FeeAmount overflow (feeAmount doesn't fit in 128 bits)")) } return feeAmount, nil }
M common/float16.go → common/float16.go

@@ -9,6 +9,8 @@ import (

"encoding/binary" "errors" "math/big" + + "github.com/hermeznetwork/tracerr" ) var (

@@ -112,7 +114,7 @@ // Do rounding check

if res.BigInt().Cmp(f) == 0 { return res, nil } - return res, ErrRoundingLoss + return res, tracerr.Wrap(ErrRoundingLoss) } // NewFloat16Floor encodes a big.Int integer as a Float16, rounding down in
M common/float16_test.go → common/float16_test.go

@@ -4,6 +4,7 @@ import (

"math/big" "testing" + "github.com/hermeznetwork/tracerr" "github.com/stretchr/testify/assert" )

@@ -65,25 +66,25 @@ assert.Equal(t, c, a)

a = big.NewInt(1024) b, err = NewFloat16(a) - assert.Equal(t, ErrRoundingLoss, err) + assert.Equal(t, ErrRoundingLoss, tracerr.Unwrap(err)) c = b.BigInt() assert.NotEqual(t, c, a) a = big.NewInt(32767) b, err = NewFloat16(a) - assert.Equal(t, ErrRoundingLoss, err) + assert.Equal(t, ErrRoundingLoss, tracerr.Unwrap(err)) c = b.BigInt() assert.NotEqual(t, c, a) a = big.NewInt(32768) b, err = NewFloat16(a) - assert.Equal(t, ErrRoundingLoss, err) + assert.Equal(t, ErrRoundingLoss, tracerr.Unwrap(err)) c = b.BigInt() assert.NotEqual(t, c, a) a = big.NewInt(65536000) b, err = NewFloat16(a) - assert.Equal(t, ErrRoundingLoss, err) + assert.Equal(t, ErrRoundingLoss, tracerr.Unwrap(err)) c = b.BigInt() assert.NotEqual(t, c, a) }
M common/l1tx.go → common/l1tx.go

@@ -7,6 +7,7 @@ "math/big"

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -58,7 +59,7 @@ txType = TxTypeCreateAccountDeposit

} else if l1Tx.ToIdx >= IdxUserThreshold { txType = TxTypeCreateAccountDepositTransfer } else { - return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx) + return l1Tx, tracerr.Wrap(fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)) } } else if l1Tx.FromIdx >= IdxUserThreshold { if l1Tx.ToIdx == Idx(0) {

@@ -72,20 +73,20 @@ } else {

txType = TxTypeDepositTransfer } } else { - return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx) + return l1Tx, tracerr.Wrap(fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)) } } else { - return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid FromIdx value: %d", l1Tx.FromIdx) + return l1Tx, tracerr.Wrap(fmt.Errorf("Can not determine type of L1Tx, invalid FromIdx value: %d", l1Tx.FromIdx)) } if l1Tx.Type != "" && l1Tx.Type != txType { - return l1Tx, fmt.Errorf("L1Tx.Type: %s, should be: %s", l1Tx.Type, txType) + return l1Tx, tracerr.Wrap(fmt.Errorf("L1Tx.Type: %s, should be: %s", l1Tx.Type, txType)) } l1Tx.Type = txType txID, err := l1Tx.CalcTxID() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } l1Tx.TxID = *txID

@@ -97,7 +98,7 @@ func (tx *L1Tx) CalcTxID() (*TxID, error) {

var txID TxID if tx.UserOrigin { if tx.ToForgeL1TxsNum == nil { - return nil, fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil") + return nil, tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil")) } txID[0] = TxIDPrefixL1UserTx var toForgeL1TxsNumBytes [8]byte

@@ -105,7 +106,7 @@ binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))

copy(txID[1:9], toForgeL1TxsNumBytes[:]) } else { if tx.BatchNum == nil { - return nil, fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil") + return nil, tracerr.Wrap(fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil")) } txID[0] = TxIDPrefixL1CoordTx var batchNumBytes [8]byte

@@ -164,7 +165,7 @@ // Total bits compressed data: 241 bits // 31 bytes in *big.Int representation

func (tx L1Tx) TxCompressedData() (*big.Int, error) { amountFloat16, err := NewFloat16(tx.Amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var b [31]byte // b[0:7] empty: no fee neither nonce

@@ -172,12 +173,12 @@ copy(b[7:11], tx.TokenID.Bytes())

copy(b[11:13], amountFloat16.Bytes()) toIdxBytes, err := tx.ToIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[13:19], toIdxBytes[:]) fromIdxBytes, err := tx.FromIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[19:25], fromIdxBytes[:]) copy(b[25:27], []byte{0, 1}) // TODO this will be generated by the ChainID config parameter

@@ -195,19 +196,19 @@ b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd

fromIdxBytes, err := tx.FromIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[0:idxLen], fromIdxBytes[6-idxLen:]) toIdxBytes, err := tx.ToIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:]) if tx.EffectiveAmount != nil { amountFloat16, err := NewFloat16(tx.EffectiveAmount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes()) }

@@ -229,23 +230,23 @@ copy(b[20:52], pkCompB[:])

} fromIdxBytes, err := tx.FromIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[52:58], fromIdxBytes[:]) loadAmountFloat16, err := NewFloat16(tx.LoadAmount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[58:60], loadAmountFloat16.Bytes()) amountFloat16, err := NewFloat16(tx.Amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[60:62], amountFloat16.Bytes()) copy(b[62:66], tx.TokenID.Bytes()) toIdxBytes, err := tx.ToIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[66:72], toIdxBytes[:]) return b[:], nil

@@ -254,7 +255,7 @@

// BytesUser encodes a L1UserTx into []byte func (tx *L1Tx) BytesUser() ([]byte, error) { if !tx.UserOrigin { - return nil, fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx") + return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx")) } return tx.BytesGeneric() }

@@ -262,7 +263,7 @@

// BytesCoordinatorTx encodes a L1CoordinatorTx into []byte func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) { if tx.UserOrigin { - return nil, fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx") + return nil, tracerr.Wrap(fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx")) } var b [L1CoordinatorTxBytesLen]byte v := compressedSignatureBytes[64]

@@ -281,7 +282,7 @@

// L1UserTxFromBytes decodes a L1Tx from []byte func L1UserTxFromBytes(b []byte) (*L1Tx, error) { if len(b) != L1UserTxBytesLen { - return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b)) + return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))) } tx := &L1Tx{

@@ -296,22 +297,22 @@ var pkComp babyjub.PublicKeyComp

copy(pkComp[:], pkCompL) tx.FromBJJ, err = pkComp.Decompress() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } fromIdx, err := IdxFromBytes(b[52:58]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tx.FromIdx = fromIdx tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt() tx.Amount = Float16FromBytes(b[60:62]).BigInt() tx.TokenID, err = TokenIDFromBytes(b[62:66]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tx.ToIdx, err = IdxFromBytes(b[66:72]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return tx, nil

@@ -325,7 +326,7 @@

// L1CoordinatorTxFromBytes decodes a L1Tx from []byte func L1CoordinatorTxFromBytes(b []byte, chainID *big.Int, hermezAddress ethCommon.Address) (*L1Tx, error) { if len(b) != L1CoordinatorTxBytesLen { - return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b)) + return nil, tracerr.Wrap(fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))) } bytesMessage := []byte("I authorize this babyjubjub key for hermez rollup account creation")

@@ -343,11 +344,11 @@ var pkComp babyjub.PublicKeyComp

copy(pkComp[:], pkCompL) tx.FromBJJ, err = pkComp.Decompress() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tx.TokenID, err = TokenIDFromBytes(b[97:101]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tx.Amount = big.NewInt(0) tx.LoadAmount = big.NewInt(0)

@@ -368,11 +369,11 @@ signature = append(signature, v)

hash := signHash(data) pubKeyBytes, err := crypto.Ecrecover(hash, signature) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey) } else {
M common/l2tx.go → common/l2tx.go

@@ -3,6 +3,8 @@

import ( "fmt" "math/big" + + "github.com/hermeznetwork/tracerr" ) // L2Tx is a struct that represents an already forged L2 tx

@@ -30,12 +32,12 @@ txType = TxTypeExit

} else if l2Tx.ToIdx >= IdxUserThreshold { txType = TxTypeTransfer } else { - return l2Tx, fmt.Errorf("Can not determine type of L2Tx, invalid ToIdx value: %d", l2Tx.ToIdx) + return l2Tx, tracerr.Wrap(fmt.Errorf("Can not determine type of L2Tx, invalid ToIdx value: %d", l2Tx.ToIdx)) } // if TxType!=l2Tx.TxType return error if l2Tx.Type != "" && l2Tx.Type != txType { - return l2Tx, fmt.Errorf("L2Tx.Type: %s, should be: %s", l2Tx.Type, txType) + return l2Tx, tracerr.Wrap(fmt.Errorf("L2Tx.Type: %s, should be: %s", l2Tx.Type, txType)) } l2Tx.Type = txType

@@ -43,12 +45,12 @@ var txid [TxIDLen]byte

txid[0] = TxIDPrefixL2Tx fromIdxBytes, err := l2Tx.FromIdx.Bytes() if err != nil { - return l2Tx, err + return l2Tx, tracerr.Wrap(err) } copy(txid[1:7], fromIdxBytes[:]) nonceBytes, err := l2Tx.Nonce.Bytes() if err != nil { - return l2Tx, err + return l2Tx, tracerr.Wrap(err) } copy(txid[7:12], nonceBytes[:]) l2Tx.TxID = TxID(txid)

@@ -111,19 +113,19 @@ b := make([]byte, ((nLevels*2)+16+8)/8) //nolint:gomnd

fromIdxBytes, err := tx.FromIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[0:idxLen], fromIdxBytes[6-idxLen:]) // [6-idxLen:] as is BigEndian toIdxBytes, err := tx.ToIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[idxLen:idxLen*2], toIdxBytes[6-idxLen:]) amountFloat16, err := NewFloat16(tx.Amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[idxLen*2:idxLen*2+2], amountFloat16.Bytes())

@@ -142,14 +144,14 @@ var paddedFromIdxBytes [6]byte

copy(paddedFromIdxBytes[6-idxLen:], b[0:idxLen]) tx.FromIdx, err = IdxFromBytes(paddedFromIdxBytes[:]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var paddedToIdxBytes [6]byte copy(paddedToIdxBytes[6-idxLen:6], b[idxLen:idxLen*2]) tx.ToIdx, err = IdxFromBytes(paddedToIdxBytes[:]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tx.Amount = Float16FromBytes(b[idxLen*2 : idxLen*2+2]).BigInt()
M common/pooll2tx.go → common/pooll2tx.go

@@ -7,6 +7,7 @@ "math/big"

"time" ethCommon "github.com/ethereum/go-ethereum/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-iden3-crypto/poseidon" )

@@ -63,12 +64,12 @@ } else if poolL2Tx.ToEthAddr != FFAddr && poolL2Tx.ToEthAddr != EmptyAddr {

txType = TxTypeTransferToEthAddr } } else { - return nil, errors.New("malformed transaction") + return nil, tracerr.Wrap(errors.New("malformed transaction")) } // if TxType!=poolL2Tx.TxType return error if poolL2Tx.Type != "" && poolL2Tx.Type != txType { - return poolL2Tx, fmt.Errorf("type: %s, should be: %s", poolL2Tx.Type, txType) + return poolL2Tx, tracerr.Wrap(fmt.Errorf("type: %s, should be: %s", poolL2Tx.Type, txType)) } poolL2Tx.Type = txType

@@ -76,19 +77,19 @@ var txid [TxIDLen]byte

txid[0] = TxIDPrefixL2Tx fromIdxBytes, err := poolL2Tx.FromIdx.Bytes() if err != nil { - return poolL2Tx, err + return poolL2Tx, tracerr.Wrap(err) } copy(txid[1:7], fromIdxBytes[:]) nonceBytes, err := poolL2Tx.Nonce.Bytes() if err != nil { - return poolL2Tx, err + return poolL2Tx, tracerr.Wrap(err) } copy(txid[7:12], nonceBytes[:]) txID := TxID(txid) // if TxID!=poolL2Tx.TxID return error if poolL2Tx.TxID != (TxID{}) && poolL2Tx.TxID != txID { - return poolL2Tx, fmt.Errorf("id: %s, should be: %s", poolL2Tx.TxID.String(), txID.String()) + return poolL2Tx, tracerr.Wrap(fmt.Errorf("id: %s, should be: %s", poolL2Tx.TxID.String(), txID.String())) } poolL2Tx.TxID = txID return poolL2Tx, nil

@@ -109,12 +110,12 @@ func (tx *PoolL2Tx) TxCompressedData() (*big.Int, error) {

// sigconstant sc, ok := new(big.Int).SetString("3322668559", 10) if !ok { - return nil, fmt.Errorf("error parsing SignatureConstant") + return nil, tracerr.Wrap(fmt.Errorf("error parsing SignatureConstant")) } amountFloat16, err := NewFloat16(tx.Amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var b [31]byte toBJJSign := byte(0)

@@ -125,19 +126,19 @@ b[0] = toBJJSign

b[1] = byte(tx.Fee) nonceBytes, err := tx.Nonce.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[2:7], nonceBytes[:]) copy(b[7:11], tx.TokenID.Bytes()) copy(b[11:13], amountFloat16.Bytes()) toIdxBytes, err := tx.ToIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[13:19], toIdxBytes[:]) fromIdxBytes, err := tx.FromIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[19:25], fromIdxBytes[:]) copy(b[25:27], []byte{0, 1}) // TODO this will be generated by the ChainID config parameter

@@ -162,7 +163,7 @@ tx.Amount = big.NewInt(0)

} amountFloat16, err := NewFloat16(tx.Amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var b [25]byte toBJJSign := byte(0)

@@ -173,19 +174,19 @@ b[0] = toBJJSign

b[1] = byte(tx.Fee) nonceBytes, err := tx.Nonce.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[2:7], nonceBytes[:]) copy(b[7:11], tx.TokenID.Bytes()) copy(b[11:13], amountFloat16.Bytes()) toIdxBytes, err := tx.ToIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[13:19], toIdxBytes[:]) fromIdxBytes, err := tx.FromIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[19:25], fromIdxBytes[:])

@@ -213,7 +214,7 @@ tx.RqAmount = big.NewInt(0)

} amountFloat16, err := NewFloat16(tx.RqAmount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var b [25]byte toBJJSign := byte(0)

@@ -224,19 +225,19 @@ b[0] = toBJJSign

b[1] = byte(tx.RqFee) nonceBytes, err := tx.RqNonce.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[2:7], nonceBytes[:]) copy(b[7:11], tx.RqTokenID.Bytes()) copy(b[11:13], amountFloat16.Bytes()) toIdxBytes, err := tx.RqToIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[13:19], toIdxBytes[:]) fromIdxBytes, err := tx.RqFromIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(b[19:25], fromIdxBytes[:])

@@ -248,7 +249,7 @@ // HashToSign returns the computed Poseidon hash from the *PoolL2Tx that will be signed by the sender.

func (tx *PoolL2Tx) HashToSign() (*big.Int, error) { toCompressedData, err := tx.TxCompressedData() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } toEthAddr := EthAddrToBigInt(tx.ToEthAddr) rqToEthAddr := EthAddrToBigInt(tx.RqToEthAddr)

@@ -258,7 +259,7 @@ toBJJY = tx.ToBJJ.Y

} rqTxCompressedDataV2, err := tx.RqTxCompressedDataV2() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } rqToBJJY := big.NewInt(0) if tx.RqToBJJ != nil {
M common/token.go → common/token.go

@@ -7,6 +7,7 @@ "math/big"

"time" ethCommon "github.com/ethereum/go-ethereum/common" + "github.com/hermeznetwork/tracerr" ) // tokenIDBytesLen defines the length of the TokenID byte array representation

@@ -47,7 +48,7 @@

// TokenIDFromBytes returns TokenID from a byte array func TokenIDFromBytes(b []byte) (TokenID, error) { if len(b) != tokenIDBytesLen { - return 0, fmt.Errorf("can not parse TokenID, bytes len %d, expected 4", len(b)) + return 0, tracerr.Wrap(fmt.Errorf("can not parse TokenID, bytes len %d, expected 4", len(b))) } tid := binary.BigEndian.Uint32(b[:4]) return TokenID(tid), nil
M common/tx.go → common/tx.go

@@ -10,6 +10,7 @@ "math/big"

"strings" ethCommon "github.com/ethereum/go-ethereum/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -40,10 +41,10 @@ // Scan implements Scanner for database/sql.

func (txid *TxID) Scan(src interface{}) error { srcB, ok := src.([]byte) if !ok { - return fmt.Errorf("can't scan %T into TxID", src) + return tracerr.Wrap(fmt.Errorf("can't scan %T into TxID", src)) } if len(srcB) != TxIDLen { - return fmt.Errorf("can't scan []byte of len %d into TxID, need %d", len(srcB), TxIDLen) + return tracerr.Wrap(fmt.Errorf("can't scan []byte of len %d into TxID, need %d", len(srcB), TxIDLen)) } copy(txid[:], srcB) return nil

@@ -65,10 +66,10 @@ txid := TxID{}

idStr = strings.TrimPrefix(idStr, "0x") decoded, err := hex.DecodeString(idStr) if err != nil { - return TxID{}, err + return TxID{}, tracerr.Wrap(err) } if len(decoded) != TxIDLen { - return txid, errors.New("Invalid idStr") + return txid, tracerr.Wrap(errors.New("Invalid idStr")) } copy(txid[:], decoded) return txid, nil

@@ -84,7 +85,7 @@ func (txid *TxID) UnmarshalText(data []byte) error {

idStr := string(data) id, err := NewTxIDFromString(idStr) if err != nil { - return err + return tracerr.Wrap(err) } *txid = id return nil
M common/utils.go → common/utils.go

@@ -5,6 +5,7 @@ "encoding/hex"

"math/big" ethCommon "github.com/ethereum/go-ethereum/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -29,7 +30,7 @@ // spec, is used for importing javascript test vectors data.

func BJJFromStringWithChecksum(s string) (*babyjub.PublicKey, error) { b, err := hex.DecodeString(s) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } pkBytes := SwapEndianness(b) var pkComp babyjub.PublicKeyComp
M common/zk.go → common/zk.go

@@ -10,6 +10,7 @@ "fmt"

"math/big" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" cryptoConstants "github.com/iden3/go-iden3-crypto/constants" "github.com/iden3/go-merkletree" "github.com/mitchellh/mapstructure"

@@ -258,11 +259,11 @@ TagName: "json",

Result: &m, }) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } err = dec.Decode(z) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } for k, v := range m {

@@ -398,13 +399,13 @@ // HashGlobalData returns the HashGlobalData

func (z ZKInputs) HashGlobalData() (*big.Int, error) { b, err := z.ToHashGlobalData() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } h := sha256.New() _, err = h.Write(b) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } r := new(big.Int).SetBytes(h.Sum(nil))

@@ -427,7 +428,7 @@ // [MAX_NLEVELS bits] newLastIdx

newLastIdx := make([]byte, bytesMaxLevels) newLastIdxBytes, err := z.Metadata.NewLastIdxRaw.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } copy(newLastIdx, newLastIdxBytes[len(newLastIdxBytes)-bytesMaxLevels:]) b = append(b, newLastIdx...)

@@ -474,7 +475,7 @@ for i := 0; i < len(z.Metadata.L2TxsData); i++ {

l2TxsData = append(l2TxsData, z.Metadata.L2TxsData[i]...) } if len(l2TxsData) > int(expectedL2TxsDataLen) { - return nil, fmt.Errorf("len(l2TxsData): %d, expected: %d", len(l2TxsData), expectedL2TxsDataLen) + return nil, tracerr.Wrap(fmt.Errorf("len(l2TxsData): %d, expected: %d", len(l2TxsData), expectedL2TxsDataLen)) } b = append(b, l2TxsData...)
M config/config.go → config/config.go

@@ -9,6 +9,7 @@ "github.com/BurntSushi/toml"

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/synchronizer" + "github.com/hermeznetwork/tracerr" "gopkg.in/go-playground/validator.v9" )

@@ -21,7 +22,7 @@ // UnmarshalText unmarshalls time duration from text.

func (d *Duration) UnmarshalText(data []byte) error { duration, err := time.ParseDuration(string(data)) if err != nil { - return err + return tracerr.Wrap(err) } d.Duration = duration return nil

@@ -104,15 +105,15 @@ // Load loads a generic config.

func Load(path string, cfg interface{}) error { bs, err := ioutil.ReadFile(path) //nolint:gosec if err != nil { - return err + return tracerr.Wrap(err) } cfgToml := string(bs) if _, err := toml.Decode(cfgToml, cfg); err != nil { - return err + return tracerr.Wrap(err) } validate := validator.New() if err := validate.Struct(cfg); err != nil { - return fmt.Errorf("error validating configuration file: %w", err) + return tracerr.Wrap(fmt.Errorf("error validating configuration file: %w", err)) } return nil }

@@ -121,7 +122,7 @@ // LoadCoordinator loads the Coordinator configuration from path.

func LoadCoordinator(path string) (*Coordinator, error) { var cfg Coordinator if err := Load(path, &cfg); err != nil { - return nil, fmt.Errorf("error loading coordinator configuration file: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("error loading coordinator configuration file: %w", err)) } return &cfg, nil }

@@ -130,7 +131,7 @@ // LoadNode loads the Node configuration from path.

func LoadNode(path string) (*Node, error) { var cfg Node if err := Load(path, &cfg); err != nil { - return nil, fmt.Errorf("error loading node configuration file: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("error loading node configuration file: %w", err)) } return &cfg, nil }
M coordinator/batch.go → coordinator/batch.go

@@ -9,6 +9,7 @@

"github.com/ethereum/go-ethereum/core/types" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/eth" + "github.com/hermeznetwork/tracerr" ) // Proof TBD this type will be received from the proof server

@@ -46,7 +47,7 @@ // storePath

func (b *BatchInfo) DebugStore(storePath string) error { batchJSON, err := json.Marshal(b) if err != nil { - return err + return tracerr.Wrap(err) } oldStateRoot := "null" if b.ZKInputs != nil && b.ZKInputs.OldStateRoot != nil {
M coordinator/coordinator.go → coordinator/coordinator.go

@@ -15,6 +15,7 @@ "github.com/hermeznetwork/hermez-node/eth"

"github.com/hermeznetwork/hermez-node/log" "github.com/hermeznetwork/hermez-node/synchronizer" "github.com/hermeznetwork/hermez-node/txselector" + "github.com/hermeznetwork/tracerr" ) var errTODO = fmt.Errorf("TODO")

@@ -93,12 +94,12 @@ initSCVars *synchronizer.SCVariables,

) (*Coordinator, error) { // nolint reason: hardcoded `1.0`, by design the percentage can't be over 100% if cfg.L1BatchTimeoutPerc >= 1.0 { //nolint:gomnd - return nil, fmt.Errorf("invalid value for Config.L1BatchTimeoutPerc (%v >= 1.0)", - cfg.L1BatchTimeoutPerc) + return nil, tracerr.Wrap(fmt.Errorf("invalid value for Config.L1BatchTimeoutPerc (%v >= 1.0)", + cfg.L1BatchTimeoutPerc)) } if cfg.EthClientAttempts < 1 { - return nil, fmt.Errorf("invalid value for Config.EthClientAttempts (%v < 1)", - cfg.EthClientAttempts) + return nil, tracerr.Wrap(fmt.Errorf("invalid value for Config.EthClientAttempts (%v < 1)", + cfg.EthClientAttempts)) } txManager := NewTxManager(&cfg, ethClient)

@@ -192,7 +193,7 @@ log.Info("Coordinator: forging state begin")

batchNum := common.BatchNum(stats.Sync.LastBatch) c.pipeline = c.newPipeline() if err := c.pipeline.Start(batchNum, stats, &c.vars); err != nil { - return err + return tracerr.Wrap(err) } } } else {

@@ -318,12 +319,12 @@ break

} select { case <-ctx.Done(): - return ErrDone + return tracerr.Wrap(ErrDone) case <-time.After(t.cfg.EthClientAttemptsDelay): } } if err != nil { - return fmt.Errorf("reached max attempts for ethClient.RollupForgeBatch: %w", err) + return tracerr.Wrap(fmt.Errorf("reached max attempts for ethClient.RollupForgeBatch: %w", err)) } batchInfo.EthTx = ethTx t.cfg.debugBatchStore(batchInfo)

@@ -344,12 +345,12 @@ break

} select { case <-ctx.Done(): - return ErrDone + return tracerr.Wrap(ErrDone) case <-time.After(t.cfg.EthClientAttemptsDelay): } } if err != nil { - return fmt.Errorf("reached max attempts for ethClient.EthTransactionReceipt: %w", err) + return tracerr.Wrap(fmt.Errorf("reached max attempts for ethClient.EthTransactionReceipt: %w", err)) } batchInfo.Receipt = receipt t.cfg.debugBatchStore(batchInfo)

@@ -361,7 +362,7 @@ receipt := batchInfo.Receipt

if receipt != nil { if receipt.Status == types.ReceiptStatusFailed { log.Errorw("TxManager receipt status is failed", "receipt", receipt) - return nil, fmt.Errorf("ethereum transaction receipt statis is failed") + return nil, tracerr.Wrap(fmt.Errorf("ethereum transaction receipt statis is failed")) } else if receipt.Status == types.ReceiptStatusSuccessful { confirm := t.lastBlock - receipt.BlockNumber.Int64() return &confirm, nil

@@ -384,7 +385,7 @@ return

case lastBlock := <-t.lastBlockCh: t.lastBlock = lastBlock case batchInfo := <-t.batchCh: - if err := t.rollupForgeBatch(ctx, batchInfo); err == ErrDone { + if err := t.rollupForgeBatch(ctx, batchInfo); tracerr.Unwrap(err) == ErrDone { continue } else if err != nil { // TODO: Reset pipeline

@@ -399,7 +400,7 @@ continue

} batchInfo := t.queue[next] err := t.ethTransactionReceipt(ctx, batchInfo) - if err == ErrDone { + if tracerr.Unwrap(err) == ErrDone { continue } else if err != nil { //nolint:staticcheck // We can't get the receipt for the

@@ -504,12 +505,12 @@

err := p.txSelector.Reset(p.batchNum) if err != nil { log.Errorw("Pipeline: TxSelector.Reset", "error", err) - return err + return tracerr.Wrap(err) } err = p.batchBuilder.Reset(p.batchNum, true) if err != nil { log.Errorw("Pipeline: BatchBuilder.Reset", "error", err) - return err + return tracerr.Wrap(err) } queueSize := 1

@@ -528,7 +529,7 @@ p.stats = syncStats

default: p.batchNum = p.batchNum + 1 batchInfo, err := p.forgeSendServerProof(p.ctx, p.batchNum) - if err == ErrDone { + if tracerr.Unwrap(err) == ErrDone { continue } if err != nil {

@@ -550,7 +551,7 @@ p.wg.Done()

return case batchInfo := <-batchChSentServerProof: err := p.waitServerProof(p.ctx, batchInfo) - if err == ErrDone { + if tracerr.Unwrap(err) == ErrDone { continue } if err != nil {

@@ -582,7 +583,7 @@ func (p *Pipeline) forgeSendServerProof(ctx context.Context, batchNum common.BatchNum) (*BatchInfo, error) {

// remove transactions from the pool that have been there for too long err := p.purgeRemoveByTimeout() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } batchInfo := BatchInfo{BatchNum: batchNum} // to accumulate metadata of the batch

@@ -598,13 +599,13 @@ // l1UserTxs, toForgeL1TxsNumber := c.historyDB.GetNextL1UserTxs() // TODO once HistoryDB is ready, uncomment

var l1UserTxs []common.L1Tx = nil // tmp, depends on HistoryDB l1UserTxsExtra, l1OperatorTxs, poolL2Txs, err = p.txSelector.GetL1L2TxSelection([]common.Idx{}, batchNum, l1UserTxs) // TODO once feesInfo is added to method return, add the var if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } } else { // 2b: only L2 txs _, poolL2Txs, err = p.txSelector.GetL2TxSelection([]common.Idx{}, batchNum) // TODO once feesInfo is added to method return, add the var if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } l1UserTxsExtra = nil l1OperatorTxs = nil

@@ -616,7 +617,7 @@ // (fromIdx, nonce) which already appears in the selected txs (includes

// all the nonces smaller than the current one) err = p.purgeInvalidDueToL2TxsSelection(poolL2Txs) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // 3. Save metadata from TxSelector output for BatchNum

@@ -631,7 +632,7 @@ ForgerAddress: p.cfg.ForgerAddress,

} zkInputs, err := p.batchBuilder.BuildBatch([]common.Idx{}, configBatch, l1UserTxsExtra, l1OperatorTxs, poolL2Txs, nil) // TODO []common.TokenID --> feesInfo if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // 5. Save metadata from BatchBuilder output for BatchNum

@@ -641,7 +642,7 @@

// 6. Wait for an available server proof blocking call serverProof, err := p.serverProofPool.Get(ctx) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } batchInfo.ServerProof = serverProof defer func() {

@@ -657,7 +658,7 @@ // 7. Call the selected idle server proof with BatchBuilder output,

// save server proof info for batchNum err = batchInfo.ServerProof.CalculateProof(zkInputs) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &batchInfo, nil

@@ -667,7 +668,7 @@ // waitServerProof gets the generated zkProof & sends it to the SmartContract

func (p *Pipeline) waitServerProof(ctx context.Context, batchInfo *BatchInfo) error { proof, err := batchInfo.ServerProof.GetProof(ctx) // blocking call, until not resolved don't continue. Returns when the proof server has calculated the proof if err != nil { - return err + return tracerr.Wrap(err) } p.serverProofPool.Add(batchInfo.ServerProof) batchInfo.ServerProof = nil
M coordinator/proofpool.go → coordinator/proofpool.go

@@ -6,6 +6,7 @@ "time"

"github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" ) // ServerProofInterface is the interface to a ServerProof that calculates zk proofs

@@ -30,13 +31,13 @@ // CalculateProof sends the *common.ZKInputs to the ServerProof to compute the

// Proof func (p *ServerProof) CalculateProof(zkInputs *common.ZKInputs) error { log.Error("TODO") - return errTODO + return tracerr.Wrap(errTODO) } // GetProof retreives the Proof from the ServerProof func (p *ServerProof) GetProof(ctx context.Context) (*Proof, error) { log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // ServerProofMock is a mock ServerProof to be used in tests. It doesn't calculate anything

@@ -56,7 +57,7 @@ select {

case <-time.After(200 * time.Millisecond): //nolint:gomnd return &Proof{}, nil case <-ctx.Done(): - return nil, ErrDone + return nil, tracerr.Wrap(ErrDone) } }

@@ -82,7 +83,7 @@ func (p *ServerProofPool) Get(ctx context.Context) (ServerProofInterface, error) {

select { case <-ctx.Done(): log.Info("ServerProofPool.Get done") - return nil, ErrDone + return nil, tracerr.Wrap(ErrDone) case serverProof := <-p.pool: return serverProof, nil }
M db/historydb/historydb.go → db/historydb/historydb.go

@@ -10,6 +10,7 @@

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/db" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/jmoiron/sqlx"

@@ -73,7 +74,7 @@ err := meddler.QueryRow(

hdb.db, block, "SELECT * FROM block WHERE eth_block_num = $1;", blockNum, ) - return block, err + return block, tracerr.Wrap(err) } // GetAllBlocks retrieve all blocks from the DB

@@ -83,7 +84,7 @@ err := meddler.QueryAll(

hdb.db, &blocks, "SELECT * FROM block;", ) - return db.SlicePtrsToSlice(blocks).([]common.Block), err + return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err) } // GetBlocks retrieve blocks from the DB, given a range of block numbers defined by from and to

@@ -94,7 +95,7 @@ hdb.db, &blocks,

"SELECT * FROM block WHERE $1 <= eth_block_num AND eth_block_num < $2;", from, to, ) - return db.SlicePtrsToSlice(blocks).([]common.Block), err + return db.SlicePtrsToSlice(blocks).([]common.Block), tracerr.Wrap(err) } // GetLastBlock retrieve the block with the highest block number from the DB

@@ -103,7 +104,7 @@ block := &common.Block{}

err := meddler.QueryRow( hdb.db, block, "SELECT * FROM block ORDER BY eth_block_num DESC LIMIT 1;", ) - return block, err + return block, tracerr.Wrap(err) } // AddBatch insert a Batch into the DB

@@ -128,13 +129,13 @@ "SELECT token_id, usd, decimals FROM token WHERE token_id IN (?)",

tokenIDs, ) if err != nil { - return err + return tracerr.Wrap(err) } query = hdb.db.Rebind(query) if err := meddler.QueryAll( hdb.db, &tokenPrices, query, args..., ); err != nil { - return err + return tracerr.Wrap(err) } } // Calculate total collected

@@ -159,7 +160,7 @@ }

func (hdb *HistoryDB) addBatches(d meddler.DB, batches []common.Batch) error { for i := 0; i < len(batches); i++ { if err := hdb.addBatch(d, &batches[i]); err != nil { - return err + return tracerr.Wrap(err) } } return nil

@@ -258,11 +259,11 @@ query = hdb.db.Rebind(queryStr)

// log.Debug(query) batchPtrs := []*BatchAPI{} if err := meddler.QueryAll(hdb.db, &batchPtrs, query, args...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } batches := db.SlicePtrsToSlice(batchPtrs).([]BatchAPI) if len(batches) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return batches, batches[0].TotalItems - uint64(len(batches)), nil }

@@ -276,7 +277,7 @@ `SELECT batch.batch_num, batch.eth_block_num, batch.forger_addr, batch.fees_collected,

batch.fee_idxs_coordinator, batch.state_root, batch.num_accounts, batch.last_idx, batch.exit_root, batch.forge_l1_txs_num, batch.slot_num, batch.total_fees_usd FROM batch;`, ) - return db.SlicePtrsToSlice(batches).([]common.Batch), err + return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err) } // GetBatches retrieve batches from the DB, given a range of batch numbers defined by from and to

@@ -287,7 +288,7 @@ hdb.db, &batches,

"SELECT * FROM batch WHERE $1 <= batch_num AND batch_num < $2;", from, to, ) - return db.SlicePtrsToSlice(batches).([]common.Batch), err + return db.SlicePtrsToSlice(batches).([]common.Batch), tracerr.Wrap(err) } // GetBatchesLen retrieve number of batches from the DB, given a slotNum

@@ -331,7 +332,7 @@ _, err = hdb.db.Exec("DELETE FROM block;")

} else { _, err = hdb.db.Exec("DELETE FROM block WHERE eth_block_num > $1;", lastValidBlock) } - return err + return tracerr.Wrap(err) } // AddBids insert Bids into the DB

@@ -352,7 +353,7 @@ err := meddler.QueryAll(

hdb.db, &bids, `SELECT bid.slot_num, bid.bid_value, bid.eth_block_num, bid.bidder_addr FROM bid;`, ) - return db.SlicePtrsToSlice(bids).([]common.Bid), err + return db.SlicePtrsToSlice(bids).([]common.Bid), tracerr.Wrap(err) } // GetBestBidAPI returns the best bid in specific slot by slotNum

@@ -364,7 +365,7 @@ FROM bid INNER JOIN block ON bid.eth_block_num = block.eth_block_num

INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr WHERE slot_num = $1 ORDER BY item_id DESC LIMIT 1;`, slotNum, ) - return *bid, err + return *bid, tracerr.Wrap(err) } // GetBestBidCoordinator returns the forger address of the highest bidder in a slot by slotNum

@@ -385,7 +386,7 @@ INNER JOIN coordinator ON bid.bidder_addr = coordinator.bidder_addr

WHERE bid.slot_num = $1 ORDER BY bid.item_id DESC LIMIT 1;`, slotNum) - return bidCoord, err + return bidCoord, tracerr.Wrap(err) } // GetBestBidsAPI returns the best bid in specific slot by slotNum

@@ -424,12 +425,12 @@ }

query = hdb.db.Rebind(queryStr) bidPtrs := []*BidAPI{} if err := meddler.QueryAll(hdb.db, &bidPtrs, query, args...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } // log.Debug(query) bids := db.SlicePtrsToSlice(bidPtrs).([]BidAPI) if len(bids) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return bids, bids[0].TotalItems - uint64(len(bids)), nil }

@@ -492,15 +493,15 @@ }

queryStr += fmt.Sprintf("LIMIT %d;", *limit) query, argsQ, err := sqlx.In(queryStr, args...) if err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } query = hdb.db.Rebind(query) bids := []*BidAPI{} if err := meddler.QueryAll(hdb.db, &bids, query, argsQ...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } if len(bids) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return db.SlicePtrsToSlice(bids).([]BidAPI), bids[0].TotalItems - uint64(len(bids)), nil }

@@ -592,7 +593,7 @@ (d.delayed_withdrawn IS NOT NULL AND e.delayed_withdrawn IS NULL AND e.owner = d.owner AND e.token = d.token)

` if len(withdrawals) > 0 { if _, err := sqlx.NamedQuery(d, query, withdrawals); err != nil { - return err + return tracerr.Wrap(err) } }

@@ -627,7 +628,7 @@ _, err := hdb.db.Exec(

"UPDATE token SET usd = $1 WHERE symbol = $2;", value, tokenSymbol, ) - return err + return tracerr.Wrap(err) } // GetToken returns a token from the DB given a TokenID

@@ -636,7 +637,7 @@ token := &TokenWithUSD{}

err := meddler.QueryRow( hdb.db, token, `SELECT * FROM token WHERE token_id = $1;`, tokenID, ) - return token, err + return token, tracerr.Wrap(err) } // GetAllTokens returns all tokens from the DB

@@ -646,7 +647,7 @@ err := meddler.QueryAll(

hdb.db, &tokens, "SELECT * FROM token ORDER BY token_id;", ) - return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), err + return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), tracerr.Wrap(err) } // GetTokens returns a list of tokens from the DB

@@ -707,15 +708,15 @@ }

queryStr += fmt.Sprintf("LIMIT %d;", *limit) query, argsQ, err := sqlx.In(queryStr, args...) if err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } query = hdb.db.Rebind(query) tokens := []*TokenWithUSD{} if err := meddler.QueryAll(hdb.db, &tokens, query, argsQ...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } if len(tokens) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return db.SlicePtrsToSlice(tokens).([]TokenWithUSD), uint64(len(tokens)) - tokens[0].TotalItems, nil }

@@ -725,13 +726,13 @@ func (hdb *HistoryDB) GetTokenSymbols() ([]string, error) {

var tokenSymbols []string rows, err := hdb.db.Query("SELECT symbol FROM token;") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } sym := new(string) for rows.Next() { err = rows.Scan(sym) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tokenSymbols = append(tokenSymbols, *sym) }

@@ -763,7 +764,7 @@ err := meddler.QueryAll(

hdb.db, &accs, "SELECT * FROM account ORDER BY idx;", ) - return db.SlicePtrsToSlice(accs).([]common.Account), err + return db.SlicePtrsToSlice(accs).([]common.Account), tracerr.Wrap(err) } // AddL1Txs inserts L1 txs to the DB. USD and LoadAmountUSD will be set automatically before storing the tx.

@@ -895,7 +896,7 @@ FROM tx INNER JOIN token ON tx.token_id = token.token_id

INNER JOIN block ON tx.eth_block_num = block.eth_block_num WHERE tx.id = $1;`, txID, ) - return tx, err + return tx, tracerr.Wrap(err) } // GetHistoryTxs returns a list of txs from the DB using the HistoryTx struct

@@ -906,7 +907,7 @@ tokenID *common.TokenID, idx *common.Idx, batchNum *uint, txType *common.TxType,

fromItem, limit *uint, order string, ) ([]TxAPI, uint64, error) { if ethAddr != nil && bjj != nil { - return nil, 0, errors.New("ethAddr and bjj are incompatible") + return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible")) } var query string var args []interface{}

@@ -1010,11 +1011,11 @@ query = hdb.db.Rebind(queryStr)

// log.Debug(query) txsPtrs := []*TxAPI{} if err := meddler.QueryAll(hdb.db, &txsPtrs, query, args...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } txs := db.SlicePtrsToSlice(txsPtrs).([]TxAPI) if len(txs) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return txs, txs[0].TotalItems - uint64(len(txs)), nil }

@@ -1028,7 +1029,7 @@ `SELECT exit_tree.batch_num, exit_tree.account_idx, exit_tree.merkle_proof,

exit_tree.balance, exit_tree.instant_withdrawn, exit_tree.delayed_withdraw_request, exit_tree.delayed_withdrawn FROM exit_tree;`, ) - return db.SlicePtrsToSlice(exits).([]common.ExitInfo), err + return db.SlicePtrsToSlice(exits).([]common.ExitInfo), tracerr.Wrap(err) } // GetExitAPI returns a exit from the DB

@@ -1046,7 +1047,7 @@ FROM exit_tree INNER JOIN account ON exit_tree.account_idx = account.idx

INNER JOIN token ON account.token_id = token.token_id WHERE exit_tree.batch_num = $1 AND exit_tree.account_idx = $2;`, batchNum, idx, ) - return exit, err + return exit, tracerr.Wrap(err) } // GetExitsAPI returns a list of exits from the DB and pagination info

@@ -1056,7 +1057,7 @@ idx *common.Idx, batchNum *uint, onlyPendingWithdraws *bool,

fromItem, limit *uint, order string, ) ([]ExitAPI, uint64, error) { if ethAddr != nil && bjj != nil { - return nil, 0, errors.New("ethAddr and bjj are incompatible") + return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible")) } var query string var args []interface{}

@@ -1152,10 +1153,10 @@ query = hdb.db.Rebind(queryStr)

// log.Debug(query) exits := []*ExitAPI{} if err := meddler.QueryAll(hdb.db, &exits, query, args...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } if len(exits) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return db.SlicePtrsToSlice(exits).([]ExitAPI), exits[0].TotalItems - uint64(len(exits)), nil }

@@ -1171,7 +1172,7 @@ tx.amount, tx.effective_amount, tx.load_amount, tx.effective_load_amount,

tx.eth_block_num, tx.type, tx.batch_num FROM tx WHERE is_l1 = TRUE AND user_origin = TRUE;`, ) - return db.SlicePtrsToSlice(txs).([]common.L1Tx), err + return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err) } // GetAllL1CoordinatorTxs returns all L1CoordinatorTxs from the DB

@@ -1185,7 +1186,7 @@ tx.amount, tx.effective_amount, tx.load_amount, tx.effective_load_amount,

tx.eth_block_num, tx.type, tx.batch_num FROM tx WHERE is_l1 = TRUE AND user_origin = FALSE;`, ) - return db.SlicePtrsToSlice(txs).([]common.L1Tx), err + return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err) } // GetAllL2Txs returns all L2Txs from the DB

@@ -1198,7 +1199,7 @@ tx.from_idx, tx.to_idx, tx.amount, tx.fee, tx.nonce,

tx.type, tx.eth_block_num FROM tx WHERE is_l1 = FALSE;`, ) - return db.SlicePtrsToSlice(txs).([]common.L2Tx), err + return db.SlicePtrsToSlice(txs).([]common.L2Tx), tracerr.Wrap(err) } // GetL1UserTxs gets L1 User Txs to be forged in the L1Batch with toForgeL1TxsNum.

@@ -1213,7 +1214,7 @@ tx.eth_block_num, tx.type, tx.batch_num

FROM tx WHERE to_forge_l1_txs_num = $1 AND is_l1 = TRUE AND user_origin = TRUE;`, toForgeL1TxsNum, ) - return db.SlicePtrsToSlice(txs).([]common.L1Tx), err + return db.SlicePtrsToSlice(txs).([]common.L1Tx), tracerr.Wrap(err) } // TODO: Think about chaning all the queries that return a last value, to queries that return the next valid value.

@@ -1233,15 +1234,15 @@ var auction common.AuctionVariables

var wDelayer common.WDelayerVariables if err := meddler.QueryRow(hdb.db, &rollup, "SELECT * FROM rollup_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil { - return nil, nil, nil, err + return nil, nil, nil, tracerr.Wrap(err) } if err := meddler.QueryRow(hdb.db, &auction, "SELECT * FROM auction_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil { - return nil, nil, nil, err + return nil, nil, nil, tracerr.Wrap(err) } if err := meddler.QueryRow(hdb.db, &wDelayer, "SELECT * FROM wdelayer_vars ORDER BY eth_block_num DESC LIMIT 1;"); err != nil { - return nil, nil, nil, err + return nil, nil, nil, tracerr.Wrap(err) } return &rollup, &auction, &wDelayer, nil }

@@ -1266,7 +1267,7 @@ func (hdb *HistoryDB) SetInitialSCVars(rollup *common.RollupVariables,

auction *common.AuctionVariables, wDelayer *common.WDelayerVariables) error { txn, err := hdb.db.Beginx() if err != nil { - return err + return tracerr.Wrap(err) } defer func() { if err != nil {

@@ -1280,13 +1281,13 @@ auction.EthBlockNum = 0

wDelayer.EthBlockNum = 0 auction.DefaultSlotSetBidSlotNum = 0 if err := hdb.setRollupVars(txn, rollup); err != nil { - return err + return tracerr.Wrap(err) } if err := hdb.setAuctionVars(txn, auction); err != nil { - return err + return tracerr.Wrap(err) } if err := hdb.setWDelayerVars(txn, wDelayer); err != nil { - return err + return tracerr.Wrap(err) } return txn.Commit()

@@ -1299,7 +1300,7 @@ // items should also be in the correct order (Accounts, Tokens, Txs, etc.)

func (hdb *HistoryDB) AddBlockSCData(blockData *common.BlockData) (err error) { txn, err := hdb.db.Beginx() if err != nil { - return err + return tracerr.Wrap(err) } defer func() { if err != nil {

@@ -1309,27 +1310,27 @@ }()

// Add block if err := hdb.addBlock(txn, &blockData.Block); err != nil { - return err + return tracerr.Wrap(err) } // Add Coordinators if len(blockData.Auction.Coordinators) > 0 { if err := hdb.addCoordinators(txn, blockData.Auction.Coordinators); err != nil { - return err + return tracerr.Wrap(err) } } // Add Bids if len(blockData.Auction.Bids) > 0 { if err := hdb.addBids(txn, blockData.Auction.Bids); err != nil { - return err + return tracerr.Wrap(err) } } // Add Tokens if len(blockData.Rollup.AddedTokens) > 0 { if err := hdb.addTokens(txn, blockData.Rollup.AddedTokens); err != nil { - return err + return tracerr.Wrap(err) } }

@@ -1366,69 +1367,69 @@ batch := &blockData.Rollup.Batches[i]

// Add Batch: this will trigger an update on the DB // that will set the batch num of forged L1 txs in this batch if err = hdb.addBatch(txn, &batch.Batch); err != nil { - return err + return tracerr.Wrap(err) } // Add accounts if len(batch.CreatedAccounts) > 0 { if err := hdb.addAccounts(txn, batch.CreatedAccounts); err != nil { - return err + return tracerr.Wrap(err) } } // Add forged l1 coordinator Txs if len(batch.L1CoordinatorTxs) > 0 { if err := hdb.addL1Txs(txn, batch.L1CoordinatorTxs); err != nil { - return err + return tracerr.Wrap(err) } } // Add l2 Txs if len(batch.L2Txs) > 0 { if err := hdb.addL2Txs(txn, batch.L2Txs); err != nil { - return err + return tracerr.Wrap(err) } } // Add user L1 txs that will be forged in next batch if userlL1s, ok := userL1s[batch.Batch.BatchNum]; ok { if err := hdb.addL1Txs(txn, userlL1s); err != nil { - return err + return tracerr.Wrap(err) } } // Add exit tree if len(batch.ExitTree) > 0 { if err := hdb.addExitTree(txn, batch.ExitTree); err != nil { - return err + return tracerr.Wrap(err) } } } // Add user L1 txs that won't be forged in this block if userL1sNotForgedInThisBlock, ok := userL1s[0]; ok { if err := hdb.addL1Txs(txn, userL1sNotForgedInThisBlock); err != nil { - return err + return tracerr.Wrap(err) } } if blockData.Rollup.Vars != nil { if err := hdb.setRollupVars(txn, blockData.Rollup.Vars); err != nil { - return err + return tracerr.Wrap(err) } } if blockData.Auction.Vars != nil { if err := hdb.setAuctionVars(txn, blockData.Auction.Vars); err != nil { - return err + return tracerr.Wrap(err) } } if blockData.WDelayer.Vars != nil { if err := hdb.setWDelayerVars(txn, blockData.WDelayer.Vars); err != nil { - return err + return tracerr.Wrap(err) } } if err := hdb.updateExitTree(txn, blockData.Block.Num, blockData.Rollup.Withdrawals, blockData.WDelayer.Withdrawals); err != nil { - return err + return tracerr.Wrap(err) } return txn.Commit()

@@ -1438,7 +1439,7 @@ // GetCoordinatorAPI returns a coordinator by its bidderAddr

func (hdb *HistoryDB) GetCoordinatorAPI(bidderAddr ethCommon.Address) (*CoordinatorAPI, error) { coordinator := &CoordinatorAPI{} err := meddler.QueryRow(hdb.db, coordinator, "SELECT * FROM coordinator WHERE bidder_addr = $1;", bidderAddr) - return coordinator, err + return coordinator, tracerr.Wrap(err) } // GetCoordinatorsAPI returns a list of coordinators from the DB and pagination info

@@ -1470,10 +1471,10 @@ query = hdb.db.Rebind(queryStr)

coordinators := []*CoordinatorAPI{} if err := meddler.QueryAll(hdb.db, &coordinators, query, args...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } if len(coordinators) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return db.SlicePtrsToSlice(coordinators).([]CoordinatorAPI), coordinators[0].TotalItems - uint64(len(coordinators)), nil

@@ -1490,7 +1491,7 @@ auctionVars := &common.AuctionVariables{}

err := meddler.QueryRow( hdb.db, auctionVars, `SELECT * FROM auction_vars;`, ) - return auctionVars, err + return auctionVars, tracerr.Wrap(err) } // GetAccountAPI returns an account by its index

@@ -1503,7 +1504,7 @@ token.eth_addr as token_eth_addr, token.name, token.symbol, token.decimals, token.usd, token.usd_update

FROM account INNER JOIN token ON account.token_id = token.token_id WHERE idx = $1;`, idx) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return account, nil

@@ -1515,7 +1516,7 @@ tokenIDs []common.TokenID, ethAddr *ethCommon.Address,

bjj *babyjub.PublicKey, fromItem, limit *uint, order string, ) ([]AccountAPI, uint64, error) { if ethAddr != nil && bjj != nil { - return nil, 0, errors.New("ethAddr and bjj are incompatible") + return nil, 0, tracerr.Wrap(errors.New("ethAddr and bjj are incompatible")) } var query string var args []interface{}

@@ -1570,16 +1571,16 @@ }

queryStr += fmt.Sprintf("LIMIT %d;", *limit) query, argsQ, err := sqlx.In(queryStr, args...) if err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } query = hdb.db.Rebind(query) accounts := []*AccountAPI{} if err := meddler.QueryAll(hdb.db, &accounts, query, argsQ...); err != nil { - return nil, 0, err + return nil, 0, tracerr.Wrap(err) } if len(accounts) == 0 { - return nil, 0, sql.ErrNoRows + return nil, 0, tracerr.Wrap(sql.ErrNoRows) } return db.SlicePtrsToSlice(accounts).([]AccountAPI),

@@ -1595,7 +1596,7 @@ hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num

FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num WHERE block.timestamp >= NOW() - INTERVAL '24 HOURS';`) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } metrics.TransactionsPerSecond = float64(metricsTotals.TotalTransactions / (24 * 60 * 60))

@@ -1611,7 +1612,7 @@ hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches,

SUM(total_fees_usd) AS total_fees FROM batch WHERE batch_num > $1;`, metricsTotals.FirstBatchNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if metricsTotals.TotalBatches > 0 { metrics.BatchFrequency = float64((24 * 60 * 60) / metricsTotals.TotalBatches)

@@ -1627,7 +1628,7 @@ err = meddler.QueryRow(

hdb.db, metrics, `SELECT COUNT(*) AS total_bjjs, COUNT(DISTINCT(bjj)) AS total_accounts FROM account;`) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return metrics, nil

@@ -1641,14 +1642,14 @@ hdb.db, metricsTotals, `SELECT COUNT(tx.*) as total_txs, MIN(tx.batch_num) as batch_num

FROM tx INNER JOIN block ON tx.eth_block_num = block.eth_block_num WHERE block.timestamp >= NOW() - INTERVAL '1 HOURS';`) if err != nil { - return 0, err + return 0, tracerr.Wrap(err) } err = meddler.QueryRow( hdb.db, metricsTotals, `SELECT COUNT(*) AS total_batches, SUM(total_fees_usd) AS total_fees FROM batch WHERE batch_num > $1;`, metricsTotals.FirstBatchNum) if err != nil { - return 0, err + return 0, tracerr.Wrap(err) } var avgTransactionFee float64
M db/historydb/historydb_test.go → db/historydb/historydb_test.go

@@ -14,6 +14,7 @@ dbUtils "github.com/hermeznetwork/hermez-node/db"

"github.com/hermeznetwork/hermez-node/log" "github.com/hermeznetwork/hermez-node/test" "github.com/hermeznetwork/hermez-node/test/til" + "github.com/hermeznetwork/tracerr" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" )

@@ -78,7 +79,7 @@ assert.NoError(t, err)

} // Add block 0 to the generated blocks blocks = append( - []common.BlockData{common.BlockData{Block: test.Block0}}, //nolint:gofmt + []common.BlockData{{Block: test.Block0}}, //nolint:gofmt blocks..., ) // Get all blocks from DB

@@ -680,7 +681,7 @@

func TestSetInitialSCVars(t *testing.T) { test.WipeDB(historyDB.DB()) _, _, _, err := historyDB.GetSCVars() - assert.Equal(t, sql.ErrNoRows, err) + assert.Equal(t, sql.ErrNoRows, tracerr.Unwrap(err)) rollup, auction, wDelayer := exampleInitSCVars() err = historyDB.SetInitialSCVars(rollup, auction, wDelayer) require.Nil(t, err)

@@ -859,7 +860,7 @@ require.Equal(t, coords[1].Bidder, forger10.Bidder)

require.Equal(t, coords[1].URL, forger10.URL) _, err = historyDB.GetBestBidCoordinator(11) - require.Equal(t, sql.ErrNoRows, err) + require.Equal(t, sql.ErrNoRows, tracerr.Unwrap(err)) } // setTestBlocks WARNING: this will delete the blocks and recreate them
M db/l2db/l2db.go → db/l2db/l2db.go

@@ -7,6 +7,7 @@

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/db" + "github.com/hermeznetwork/tracerr" "github.com/jmoiron/sqlx" //nolint:errcheck // driver for postgres DB

@@ -51,7 +52,7 @@ `INSERT INTO account_creation_auth (eth_addr, bjj, signature)

VALUES ($1, $2, $3);`, auth.EthAddr, auth.BJJ, auth.Signature, ) - return err + return tracerr.Wrap(err) } // GetAccountCreationAuth returns an account creation authorization from the DB

@@ -170,7 +171,7 @@ l2db.db, &txs,

selectPoolTxCommon+"WHERE state = $1", common.PoolL2TxStatePending, ) - return db.SlicePtrsToSlice(txs).([]common.PoolL2Tx), err + return db.SlicePtrsToSlice(txs).([]common.PoolL2Tx), tracerr.Wrap(err) } // StartForging updates the state of the transactions that will begin the forging process.

@@ -186,11 +187,11 @@ common.PoolL2TxStatePending,

txIDs, ) if err != nil { - return err + return tracerr.Wrap(err) } query = l2db.db.Rebind(query) _, err = l2db.db.Exec(query, args...) - return err + return tracerr.Wrap(err) } // DoneForging updates the state of the transactions that have been forged

@@ -206,11 +207,11 @@ common.PoolL2TxStateForging,

txIDs, ) if err != nil { - return err + return tracerr.Wrap(err) } query = l2db.db.Rebind(query) _, err = l2db.db.Exec(query, args...) - return err + return tracerr.Wrap(err) } // InvalidateTxs updates the state of the transactions that are invalid.

@@ -225,11 +226,11 @@ batchNum,

txIDs, ) if err != nil { - return err + return tracerr.Wrap(err) } query = l2db.db.Rebind(query) _, err = l2db.db.Exec(query, args...) - return err + return tracerr.Wrap(err) } // CheckNonces invalidate txs with nonces that are smaller or equal than their respective accounts nonces.

@@ -237,7 +238,7 @@ // The state of the affected txs will be changed from Pending -> Invalid

func (l2db *L2DB) CheckNonces(updatedAccounts []common.Account, batchNum common.BatchNum) (err error) { txn, err := l2db.db.Beginx() if err != nil { - return err + return tracerr.Wrap(err) } defer func() { // Rollback the transaction if there was an error.

@@ -257,7 +258,7 @@ updatedAccounts[i].Idx,

updatedAccounts[i].Nonce, ) if err != nil { - return err + return tracerr.Wrap(err) } } return txn.Commit()

@@ -274,7 +275,7 @@ common.PoolL2TxStateForged,

common.PoolL2TxStateInvalid, lastValidBatch, ) - return err + return tracerr.Wrap(err) } // Purge deletes transactions that have been forged or marked as invalid for longer than the safety period

@@ -282,7 +283,7 @@ // it also deletes txs that has been in the L2DB for longer than the ttl if maxTxs has been exceeded

func (l2db *L2DB) Purge(currentBatchNum common.BatchNum) (err error) { txn, err := l2db.db.Beginx() if err != nil { - return err + return tracerr.Wrap(err) } defer func() { // Rollback the transaction if there was an error.

@@ -298,7 +299,7 @@ l2db.maxTxs,

time.Unix(now-int64(l2db.ttl.Seconds()), 0), ) if err != nil { - return err + return tracerr.Wrap(err) } // Delete txs that have been marked as forged / invalid after the safety period _, err = txn.Exec(

@@ -309,7 +310,7 @@ common.PoolL2TxStateForged,

common.PoolL2TxStateInvalid, ) if err != nil { - return err + return tracerr.Wrap(err) } return txn.Commit() }
M db/l2db/l2db_test.go → db/l2db/l2db_test.go

@@ -14,6 +14,7 @@ "github.com/hermeznetwork/hermez-node/db/historydb"

"github.com/hermeznetwork/hermez-node/log" "github.com/hermeznetwork/hermez-node/test" "github.com/hermeznetwork/hermez-node/test/til" + "github.com/hermeznetwork/tracerr" "github.com/stretchr/testify/assert" )

@@ -69,12 +70,12 @@ CoordUser: "A",

} blocks, err := tc.GenerateBlocks(setBlockchain) if err != nil { - return err + return tracerr.Wrap(err) } err = tc.FillBlocksExtra(blocks, &tilCfgExtra) if err != nil { - return err + return tracerr.Wrap(err) } tokens = make(map[common.TokenID]historydb.TokenWithUSD) tokensValue = make(map[common.TokenID]float64)

@@ -85,7 +86,7 @@ // Add all blocks except for the last one

for i := range blocks[:len(blocks)-1] { err = historyDB.AddBlockSCData(&blocks[i]) if err != nil { - return err + return tracerr.Wrap(err) } for _, batch := range blocks[i].Rollup.Batches { for _, account := range batch.CreatedAccounts {

@@ -110,7 +111,7 @@ // Set value to the tokens (tokens have no symbol)

tokenSymbol := "" err := historyDB.UpdateTokenValue(tokenSymbol, value) if err != nil { - return err + return tracerr.Wrap(err) } } return nil

@@ -135,7 +136,7 @@ PoolExit(2) B: 3 (1)

` poolL2Txs, err := tc.GeneratePoolL2Txs(setPool) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return poolL2Txs, nil }
M db/statedb/statedb.go → db/statedb/statedb.go

@@ -9,6 +9,7 @@ "strconv"

"github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-merkletree" "github.com/iden3/go-merkletree/db" "github.com/iden3/go-merkletree/db/pebble"

@@ -92,18 +93,18 @@ var sto *pebble.PebbleStorage

var err error sto, err = pebble.NewPebbleStorage(path+PathCurrent, false) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var mt *merkletree.MerkleTree = nil if typ == TypeSynchronizer || typ == TypeBatchBuilder { mt, err = merkletree.NewMerkleTree(sto.WithPrefix(PrefixKeyMT), nLevels) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } } if typ == TypeTxSelector && nLevels != 0 { - return nil, fmt.Errorf("invalid StateDB parameters: StateDB type==TypeStateDB can not have nLevels!=0") + return nil, tracerr.Wrap(fmt.Errorf("invalid StateDB parameters: StateDB type==TypeStateDB can not have nLevels!=0")) } sdb := &StateDB{

@@ -116,13 +117,13 @@

// load currentBatch sdb.currentBatch, err = sdb.GetCurrentBatch() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // make reset (get checkpoint) at currentBatch err = sdb.reset(sdb.currentBatch, false) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return sdb, nil

@@ -136,11 +137,11 @@

// GetCurrentBatch returns the current BatchNum stored in the StateDB func (s *StateDB) GetCurrentBatch() (common.BatchNum, error) { cbBytes, err := s.db.Get(KeyCurrentBatch) - if err == db.ErrNotFound { + if tracerr.Unwrap(err) == db.ErrNotFound { return 0, nil } if err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return common.BatchNumFromBytes(cbBytes) }

@@ -149,14 +150,14 @@ // setCurrentBatch stores the current BatchNum in the StateDB

func (s *StateDB) setCurrentBatch() error { tx, err := s.db.NewTx() if err != nil { - return err + return tracerr.Wrap(err) } err = tx.Put(KeyCurrentBatch, s.currentBatch.Bytes()) if err != nil { - return err + return tracerr.Wrap(err) } if err := tx.Commit(); err != nil { - return err + return tracerr.Wrap(err) } return nil }

@@ -171,23 +172,23 @@ checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(s.currentBatch))

err := s.setCurrentBatch() if err != nil { - return err + return tracerr.Wrap(err) } // if checkpoint BatchNum already exist in disk, delete it if _, err := os.Stat(checkpointPath); !os.IsNotExist(err) { err := os.RemoveAll(checkpointPath) if err != nil { - return err + return tracerr.Wrap(err) } } else if err != nil && !os.IsNotExist(err) { - return err + return tracerr.Wrap(err) } // execute Checkpoint err = s.db.Pebble().Checkpoint(checkpointPath) if err != nil { - return err + return tracerr.Wrap(err) } return nil

@@ -198,7 +199,7 @@ func (s *StateDB) DeleteCheckpoint(batchNum common.BatchNum) error {

checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(batchNum)) if _, err := os.Stat(checkpointPath); os.IsNotExist(err) { - return fmt.Errorf("Checkpoint with batchNum %d does not exist in DB", batchNum) + return tracerr.Wrap(fmt.Errorf("Checkpoint with batchNum %d does not exist in DB", batchNum)) } return os.RemoveAll(checkpointPath)

@@ -209,15 +210,15 @@ // Remove dest folder (if it exists) before doing the checkpoint

if _, err := os.Stat(dest); !os.IsNotExist(err) { err := os.RemoveAll(dest) if err != nil { - return err + return tracerr.Wrap(err) } } else if err != nil && !os.IsNotExist(err) { - return err + return tracerr.Wrap(err) } sto, err := pebble.NewPebbleStorage(source, false) if err != nil { - return err + return tracerr.Wrap(err) } defer func() { errClose := sto.Pebble().Close()

@@ -229,7 +230,7 @@

// execute Checkpoint err = sto.Pebble().Checkpoint(dest) if err != nil { - return err + return tracerr.Wrap(err) } return nil

@@ -253,19 +254,19 @@ currentPath := s.path + PathCurrent

if closeCurrent { if err := s.db.Pebble().Close(); err != nil { - return err + return tracerr.Wrap(err) } } // remove 'current' err := os.RemoveAll(currentPath) if err != nil { - return err + return tracerr.Wrap(err) } if batchNum == 0 { // if batchNum == 0, open the new fresh 'current' sto, err := pebble.NewPebbleStorage(currentPath, false) if err != nil { - return err + return tracerr.Wrap(err) } s.db = sto s.idx = 255

@@ -275,7 +276,7 @@ if s.mt != nil {

// open the MT for the current s.db mt, err := merkletree.NewMerkleTree(s.db.WithPrefix(PrefixKeyMT), s.mt.MaxLevels()) if err != nil { - return err + return tracerr.Wrap(err) } s.mt = mt }

@@ -286,32 +287,32 @@ checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(batchNum))

// copy 'BatchNumX' to 'current' err = pebbleMakeCheckpoint(checkpointPath, currentPath) if err != nil { - return err + return tracerr.Wrap(err) } // open the new 'current' sto, err := pebble.NewPebbleStorage(currentPath, false) if err != nil { - return err + return tracerr.Wrap(err) } s.db = sto // get currentBatch num s.currentBatch, err = s.GetCurrentBatch() if err != nil { - return err + return tracerr.Wrap(err) } // idx is obtained from the statedb reset s.idx, err = s.getIdx() if err != nil { - return err + return tracerr.Wrap(err) } if s.mt != nil { // open the MT for the current s.db mt, err := merkletree.NewMerkleTree(s.db.WithPrefix(PrefixKeyMT), s.mt.MaxLevels()) if err != nil { - return err + return tracerr.Wrap(err) } s.mt = mt }

@@ -335,18 +336,18 @@ // this example: https://github.com/cockroachdb/pebble/pull/923/files

if err := idxDB.Iterate(func(k []byte, v []byte) (bool, error) { idx, err := common.IdxFromBytes(k) if err != nil { - return false, err + return false, tracerr.Wrap(err) } idxs = append(idxs, idx) return true, nil }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } accs := []common.Account{} for i := range idxs { acc, err := s.GetAccount(idxs[i]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } accs = append(accs, *acc) }

@@ -358,21 +359,21 @@ // from ExitTree. GetAccount returns the account for the given Idx

func getAccountInTreeDB(sto db.Storage, idx common.Idx) (*common.Account, error) { idxBytes, err := idx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } vBytes, err := sto.Get(append(PrefixKeyIdx, idxBytes[:]...)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } accBytes, err := sto.Get(append(PrefixKeyAccHash, vBytes...)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var b [32 * common.NLeafElems]byte copy(b[:], accBytes) account, err := common.AccountFromBytes(b) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } account.Idx = idx return account, nil

@@ -384,11 +385,11 @@ // MerkleTree, returning a CircomProcessorProof.

func (s *StateDB) CreateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) { cpp, err := createAccountInTreeDB(s.db, s.mt, idx, account) if err != nil { - return cpp, err + return cpp, tracerr.Wrap(err) } // store idx by EthAddr & BJJ err = s.setIdxByEthAddrBJJ(idx, account.EthAddr, account.PublicKey, account.TokenID) - return cpp, err + return cpp, tracerr.Wrap(err) } // createAccountInTreeDB is abstracted from StateDB to be used from StateDB and

@@ -399,39 +400,39 @@ func createAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {

// store at the DB the key: v, and value: leaf.Bytes() v, err := account.HashValue() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } accountBytes, err := account.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // store the Leaf value tx, err := sto.NewTx() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } idxBytes, err := idx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } _, err = tx.Get(append(PrefixKeyIdx, idxBytes[:]...)) - if err != db.ErrNotFound { - return nil, ErrAccountAlreadyExists + if tracerr.Unwrap(err) != db.ErrNotFound { + return nil, tracerr.Wrap(ErrAccountAlreadyExists) } err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if err := tx.Commit(); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if mt != nil {

@@ -456,32 +457,32 @@ func updateAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {

// store at the DB the key: v, and value: account.Bytes() v, err := account.HashValue() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } accountBytes, err := account.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tx, err := sto.NewTx() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } idxBytes, err := idx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if err := tx.Commit(); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if mt != nil {

@@ -493,7 +494,7 @@

// MTGetProof returns the CircomVerifierProof for a given Idx func (s *StateDB) MTGetProof(idx common.Idx) (*merkletree.CircomVerifierProof, error) { if s.mt == nil { - return nil, ErrStateDBWithoutMT + return nil, tracerr.Wrap(ErrStateDBWithoutMT) } return s.mt.GenerateCircomVerifierProof(idx.BigInt(), s.mt.Root()) }

@@ -516,7 +517,7 @@ // synchronizerDB

func NewLocalStateDB(path string, synchronizerDB *StateDB, typ TypeStateDB, nLevels int) (*LocalStateDB, error) { s, err := NewStateDB(path, typ, nLevels) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &LocalStateDB{ s,

@@ -540,44 +541,44 @@ if fromSynchronizer {

// use checkpoint from SynchronizerStateDB if _, err := os.Stat(synchronizerCheckpointPath); os.IsNotExist(err) { // if synchronizerStateDB does not have checkpoint at batchNum, return err - return fmt.Errorf("Checkpoint not exist in Synchronizer") + return tracerr.Wrap(fmt.Errorf("Checkpoint not exist in Synchronizer")) } if err := l.db.Pebble().Close(); err != nil { - return err + return tracerr.Wrap(err) } // remove 'current' err := os.RemoveAll(currentPath) if err != nil { - return err + return tracerr.Wrap(err) } // copy synchronizer'BatchNumX' to 'current' err = pebbleMakeCheckpoint(synchronizerCheckpointPath, currentPath) if err != nil { - return err + return tracerr.Wrap(err) } // copy synchronizer'BatchNumX' to 'BatchNumX' err = pebbleMakeCheckpoint(synchronizerCheckpointPath, checkpointPath) if err != nil { - return err + return tracerr.Wrap(err) } // open the new 'current' sto, err := pebble.NewPebbleStorage(currentPath, false) if err != nil { - return err + return tracerr.Wrap(err) } l.db = sto // get currentBatch num l.currentBatch, err = l.GetCurrentBatch() if err != nil { - return err + return tracerr.Wrap(err) } // open the MT for the current s.db mt, err := merkletree.NewMerkleTree(l.db.WithPrefix(PrefixKeyMT), l.mt.MaxLevels()) if err != nil { - return err + return tracerr.Wrap(err) } l.mt = mt
M db/statedb/statedb_test.go → db/statedb/statedb_test.go

@@ -12,6 +12,7 @@

ethCommon "github.com/ethereum/go-ethereum/common" ethCrypto "github.com/ethereum/go-ethereum/crypto" "github.com/hermeznetwork/hermez-node/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-merkletree/db" "github.com/stretchr/testify/assert"

@@ -69,7 +70,7 @@ sdb, err = NewStateDB(dir, TypeTxSelector, 0)

assert.Nil(t, err) v, err = sdb.db.Get(k0) assert.NotNil(t, err) - assert.Equal(t, db.ErrNotFound, err) + assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err)) assert.Nil(t, v) // store the same data from the beginning that has ben lost since last NewStateDB

@@ -116,7 +117,7 @@ assert.Equal(t, v0, v)

v, err = sdb.db.Get(k1) assert.NotNil(t, err) - assert.Equal(t, db.ErrNotFound, err) + assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err)) assert.Nil(t, v) }

@@ -138,7 +139,7 @@ // get non-existing account, expecting an error

unexistingAccount := common.Idx(1) _, err = sdb.GetAccount(unexistingAccount) assert.NotNil(t, err) - assert.Equal(t, db.ErrNotFound, err) + assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err)) // add test accounts for i := 0; i < len(accounts); i++ {

@@ -159,7 +160,7 @@ _, err = sdb.GetAccount(existingAccount) // check that exist

assert.Nil(t, err) _, err = sdb.CreateAccount(common.Idx(256), accounts[1]) // check that can not be created twice assert.NotNil(t, err) - assert.Equal(t, ErrAccountAlreadyExists, err) + assert.Equal(t, ErrAccountAlreadyExists, tracerr.Unwrap(err)) // update accounts for i := 0; i < len(accounts); i++ {

@@ -171,7 +172,7 @@ }

_, err = sdb.MTGetProof(common.Idx(1)) assert.NotNil(t, err) - assert.Equal(t, ErrStateDBWithoutMT, err) + assert.Equal(t, ErrStateDBWithoutMT, tracerr.Unwrap(err)) } func TestStateDBWithMT(t *testing.T) {

@@ -191,7 +192,7 @@

// get non-existing account, expecting an error _, err = sdb.GetAccount(common.Idx(1)) assert.NotNil(t, err) - assert.Equal(t, db.ErrNotFound, err) + assert.Equal(t, db.ErrNotFound, tracerr.Unwrap(err)) // add test accounts for i := 0; i < len(accounts); i++ {

@@ -210,7 +211,7 @@ _, err = sdb.GetAccount(common.Idx(256)) // check that exist

assert.Nil(t, err) _, err = sdb.CreateAccount(common.Idx(256), accounts[1]) // check that can not be created twice assert.NotNil(t, err) - assert.Equal(t, ErrAccountAlreadyExists, err) + assert.Equal(t, ErrAccountAlreadyExists, tracerr.Unwrap(err)) _, err = sdb.MTGetProof(common.Idx(256)) assert.Nil(t, err)
M db/statedb/txprocessors.go → db/statedb/txprocessors.go

@@ -10,6 +10,7 @@ "os"

"github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-merkletree" "github.com/iden3/go-merkletree/db"

@@ -70,12 +71,12 @@ var exitTree *merkletree.MerkleTree

var createdAccounts []common.Account if s.zki != nil { - return nil, errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty") + return nil, tracerr.Wrap(errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty")) } defer s.resetZKInputs() if len(coordIdxs) >= int(ptc.MaxFeeTx) { - return nil, fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), ptc.MaxFeeTx) + return nil, tracerr.Wrap(fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), ptc.MaxFeeTx)) } s.accumulatedFees = make(map[common.Idx]*big.Int)

@@ -104,7 +105,7 @@ // is only needed in memory

if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder { tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } defer func() { if err := os.RemoveAll(tmpDir); err != nil {

@@ -113,11 +114,11 @@ }

}() sto, err := pebble.NewPebbleStorage(tmpDir, false) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } exitTree, err = merkletree.NewMerkleTree(sto, s.mt.MaxLevels()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } }

@@ -126,7 +127,7 @@ for i := 0; i < len(l1usertxs); i++ {

// assumption: l1usertx are sorted by L1Tx.Position exitIdx, exitAccount, newExit, createdAccount, err := s.processL1Tx(exitTree, &l1usertxs[i]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if s.typ == TypeSynchronizer && createdAccount != nil { createdAccounts = append(createdAccounts, *createdAccount)

@@ -135,13 +136,13 @@

if s.zki != nil { l1TxData, err := l1usertxs[i].BytesGeneric() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } s.zki.Metadata.L1TxsData = append(s.zki.Metadata.L1TxsData, l1TxData) l1TxDataAvailability, err := l1usertxs[i].BytesDataAvailability(s.zki.Metadata.NLevels) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } s.zki.Metadata.L1TxsDataAvailability = append(s.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)

@@ -167,7 +168,7 @@ // Process L1CoordinatorTxs

for i := 0; i < len(l1coordinatortxs); i++ { exitIdx, _, _, createdAccount, err := s.processL1Tx(exitTree, &l1coordinatortxs[i]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if exitIdx != nil { log.Error("Unexpected Exit in L1CoordinatorTx")

@@ -178,7 +179,7 @@ }

if s.zki != nil { l1TxData, err := l1coordinatortxs[i].BytesGeneric() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } s.zki.Metadata.L1TxsData = append(s.zki.Metadata.L1TxsData, l1TxData)

@@ -200,7 +201,7 @@ // coordIdxs. In this way, if a coordIdx uses an Idx that is being

// created in the current batch, at this point the Idx will be created coordIdxsMap, err := s.getTokenIDsFromIdxs(coordIdxs) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // collectedFees will contain the amount of fee collected for each // TokenID

@@ -217,7 +218,7 @@ // get the feePlanTokens

feePlanTokens, err := s.getFeePlanTokens(coordIdxs, l2txs) if err != nil { log.Error(err) - return nil, err + return nil, tracerr.Wrap(err) } copy(s.zki.FeePlanTokens, feePlanTokens) }

@@ -226,12 +227,12 @@ // Process L2Txs

for i := 0; i < len(l2txs); i++ { exitIdx, exitAccount, newExit, err := s.processL2Tx(coordIdxsMap, collectedFees, exitTree, &l2txs[i]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if s.zki != nil { l2TxData, err := l2txs[i].L2Tx().BytesDataAvailability(s.zki.Metadata.NLevels) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } s.zki.Metadata.L2TxsData = append(s.zki.Metadata.L2TxsData, l2TxData)

@@ -271,13 +272,13 @@ // send the fee to the Idx of the Coordinator for the TokenID

accCoord, err := s.GetAccount(idx) if err != nil { log.Errorw("Can not distribute accumulated fees to coordinator account: No coord Idx to receive fee", "idx", idx) - return nil, err + return nil, tracerr.Wrap(err) } accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee) pFee, err := s.UpdateAccount(idx, accCoord) if err != nil { log.Error(err) - return nil, err + return nil, tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()

@@ -315,7 +316,7 @@

// 0. generate MerkleProof p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // 1. generate common.ExitInfo ei := common.ExitInfo{

@@ -389,7 +390,7 @@ for i := 0; i < len(coordIdxs); i++ {

acc, err := s.GetAccount(coordIdxs[i]) if err != nil { log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s", coordIdxs[i], err.Error()) - return nil, err + return nil, tracerr.Wrap(err) } coordTokenIDs[acc.TokenID] = true }

@@ -401,7 +402,7 @@ // AccountsDB (in the StateDB)

acc, err := s.GetAccount(l2txs[i].FromIdx) if err != nil { log.Errorf("could not get account to determine TokenID of L2Tx: FromIdx %d not found: %s", l2txs[i].FromIdx, err.Error()) - return nil, err + return nil, tracerr.Wrap(err) } if _, ok := coordTokenIDs[acc.TokenID]; ok { tokenIDs[acc.TokenID] = true

@@ -429,7 +430,7 @@ var err error

s.zki.TxCompressedData[s.i], err = tx.TxCompressedData() if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } s.zki.FromIdx[s.i] = tx.FromIdx.BigInt() s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()

@@ -460,7 +461,7 @@ // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.

err := s.applyTransfer(nil, nil, tx.Tx(), 0) if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } case common.TxTypeCreateAccountDeposit: s.computeEffectiveAmounts(tx)

@@ -469,7 +470,7 @@ // add new account to the MT, update balance of the MT account

err := s.applyCreateAccount(tx) if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } // TODO applyCreateAccount will return the created account, // which in the case type==TypeSynchronizer will be added to an

@@ -481,7 +482,7 @@ // update balance of the MT account

err := s.applyDeposit(tx, false) if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } case common.TxTypeDepositTransfer: s.computeEffectiveAmounts(tx)

@@ -491,7 +492,7 @@ // & receiver

err := s.applyDeposit(tx, true) if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } case common.TxTypeCreateAccountDepositTransfer: s.computeEffectiveAmounts(tx)

@@ -501,7 +502,7 @@ // update balance & nonce of sender & receiver

err := s.applyCreateAccountDepositTransfer(tx) if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } case common.TxTypeForceExit: s.computeEffectiveAmounts(tx)

@@ -511,7 +512,7 @@ // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees

exitAccount, newExit, err := s.applyExit(nil, nil, exitTree, tx.Tx()) if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } return &tx.FromIdx, exitAccount, newExit, nil, nil default:

@@ -523,7 +524,7 @@ var err error

createdAccount, err = s.GetAccount(s.idx) if err != nil { log.Error(err) - return nil, nil, false, nil, err + return nil, nil, false, nil, tracerr.Wrap(err) } }

@@ -542,12 +543,12 @@ if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {

if s.typ == TypeSynchronizer { // this should never be reached log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0") - return nil, nil, false, fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0") + return nil, nil, false, tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0")) } // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, tx.TokenID) if err != nil { - return nil, nil, false, err + return nil, nil, false, tracerr.Wrap(err) } }

@@ -556,11 +557,11 @@ if s.zki != nil {

// Txs s.zki.TxCompressedData[s.i], err = tx.TxCompressedData() if err != nil { - return nil, nil, false, err + return nil, nil, false, tracerr.Wrap(err) } s.zki.TxCompressedDataV2[s.i], err = tx.TxCompressedDataV2() if err != nil { - return nil, nil, false, err + return nil, nil, false, tracerr.Wrap(err) } s.zki.FromIdx[s.i] = tx.FromIdx.BigInt() s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()

@@ -589,7 +590,7 @@ // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO

signature, err := tx.Signature.Decompress() if err != nil { log.Error(err) - return nil, nil, false, err + return nil, nil, false, tracerr.Wrap(err) } s.zki.S[s.i] = signature.S s.zki.R8x[s.i] = signature.R8.X

@@ -602,7 +603,7 @@ // as type==TypeSynchronizer, always tx.ToIdx!=0

acc, err := s.GetAccount(tx.FromIdx) if err != nil { log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err) - return nil, nil, false, err + return nil, nil, false, tracerr.Wrap(err) } tx.Nonce = acc.Nonce + 1 tx.TokenID = acc.TokenID

@@ -615,14 +616,14 @@ // balance & nonce

err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx) if err != nil { log.Error(err) - return nil, nil, false, err + return nil, nil, false, tracerr.Wrap(err) } case common.TxTypeExit: // execute exit flow exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx()) if err != nil { log.Error(err) - return nil, nil, false, err + return nil, nil, false, tracerr.Wrap(err) } return &tx.FromIdx, exitAccount, newExit, nil default:

@@ -643,7 +644,7 @@ }

p, err := s.CreateAccount(common.Idx(s.idx+1), account) if err != nil { - return err + return tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID1[s.i] = tx.TokenID.BigInt()

@@ -683,7 +684,7 @@ func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {

// deposit the tx.EffectiveLoadAmount into the sender account accSender, err := s.GetAccount(tx.FromIdx) if err != nil { - return err + return tracerr.Wrap(err) } accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveLoadAmount)

@@ -692,7 +693,7 @@ var accReceiver *common.Account

if transfer { accReceiver, err = s.GetAccount(tx.ToIdx) if err != nil { - return err + return tracerr.Wrap(err) } // subtract amount to the sender accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)

@@ -702,7 +703,7 @@ }

// update sender account in localStateDB p, err := s.UpdateAccount(tx.FromIdx, accSender) if err != nil { - return err + return tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()

@@ -722,7 +723,7 @@ if transfer {

// update receiver account in localStateDB p, err := s.UpdateAccount(tx.ToIdx, accReceiver) if err != nil { - return err + return tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()

@@ -757,7 +758,7 @@ // get sender and receiver accounts from localStateDB

accSender, err := s.GetAccount(tx.FromIdx) if err != nil { log.Error(err) - return err + return tracerr.Wrap(err) } if !tx.IsL1 { // increment nonce

@@ -766,7 +767,7 @@

// compute fee and subtract it from the accSender fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee) if err != nil { - return err + return tracerr.Wrap(err) } feeAndAmount := new(big.Int).Add(tx.Amount, fee) accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)

@@ -798,7 +799,7 @@ } else {

accReceiver, err = s.GetAccount(auxToIdx) if err != nil { log.Error(err) - return err + return tracerr.Wrap(err) } }

@@ -809,7 +810,7 @@ // update sender account in localStateDB

pSender, err := s.UpdateAccount(tx.FromIdx, accSender) if err != nil { log.Error(err) - return err + return tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()

@@ -826,7 +827,7 @@

// update receiver account in localStateDB pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver) if err != nil { - return err + return tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()

@@ -855,7 +856,7 @@ EthAddr: tx.FromEthAddr,

} accReceiver, err := s.GetAccount(tx.ToIdx) if err != nil { - return err + return tracerr.Wrap(err) } // subtract amount to the sender accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)

@@ -865,7 +866,7 @@

// create Account of the Sender p, err := s.CreateAccount(common.Idx(s.idx+1), accSender) if err != nil { - return err + return tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID1[s.i] = tx.TokenID.BigInt()

@@ -895,7 +896,7 @@

// update receiver account in localStateDB p, err = s.UpdateAccount(tx.ToIdx, accReceiver) if err != nil { - return err + return tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()

@@ -922,7 +923,7 @@ // 0. subtract tx.Amount from current Account in StateMT

// add the tx.Amount into the Account (tx.FromIdx) in the ExitMT acc, err := s.GetAccount(tx.FromIdx) if err != nil { - return nil, false, err + return nil, false, tracerr.Wrap(err) } if !tx.IsL1 {

@@ -932,7 +933,7 @@

// compute fee and subtract it from the accSender fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee) if err != nil { - return nil, false, err + return nil, false, tracerr.Wrap(err) } feeAndAmount := new(big.Int).Add(tx.Amount, fee) acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)

@@ -956,7 +957,7 @@ }

p, err := s.UpdateAccount(tx.FromIdx, acc) if err != nil { - return nil, false, err + return nil, false, tracerr.Wrap(err) } if s.zki != nil { s.zki.TokenID1[s.i] = acc.TokenID.BigInt()

@@ -974,7 +975,7 @@ if exitTree == nil {

return nil, false, nil } exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx) - if err == db.ErrNotFound { + if tracerr.Unwrap(err) == db.ErrNotFound { // 1a. if idx does not exist in exitTree: // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount) exitAccount := &common.Account{

@@ -985,16 +986,16 @@ PublicKey: acc.PublicKey,

EthAddr: acc.EthAddr, } _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount) - return exitAccount, true, err + return exitAccount, true, tracerr.Wrap(err) } else if err != nil { - return exitAccount, false, err + return exitAccount, false, tracerr.Wrap(err) } // 1b. if idx already exist in exitTree: // update account, where account.Balance += exitAmount exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount) _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount) - return exitAccount, false, err + return exitAccount, false, tracerr.Wrap(err) } // computeEffectiveAmounts checks that the L1Tx data is correct

@@ -1084,11 +1085,11 @@ // getIdx returns the stored Idx from the localStateDB, which is the last Idx

// used for an Account in the localStateDB. func (s *StateDB) getIdx() (common.Idx, error) { idxBytes, err := s.DB().Get(keyidx) - if err == db.ErrNotFound { + if tracerr.Unwrap(err) == db.ErrNotFound { return 0, nil } if err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return common.IdxFromBytes(idxBytes[:]) }

@@ -1097,18 +1098,18 @@ // setIdx stores Idx in the localStateDB

func (s *StateDB) setIdx(idx common.Idx) error { tx, err := s.DB().NewTx() if err != nil { - return err + return tracerr.Wrap(err) } idxBytes, err := idx.Bytes() if err != nil { - return err + return tracerr.Wrap(err) } err = tx.Put(keyidx, idxBytes[:]) if err != nil { - return err + return tracerr.Wrap(err) } if err := tx.Commit(); err != nil { - return err + return tracerr.Wrap(err) } return nil }
M db/statedb/utils.go → db/statedb/utils.go

@@ -8,6 +8,7 @@

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-merkletree" )

@@ -46,7 +47,7 @@ }

} if pk == nil { - return fmt.Errorf("BabyJubJub pk not defined") + return tracerr.Wrap(fmt.Errorf("BabyJubJub pk not defined")) } // store idx for EthAddr & BJJ assuming that EthAddr & BJJ still don't

@@ -55,28 +56,28 @@ // bigger than the given one, so should be updated to the new one

// (smaller) tx, err := s.db.NewTx() if err != nil { - return err + return tracerr.Wrap(err) } idxBytes, err := idx.Bytes() if err != nil { - return err + return tracerr.Wrap(err) } // store Addr&BJJ-idx k := concatEthAddrBJJTokenID(addr, pk, tokenID) err = tx.Put(append(PrefixKeyAddrBJJ, k...), idxBytes[:]) if err != nil { - return err + return tracerr.Wrap(err) } // store Addr-idx k = concatEthAddrTokenID(addr, tokenID) err = tx.Put(append(PrefixKeyAddr, k...), idxBytes[:]) if err != nil { - return err + return tracerr.Wrap(err) } err = tx.Commit() if err != nil { - return err + return tracerr.Wrap(err) } return nil }

@@ -88,11 +89,11 @@ func (s *StateDB) GetIdxByEthAddr(addr ethCommon.Address, tokenID common.TokenID) (common.Idx, error) {

k := concatEthAddrTokenID(addr, tokenID) b, err := s.db.Get(append(PrefixKeyAddr, k...)) if err != nil { - return common.Idx(0), fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), tokenID) + return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), tokenID)) } idx, err := common.IdxFromBytes(b) if err != nil { - return common.Idx(0), fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", err, addr.Hex(), tokenID) + return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", err, addr.Hex(), tokenID)) } return idx, nil }

@@ -112,16 +113,16 @@ // case ToEthAddr!=0 && ToBJJ!=0

k := concatEthAddrBJJTokenID(addr, pk, tokenID) b, err := s.db.Get(append(PrefixKeyAddrBJJ, k...)) if err != nil { - return common.Idx(0), fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), pk, tokenID) + return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), pk, tokenID)) } idx, err := common.IdxFromBytes(b) if err != nil { - return common.Idx(0), fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", err, addr.Hex(), pk, tokenID) + return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", err, addr.Hex(), pk, tokenID)) } return idx, nil } // rest of cases (included case ToEthAddr==0) are not possible - return common.Idx(0), fmt.Errorf("GetIdxByEthAddrBJJ: Not found, %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrGetIdxNoCase, addr.Hex(), pk, tokenID) + return common.Idx(0), tracerr.Wrap(fmt.Errorf("GetIdxByEthAddrBJJ: Not found, %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrGetIdxNoCase, addr.Hex(), pk, tokenID)) } func (s *StateDB) getTokenIDsFromIdxs(idxs []common.Idx) (map[common.TokenID]common.Idx, error) {

@@ -129,7 +130,7 @@ m := make(map[common.TokenID]common.Idx)

for i := 0; i < len(idxs); i++ { a, err := s.GetAccount(idxs[i]) if err != nil { - return nil, fmt.Errorf("getTokenIDsFromIdxs error on GetAccount with Idx==%d: %s", idxs[i], err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("getTokenIDsFromIdxs error on GetAccount with Idx==%d: %s", idxs[i], err.Error())) } m[a.TokenID] = idxs[i] }
M db/statedb/utils_test.go → db/statedb/utils_test.go

@@ -9,6 +9,7 @@ "testing"

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"

@@ -84,7 +85,7 @@ // expect error when trying to get Idx by addr2 & pk2

idxR, err = sdb.GetIdxByEthAddrBJJ(addr2, pk2, tokenID0) assert.NotNil(t, err) expectedErr := fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr2.Hex(), pk2, tokenID0) - assert.Equal(t, expectedErr, err) + assert.Equal(t, expectedErr, tracerr.Unwrap(err)) assert.Equal(t, common.Idx(0), idxR) // expect error when trying to get Idx by addr with not used TokenID _, err = sdb.GetIdxByEthAddr(addr, tokenID1)
M db/utils.go → db/utils.go

@@ -8,6 +8,7 @@ "strings"

"github.com/gobuffalo/packr/v2" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/jmoiron/sqlx" migrate "github.com/rubenv/sql-migrate" "github.com/russross/meddler"

@@ -29,7 +30,7 @@ name,

) db, err := sqlx.Connect("postgres", psqlconn) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // Run DB migrations migrations := &migrate.PackrMigrationSource{

@@ -37,7 +38,7 @@ Box: packr.New("hermez-db-migrations", "./migrations"),

} nMigrations, err := migrate.Exec(db.DB, "postgres", migrations, migrate.Up) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } log.Info("successfully ran ", nMigrations, " migrations") return db, nil

@@ -64,7 +65,7 @@ for i := 0; i < arrayLen; i++ {

arg := arrayValue.Index(i).Addr().Interface() elemArglist, err := meddler.Default.Values(arg, true) if err != nil { - return err + return tracerr.Wrap(err) } arglist = append(arglist, elemArglist...) value := "("

@@ -76,7 +77,7 @@ valueStrings = append(valueStrings, value)

} stmt := fmt.Sprintf(q, strings.Join(valueStrings, ",")) _, err := db.Exec(stmt, arglist...) - return err + return tracerr.Wrap(err) } // BigIntMeddler encodes or decodes the field value to or from JSON

@@ -92,7 +93,7 @@ // PostRead is called after a Scan operation for fields that have the BigIntMeddler

func (b BigIntMeddler) PostRead(fieldPtr, scanTarget interface{}) error { ptr := scanTarget.(*string) if ptr == nil { - return fmt.Errorf("BigIntMeddler.PostRead: nil pointer") + return tracerr.Wrap(fmt.Errorf("BigIntMeddler.PostRead: nil pointer")) } field := fieldPtr.(**big.Int) *field = new(big.Int).SetBytes([]byte(*ptr))

@@ -126,7 +127,7 @@ }

// not null ptr := (*ptrPtr).([]byte) if ptr == nil { - return fmt.Errorf("BigIntMeddler.PostRead: nil pointer") + return tracerr.Wrap(fmt.Errorf("BigIntMeddler.PostRead: nil pointer")) } *field = new(big.Int).SetBytes(ptr) return nil
M eth/auction.go → eth/auction.go

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

HermezAuctionProtocol "github.com/hermeznetwork/hermez-node/eth/contracts/auction" HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" ) // SlotState is the state of a slot

@@ -238,15 +239,15 @@ // NewAuctionClient creates a new AuctionClient. `tokenAddress` is the address of the HEZ tokens.

func NewAuctionClient(client *EthereumClient, address ethCommon.Address, tokenHEZCfg TokenConfig) (*AuctionClient, error) { contractAbi, err := abi.JSON(strings.NewReader(string(HermezAuctionProtocol.HermezAuctionProtocolABI))) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } auction, err := HermezAuctionProtocol.NewHermezAuctionProtocol(address, client.Client()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tokenHEZ, err := HEZ.NewHEZ(tokenHEZCfg.Address, client.Client()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &AuctionClient{ client: client,

@@ -268,7 +269,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetSlotDeadline(auth, newDeadline) }, ); err != nil { - return nil, fmt.Errorf("Failed setting slotDeadline: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting slotDeadline: %w", err)) } return tx, nil }

@@ -277,9 +278,9 @@ // AuctionGetSlotDeadline is the interface to call the smart contract function

func (c *AuctionClient) AuctionGetSlotDeadline() (slotDeadline uint8, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { slotDeadline, err = c.auction.GetSlotDeadline(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return slotDeadline, nil }

@@ -292,7 +293,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetOpenAuctionSlots(auth, newOpenAuctionSlots) }, ); err != nil { - return nil, fmt.Errorf("Failed setting openAuctionSlots: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting openAuctionSlots: %w", err)) } return tx, nil }

@@ -301,9 +302,9 @@ // AuctionGetOpenAuctionSlots is the interface to call the smart contract function

func (c *AuctionClient) AuctionGetOpenAuctionSlots() (openAuctionSlots uint16, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { openAuctionSlots, err = c.auction.GetOpenAuctionSlots(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return openAuctionSlots, nil }

@@ -316,7 +317,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetClosedAuctionSlots(auth, newClosedAuctionSlots) }, ); err != nil { - return nil, fmt.Errorf("Failed setting closedAuctionSlots: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting closedAuctionSlots: %w", err)) } return tx, nil }

@@ -325,9 +326,9 @@ // AuctionGetClosedAuctionSlots is the interface to call the smart contract function

func (c *AuctionClient) AuctionGetClosedAuctionSlots() (closedAuctionSlots uint16, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { closedAuctionSlots, err = c.auction.GetClosedAuctionSlots(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return closedAuctionSlots, nil }

@@ -340,7 +341,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetOutbidding(auth, newOutbidding) }, ); err != nil { - return nil, fmt.Errorf("Failed setting setOutbidding: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting setOutbidding: %w", err)) } return tx, nil }

@@ -349,9 +350,9 @@ // AuctionGetOutbidding is the interface to call the smart contract function

func (c *AuctionClient) AuctionGetOutbidding() (outbidding uint16, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { outbidding, err = c.auction.GetOutbidding(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return outbidding, nil }

@@ -364,7 +365,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetAllocationRatio(auth, newAllocationRatio) }, ); err != nil { - return nil, fmt.Errorf("Failed setting allocationRatio: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting allocationRatio: %w", err)) } return tx, nil }

@@ -373,9 +374,9 @@ // AuctionGetAllocationRatio is the interface to call the smart contract function

func (c *AuctionClient) AuctionGetAllocationRatio() (allocationRation [3]uint16, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { allocationRation, err = c.auction.GetAllocationRatio(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return [3]uint16{}, err + return [3]uint16{}, tracerr.Wrap(err) } return allocationRation, nil }

@@ -388,7 +389,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetDonationAddress(auth, newDonationAddress) }, ); err != nil { - return nil, fmt.Errorf("Failed setting donationAddress: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting donationAddress: %w", err)) } return tx, nil }

@@ -398,9 +399,9 @@ func (c *AuctionClient) AuctionGetDonationAddress() (donationAddress *ethCommon.Address, err error) {

var _donationAddress ethCommon.Address if err := c.client.Call(func(ec *ethclient.Client) error { _donationAddress, err = c.auction.GetDonationAddress(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &_donationAddress, nil }

@@ -413,7 +414,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetBootCoordinator(auth, newBootCoordinator) }, ); err != nil { - return nil, fmt.Errorf("Failed setting bootCoordinator: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting bootCoordinator: %w", err)) } return tx, nil }

@@ -423,9 +424,9 @@ func (c *AuctionClient) AuctionGetBootCoordinator() (bootCoordinator *ethCommon.Address, err error) {

var _bootCoordinator ethCommon.Address if err := c.client.Call(func(ec *ethclient.Client) error { _bootCoordinator, err = c.auction.GetBootCoordinator(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &_bootCoordinator, nil }

@@ -439,7 +440,7 @@ slotSetToSend := big.NewInt(slotSet)

return c.auction.ChangeDefaultSlotSetBid(auth, slotSetToSend, newInitialMinBid) }, ); err != nil { - return nil, fmt.Errorf("Failed changing slotSet Bid: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed changing slotSet Bid: %w", err)) } return tx, nil }

@@ -448,9 +449,9 @@ // AuctionGetClaimableHEZ is the interface to call the smart contract function

func (c *AuctionClient) AuctionGetClaimableHEZ(claimAddress ethCommon.Address) (claimableHEZ *big.Int, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { claimableHEZ, err = c.auction.GetClaimableHEZ(nil, claimAddress) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return claimableHEZ, nil }

@@ -463,7 +464,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.SetCoordinator(auth, forger, coordinatorURL) }, ); err != nil { - return nil, fmt.Errorf("Failed set coordinator: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed set coordinator: %w", err)) } return tx, nil }

@@ -473,9 +474,9 @@ func (c *AuctionClient) AuctionGetCurrentSlotNumber() (currentSlotNumber int64, err error) {

var _currentSlotNumber *big.Int if err := c.client.Call(func(ec *ethclient.Client) error { _currentSlotNumber, err = c.auction.GetCurrentSlotNumber(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return _currentSlotNumber.Int64(), nil }

@@ -485,9 +486,9 @@ func (c *AuctionClient) AuctionGetMinBidBySlot(slot int64) (minBid *big.Int, err error) {

if err := c.client.Call(func(ec *ethclient.Client) error { slotToSend := big.NewInt(slot) minBid, err = c.auction.GetMinBidBySlot(nil, slotToSend) - return err + return tracerr.Wrap(err) }); err != nil { - return big.NewInt(0), err + return big.NewInt(0), tracerr.Wrap(err) } return minBid, nil }

@@ -497,9 +498,9 @@ func (c *AuctionClient) AuctionGetSlotSet(slot int64) (slotSet *big.Int, err error) {

if err := c.client.Call(func(ec *ethclient.Client) error { slotToSend := big.NewInt(slot) slotSet, err = c.auction.GetSlotSet(nil, slotToSend) - return err + return tracerr.Wrap(err) }); err != nil { - return big.NewInt(0), err + return big.NewInt(0), tracerr.Wrap(err) } return slotSet, nil }

@@ -508,9 +509,9 @@ // AuctionGetDefaultSlotSetBid is the interface to call the smart contract function

func (c *AuctionClient) AuctionGetDefaultSlotSetBid(slotSet uint8) (minBidSlotSet *big.Int, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { minBidSlotSet, err = c.auction.GetDefaultSlotSetBid(nil, slotSet) - return err + return tracerr.Wrap(err) }); err != nil { - return big.NewInt(0), err + return big.NewInt(0), tracerr.Wrap(err) } return minBidSlotSet, nil }

@@ -520,9 +521,9 @@ func (c *AuctionClient) AuctionGetSlotNumber(blockNum int64) (slot int64, err error) {

var _slot *big.Int if err := c.client.Call(func(ec *ethclient.Client) error { _slot, err = c.auction.GetSlotNumber(nil, big.NewInt(blockNum)) - return err + return tracerr.Wrap(err) }); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return _slot.Int64(), nil }

@@ -536,7 +537,7 @@ owner := c.client.account.Address

spender := c.address nonce, err := c.tokenHEZ.Nonces(nil, owner) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tokenName := c.tokenHEZCfg.Name tokenAddr := c.tokenHEZCfg.Address

@@ -548,7 +549,7 @@ _slot := big.NewInt(slot)

return c.auction.ProcessBid(auth, amount, _slot, bidAmount, permit) }, ); err != nil { - return nil, fmt.Errorf("Failed bid: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed bid: %w", err)) } return tx, nil }

@@ -563,7 +564,7 @@ owner := c.client.account.Address

spender := c.address nonce, err := c.tokenHEZ.Nonces(nil, owner) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tokenName := c.tokenHEZCfg.Name tokenAddr := c.tokenHEZCfg.Address

@@ -577,7 +578,7 @@ _endingSlot := big.NewInt(endingSlot)

return c.auction.ProcessMultiBid(auth, amount, _startingSlot, _endingSlot, slotSets, maxBid, minBid, permit) }, ); err != nil { - return nil, fmt.Errorf("Failed multibid: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed multibid: %w", err)) } return tx, nil }

@@ -586,9 +587,9 @@ // AuctionCanForge is the interface to call the smart contract function

func (c *AuctionClient) AuctionCanForge(forger ethCommon.Address, blockNum int64) (canForge bool, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { canForge, err = c.auction.CanForge(nil, forger, big.NewInt(blockNum)) - return err + return tracerr.Wrap(err) }); err != nil { - return false, err + return false, tracerr.Wrap(err) } return canForge, nil }

@@ -601,7 +602,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.ClaimHEZ(auth) }, ); err != nil { - return nil, fmt.Errorf("Failed claim HEZ: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed claim HEZ: %w", err)) } return tx, nil }

@@ -614,7 +615,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.auction.Forge(auth, forger) }, ); err != nil { - return nil, fmt.Errorf("Failed forge: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed forge: %w", err)) } return tx, nil }

@@ -625,25 +626,25 @@ auctionConstants = new(common.AuctionConstants)

if err := c.client.Call(func(ec *ethclient.Client) error { auctionConstants.BlocksPerSlot, err = c.auction.BLOCKSPERSLOT(nil) if err != nil { - return err + return tracerr.Wrap(err) } genesisBlock, err := c.auction.GenesisBlock(nil) if err != nil { - return err + return tracerr.Wrap(err) } auctionConstants.GenesisBlockNum = genesisBlock.Int64() auctionConstants.HermezRollup, err = c.auction.HermezRollup(nil) if err != nil { - return err + return tracerr.Wrap(err) } auctionConstants.InitialMinimalBidding, err = c.auction.INITIALMINIMALBIDDING(nil) if err != nil { - return err + return tracerr.Wrap(err) } auctionConstants.TokenHEZ, err = c.auction.TokenHEZ(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return auctionConstants, nil }

@@ -654,43 +655,43 @@ auctionVariables = new(common.AuctionVariables)

if err := c.client.Call(func(ec *ethclient.Client) error { auctionVariables.AllocationRatio, err = c.AuctionGetAllocationRatio() if err != nil { - return err + return tracerr.Wrap(err) } bootCoordinator, err := c.AuctionGetBootCoordinator() if err != nil { - return err + return tracerr.Wrap(err) } auctionVariables.BootCoordinator = *bootCoordinator auctionVariables.ClosedAuctionSlots, err = c.AuctionGetClosedAuctionSlots() if err != nil { - return err + return tracerr.Wrap(err) } var defaultSlotSetBid [6]*big.Int for i := uint8(0); i < 6; i++ { bid, err := c.AuctionGetDefaultSlotSetBid(i) if err != nil { - return err + return tracerr.Wrap(err) } defaultSlotSetBid[i] = bid } auctionVariables.DefaultSlotSetBid = defaultSlotSetBid donationAddress, err := c.AuctionGetDonationAddress() if err != nil { - return err + return tracerr.Wrap(err) } auctionVariables.DonationAddress = *donationAddress auctionVariables.OpenAuctionSlots, err = c.AuctionGetOpenAuctionSlots() if err != nil { - return err + return tracerr.Wrap(err) } auctionVariables.Outbidding, err = c.AuctionGetOutbidding() if err != nil { - return err + return tracerr.Wrap(err) } auctionVariables.SlotDeadline, err = c.AuctionGetSlotDeadline() - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return auctionVariables, nil }

@@ -729,7 +730,7 @@ }

logs, err := c.client.client.FilterLogs(context.TODO(), query) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } if len(logs) > 0 { blockHash = &logs[0].BlockHash

@@ -737,7 +738,7 @@ }

for _, vLog := range logs { if vLog.BlockHash != *blockHash { log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String()) - return nil, nil, ErrBlockHashMismatchEvent + return nil, nil, tracerr.Wrap(ErrBlockHashMismatchEvent) } switch vLog.Topics[0] { case logAuctionNewBid:

@@ -748,7 +749,7 @@ Address ethCommon.Address

} var newBid AuctionEventNewBid if err := c.contractAbi.Unpack(&auxNewBid, "NewBid", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } newBid.BidAmount = auxNewBid.BidAmount newBid.Slot = new(big.Int).SetBytes(vLog.Topics[1][:]).Int64()

@@ -757,19 +758,19 @@ auctionEvents.NewBid = append(auctionEvents.NewBid, newBid)

case logAuctionNewSlotDeadline: var newSlotDeadline AuctionEventNewSlotDeadline if err := c.contractAbi.Unpack(&newSlotDeadline, "NewSlotDeadline", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } auctionEvents.NewSlotDeadline = append(auctionEvents.NewSlotDeadline, newSlotDeadline) case logAuctionNewClosedAuctionSlots: var newClosedAuctionSlots AuctionEventNewClosedAuctionSlots if err := c.contractAbi.Unpack(&newClosedAuctionSlots, "NewClosedAuctionSlots", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } auctionEvents.NewClosedAuctionSlots = append(auctionEvents.NewClosedAuctionSlots, newClosedAuctionSlots) case logAuctionNewOutbidding: var newOutbidding AuctionEventNewOutbidding if err := c.contractAbi.Unpack(&newOutbidding, "NewOutbidding", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } auctionEvents.NewOutbidding = append(auctionEvents.NewOutbidding, newOutbidding) case logAuctionNewDonationAddress:

@@ -783,19 +784,19 @@ auctionEvents.NewBootCoordinator = append(auctionEvents.NewBootCoordinator, newBootCoordinator)

case logAuctionNewOpenAuctionSlots: var newOpenAuctionSlots AuctionEventNewOpenAuctionSlots if err := c.contractAbi.Unpack(&newOpenAuctionSlots, "NewOpenAuctionSlots", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } auctionEvents.NewOpenAuctionSlots = append(auctionEvents.NewOpenAuctionSlots, newOpenAuctionSlots) case logAuctionNewAllocationRatio: var newAllocationRatio AuctionEventNewAllocationRatio if err := c.contractAbi.Unpack(&newAllocationRatio, "NewAllocationRatio", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } auctionEvents.NewAllocationRatio = append(auctionEvents.NewAllocationRatio, newAllocationRatio) case logAuctionSetCoordinator: var setCoordinator AuctionEventSetCoordinator if err := c.contractAbi.Unpack(&setCoordinator, "SetCoordinator", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } setCoordinator.BidderAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes()) setCoordinator.ForgerAddress = ethCommon.BytesToAddress(vLog.Topics[2].Bytes())

@@ -803,7 +804,7 @@ auctionEvents.SetCoordinator = append(auctionEvents.SetCoordinator, setCoordinator)

case logAuctionNewForgeAllocated: var newForgeAllocated AuctionEventNewForgeAllocated if err := c.contractAbi.Unpack(&newForgeAllocated, "NewForgeAllocated", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } newForgeAllocated.Bidder = ethCommon.BytesToAddress(vLog.Topics[1].Bytes()) newForgeAllocated.Forger = ethCommon.BytesToAddress(vLog.Topics[2].Bytes())

@@ -816,7 +817,7 @@ NewInitialMinBid *big.Int

} var newDefaultSlotSetBid AuctionEventNewDefaultSlotSetBid if err := c.contractAbi.Unpack(&auxNewDefaultSlotSetBid, "NewDefaultSlotSetBid", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } newDefaultSlotSetBid.NewInitialMinBid = auxNewDefaultSlotSetBid.NewInitialMinBid newDefaultSlotSetBid.SlotSet = auxNewDefaultSlotSetBid.SlotSet.Int64()

@@ -829,7 +830,7 @@ auctionEvents.NewForge = append(auctionEvents.NewForge, newForge)

case logAuctionHEZClaimed: var HEZClaimed AuctionEventHEZClaimed if err := c.contractAbi.Unpack(&HEZClaimed, "HEZClaimed", vLog.Data); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } HEZClaimed.Owner = ethCommon.BytesToAddress(vLog.Topics[1].Bytes()) auctionEvents.HEZClaimed = append(auctionEvents.HEZClaimed, HEZClaimed)
M eth/client.go → eth/client.go

@@ -7,6 +7,7 @@ "github.com/ethereum/go-ethereum/accounts"

ethKeystore "github.com/ethereum/go-ethereum/accounts/keystore" ethCommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" + "github.com/hermeznetwork/tracerr" ) var errTODO = fmt.Errorf("TODO: Not implemented yet")

@@ -67,15 +68,15 @@ func NewClient(client *ethclient.Client, account *accounts.Account, ks *ethKeystore.KeyStore, cfg *ClientConfig) (*Client, error) {

ethereumClient := NewEthereumClient(client, account, ks, &cfg.Ethereum) auctionClient, err := NewAuctionClient(ethereumClient, cfg.Auction.Address, cfg.Auction.TokenHEZ) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } rollupClient, err := NewRollupClient(ethereumClient, cfg.Rollup.Address, cfg.Auction.TokenHEZ) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } wDelayerClient, err := NewWDelayerClient(ethereumClient, cfg.WDelayer.Address) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &Client{ EthereumClient: *ethereumClient,
M eth/contracts/auction/HermezAuctionProtocol.go → eth/contracts/auction/HermezAuctionProtocol.go

@@ -13,6 +13,7 @@ "github.com/ethereum/go-ethereum/accounts/abi/bind"

"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/event" + "github.com/hermeznetwork/tracerr" ) // Reference imports to suppress errors if they are not otherwise used.

@@ -36,12 +37,12 @@ // DeployHermezAuctionProtocol deploys a new Ethereum contract, binding an instance of HermezAuctionProtocol to it.

func DeployHermezAuctionProtocol(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *HermezAuctionProtocol, error) { parsed, err := abi.JSON(strings.NewReader(HermezAuctionProtocolABI)) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(HermezAuctionProtocolBin), backend) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } return address, tx, &HermezAuctionProtocol{HermezAuctionProtocolCaller: HermezAuctionProtocolCaller{contract: contract}, HermezAuctionProtocolTransactor: HermezAuctionProtocolTransactor{contract: contract}, HermezAuctionProtocolFilterer: HermezAuctionProtocolFilterer{contract: contract}}, nil }

@@ -109,7 +110,7 @@ // NewHermezAuctionProtocol creates a new instance of HermezAuctionProtocol, bound to a specific deployed contract.

func NewHermezAuctionProtocol(address common.Address, backend bind.ContractBackend) (*HermezAuctionProtocol, error) { contract, err := bindHermezAuctionProtocol(address, backend, backend, backend) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocol{HermezAuctionProtocolCaller: HermezAuctionProtocolCaller{contract: contract}, HermezAuctionProtocolTransactor: HermezAuctionProtocolTransactor{contract: contract}, HermezAuctionProtocolFilterer: HermezAuctionProtocolFilterer{contract: contract}}, nil }

@@ -118,7 +119,7 @@ // NewHermezAuctionProtocolCaller creates a new read-only instance of HermezAuctionProtocol, bound to a specific deployed contract.

func NewHermezAuctionProtocolCaller(address common.Address, caller bind.ContractCaller) (*HermezAuctionProtocolCaller, error) { contract, err := bindHermezAuctionProtocol(address, caller, nil, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolCaller{contract: contract}, nil }

@@ -127,7 +128,7 @@ // NewHermezAuctionProtocolTransactor creates a new write-only instance of HermezAuctionProtocol, bound to a specific deployed contract.

func NewHermezAuctionProtocolTransactor(address common.Address, transactor bind.ContractTransactor) (*HermezAuctionProtocolTransactor, error) { contract, err := bindHermezAuctionProtocol(address, nil, transactor, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolTransactor{contract: contract}, nil }

@@ -136,7 +137,7 @@ // NewHermezAuctionProtocolFilterer creates a new log filterer instance of HermezAuctionProtocol, bound to a specific deployed contract.

func NewHermezAuctionProtocolFilterer(address common.Address, filterer bind.ContractFilterer) (*HermezAuctionProtocolFilterer, error) { contract, err := bindHermezAuctionProtocol(address, nil, nil, filterer) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolFilterer{contract: contract}, nil }

@@ -145,7 +146,7 @@ // bindHermezAuctionProtocol binds a generic wrapper to an already deployed contract.

func bindHermezAuctionProtocol(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader(HermezAuctionProtocolABI)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil }

@@ -197,7 +198,7 @@ ret0 = new(uint8)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "BLOCKS_PER_SLOT") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // BLOCKSPERSLOT is a free data retrieval call binding the contract method 0x2243de47.

@@ -223,7 +224,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "INITIAL_MINIMAL_BIDDING") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // INITIALMINIMALBIDDING is a free data retrieval call binding the contract method 0xe6065914.

@@ -249,7 +250,7 @@ ret0 = new(bool)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "canForge", forger, blockNumber) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // CanForge is a free data retrieval call binding the contract method 0x83b1f6a0.

@@ -279,7 +280,7 @@ CoordinatorURL string

}) out := ret err := _HermezAuctionProtocol.contract.Call(opts, out, "coordinators", arg0) - return *ret, err + return *ret, tracerr.Wrap(err) } // Coordinators is a free data retrieval call binding the contract method 0xa48af096.

@@ -311,7 +312,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "genesisBlock") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GenesisBlock is a free data retrieval call binding the contract method 0x4cdc9c63.

@@ -337,7 +338,7 @@ ret0 = new([3]uint16)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getAllocationRatio") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetAllocationRatio is a free data retrieval call binding the contract method 0xec29159b.

@@ -363,7 +364,7 @@ ret0 = new(common.Address)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getBootCoordinator") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetBootCoordinator is a free data retrieval call binding the contract method 0xb5f7f2f0.

@@ -389,7 +390,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getClaimableHEZ", bidder) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetClaimableHEZ is a free data retrieval call binding the contract method 0x5cca4903.

@@ -415,7 +416,7 @@ ret0 = new(uint16)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getClosedAuctionSlots") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetClosedAuctionSlots is a free data retrieval call binding the contract method 0x4da9639d.

@@ -441,7 +442,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getCurrentSlotNumber") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetCurrentSlotNumber is a free data retrieval call binding the contract method 0x0c4da4f6.

@@ -467,7 +468,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getDefaultSlotSetBid", slotSet) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetDefaultSlotSetBid is a free data retrieval call binding the contract method 0x564e6a71.

@@ -493,7 +494,7 @@ ret0 = new(common.Address)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getDonationAddress") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetDonationAddress is a free data retrieval call binding the contract method 0x54c03ab7.

@@ -519,7 +520,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getMinBidBySlot", slot) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetMinBidBySlot is a free data retrieval call binding the contract method 0x37d1bd0b.

@@ -545,7 +546,7 @@ ret0 = new(uint16)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getOpenAuctionSlots") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetOpenAuctionSlots is a free data retrieval call binding the contract method 0xac4b9012.

@@ -571,7 +572,7 @@ ret0 = new(uint16)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getOutbidding") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetOutbidding is a free data retrieval call binding the contract method 0x55b442e6.

@@ -597,7 +598,7 @@ ret0 = new(uint8)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getSlotDeadline") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetSlotDeadline is a free data retrieval call binding the contract method 0x13de9af2.

@@ -623,7 +624,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getSlotNumber", blockNumber) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetSlotNumber is a free data retrieval call binding the contract method 0xb3dc7bb1.

@@ -649,7 +650,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "getSlotSet", slot) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetSlotSet is a free data retrieval call binding the contract method 0xac5f658b.

@@ -675,7 +676,7 @@ ret0 = new(common.Address)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "hermezRollup") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // HermezRollup is a free data retrieval call binding the contract method 0xaebd6d98.

@@ -701,7 +702,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "pendingBalances", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // PendingBalances is a free data retrieval call binding the contract method 0xecdae41b.

@@ -735,7 +736,7 @@ ClosedMinBid *big.Int

}) out := ret err := _HermezAuctionProtocol.contract.Call(opts, out, "slots", arg0) - return *ret, err + return *ret, tracerr.Wrap(err) } // Slots is a free data retrieval call binding the contract method 0xbc415567.

@@ -771,7 +772,7 @@ ret0 = new(common.Address)

) out := ret0 err := _HermezAuctionProtocol.contract.Call(opts, out, "tokenHEZ") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // TokenHEZ is a free data retrieval call binding the contract method 0x79a135e3.

@@ -1168,7 +1169,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "HEZClaimed", ownerRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolHEZClaimedIterator{contract: _HermezAuctionProtocol.contract, event: "HEZClaimed", logs: logs, sub: sub}, nil }

@@ -1185,7 +1186,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "HEZClaimed", ownerRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1195,19 +1196,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolHEZClaimed) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "HEZClaimed", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1221,7 +1222,7 @@ // Solidity: event HEZClaimed(address indexed owner, uint128 amount)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseHEZClaimed(log types.Log) (*HermezAuctionProtocolHEZClaimed, error) { event := new(HermezAuctionProtocolHEZClaimed) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "HEZClaimed", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1306,7 +1307,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) FilterNewAllocationRatio(opts *bind.FilterOpts) (*HermezAuctionProtocolNewAllocationRatioIterator, error) {

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewAllocationRatio") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewAllocationRatioIterator{contract: _HermezAuctionProtocol.contract, event: "NewAllocationRatio", logs: logs, sub: sub}, nil }

@@ -1318,7 +1319,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) WatchNewAllocationRatio(opts *bind.WatchOpts, sink chan<- *HermezAuctionProtocolNewAllocationRatio) (event.Subscription, error) {

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewAllocationRatio") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1328,19 +1329,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewAllocationRatio) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewAllocationRatio", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1354,7 +1355,7 @@ // Solidity: event NewAllocationRatio(uint16[3] newAllocationRatio)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewAllocationRatio(log types.Log) (*HermezAuctionProtocolNewAllocationRatio, error) { event := new(HermezAuctionProtocolNewAllocationRatio) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewAllocationRatio", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1451,7 +1452,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewBid", slotRule, bidderRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewBidIterator{contract: _HermezAuctionProtocol.contract, event: "NewBid", logs: logs, sub: sub}, nil }

@@ -1473,7 +1474,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewBid", slotRule, bidderRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1483,19 +1484,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewBid) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewBid", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1509,7 +1510,7 @@ // Solidity: event NewBid(uint128 indexed slot, uint128 bidAmount, address indexed bidder)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewBid(log types.Log) (*HermezAuctionProtocolNewBid, error) { event := new(HermezAuctionProtocolNewBid) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewBid", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1599,7 +1600,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewBootCoordinator", newBootCoordinatorRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewBootCoordinatorIterator{contract: _HermezAuctionProtocol.contract, event: "NewBootCoordinator", logs: logs, sub: sub}, nil }

@@ -1616,7 +1617,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewBootCoordinator", newBootCoordinatorRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1626,19 +1627,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewBootCoordinator) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewBootCoordinator", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1652,7 +1653,7 @@ // Solidity: event NewBootCoordinator(address indexed newBootCoordinator)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewBootCoordinator(log types.Log) (*HermezAuctionProtocolNewBootCoordinator, error) { event := new(HermezAuctionProtocolNewBootCoordinator) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewBootCoordinator", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1737,7 +1738,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) FilterNewClosedAuctionSlots(opts *bind.FilterOpts) (*HermezAuctionProtocolNewClosedAuctionSlotsIterator, error) {

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewClosedAuctionSlots") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewClosedAuctionSlotsIterator{contract: _HermezAuctionProtocol.contract, event: "NewClosedAuctionSlots", logs: logs, sub: sub}, nil }

@@ -1749,7 +1750,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) WatchNewClosedAuctionSlots(opts *bind.WatchOpts, sink chan<- *HermezAuctionProtocolNewClosedAuctionSlots) (event.Subscription, error) {

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewClosedAuctionSlots") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1759,19 +1760,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewClosedAuctionSlots) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewClosedAuctionSlots", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1785,7 +1786,7 @@ // Solidity: event NewClosedAuctionSlots(uint16 newClosedAuctionSlots)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewClosedAuctionSlots(log types.Log) (*HermezAuctionProtocolNewClosedAuctionSlots, error) { event := new(HermezAuctionProtocolNewClosedAuctionSlots) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewClosedAuctionSlots", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1871,7 +1872,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) FilterNewDefaultSlotSetBid(opts *bind.FilterOpts) (*HermezAuctionProtocolNewDefaultSlotSetBidIterator, error) {

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewDefaultSlotSetBid") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewDefaultSlotSetBidIterator{contract: _HermezAuctionProtocol.contract, event: "NewDefaultSlotSetBid", logs: logs, sub: sub}, nil }

@@ -1883,7 +1884,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) WatchNewDefaultSlotSetBid(opts *bind.WatchOpts, sink chan<- *HermezAuctionProtocolNewDefaultSlotSetBid) (event.Subscription, error) {

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewDefaultSlotSetBid") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1893,19 +1894,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewDefaultSlotSetBid) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewDefaultSlotSetBid", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1919,7 +1920,7 @@ // Solidity: event NewDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewDefaultSlotSetBid(log types.Log) (*HermezAuctionProtocolNewDefaultSlotSetBid, error) { event := new(HermezAuctionProtocolNewDefaultSlotSetBid) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewDefaultSlotSetBid", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2009,7 +2010,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewDonationAddress", newDonationAddressRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewDonationAddressIterator{contract: _HermezAuctionProtocol.contract, event: "NewDonationAddress", logs: logs, sub: sub}, nil }

@@ -2026,7 +2027,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewDonationAddress", newDonationAddressRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2036,19 +2037,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewDonationAddress) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewDonationAddress", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2062,7 +2063,7 @@ // Solidity: event NewDonationAddress(address indexed newDonationAddress)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewDonationAddress(log types.Log) (*HermezAuctionProtocolNewDonationAddress, error) { event := new(HermezAuctionProtocolNewDonationAddress) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewDonationAddress", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2157,7 +2158,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewForge", forgerRule, slotToForgeRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewForgeIterator{contract: _HermezAuctionProtocol.contract, event: "NewForge", logs: logs, sub: sub}, nil }

@@ -2178,7 +2179,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewForge", forgerRule, slotToForgeRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2188,19 +2189,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewForge) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewForge", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2214,7 +2215,7 @@ // Solidity: event NewForge(address indexed forger, uint128 indexed slotToForge)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewForge(log types.Log) (*HermezAuctionProtocolNewForge, error) { event := new(HermezAuctionProtocolNewForge) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewForge", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2317,7 +2318,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewForgeAllocated", bidderRule, forgerRule, slotToForgeRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewForgeAllocatedIterator{contract: _HermezAuctionProtocol.contract, event: "NewForgeAllocated", logs: logs, sub: sub}, nil }

@@ -2342,7 +2343,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewForgeAllocated", bidderRule, forgerRule, slotToForgeRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2352,19 +2353,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewForgeAllocated) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewForgeAllocated", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2378,7 +2379,7 @@ // Solidity: event NewForgeAllocated(address indexed bidder, address indexed forger, uint128 indexed slotToForge, uint128 burnAmount, uint128 donationAmount, uint128 governanceAmount)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewForgeAllocated(log types.Log) (*HermezAuctionProtocolNewForgeAllocated, error) { event := new(HermezAuctionProtocolNewForgeAllocated) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewForgeAllocated", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2463,7 +2464,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) FilterNewOpenAuctionSlots(opts *bind.FilterOpts) (*HermezAuctionProtocolNewOpenAuctionSlotsIterator, error) {

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewOpenAuctionSlots") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewOpenAuctionSlotsIterator{contract: _HermezAuctionProtocol.contract, event: "NewOpenAuctionSlots", logs: logs, sub: sub}, nil }

@@ -2475,7 +2476,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) WatchNewOpenAuctionSlots(opts *bind.WatchOpts, sink chan<- *HermezAuctionProtocolNewOpenAuctionSlots) (event.Subscription, error) {

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewOpenAuctionSlots") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2485,19 +2486,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewOpenAuctionSlots) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewOpenAuctionSlots", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2511,7 +2512,7 @@ // Solidity: event NewOpenAuctionSlots(uint16 newOpenAuctionSlots)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewOpenAuctionSlots(log types.Log) (*HermezAuctionProtocolNewOpenAuctionSlots, error) { event := new(HermezAuctionProtocolNewOpenAuctionSlots) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewOpenAuctionSlots", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2596,7 +2597,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) FilterNewOutbidding(opts *bind.FilterOpts) (*HermezAuctionProtocolNewOutbiddingIterator, error) {

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewOutbidding") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewOutbiddingIterator{contract: _HermezAuctionProtocol.contract, event: "NewOutbidding", logs: logs, sub: sub}, nil }

@@ -2608,7 +2609,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) WatchNewOutbidding(opts *bind.WatchOpts, sink chan<- *HermezAuctionProtocolNewOutbidding) (event.Subscription, error) {

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewOutbidding") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2618,19 +2619,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewOutbidding) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewOutbidding", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2644,7 +2645,7 @@ // Solidity: event NewOutbidding(uint16 newOutbidding)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewOutbidding(log types.Log) (*HermezAuctionProtocolNewOutbidding, error) { event := new(HermezAuctionProtocolNewOutbidding) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewOutbidding", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2729,7 +2730,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) FilterNewSlotDeadline(opts *bind.FilterOpts) (*HermezAuctionProtocolNewSlotDeadlineIterator, error) {

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "NewSlotDeadline") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolNewSlotDeadlineIterator{contract: _HermezAuctionProtocol.contract, event: "NewSlotDeadline", logs: logs, sub: sub}, nil }

@@ -2741,7 +2742,7 @@ func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) WatchNewSlotDeadline(opts *bind.WatchOpts, sink chan<- *HermezAuctionProtocolNewSlotDeadline) (event.Subscription, error) {

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "NewSlotDeadline") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2751,19 +2752,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolNewSlotDeadline) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewSlotDeadline", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2777,7 +2778,7 @@ // Solidity: event NewSlotDeadline(uint8 newSlotDeadline)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseNewSlotDeadline(log types.Log) (*HermezAuctionProtocolNewSlotDeadline, error) { event := new(HermezAuctionProtocolNewSlotDeadline) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "NewSlotDeadline", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2873,7 +2874,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.FilterLogs(opts, "SetCoordinator", bidderRule, forgerRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAuctionProtocolSetCoordinatorIterator{contract: _HermezAuctionProtocol.contract, event: "SetCoordinator", logs: logs, sub: sub}, nil }

@@ -2894,7 +2895,7 @@ }

logs, sub, err := _HermezAuctionProtocol.contract.WatchLogs(opts, "SetCoordinator", bidderRule, forgerRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2904,19 +2905,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAuctionProtocolSetCoordinator) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "SetCoordinator", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2930,7 +2931,7 @@ // Solidity: event SetCoordinator(address indexed bidder, address indexed forger, string coordinatorURL)

func (_HermezAuctionProtocol *HermezAuctionProtocolFilterer) ParseSetCoordinator(log types.Log) (*HermezAuctionProtocolSetCoordinator, error) { event := new(HermezAuctionProtocolSetCoordinator) if err := _HermezAuctionProtocol.contract.UnpackLog(event, "SetCoordinator", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }
M eth/contracts/hermez/Hermez.go → eth/contracts/hermez/Hermez.go

@@ -13,6 +13,7 @@ "github.com/ethereum/go-ethereum/accounts/abi/bind"

"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/event" + "github.com/hermeznetwork/tracerr" ) // Reference imports to suppress errors if they are not otherwise used.

@@ -36,12 +37,12 @@ // DeployHermez deploys a new Ethereum contract, binding an instance of Hermez to it.

func DeployHermez(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *Hermez, error) { parsed, err := abi.JSON(strings.NewReader(HermezABI)) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(HermezBin), backend) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } return address, tx, &Hermez{HermezCaller: HermezCaller{contract: contract}, HermezTransactor: HermezTransactor{contract: contract}, HermezFilterer: HermezFilterer{contract: contract}}, nil }

@@ -109,7 +110,7 @@ // NewHermez creates a new instance of Hermez, bound to a specific deployed contract.

func NewHermez(address common.Address, backend bind.ContractBackend) (*Hermez, error) { contract, err := bindHermez(address, backend, backend, backend) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &Hermez{HermezCaller: HermezCaller{contract: contract}, HermezTransactor: HermezTransactor{contract: contract}, HermezFilterer: HermezFilterer{contract: contract}}, nil }

@@ -118,7 +119,7 @@ // NewHermezCaller creates a new read-only instance of Hermez, bound to a specific deployed contract.

func NewHermezCaller(address common.Address, caller bind.ContractCaller) (*HermezCaller, error) { contract, err := bindHermez(address, caller, nil, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezCaller{contract: contract}, nil }

@@ -127,7 +128,7 @@ // NewHermezTransactor creates a new write-only instance of Hermez, bound to a specific deployed contract.

func NewHermezTransactor(address common.Address, transactor bind.ContractTransactor) (*HermezTransactor, error) { contract, err := bindHermez(address, nil, transactor, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezTransactor{contract: contract}, nil }

@@ -136,7 +137,7 @@ // NewHermezFilterer creates a new log filterer instance of Hermez, bound to a specific deployed contract.

func NewHermezFilterer(address common.Address, filterer bind.ContractFilterer) (*HermezFilterer, error) { contract, err := bindHermez(address, nil, nil, filterer) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezFilterer{contract: contract}, nil }

@@ -145,7 +146,7 @@ // bindHermez binds a generic wrapper to an already deployed contract.

func bindHermez(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader(HermezABI)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil }

@@ -197,7 +198,7 @@ ret0 = new(uint8)

) out := ret0 err := _Hermez.contract.Call(opts, out, "ABSOLUTE_MAX_L1L2BATCHTIMEOUT") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // ABSOLUTEMAXL1L2BATCHTIMEOUT is a free data retrieval call binding the contract method 0x95a09f2a.

@@ -233,7 +234,7 @@ MaxWithdrawals *big.Int

}) out := ret err := _Hermez.contract.Call(opts, out, "buckets", arg0) - return *ret, err + return *ret, tracerr.Wrap(err) } // Buckets is a free data retrieval call binding the contract method 0x9b51fb0d.

@@ -271,7 +272,7 @@ ret0 = new(bool)

) out := ret0 err := _Hermez.contract.Call(opts, out, "exitNullifierMap", arg0, arg1) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // ExitNullifierMap is a free data retrieval call binding the contract method 0xe9b5269c.

@@ -297,7 +298,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _Hermez.contract.Call(opts, out, "exitRootsMap", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // ExitRootsMap is a free data retrieval call binding the contract method 0x506d5463.

@@ -323,7 +324,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _Hermez.contract.Call(opts, out, "feeAddToken") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // FeeAddToken is a free data retrieval call binding the contract method 0xbded9bb8.

@@ -349,7 +350,7 @@ ret0 = new(uint8)

) out := ret0 err := _Hermez.contract.Call(opts, out, "forgeL1L2BatchTimeout") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // ForgeL1L2BatchTimeout is a free data retrieval call binding the contract method 0xa3275838.

@@ -375,7 +376,7 @@ ret0 = new(common.Address)

) out := ret0 err := _Hermez.contract.Call(opts, out, "hermezAuctionContract") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // HermezAuctionContract is a free data retrieval call binding the contract method 0x2bd83626.

@@ -401,7 +402,7 @@ ret0 = new(common.Address)

) out := ret0 err := _Hermez.contract.Call(opts, out, "hermezGovernanceDAOAddress") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // HermezGovernanceDAOAddress is a free data retrieval call binding the contract method 0xdd46bf84.

@@ -427,7 +428,7 @@ ret0 = new(bool)

) out := ret0 err := _Hermez.contract.Call(opts, out, "instantWithdrawalViewer", tokenAddress, amount) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // InstantWithdrawalViewer is a free data retrieval call binding the contract method 0x375110aa.

@@ -453,7 +454,7 @@ ret0 = new(uint64)

) out := ret0 err := _Hermez.contract.Call(opts, out, "lastForgedBatch") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // LastForgedBatch is a free data retrieval call binding the contract method 0x44e0b2ce.

@@ -479,7 +480,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _Hermez.contract.Call(opts, out, "lastIdx") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // LastIdx is a free data retrieval call binding the contract method 0xd486645c.

@@ -505,7 +506,7 @@ ret0 = new(uint64)

) out := ret0 err := _Hermez.contract.Call(opts, out, "lastL1L2Batch") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // LastL1L2Batch is a free data retrieval call binding the contract method 0x84ef9ed4.

@@ -531,7 +532,7 @@ ret0 = new([]byte)

) out := ret0 err := _Hermez.contract.Call(opts, out, "mapL1TxQueue", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // MapL1TxQueue is a free data retrieval call binding the contract method 0xe796fcf3.

@@ -557,7 +558,7 @@ ret0 = new(uint64)

) out := ret0 err := _Hermez.contract.Call(opts, out, "nextL1FillingQueue") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // NextL1FillingQueue is a free data retrieval call binding the contract method 0x0ee8e52b.

@@ -583,7 +584,7 @@ ret0 = new(uint64)

) out := ret0 err := _Hermez.contract.Call(opts, out, "nextL1ToForgeQueue") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // NextL1ToForgeQueue is a free data retrieval call binding the contract method 0xd0f32e67.

@@ -609,7 +610,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _Hermez.contract.Call(opts, out, "registerTokensCount") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // RegisterTokensCount is a free data retrieval call binding the contract method 0x9f34e9a3.

@@ -641,7 +642,7 @@ NLevels *big.Int

}) out := ret err := _Hermez.contract.Call(opts, out, "rollupVerifiers", arg0) - return *ret, err + return *ret, tracerr.Wrap(err) } // RollupVerifiers is a free data retrieval call binding the contract method 0x38330200.

@@ -675,7 +676,7 @@ ret0 = new(common.Address)

) out := ret0 err := _Hermez.contract.Call(opts, out, "safetyAddress") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // SafetyAddress is a free data retrieval call binding the contract method 0xe56e27ae.

@@ -701,7 +702,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _Hermez.contract.Call(opts, out, "stateRootMap", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // StateRootMap is a free data retrieval call binding the contract method 0x86c6acc1.

@@ -727,7 +728,7 @@ ret0 = new(uint64)

) out := ret0 err := _Hermez.contract.Call(opts, out, "tokenExchange", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // TokenExchange is a free data retrieval call binding the contract method 0x0dd94b96.

@@ -753,7 +754,7 @@ ret0 = new(common.Address)

) out := ret0 err := _Hermez.contract.Call(opts, out, "tokenHEZ") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // TokenHEZ is a free data retrieval call binding the contract method 0x79a135e3.

@@ -779,7 +780,7 @@ ret0 = new(common.Address)

) out := ret0 err := _Hermez.contract.Call(opts, out, "tokenList", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // TokenList is a free data retrieval call binding the contract method 0x9ead7222.

@@ -805,7 +806,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _Hermez.contract.Call(opts, out, "tokenMap", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // TokenMap is a free data retrieval call binding the contract method 0x004aca6e.

@@ -831,7 +832,7 @@ ret0 = new(common.Address)

) out := ret0 err := _Hermez.contract.Call(opts, out, "withdrawDelayerContract") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // WithdrawDelayerContract is a free data retrieval call binding the contract method 0x1b0a8223.

@@ -857,7 +858,7 @@ ret0 = new(common.Address)

) out := ret0 err := _Hermez.contract.Call(opts, out, "withdrawVerifier") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // WithdrawVerifier is a free data retrieval call binding the contract method 0x864eb164.

@@ -883,7 +884,7 @@ ret0 = new(uint64)

) out := ret0 err := _Hermez.contract.Call(opts, out, "withdrawalDelay") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // WithdrawalDelay is a free data retrieval call binding the contract method 0xa7ab6961.

@@ -1238,7 +1239,7 @@ }

logs, sub, err := _Hermez.contract.FilterLogs(opts, "AddToken", tokenAddressRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezAddTokenIterator{contract: _Hermez.contract, event: "AddToken", logs: logs, sub: sub}, nil }

@@ -1255,7 +1256,7 @@ }

logs, sub, err := _Hermez.contract.WatchLogs(opts, "AddToken", tokenAddressRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1265,19 +1266,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezAddToken) if err := _Hermez.contract.UnpackLog(event, "AddToken", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1291,7 +1292,7 @@ // Solidity: event AddToken(address indexed tokenAddress, uint32 tokenID)

func (_Hermez *HermezFilterer) ParseAddToken(log types.Log) (*HermezAddToken, error) { event := new(HermezAddToken) if err := _Hermez.contract.UnpackLog(event, "AddToken", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1381,7 +1382,7 @@ }

logs, sub, err := _Hermez.contract.FilterLogs(opts, "ForgeBatch", batchNumRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezForgeBatchIterator{contract: _Hermez.contract, event: "ForgeBatch", logs: logs, sub: sub}, nil }

@@ -1398,7 +1399,7 @@ }

logs, sub, err := _Hermez.contract.WatchLogs(opts, "ForgeBatch", batchNumRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1408,19 +1409,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezForgeBatch) if err := _Hermez.contract.UnpackLog(event, "ForgeBatch", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1434,7 +1435,7 @@ // Solidity: event ForgeBatch(uint64 indexed batchNum)

func (_Hermez *HermezFilterer) ParseForgeBatch(log types.Log) (*HermezForgeBatch, error) { event := new(HermezForgeBatch) if err := _Hermez.contract.UnpackLog(event, "ForgeBatch", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1530,7 +1531,7 @@ }

logs, sub, err := _Hermez.contract.FilterLogs(opts, "L1UserTxEvent", queueIndexRule, positionRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezL1UserTxEventIterator{contract: _Hermez.contract, event: "L1UserTxEvent", logs: logs, sub: sub}, nil }

@@ -1551,7 +1552,7 @@ }

logs, sub, err := _Hermez.contract.WatchLogs(opts, "L1UserTxEvent", queueIndexRule, positionRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1561,19 +1562,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezL1UserTxEvent) if err := _Hermez.contract.UnpackLog(event, "L1UserTxEvent", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1587,7 +1588,7 @@ // Solidity: event L1UserTxEvent(uint64 indexed queueIndex, uint8 indexed position, bytes l1UserTx)

func (_Hermez *HermezFilterer) ParseL1UserTxEvent(log types.Log) (*HermezL1UserTxEvent, error) { event := new(HermezL1UserTxEvent) if err := _Hermez.contract.UnpackLog(event, "L1UserTxEvent", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1671,7 +1672,7 @@ func (_Hermez *HermezFilterer) FilterSafeMode(opts *bind.FilterOpts) (*HermezSafeModeIterator, error) {

logs, sub, err := _Hermez.contract.FilterLogs(opts, "SafeMode") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezSafeModeIterator{contract: _Hermez.contract, event: "SafeMode", logs: logs, sub: sub}, nil }

@@ -1683,7 +1684,7 @@ func (_Hermez *HermezFilterer) WatchSafeMode(opts *bind.WatchOpts, sink chan<- *HermezSafeMode) (event.Subscription, error) {

logs, sub, err := _Hermez.contract.WatchLogs(opts, "SafeMode") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1693,19 +1694,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezSafeMode) if err := _Hermez.contract.UnpackLog(event, "SafeMode", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1719,7 +1720,7 @@ // Solidity: event SafeMode()

func (_Hermez *HermezFilterer) ParseSafeMode(log types.Log) (*HermezSafeMode, error) { event := new(HermezSafeMode) if err := _Hermez.contract.UnpackLog(event, "SafeMode", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1815,7 +1816,7 @@ }

logs, sub, err := _Hermez.contract.FilterLogs(opts, "UpdateBucketWithdraw", numBucketRule, blockStampRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezUpdateBucketWithdrawIterator{contract: _Hermez.contract, event: "UpdateBucketWithdraw", logs: logs, sub: sub}, nil }

@@ -1836,7 +1837,7 @@ }

logs, sub, err := _Hermez.contract.WatchLogs(opts, "UpdateBucketWithdraw", numBucketRule, blockStampRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1846,19 +1847,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezUpdateBucketWithdraw) if err := _Hermez.contract.UnpackLog(event, "UpdateBucketWithdraw", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1872,7 +1873,7 @@ // Solidity: event UpdateBucketWithdraw(uint8 indexed numBucket, uint256 indexed blockStamp, uint256 withdrawals)

func (_Hermez *HermezFilterer) ParseUpdateBucketWithdraw(log types.Log) (*HermezUpdateBucketWithdraw, error) { event := new(HermezUpdateBucketWithdraw) if err := _Hermez.contract.UnpackLog(event, "UpdateBucketWithdraw", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1957,7 +1958,7 @@ func (_Hermez *HermezFilterer) FilterUpdateBucketsParameters(opts *bind.FilterOpts) (*HermezUpdateBucketsParametersIterator, error) {

logs, sub, err := _Hermez.contract.FilterLogs(opts, "UpdateBucketsParameters") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezUpdateBucketsParametersIterator{contract: _Hermez.contract, event: "UpdateBucketsParameters", logs: logs, sub: sub}, nil }

@@ -1969,7 +1970,7 @@ func (_Hermez *HermezFilterer) WatchUpdateBucketsParameters(opts *bind.WatchOpts, sink chan<- *HermezUpdateBucketsParameters) (event.Subscription, error) {

logs, sub, err := _Hermez.contract.WatchLogs(opts, "UpdateBucketsParameters") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1979,19 +1980,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezUpdateBucketsParameters) if err := _Hermez.contract.UnpackLog(event, "UpdateBucketsParameters", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2005,7 +2006,7 @@ // Solidity: event UpdateBucketsParameters(uint256[4][5] arrayBuckets)

func (_Hermez *HermezFilterer) ParseUpdateBucketsParameters(log types.Log) (*HermezUpdateBucketsParameters, error) { event := new(HermezUpdateBucketsParameters) if err := _Hermez.contract.UnpackLog(event, "UpdateBucketsParameters", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2090,7 +2091,7 @@ func (_Hermez *HermezFilterer) FilterUpdateFeeAddToken(opts *bind.FilterOpts) (*HermezUpdateFeeAddTokenIterator, error) {

logs, sub, err := _Hermez.contract.FilterLogs(opts, "UpdateFeeAddToken") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezUpdateFeeAddTokenIterator{contract: _Hermez.contract, event: "UpdateFeeAddToken", logs: logs, sub: sub}, nil }

@@ -2102,7 +2103,7 @@ func (_Hermez *HermezFilterer) WatchUpdateFeeAddToken(opts *bind.WatchOpts, sink chan<- *HermezUpdateFeeAddToken) (event.Subscription, error) {

logs, sub, err := _Hermez.contract.WatchLogs(opts, "UpdateFeeAddToken") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2112,19 +2113,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezUpdateFeeAddToken) if err := _Hermez.contract.UnpackLog(event, "UpdateFeeAddToken", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2138,7 +2139,7 @@ // Solidity: event UpdateFeeAddToken(uint256 newFeeAddToken)

func (_Hermez *HermezFilterer) ParseUpdateFeeAddToken(log types.Log) (*HermezUpdateFeeAddToken, error) { event := new(HermezUpdateFeeAddToken) if err := _Hermez.contract.UnpackLog(event, "UpdateFeeAddToken", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2223,7 +2224,7 @@ func (_Hermez *HermezFilterer) FilterUpdateForgeL1L2BatchTimeout(opts *bind.FilterOpts) (*HermezUpdateForgeL1L2BatchTimeoutIterator, error) {

logs, sub, err := _Hermez.contract.FilterLogs(opts, "UpdateForgeL1L2BatchTimeout") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezUpdateForgeL1L2BatchTimeoutIterator{contract: _Hermez.contract, event: "UpdateForgeL1L2BatchTimeout", logs: logs, sub: sub}, nil }

@@ -2235,7 +2236,7 @@ func (_Hermez *HermezFilterer) WatchUpdateForgeL1L2BatchTimeout(opts *bind.WatchOpts, sink chan<- *HermezUpdateForgeL1L2BatchTimeout) (event.Subscription, error) {

logs, sub, err := _Hermez.contract.WatchLogs(opts, "UpdateForgeL1L2BatchTimeout") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2245,19 +2246,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezUpdateForgeL1L2BatchTimeout) if err := _Hermez.contract.UnpackLog(event, "UpdateForgeL1L2BatchTimeout", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2271,7 +2272,7 @@ // Solidity: event UpdateForgeL1L2BatchTimeout(uint8 newForgeL1L2BatchTimeout)

func (_Hermez *HermezFilterer) ParseUpdateForgeL1L2BatchTimeout(log types.Log) (*HermezUpdateForgeL1L2BatchTimeout, error) { event := new(HermezUpdateForgeL1L2BatchTimeout) if err := _Hermez.contract.UnpackLog(event, "UpdateForgeL1L2BatchTimeout", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2357,7 +2358,7 @@ func (_Hermez *HermezFilterer) FilterUpdateTokenExchange(opts *bind.FilterOpts) (*HermezUpdateTokenExchangeIterator, error) {

logs, sub, err := _Hermez.contract.FilterLogs(opts, "UpdateTokenExchange") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezUpdateTokenExchangeIterator{contract: _Hermez.contract, event: "UpdateTokenExchange", logs: logs, sub: sub}, nil }

@@ -2369,7 +2370,7 @@ func (_Hermez *HermezFilterer) WatchUpdateTokenExchange(opts *bind.WatchOpts, sink chan<- *HermezUpdateTokenExchange) (event.Subscription, error) {

logs, sub, err := _Hermez.contract.WatchLogs(opts, "UpdateTokenExchange") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2379,19 +2380,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezUpdateTokenExchange) if err := _Hermez.contract.UnpackLog(event, "UpdateTokenExchange", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2405,7 +2406,7 @@ // Solidity: event UpdateTokenExchange(address[] addressArray, uint64[] valueArray)

func (_Hermez *HermezFilterer) ParseUpdateTokenExchange(log types.Log) (*HermezUpdateTokenExchange, error) { event := new(HermezUpdateTokenExchange) if err := _Hermez.contract.UnpackLog(event, "UpdateTokenExchange", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2490,7 +2491,7 @@ func (_Hermez *HermezFilterer) FilterUpdateWithdrawalDelay(opts *bind.FilterOpts) (*HermezUpdateWithdrawalDelayIterator, error) {

logs, sub, err := _Hermez.contract.FilterLogs(opts, "UpdateWithdrawalDelay") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezUpdateWithdrawalDelayIterator{contract: _Hermez.contract, event: "UpdateWithdrawalDelay", logs: logs, sub: sub}, nil }

@@ -2502,7 +2503,7 @@ func (_Hermez *HermezFilterer) WatchUpdateWithdrawalDelay(opts *bind.WatchOpts, sink chan<- *HermezUpdateWithdrawalDelay) (event.Subscription, error) {

logs, sub, err := _Hermez.contract.WatchLogs(opts, "UpdateWithdrawalDelay") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2512,19 +2513,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezUpdateWithdrawalDelay) if err := _Hermez.contract.UnpackLog(event, "UpdateWithdrawalDelay", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2538,7 +2539,7 @@ // Solidity: event UpdateWithdrawalDelay(uint64 newWithdrawalDelay)

func (_Hermez *HermezFilterer) ParseUpdateWithdrawalDelay(log types.Log) (*HermezUpdateWithdrawalDelay, error) { event := new(HermezUpdateWithdrawalDelay) if err := _Hermez.contract.UnpackLog(event, "UpdateWithdrawalDelay", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -2638,7 +2639,7 @@ }

logs, sub, err := _Hermez.contract.FilterLogs(opts, "WithdrawEvent", idxRule, numExitRootRule, instantWithdrawRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HermezWithdrawEventIterator{contract: _Hermez.contract, event: "WithdrawEvent", logs: logs, sub: sub}, nil }

@@ -2663,7 +2664,7 @@ }

logs, sub, err := _Hermez.contract.WatchLogs(opts, "WithdrawEvent", idxRule, numExitRootRule, instantWithdrawRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -2673,19 +2674,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HermezWithdrawEvent) if err := _Hermez.contract.UnpackLog(event, "WithdrawEvent", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -2699,7 +2700,7 @@ // Solidity: event WithdrawEvent(uint48 indexed idx, uint48 indexed numExitRoot, bool indexed instantWithdraw)

func (_Hermez *HermezFilterer) ParseWithdrawEvent(log types.Log) (*HermezWithdrawEvent, error) { event := new(HermezWithdrawEvent) if err := _Hermez.contract.UnpackLog(event, "WithdrawEvent", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }
M eth/contracts/tokenHEZ/HEZ.go → eth/contracts/tokenHEZ/HEZ.go

@@ -13,6 +13,7 @@ "github.com/ethereum/go-ethereum/accounts/abi/bind"

"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/event" + "github.com/hermeznetwork/tracerr" ) // Reference imports to suppress errors if they are not otherwise used.

@@ -36,12 +37,12 @@ // DeployHEZ deploys a new Ethereum contract, binding an instance of HEZ to it.

func DeployHEZ(auth *bind.TransactOpts, backend bind.ContractBackend, initialHolder common.Address) (common.Address, *types.Transaction, *HEZ, error) { parsed, err := abi.JSON(strings.NewReader(HEZABI)) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(HEZBin), backend, initialHolder) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } return address, tx, &HEZ{HEZCaller: HEZCaller{contract: contract}, HEZTransactor: HEZTransactor{contract: contract}, HEZFilterer: HEZFilterer{contract: contract}}, nil }

@@ -109,7 +110,7 @@ // NewHEZ creates a new instance of HEZ, bound to a specific deployed contract.

func NewHEZ(address common.Address, backend bind.ContractBackend) (*HEZ, error) { contract, err := bindHEZ(address, backend, backend, backend) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HEZ{HEZCaller: HEZCaller{contract: contract}, HEZTransactor: HEZTransactor{contract: contract}, HEZFilterer: HEZFilterer{contract: contract}}, nil }

@@ -118,7 +119,7 @@ // NewHEZCaller creates a new read-only instance of HEZ, bound to a specific deployed contract.

func NewHEZCaller(address common.Address, caller bind.ContractCaller) (*HEZCaller, error) { contract, err := bindHEZ(address, caller, nil, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HEZCaller{contract: contract}, nil }

@@ -127,7 +128,7 @@ // NewHEZTransactor creates a new write-only instance of HEZ, bound to a specific deployed contract.

func NewHEZTransactor(address common.Address, transactor bind.ContractTransactor) (*HEZTransactor, error) { contract, err := bindHEZ(address, nil, transactor, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HEZTransactor{contract: contract}, nil }

@@ -136,7 +137,7 @@ // NewHEZFilterer creates a new log filterer instance of HEZ, bound to a specific deployed contract.

func NewHEZFilterer(address common.Address, filterer bind.ContractFilterer) (*HEZFilterer, error) { contract, err := bindHEZ(address, nil, nil, filterer) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HEZFilterer{contract: contract}, nil }

@@ -145,7 +146,7 @@ // bindHEZ binds a generic wrapper to an already deployed contract.

func bindHEZ(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader(HEZABI)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil }

@@ -197,7 +198,7 @@ ret0 = new([32]byte)

) out := ret0 err := _HEZ.contract.Call(opts, out, "EIP712DOMAIN_HASH") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // EIP712DOMAINHASH is a free data retrieval call binding the contract method 0xc473af33.

@@ -223,7 +224,7 @@ ret0 = new([32]byte)

) out := ret0 err := _HEZ.contract.Call(opts, out, "NAME_HASH") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // NAMEHASH is a free data retrieval call binding the contract method 0x04622c2e.

@@ -249,7 +250,7 @@ ret0 = new([32]byte)

) out := ret0 err := _HEZ.contract.Call(opts, out, "PERMIT_TYPEHASH") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // PERMITTYPEHASH is a free data retrieval call binding the contract method 0x30adf81f.

@@ -275,7 +276,7 @@ ret0 = new([32]byte)

) out := ret0 err := _HEZ.contract.Call(opts, out, "TRANSFER_WITH_AUTHORIZATION_TYPEHASH") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // TRANSFERWITHAUTHORIZATIONTYPEHASH is a free data retrieval call binding the contract method 0xa0cc6a68.

@@ -301,7 +302,7 @@ ret0 = new([32]byte)

) out := ret0 err := _HEZ.contract.Call(opts, out, "VERSION_HASH") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // VERSIONHASH is a free data retrieval call binding the contract method 0x9e4e7318.

@@ -327,7 +328,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HEZ.contract.Call(opts, out, "allowance", arg0, arg1) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // Allowance is a free data retrieval call binding the contract method 0xdd62ed3e.

@@ -353,7 +354,7 @@ ret0 = new(bool)

) out := ret0 err := _HEZ.contract.Call(opts, out, "authorizationState", arg0, arg1) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // AuthorizationState is a free data retrieval call binding the contract method 0xe94a0102.

@@ -379,7 +380,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HEZ.contract.Call(opts, out, "balanceOf", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // BalanceOf is a free data retrieval call binding the contract method 0x70a08231.

@@ -405,7 +406,7 @@ ret0 = new(uint8)

) out := ret0 err := _HEZ.contract.Call(opts, out, "decimals") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // Decimals is a free data retrieval call binding the contract method 0x313ce567.

@@ -431,7 +432,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HEZ.contract.Call(opts, out, "getChainId") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetChainId is a free data retrieval call binding the contract method 0x3408e470.

@@ -457,7 +458,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HEZ.contract.Call(opts, out, "initialBalance") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // InitialBalance is a free data retrieval call binding the contract method 0x18369a2a.

@@ -483,7 +484,7 @@ ret0 = new(string)

) out := ret0 err := _HEZ.contract.Call(opts, out, "name") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // Name is a free data retrieval call binding the contract method 0x06fdde03.

@@ -509,7 +510,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HEZ.contract.Call(opts, out, "nonces", arg0) - return *ret0, err + return *ret0, tracerr.Wrap(err) } // Nonces is a free data retrieval call binding the contract method 0x7ecebe00.

@@ -535,7 +536,7 @@ ret0 = new(string)

) out := ret0 err := _HEZ.contract.Call(opts, out, "symbol") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // Symbol is a free data retrieval call binding the contract method 0x95d89b41.

@@ -561,7 +562,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _HEZ.contract.Call(opts, out, "totalSupply") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // TotalSupply is a free data retrieval call binding the contract method 0x18160ddd.

@@ -795,7 +796,7 @@ }

logs, sub, err := _HEZ.contract.FilterLogs(opts, "Approval", ownerRule, spenderRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HEZApprovalIterator{contract: _HEZ.contract, event: "Approval", logs: logs, sub: sub}, nil }

@@ -816,7 +817,7 @@ }

logs, sub, err := _HEZ.contract.WatchLogs(opts, "Approval", ownerRule, spenderRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -826,19 +827,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HEZApproval) if err := _HEZ.contract.UnpackLog(event, "Approval", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -852,7 +853,7 @@ // Solidity: event Approval(address indexed owner, address indexed spender, uint256 value)

func (_HEZ *HEZFilterer) ParseApproval(log types.Log) (*HEZApproval, error) { event := new(HEZApproval) if err := _HEZ.contract.UnpackLog(event, "Approval", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -947,7 +948,7 @@ }

logs, sub, err := _HEZ.contract.FilterLogs(opts, "AuthorizationUsed", authorizerRule, nonceRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HEZAuthorizationUsedIterator{contract: _HEZ.contract, event: "AuthorizationUsed", logs: logs, sub: sub}, nil }

@@ -968,7 +969,7 @@ }

logs, sub, err := _HEZ.contract.WatchLogs(opts, "AuthorizationUsed", authorizerRule, nonceRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -978,19 +979,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HEZAuthorizationUsed) if err := _HEZ.contract.UnpackLog(event, "AuthorizationUsed", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1004,7 +1005,7 @@ // Solidity: event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce)

func (_HEZ *HEZFilterer) ParseAuthorizationUsed(log types.Log) (*HEZAuthorizationUsed, error) { event := new(HEZAuthorizationUsed) if err := _HEZ.contract.UnpackLog(event, "AuthorizationUsed", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1100,7 +1101,7 @@ }

logs, sub, err := _HEZ.contract.FilterLogs(opts, "Transfer", fromRule, toRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &HEZTransferIterator{contract: _HEZ.contract, event: "Transfer", logs: logs, sub: sub}, nil }

@@ -1121,7 +1122,7 @@ }

logs, sub, err := _HEZ.contract.WatchLogs(opts, "Transfer", fromRule, toRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1131,19 +1132,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(HEZTransfer) if err := _HEZ.contract.UnpackLog(event, "Transfer", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1157,7 +1158,7 @@ // Solidity: event Transfer(address indexed from, address indexed to, uint256 value)

func (_HEZ *HEZFilterer) ParseTransfer(log types.Log) (*HEZTransfer, error) { event := new(HEZTransfer) if err := _HEZ.contract.UnpackLog(event, "Transfer", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }
M eth/contracts/withdrawdelayer/WithdrawalDelayer.go → eth/contracts/withdrawdelayer/WithdrawalDelayer.go

@@ -13,6 +13,7 @@ "github.com/ethereum/go-ethereum/accounts/abi/bind"

"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/event" + "github.com/hermeznetwork/tracerr" ) // Reference imports to suppress errors if they are not otherwise used.

@@ -36,12 +37,12 @@ // DeployWithdrawalDelayer deploys a new Ethereum contract, binding an instance of WithdrawalDelayer to it.

func DeployWithdrawalDelayer(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, *types.Transaction, *WithdrawalDelayer, error) { parsed, err := abi.JSON(strings.NewReader(WithdrawalDelayerABI)) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(WithdrawalDelayerBin), backend) if err != nil { - return common.Address{}, nil, nil, err + return common.Address{}, nil, nil, tracerr.Wrap(err) } return address, tx, &WithdrawalDelayer{WithdrawalDelayerCaller: WithdrawalDelayerCaller{contract: contract}, WithdrawalDelayerTransactor: WithdrawalDelayerTransactor{contract: contract}, WithdrawalDelayerFilterer: WithdrawalDelayerFilterer{contract: contract}}, nil }

@@ -109,7 +110,7 @@ // NewWithdrawalDelayer creates a new instance of WithdrawalDelayer, bound to a specific deployed contract.

func NewWithdrawalDelayer(address common.Address, backend bind.ContractBackend) (*WithdrawalDelayer, error) { contract, err := bindWithdrawalDelayer(address, backend, backend, backend) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayer{WithdrawalDelayerCaller: WithdrawalDelayerCaller{contract: contract}, WithdrawalDelayerTransactor: WithdrawalDelayerTransactor{contract: contract}, WithdrawalDelayerFilterer: WithdrawalDelayerFilterer{contract: contract}}, nil }

@@ -118,7 +119,7 @@ // NewWithdrawalDelayerCaller creates a new read-only instance of WithdrawalDelayer, bound to a specific deployed contract.

func NewWithdrawalDelayerCaller(address common.Address, caller bind.ContractCaller) (*WithdrawalDelayerCaller, error) { contract, err := bindWithdrawalDelayer(address, caller, nil, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerCaller{contract: contract}, nil }

@@ -127,7 +128,7 @@ // NewWithdrawalDelayerTransactor creates a new write-only instance of WithdrawalDelayer, bound to a specific deployed contract.

func NewWithdrawalDelayerTransactor(address common.Address, transactor bind.ContractTransactor) (*WithdrawalDelayerTransactor, error) { contract, err := bindWithdrawalDelayer(address, nil, transactor, nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerTransactor{contract: contract}, nil }

@@ -136,7 +137,7 @@ // NewWithdrawalDelayerFilterer creates a new log filterer instance of WithdrawalDelayer, bound to a specific deployed contract.

func NewWithdrawalDelayerFilterer(address common.Address, filterer bind.ContractFilterer) (*WithdrawalDelayerFilterer, error) { contract, err := bindWithdrawalDelayer(address, nil, nil, filterer) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerFilterer{contract: contract}, nil }

@@ -145,7 +146,7 @@ // bindWithdrawalDelayer binds a generic wrapper to an already deployed contract.

func bindWithdrawalDelayer(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader(WithdrawalDelayerABI)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil }

@@ -197,7 +198,7 @@ ret0 = new(uint64)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "MAX_EMERGENCY_MODE_TIME") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // MAXEMERGENCYMODETIME is a free data retrieval call binding the contract method 0xb4b8e39d.

@@ -223,7 +224,7 @@ ret0 = new(uint64)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "MAX_WITHDRAWAL_DELAY") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // MAXWITHDRAWALDELAY is a free data retrieval call binding the contract method 0xa238f9df.

@@ -253,7 +254,7 @@ ret0,

ret1, } err := _WithdrawalDelayer.contract.Call(opts, out, "depositInfo", _owner, _token) - return *ret0, *ret1, err + return *ret0, *ret1, tracerr.Wrap(err) } // DepositInfo is a free data retrieval call binding the contract method 0x493b0170.

@@ -283,7 +284,7 @@ DepositTimestamp uint64

}) out := ret err := _WithdrawalDelayer.contract.Call(opts, out, "deposits", arg0) - return *ret, err + return *ret, tracerr.Wrap(err) } // Deposits is a free data retrieval call binding the contract method 0x3d4dff7b.

@@ -315,7 +316,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "getEmergencyModeStartingTime") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetEmergencyModeStartingTime is a free data retrieval call binding the contract method 0x668cdd67.

@@ -341,7 +342,7 @@ ret0 = new(common.Address)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "getHermezGovernanceDAOAddress") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetHermezGovernanceDAOAddress is a free data retrieval call binding the contract method 0x580fc611.

@@ -367,7 +368,7 @@ ret0 = new(common.Address)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "getHermezKeeperAddress") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetHermezKeeperAddress is a free data retrieval call binding the contract method 0x305887f9.

@@ -393,7 +394,7 @@ ret0 = new(common.Address)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "getWhiteHackGroupAddress") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetWhiteHackGroupAddress is a free data retrieval call binding the contract method 0xae7efbbd.

@@ -419,7 +420,7 @@ ret0 = new(*big.Int)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "getWithdrawalDelay") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // GetWithdrawalDelay is a free data retrieval call binding the contract method 0x03160940.

@@ -445,7 +446,7 @@ ret0 = new(common.Address)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "hermezRollupAddress") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // HermezRollupAddress is a free data retrieval call binding the contract method 0x0fd266d7.

@@ -471,7 +472,7 @@ ret0 = new(bool)

) out := ret0 err := _WithdrawalDelayer.contract.Call(opts, out, "isEmergencyMode") - return *ret0, err + return *ret0, tracerr.Wrap(err) } // IsEmergencyMode is a free data retrieval call binding the contract method 0x20a194b8.

@@ -769,7 +770,7 @@ }

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "Deposit", ownerRule, tokenRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerDepositIterator{contract: _WithdrawalDelayer.contract, event: "Deposit", logs: logs, sub: sub}, nil }

@@ -790,7 +791,7 @@ }

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "Deposit", ownerRule, tokenRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -800,19 +801,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerDeposit) if err := _WithdrawalDelayer.contract.UnpackLog(event, "Deposit", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -826,7 +827,7 @@ // Solidity: event Deposit(address indexed owner, address indexed token, uint192 amount, uint64 depositTimestamp)

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseDeposit(log types.Log) (*WithdrawalDelayerDeposit, error) { event := new(WithdrawalDelayerDeposit) if err := _WithdrawalDelayer.contract.UnpackLog(event, "Deposit", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -910,7 +911,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) FilterEmergencyModeEnabled(opts *bind.FilterOpts) (*WithdrawalDelayerEmergencyModeEnabledIterator, error) {

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "EmergencyModeEnabled") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerEmergencyModeEnabledIterator{contract: _WithdrawalDelayer.contract, event: "EmergencyModeEnabled", logs: logs, sub: sub}, nil }

@@ -922,7 +923,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) WatchEmergencyModeEnabled(opts *bind.WatchOpts, sink chan<- *WithdrawalDelayerEmergencyModeEnabled) (event.Subscription, error) {

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "EmergencyModeEnabled") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -932,19 +933,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerEmergencyModeEnabled) if err := _WithdrawalDelayer.contract.UnpackLog(event, "EmergencyModeEnabled", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -958,7 +959,7 @@ // Solidity: event EmergencyModeEnabled()

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseEmergencyModeEnabled(log types.Log) (*WithdrawalDelayerEmergencyModeEnabled, error) { event := new(WithdrawalDelayerEmergencyModeEnabled) if err := _WithdrawalDelayer.contract.UnpackLog(event, "EmergencyModeEnabled", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1059,7 +1060,7 @@ }

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "EscapeHatchWithdrawal", whoRule, toRule, tokenRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerEscapeHatchWithdrawalIterator{contract: _WithdrawalDelayer.contract, event: "EscapeHatchWithdrawal", logs: logs, sub: sub}, nil }

@@ -1084,7 +1085,7 @@ }

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "EscapeHatchWithdrawal", whoRule, toRule, tokenRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1094,19 +1095,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerEscapeHatchWithdrawal) if err := _WithdrawalDelayer.contract.UnpackLog(event, "EscapeHatchWithdrawal", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1120,7 +1121,7 @@ // Solidity: event EscapeHatchWithdrawal(address indexed who, address indexed to, address indexed token, uint256 amount)

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseEscapeHatchWithdrawal(log types.Log) (*WithdrawalDelayerEscapeHatchWithdrawal, error) { event := new(WithdrawalDelayerEscapeHatchWithdrawal) if err := _WithdrawalDelayer.contract.UnpackLog(event, "EscapeHatchWithdrawal", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1205,7 +1206,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) FilterNewHermezGovernanceDAOAddress(opts *bind.FilterOpts) (*WithdrawalDelayerNewHermezGovernanceDAOAddressIterator, error) {

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "NewHermezGovernanceDAOAddress") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerNewHermezGovernanceDAOAddressIterator{contract: _WithdrawalDelayer.contract, event: "NewHermezGovernanceDAOAddress", logs: logs, sub: sub}, nil }

@@ -1217,7 +1218,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) WatchNewHermezGovernanceDAOAddress(opts *bind.WatchOpts, sink chan<- *WithdrawalDelayerNewHermezGovernanceDAOAddress) (event.Subscription, error) {

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "NewHermezGovernanceDAOAddress") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1227,19 +1228,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerNewHermezGovernanceDAOAddress) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewHermezGovernanceDAOAddress", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1253,7 +1254,7 @@ // Solidity: event NewHermezGovernanceDAOAddress(address newHermezGovernanceDAOAddress)

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseNewHermezGovernanceDAOAddress(log types.Log) (*WithdrawalDelayerNewHermezGovernanceDAOAddress, error) { event := new(WithdrawalDelayerNewHermezGovernanceDAOAddress) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewHermezGovernanceDAOAddress", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1338,7 +1339,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) FilterNewHermezKeeperAddress(opts *bind.FilterOpts) (*WithdrawalDelayerNewHermezKeeperAddressIterator, error) {

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "NewHermezKeeperAddress") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerNewHermezKeeperAddressIterator{contract: _WithdrawalDelayer.contract, event: "NewHermezKeeperAddress", logs: logs, sub: sub}, nil }

@@ -1350,7 +1351,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) WatchNewHermezKeeperAddress(opts *bind.WatchOpts, sink chan<- *WithdrawalDelayerNewHermezKeeperAddress) (event.Subscription, error) {

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "NewHermezKeeperAddress") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1360,19 +1361,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerNewHermezKeeperAddress) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewHermezKeeperAddress", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1386,7 +1387,7 @@ // Solidity: event NewHermezKeeperAddress(address newHermezKeeperAddress)

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseNewHermezKeeperAddress(log types.Log) (*WithdrawalDelayerNewHermezKeeperAddress, error) { event := new(WithdrawalDelayerNewHermezKeeperAddress) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewHermezKeeperAddress", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1471,7 +1472,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) FilterNewWhiteHackGroupAddress(opts *bind.FilterOpts) (*WithdrawalDelayerNewWhiteHackGroupAddressIterator, error) {

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "NewWhiteHackGroupAddress") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerNewWhiteHackGroupAddressIterator{contract: _WithdrawalDelayer.contract, event: "NewWhiteHackGroupAddress", logs: logs, sub: sub}, nil }

@@ -1483,7 +1484,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) WatchNewWhiteHackGroupAddress(opts *bind.WatchOpts, sink chan<- *WithdrawalDelayerNewWhiteHackGroupAddress) (event.Subscription, error) {

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "NewWhiteHackGroupAddress") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1493,19 +1494,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerNewWhiteHackGroupAddress) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewWhiteHackGroupAddress", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1519,7 +1520,7 @@ // Solidity: event NewWhiteHackGroupAddress(address newWhiteHackGroupAddress)

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseNewWhiteHackGroupAddress(log types.Log) (*WithdrawalDelayerNewWhiteHackGroupAddress, error) { event := new(WithdrawalDelayerNewWhiteHackGroupAddress) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewWhiteHackGroupAddress", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1604,7 +1605,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) FilterNewWithdrawalDelay(opts *bind.FilterOpts) (*WithdrawalDelayerNewWithdrawalDelayIterator, error) {

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "NewWithdrawalDelay") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerNewWithdrawalDelayIterator{contract: _WithdrawalDelayer.contract, event: "NewWithdrawalDelay", logs: logs, sub: sub}, nil }

@@ -1616,7 +1617,7 @@ func (_WithdrawalDelayer *WithdrawalDelayerFilterer) WatchNewWithdrawalDelay(opts *bind.WatchOpts, sink chan<- *WithdrawalDelayerNewWithdrawalDelay) (event.Subscription, error) {

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "NewWithdrawalDelay") if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1626,19 +1627,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerNewWithdrawalDelay) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewWithdrawalDelay", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1652,7 +1653,7 @@ // Solidity: event NewWithdrawalDelay(uint64 withdrawalDelay)

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseNewWithdrawalDelay(log types.Log) (*WithdrawalDelayerNewWithdrawalDelay, error) { event := new(WithdrawalDelayerNewWithdrawalDelay) if err := _WithdrawalDelayer.contract.UnpackLog(event, "NewWithdrawalDelay", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }

@@ -1748,7 +1749,7 @@ }

logs, sub, err := _WithdrawalDelayer.contract.FilterLogs(opts, "Withdraw", tokenRule, ownerRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WithdrawalDelayerWithdrawIterator{contract: _WithdrawalDelayer.contract, event: "Withdraw", logs: logs, sub: sub}, nil }

@@ -1769,7 +1770,7 @@ }

logs, sub, err := _WithdrawalDelayer.contract.WatchLogs(opts, "Withdraw", tokenRule, ownerRule) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event.NewSubscription(func(quit <-chan struct{}) error { defer sub.Unsubscribe()

@@ -1779,19 +1780,19 @@ case log := <-logs:

// New log arrived, parse the event and forward to the user event := new(WithdrawalDelayerWithdraw) if err := _WithdrawalDelayer.contract.UnpackLog(event, "Withdraw", log); err != nil { - return err + return tracerr.Wrap(err) } event.Raw = log select { case sink <- event: case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil } case err := <-sub.Err(): - return err + return tracerr.Wrap(err) case <-quit: return nil }

@@ -1805,7 +1806,7 @@ // Solidity: event Withdraw(address indexed token, address indexed owner, uint192 amount)

func (_WithdrawalDelayer *WithdrawalDelayerFilterer) ParseWithdraw(log types.Log) (*WithdrawalDelayerWithdraw, error) { event := new(WithdrawalDelayerWithdraw) if err := _WithdrawalDelayer.contract.UnpackLog(event, "Withdraw", log); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return event, nil }
M eth/ethereum.go → eth/ethereum.go

@@ -15,6 +15,7 @@ "github.com/ethereum/go-ethereum/ethclient"

"github.com/hermeznetwork/hermez-node/common" HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" ) // ERC20Consts are the constants defined in a particular ERC20 Token instance

@@ -105,7 +106,7 @@

// EthAddress returns the ethereum address of the account loaded into the EthereumClient func (c *EthereumClient) EthAddress() (*ethCommon.Address, error) { if c.account == nil { - return nil, ErrAccountNil + return nil, tracerr.Wrap(ErrAccountNil) } return &c.account.Address, nil }

@@ -116,12 +117,12 @@ // call.

func (c *EthereumClient) CallAuth(gasLimit uint64, fn func(*ethclient.Client, *bind.TransactOpts) (*types.Transaction, error)) (*types.Transaction, error) { if c.account == nil { - return nil, ErrAccountNil + return nil, tracerr.Wrap(ErrAccountNil) } gasPrice, err := c.client.SuggestGasPrice(context.Background()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } inc := new(big.Int).Set(gasPrice) inc.Div(inc, new(big.Int).SetUint64(c.config.GasPriceDiv))

@@ -130,7 +131,7 @@ log.Debugw("Transaction metadata", "gasPrice", gasPrice)

auth, err := bind.NewKeyStoreTransactor(c.ks, *c.account) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } auth.Value = big.NewInt(0) // in wei if gasLimit == 0 {

@@ -144,7 +145,7 @@ tx, err := fn(c.client, auth)

if tx != nil { log.Debugw("Transaction", "tx", tx.Hash().Hex(), "nonce", tx.Nonce()) } - return tx, err + return tx, tracerr.Wrap(err) } // ContractData contains the contract data

@@ -167,20 +168,20 @@ c.config.DeployGasLimit,

func(client *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) { addr, tx, _, err := fn(client, auth) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } contractData.Address = addr return tx, nil }, ) if err != nil { - return contractData, fmt.Errorf(errStrDeploy, name, err) + return contractData, tracerr.Wrap(fmt.Errorf(errStrDeploy, name, err)) } log.Infow("Waiting receipt", "tx", tx.Hash().Hex(), "contract", name) contractData.Tx = tx receipt, err := c.WaitReceipt(tx) if err != nil { - return contractData, fmt.Errorf(errStrWaitReceipt, name, err) + return contractData, tracerr.Wrap(fmt.Errorf(errStrWaitReceipt, name, err)) } contractData.Receipt = receipt return contractData, nil

@@ -229,16 +230,16 @@ }

if receipt != nil && receipt.Status == types.ReceiptStatusFailed { log.Errorw("Failed transaction", "tx", txHash.Hex()) - return receipt, ErrReceiptStatusFailed + return receipt, tracerr.Wrap(ErrReceiptStatusFailed) } if receipt == nil { log.Debugw("Pendingtransaction / Wait receipt timeout", "tx", txHash.Hex(), "lasterr", err) - return receipt, ErrReceiptNotReceived + return receipt, tracerr.Wrap(ErrReceiptNotReceived) } log.Debugw("Successful transaction", "tx", txHash.Hex()) - return receipt, err + return receipt, tracerr.Wrap(err) } // EthLastBlock returns the last block number in the blockchain

@@ -247,7 +248,7 @@ ctx, cancel := context.WithTimeout(context.TODO(), 1*time.Second)

defer cancel() header, err := c.client.HeaderByNumber(ctx, nil) if err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return header.Number.Int64(), nil }

@@ -266,7 +267,7 @@ blockNum = nil

} block, err := c.client.BlockByNumber(ctx, blockNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } b := &common.Block{ Num: block.Number().Int64(),

@@ -283,21 +284,21 @@ // We use the HEZ token smart contract interfacehere because it's an

// ERC20, which allows us to access the standard ERC20 constants. instance, err := HEZ.NewHEZ(tokenAddress, c.client) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } name, err := instance.Name(nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } symbol, err := instance.Symbol(nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } decimals, err := instance.Decimals(nil) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &ERC20Consts{ Name: name,
M eth/rollup.go → eth/rollup.go

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

Hermez "github.com/hermeznetwork/hermez-node/eth/contracts/hermez" HEZ "github.com/hermeznetwork/hermez-node/eth/contracts/tokenHEZ" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -202,19 +203,19 @@ // NewRollupClient creates a new RollupClient

func NewRollupClient(client *EthereumClient, address ethCommon.Address, tokenHEZCfg TokenConfig) (*RollupClient, error) { contractAbi, err := abi.JSON(strings.NewReader(string(Hermez.HermezABI))) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } hermez, err := Hermez.NewHermez(address, client.Client()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tokenHEZ, err := HEZ.NewHEZ(tokenHEZCfg.Address, client.Client()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } chainID, err := client.client.ChainID(context.Background()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &RollupClient{ client: client,

@@ -234,7 +235,7 @@ 1000000, //nolint:gomnd

func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) { rollupConst, err := c.RollupConstants() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } nLevels := rollupConst.Verifiers[args.VerifierIdx].NLevels lenBytes := nLevels / 8 //nolint:gomnd

@@ -244,7 +245,7 @@ for i := 0; i < len(args.L1CoordinatorTxs); i++ {

l1 := args.L1CoordinatorTxs[i] bytesl1, err := l1.BytesCoordinatorTx(args.L1CoordinatorTxsAuths[i]) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } l1CoordinatorBytes = append(l1CoordinatorBytes, bytesl1[:]...) }

@@ -253,14 +254,14 @@ for i := 0; i < len(args.L2TxsData); i++ {

l2 := args.L2TxsData[i] bytesl2, err := l2.BytesDataAvailability(uint32(nLevels)) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } l2DataBytes = append(l2DataBytes, bytesl2[:]...) } var feeIdxCoordinator []byte if len(args.FeeIdxCoordinator) > common.RollupConstMaxFeeIdxCoordinator { - return nil, fmt.Errorf("len(args.FeeIdxCoordinator) > %v", - common.RollupConstMaxFeeIdxCoordinator) + return nil, tracerr.Wrap(fmt.Errorf("len(args.FeeIdxCoordinator) > %v", + common.RollupConstMaxFeeIdxCoordinator)) } for i := 0; i < common.RollupConstMaxFeeIdxCoordinator; i++ { feeIdx := common.Idx(0)

@@ -269,14 +270,14 @@ feeIdx = args.FeeIdxCoordinator[i]

} bytesFeeIdx, err := feeIdx.Bytes() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } feeIdxCoordinator = append(feeIdxCoordinator, bytesFeeIdx[len(bytesFeeIdx)-int(lenBytes):]...) } return c.hermez.ForgeBatch(auth, newLastIdx, args.NewStRoot, args.NewExitRoot, l1CoordinatorBytes, l2DataBytes, feeIdxCoordinator, args.VerifierIdx, args.L1Batch, args.ProofA, args.ProofB, args.ProofC) }, ); err != nil { - return nil, fmt.Errorf("Failed forge batch: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed forge batch: %w", err)) } return tx, nil }

@@ -292,7 +293,7 @@ owner := c.client.account.Address

spender := c.address nonce, err := c.tokenHEZ.Nonces(nil, owner) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tokenName := c.tokenHEZCfg.Name tokenAddr := c.tokenHEZCfg.Address

@@ -303,7 +304,7 @@

return c.hermez.AddToken(auth, tokenAddress, permit) }, ); err != nil { - return nil, fmt.Errorf("Failed add Token %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed add Token %w", err)) } return tx, nil }

@@ -321,7 +322,7 @@ idxBig := big.NewInt(idx)

return c.hermez.WithdrawMerkleProof(auth, tokenID, amount, babyPubKey, numExitRootB, siblings, idxBig, instantWithdraw) }, ); err != nil { - return nil, fmt.Errorf("Failed update WithdrawMerkleProof: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed update WithdrawMerkleProof: %w", err)) } return tx, nil }

@@ -329,7 +330,7 @@

// RollupWithdrawCircuit is the interface to call the smart contract function func (c *RollupClient) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error) { log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // RollupL1UserTxERC20ETH is the interface to call the smart contract function

@@ -344,11 +345,11 @@ fromIdxBig := big.NewInt(fromIdx)

toIdxBig := big.NewInt(toIdx) loadAmountF, err := common.NewFloat16(loadAmount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } amountF, err := common.NewFloat16(amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if tokenID == 0 { auth.Value = loadAmount

@@ -358,7 +359,7 @@ return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),

uint16(amountF), tokenID, toIdxBig, permit) }, ); err != nil { - return nil, fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed add L1 Tx ERC20/ETH: %w", err)) } return tx, nil }

@@ -375,11 +376,11 @@ fromIdxBig := big.NewInt(fromIdx)

toIdxBig := big.NewInt(toIdx) loadAmountF, err := common.NewFloat16(loadAmount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } amountF, err := common.NewFloat16(amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if tokenID == 0 { auth.Value = loadAmount

@@ -388,7 +389,7 @@ owner := c.client.account.Address

spender := c.address nonce, err := c.tokenHEZ.Nonces(nil, owner) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tokenName := c.tokenHEZCfg.Name tokenAddr := c.tokenHEZCfg.Address

@@ -399,7 +400,7 @@ return c.hermez.AddL1Transaction(auth, babyPubKey, fromIdxBig, uint16(loadAmountF),

uint16(amountF), tokenID, toIdxBig, permit) }, ); err != nil { - return nil, fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed add L1 Tx ERC20Permit: %w", err)) } return tx, nil }

@@ -408,9 +409,9 @@ // RollupRegisterTokensCount is the interface to call the smart contract function

func (c *RollupClient) RollupRegisterTokensCount() (registerTokensCount *big.Int, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { registerTokensCount, err = c.hermez.RegisterTokensCount(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return registerTokensCount, nil }

@@ -420,9 +421,9 @@ func (c *RollupClient) RollupLastForgedBatch() (lastForgedBatch int64, err error) {

if err := c.client.Call(func(ec *ethclient.Client) error { _lastForgedBatch, err := c.hermez.LastForgedBatch(nil) lastForgedBatch = int64(_lastForgedBatch) - return err + return tracerr.Wrap(err) }); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return lastForgedBatch, nil }

@@ -435,7 +436,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.hermez.UpdateForgeL1L2BatchTimeout(auth, uint8(newForgeL1L2BatchTimeout)) }, ); err != nil { - return nil, fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed update ForgeL1L2BatchTimeout: %w", err)) } return tx, nil }

@@ -448,7 +449,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.hermez.UpdateFeeAddToken(auth, newFeeAddToken) }, ); err != nil { - return nil, fmt.Errorf("Failed update FeeAddToken: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed update FeeAddToken: %w", err)) } return tx, nil }

@@ -459,18 +460,18 @@ rollupConstants = new(common.RollupConstants)

if err := c.client.Call(func(ec *ethclient.Client) error { absoluteMaxL1L2BatchTimeout, err := c.hermez.ABSOLUTEMAXL1L2BATCHTIMEOUT(nil) if err != nil { - return err + return tracerr.Wrap(err) } rollupConstants.AbsoluteMaxL1L2BatchTimeout = int64(absoluteMaxL1L2BatchTimeout) rollupConstants.TokenHEZ, err = c.hermez.TokenHEZ(nil) if err != nil { - return err + return tracerr.Wrap(err) } for i := int64(0); i < int64(common.LenVerifiers); i++ { var newRollupVerifier common.RollupVerifierStruct rollupVerifier, err := c.hermez.RollupVerifiers(nil, big.NewInt(i)) if err != nil { - return err + return tracerr.Wrap(err) } newRollupVerifier.MaxTx = rollupVerifier.MaxTx.Int64() newRollupVerifier.NLevels = rollupVerifier.NLevels.Int64()

@@ -478,20 +479,20 @@ rollupConstants.Verifiers = append(rollupConstants.Verifiers, newRollupVerifier)

} rollupConstants.HermezAuctionContract, err = c.hermez.HermezAuctionContract(nil) if err != nil { - return err + return tracerr.Wrap(err) } rollupConstants.HermezGovernanceDAOAddress, err = c.hermez.HermezGovernanceDAOAddress(nil) if err != nil { - return err + return tracerr.Wrap(err) } rollupConstants.SafetyAddress, err = c.hermez.SafetyAddress(nil) if err != nil { - return err + return tracerr.Wrap(err) } rollupConstants.WithdrawDelayerContract, err = c.hermez.WithdrawDelayerContract(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return rollupConstants, nil }

@@ -521,7 +522,7 @@ Topics: [][]ethCommon.Hash{},

} logs, err := c.client.client.FilterLogs(context.Background(), query) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } if len(logs) > 0 { blockHash = &logs[0].BlockHash

@@ -529,7 +530,7 @@ }

for _, vLog := range logs { if vLog.BlockHash != *blockHash { log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String()) - return nil, nil, ErrBlockHashMismatchEvent + return nil, nil, tracerr.Wrap(ErrBlockHashMismatchEvent) } switch vLog.Topics[0] { case logHermezL1UserTxEvent:

@@ -537,11 +538,11 @@ var L1UserTxAux RollupEventL1UserTxAux

var L1UserTx RollupEventL1UserTx err := c.contractAbi.Unpack(&L1UserTxAux, "L1UserTxEvent", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } L1Tx, err := common.L1UserTxFromBytes(L1UserTxAux.L1UserTx) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } toForgeL1TxsNum := new(big.Int).SetBytes(vLog.Topics[1][:]).Int64() L1Tx.ToForgeL1TxsNum = &toForgeL1TxsNum

@@ -553,7 +554,7 @@ case logHermezAddToken:

var addToken RollupEventAddToken err := c.contractAbi.Unpack(&addToken, "AddToken", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } addToken.TokenAddress = ethCommon.BytesToAddress(vLog.Topics[1].Bytes()) rollupEvents.AddToken = append(rollupEvents.AddToken, addToken)

@@ -569,7 +570,7 @@ NewForgeL1L2BatchTimeout uint8

} err := c.contractAbi.Unpack(&updateForgeL1L2BatchTimeout, "UpdateForgeL1L2BatchTimeout", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } rollupEvents.UpdateForgeL1L2BatchTimeout = append(rollupEvents.UpdateForgeL1L2BatchTimeout, RollupEventUpdateForgeL1L2BatchTimeout{

@@ -579,7 +580,7 @@ case logHermezUpdateFeeAddToken:

var updateFeeAddToken RollupEventUpdateFeeAddToken err := c.contractAbi.Unpack(&updateFeeAddToken, "UpdateFeeAddToken", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } rollupEvents.UpdateFeeAddToken = append(rollupEvents.UpdateFeeAddToken, updateFeeAddToken) case logHermezWithdrawEvent:

@@ -602,25 +603,25 @@ // Rollup Smart Contract in the given transaction, and the sender address.

func (c *RollupClient) RollupForgeBatchArgs(ethTxHash ethCommon.Hash) (*RollupForgeBatchArgs, *ethCommon.Address, error) { tx, _, err := c.client.client.TransactionByHash(context.Background(), ethTxHash) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } txData := tx.Data() method, err := c.contractAbi.MethodById(txData[:4]) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } receipt, err := c.client.client.TransactionReceipt(context.Background(), ethTxHash) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } sender, err := c.client.client.TransactionSender(context.Background(), tx, receipt.Logs[0].BlockHash, receipt.Logs[0].Index) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } var aux RollupForgeBatchArgsAux if err := method.Inputs.Unpack(&aux, txData[4:]); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } rollupForgeBatchArgs := RollupForgeBatchArgs{ L1Batch: aux.L1Batch,

@@ -648,14 +649,14 @@ signature = append(signature, s[:]...)

signature = append(signature, v) l1Tx, err := common.L1CoordinatorTxFromBytes(bytesL1Coordinator, c.chainID, c.address) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } rollupForgeBatchArgs.L1CoordinatorTxs = append(rollupForgeBatchArgs.L1CoordinatorTxs, *l1Tx) rollupForgeBatchArgs.L1CoordinatorTxsAuths = append(rollupForgeBatchArgs.L1CoordinatorTxsAuths, signature) } rollupConsts, err := c.RollupConstants() if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } nLevels := rollupConsts.Verifiers[rollupForgeBatchArgs.VerifierIdx].NLevels lenL2TxsBytes := int((nLevels/8)*2 + 2 + 1)

@@ -663,7 +664,7 @@ numTxsL2 := len(aux.L2TxsData) / lenL2TxsBytes

for i := 0; i < numTxsL2; i++ { l2Tx, err := common.L2TxFromBytes(aux.L2TxsData[i*lenL2TxsBytes:(i+1)*lenL2TxsBytes], int(nLevels)) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } rollupForgeBatchArgs.L2TxsData = append(rollupForgeBatchArgs.L2TxsData, *l2Tx) }

@@ -679,7 +680,7 @@ copy(paddedFeeIdx[:], aux.FeeIdxCoordinator[i*lenFeeIdxCoordinatorBytes:(i+1)*lenFeeIdxCoordinatorBytes])

} feeIdxCoordinator, err := common.IdxFromBytes(paddedFeeIdx[:]) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } if feeIdxCoordinator != common.Idx(0) { rollupForgeBatchArgs.FeeIdxCoordinator = append(rollupForgeBatchArgs.FeeIdxCoordinator, feeIdxCoordinator)
M eth/wdelayer.go → eth/wdelayer.go

@@ -16,6 +16,7 @@ "github.com/ethereum/go-ethereum/ethclient"

"github.com/hermeznetwork/hermez-node/common" WithdrawalDelayer "github.com/hermeznetwork/hermez-node/eth/contracts/withdrawdelayer" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" ) // DepositState is the state of Deposit

@@ -140,11 +141,11 @@ // NewWDelayerClient creates a new WDelayerClient

func NewWDelayerClient(client *EthereumClient, address ethCommon.Address) (*WDelayerClient, error) { contractAbi, err := abi.JSON(strings.NewReader(string(WithdrawalDelayer.WithdrawalDelayerABI))) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } wdelayer, err := WithdrawalDelayer.NewWithdrawalDelayer(address, client.Client()) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &WDelayerClient{ client: client,

@@ -159,9 +160,9 @@ func (c *WDelayerClient) WDelayerGetHermezGovernanceDAOAddress() (hermezGovernanceDAOAddress *ethCommon.Address, err error) {

var _hermezGovernanceDAOAddress ethCommon.Address if err := c.client.Call(func(ec *ethclient.Client) error { _hermezGovernanceDAOAddress, err = c.wdelayer.GetHermezGovernanceDAOAddress(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &_hermezGovernanceDAOAddress, nil }

@@ -174,7 +175,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.SetHermezGovernanceDAOAddress(auth, newAddress) }, ); err != nil { - return nil, fmt.Errorf("Failed setting hermezGovernanceDAOAddress: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting hermezGovernanceDAOAddress: %w", err)) } return tx, nil }

@@ -184,9 +185,9 @@ func (c *WDelayerClient) WDelayerGetHermezKeeperAddress() (hermezKeeperAddress *ethCommon.Address, err error) {

var _hermezKeeperAddress ethCommon.Address if err := c.client.Call(func(ec *ethclient.Client) error { _hermezKeeperAddress, err = c.wdelayer.GetHermezKeeperAddress(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &_hermezKeeperAddress, nil }

@@ -199,7 +200,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.SetHermezKeeperAddress(auth, newAddress) }, ); err != nil { - return nil, fmt.Errorf("Failed setting hermezKeeperAddress: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting hermezKeeperAddress: %w", err)) } return tx, nil }

@@ -209,9 +210,9 @@ func (c *WDelayerClient) WDelayerGetWhiteHackGroupAddress() (whiteHackGroupAddress *ethCommon.Address, err error) {

var _whiteHackGroupAddress ethCommon.Address if err := c.client.Call(func(ec *ethclient.Client) error { _whiteHackGroupAddress, err = c.wdelayer.GetWhiteHackGroupAddress(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &_whiteHackGroupAddress, nil }

@@ -224,7 +225,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.SetWhiteHackGroupAddress(auth, newAddress) }, ); err != nil { - return nil, fmt.Errorf("Failed setting whiteHackGroupAddress: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting whiteHackGroupAddress: %w", err)) } return tx, nil }

@@ -233,9 +234,9 @@ // WDelayerIsEmergencyMode is the interface to call the smart contract function

func (c *WDelayerClient) WDelayerIsEmergencyMode() (ermergencyMode bool, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { ermergencyMode, err = c.wdelayer.IsEmergencyMode(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return false, err + return false, tracerr.Wrap(err) } return ermergencyMode, nil }

@@ -244,9 +245,9 @@ // WDelayerGetWithdrawalDelay is the interface to call the smart contract function

func (c *WDelayerClient) WDelayerGetWithdrawalDelay() (withdrawalDelay *big.Int, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { withdrawalDelay, err = c.wdelayer.GetWithdrawalDelay(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return withdrawalDelay, nil }

@@ -255,9 +256,9 @@ // WDelayerGetEmergencyModeStartingTime is the interface to call the smart contract function

func (c *WDelayerClient) WDelayerGetEmergencyModeStartingTime() (emergencyModeStartingTime *big.Int, err error) { if err := c.client.Call(func(ec *ethclient.Client) error { emergencyModeStartingTime, err = c.wdelayer.GetEmergencyModeStartingTime(nil) - return err + return tracerr.Wrap(err) }); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return emergencyModeStartingTime, nil }

@@ -270,7 +271,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.EnableEmergencyMode(auth) }, ); err != nil { - return nil, fmt.Errorf("Failed setting enable emergency mode: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting enable emergency mode: %w", err)) } return tx, nil }

@@ -283,7 +284,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.ChangeWithdrawalDelay(auth, newWithdrawalDelay) }, ); err != nil { - return nil, fmt.Errorf("Failed setting withdrawal delay: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed setting withdrawal delay: %w", err)) } return tx, nil }

@@ -294,9 +295,9 @@ if err := c.client.Call(func(ec *ethclient.Client) error {

amount, depositTimestamp, err := c.wdelayer.DepositInfo(nil, owner, token) depositInfo.Amount = amount depositInfo.DepositTimestamp = depositTimestamp - return err + return tracerr.Wrap(err) }); err != nil { - return depositInfo, err + return depositInfo, tracerr.Wrap(err) } return depositInfo, nil }

@@ -309,7 +310,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.Deposit(auth, owner, token, amount) }, ); err != nil { - return nil, fmt.Errorf("Failed deposit: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed deposit: %w", err)) } return tx, nil }

@@ -322,7 +323,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.Withdrawal(auth, owner, token) }, ); err != nil { - return nil, fmt.Errorf("Failed withdrawal: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed withdrawal: %w", err)) } return tx, nil }

@@ -335,7 +336,7 @@ func(ec *ethclient.Client, auth *bind.TransactOpts) (*types.Transaction, error) {

return c.wdelayer.EscapeHatchWithdrawal(auth, to, token, amount) }, ); err != nil { - return nil, fmt.Errorf("Failed escapeHatchWithdrawal: %w", err) + return nil, tracerr.Wrap(fmt.Errorf("Failed escapeHatchWithdrawal: %w", err)) } return tx, nil }

@@ -346,19 +347,19 @@ constants = new(common.WDelayerConstants)

if err := c.client.Call(func(ec *ethclient.Client) error { constants.MaxWithdrawalDelay, err = c.wdelayer.MAXWITHDRAWALDELAY(nil) if err != nil { - return err + return tracerr.Wrap(err) } constants.MaxEmergencyModeTime, err = c.wdelayer.MAXEMERGENCYMODETIME(nil) if err != nil { - return err + return tracerr.Wrap(err) } constants.HermezRollup, err = c.wdelayer.HermezRollupAddress(nil) if err != nil { - return err + return tracerr.Wrap(err) } - return err + return tracerr.Wrap(err) }); err != nil { - return constants, err + return constants, tracerr.Wrap(err) } return constants, nil }

@@ -393,7 +394,7 @@ }

logs, err := c.client.client.FilterLogs(context.Background(), query) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } if len(logs) > 0 { blockHash = &logs[0].BlockHash

@@ -401,14 +402,14 @@ }

for _, vLog := range logs { if vLog.BlockHash != *blockHash { log.Errorw("Block hash mismatch", "expected", blockHash.String(), "got", vLog.BlockHash.String()) - return nil, nil, ErrBlockHashMismatchEvent + return nil, nil, tracerr.Wrap(ErrBlockHashMismatchEvent) } switch vLog.Topics[0] { case logWDelayerDeposit: var deposit WDelayerEventDeposit err := c.contractAbi.Unpack(&deposit, "Deposit", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } deposit.Owner = ethCommon.BytesToAddress(vLog.Topics[1].Bytes()) deposit.Token = ethCommon.BytesToAddress(vLog.Topics[2].Bytes())

@@ -419,7 +420,7 @@ case logWDelayerWithdraw:

var withdraw WDelayerEventWithdraw err := c.contractAbi.Unpack(&withdraw, "Withdraw", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } withdraw.Token = ethCommon.BytesToAddress(vLog.Topics[1].Bytes()) withdraw.Owner = ethCommon.BytesToAddress(vLog.Topics[2].Bytes())

@@ -433,7 +434,7 @@ case logWDelayerNewWithdrawalDelay:

var withdrawalDelay WDelayerEventNewWithdrawalDelay err := c.contractAbi.Unpack(&withdrawalDelay, "NewWithdrawalDelay", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } wdelayerEvents.NewWithdrawalDelay = append(wdelayerEvents.NewWithdrawalDelay, withdrawalDelay)

@@ -441,7 +442,7 @@ case logWDelayerEscapeHatchWithdrawal:

var escapeHatchWithdrawal WDelayerEventEscapeHatchWithdrawal err := c.contractAbi.Unpack(&escapeHatchWithdrawal, "EscapeHatchWithdrawal", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } escapeHatchWithdrawal.Who = ethCommon.BytesToAddress(vLog.Topics[1].Bytes()) escapeHatchWithdrawal.To = ethCommon.BytesToAddress(vLog.Topics[2].Bytes())

@@ -452,7 +453,7 @@ case logWDelayerNewHermezKeeperAddress:

var keeperAddress WDelayerEventNewHermezKeeperAddress err := c.contractAbi.Unpack(&keeperAddress, "NewHermezKeeperAddress", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } wdelayerEvents.NewHermezKeeperAddress = append(wdelayerEvents.NewHermezKeeperAddress, keeperAddress)

@@ -460,7 +461,7 @@ case logWDelayerNewWhiteHackGroupAddress:

var whiteHackGroupAddress WDelayerEventNewWhiteHackGroupAddress err := c.contractAbi.Unpack(&whiteHackGroupAddress, "NewWhiteHackGroupAddress", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } wdelayerEvents.NewWhiteHackGroupAddress = append(wdelayerEvents.NewWhiteHackGroupAddress, whiteHackGroupAddress)

@@ -468,7 +469,7 @@ case logWDelayerNewHermezGovernanceDAOAddress:

var governanceDAOAddress WDelayerEventNewHermezGovernanceDAOAddress err := c.contractAbi.Unpack(&governanceDAOAddress, "NewHermezGovernanceDAOAddress", vLog.Data) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } wdelayerEvents.NewHermezGovernanceDAOAddress = append(wdelayerEvents.NewHermezGovernanceDAOAddress, governanceDAOAddress) }
M go.mod → go.mod

@@ -12,6 +12,7 @@ github.com/gin-contrib/cors v1.3.1

github.com/gin-gonic/gin v1.5.0 github.com/go-sql-driver/mysql v1.5.0 // indirect github.com/gobuffalo/packr/v2 v2.8.0 + github.com/hermeznetwork/tracerr v0.3.1-0.20201126162137-de9930d0cf29 github.com/iden3/go-iden3-crypto v0.0.6-0.20201016142444-94e92e88fb4e github.com/iden3/go-merkletree v0.0.0-20201103115630-ad30c8309b44 github.com/jinzhu/copier v0.0.0-20190924061706-b57f9002281a
M go.sum → go.sum

@@ -300,6 +300,8 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=

github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hermeznetwork/tracerr v0.3.1-0.20201126162137-de9930d0cf29 h1:dlXz/aVJfCh/wvF6jjsrl/lqHJbOigQLG6vFF5zGuNs= +github.com/hermeznetwork/tracerr v0.3.1-0.20201126162137-de9930d0cf29/go.mod h1:nsWC1+tc4qUEbUGRv4DcPJJTjLsedlPajlFmpJoohK4= github.com/holiman/uint256 v1.1.0 h1:Iye6ze0DW9s+7EMn8y6Q4ebegDzpu28JQHEVM1Bq+Wg= github.com/holiman/uint256 v1.1.0/go.mod h1:y4ga/t+u+Xwd7CpDgZESaRcWy0I7XMlTMA25ApIH5Jw= github.com/howeyc/fsnotify v0.9.0/go.mod h1:41HzSPxBGeFRQKEEwgh49TRw/nKBsYZ2cF1OzPjSJsA=

@@ -388,6 +390,8 @@ github.com/lib/pq v1.8.0 h1:9xohqzkUwzR4Ga4ivdTcawVS89YSDVxXMa3xJX3cGzg=

github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= +github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e h1:9MlwzLdW7QSDrhDjFlsEYmxpFyIoXmYRon3dt0io31k= +github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/markbates/errx v1.1.0 h1:QDFeR+UP95dO12JgW+tgi2UVfo0V8YBHiUIOaeBPiEI=
M log/log.go → log/log.go

@@ -2,8 +2,10 @@ package log

import ( "fmt" + "strings" "time" + "github.com/hermeznetwork/tracerr" "go.uber.org/zap" "go.uber.org/zap/zapcore" )

@@ -48,7 +50,8 @@

CallerKey: "caller", EncodeCaller: zapcore.ShortCallerEncoder, - StacktraceKey: "stacktrace", + // StacktraceKey: "stacktrace", + StacktraceKey: "", LineEnding: zapcore.DefaultLineEnding, }, }

@@ -65,6 +68,27 @@

log.Infof("log level: %s", level) } +func sprintStackTrace(st []tracerr.Frame) string { + builder := strings.Builder{} + for _, f := range st { + builder.WriteString(fmt.Sprintf("\n%s:%d %s()", f.Path, f.Line, f.Func)) + } + builder.WriteString("\n") + return builder.String() +} + +// appendStackTraceMaybeArgs will append the stacktrace to the args if one of them +// is a tracerr.Error +func appendStackTraceMaybeArgs(args []interface{}) []interface{} { + for i := range args { + if err, ok := args[i].(tracerr.Error); ok { + st := err.StackTrace() + return append(args, sprintStackTrace(st)) + } + } + return args +} + // Debug calls log.Debug func Debug(args ...interface{}) { log.Debug(args...)

@@ -77,16 +101,19 @@ }

// Warn calls log.Warn func Warn(args ...interface{}) { + args = appendStackTraceMaybeArgs(args) log.Warn(args...) } // Error calls log.Error func Error(args ...interface{}) { + args = appendStackTraceMaybeArgs(args) log.Error(args...) } // Fatal calls log.Fatal func Fatal(args ...interface{}) { + args = appendStackTraceMaybeArgs(args) log.Fatal(args...) }

@@ -115,6 +142,21 @@ func Errorf(template string, args ...interface{}) {

log.Errorf(template, args...) } +// appendStackTraceMaybeKV will append the stacktrace to the KV if one of them +// is a tracerr.Error +func appendStackTraceMaybeKV(msg string, kv []interface{}) string { + for i := range kv { + if i%2 == 0 { + continue + } + if err, ok := kv[i].(tracerr.Error); ok { + st := err.StackTrace() + return fmt.Sprintf("%v: %v%v\n", msg, err, sprintStackTrace(st)) + } + } + return msg +} + // Debugw calls log.Debugw func Debugw(template string, kv ...interface{}) { log.Debugw(template, kv...)

@@ -127,15 +169,18 @@ }

// Warnw calls log.Warnw func Warnw(template string, kv ...interface{}) { + template = appendStackTraceMaybeKV(template, kv) log.Warnw(template, kv...) } // Errorw calls log.Errorw func Errorw(template string, kv ...interface{}) { + template = appendStackTraceMaybeKV(template, kv) log.Errorw(template, kv...) } // Fatalw calls log.Fatalw func Fatalw(template string, kv ...interface{}) { + template = appendStackTraceMaybeKV(template, kv) log.Fatalw(template, kv...) }
M node/node.go → node/node.go

@@ -24,6 +24,7 @@ "github.com/hermeznetwork/hermez-node/log"

"github.com/hermeznetwork/hermez-node/synchronizer" "github.com/hermeznetwork/hermez-node/test/debugapi" "github.com/hermeznetwork/hermez-node/txselector" + "github.com/hermeznetwork/tracerr" "github.com/jmoiron/sqlx" )

@@ -73,19 +74,19 @@ cfg.PostgreSQL.Password,

cfg.PostgreSQL.Name, ) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } historyDB := historydb.NewHistoryDB(db) stateDB, err := statedb.NewStateDB(cfg.StateDB.Path, statedb.TypeSynchronizer, 32) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } ethClient, err := ethclient.Dial(cfg.Web3.URL) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } var ethCfg eth.EthereumConfig if mode == ModeCoordinator {

@@ -114,7 +115,7 @@ Address: cfg.SmartContracts.WDelayer,

}, }) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } sync, err := synchronizer.NewSynchronizer(client, historyDB, stateDB, synchronizer.Config{

@@ -123,7 +124,7 @@ InitialVariables: cfg.Synchronizer.InitialVariables,

StatsRefreshPeriod: cfg.Synchronizer.StatsRefreshPeriod.Duration, }) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } varsRollup, varsAuction, varsWDelayer := sync.SCVars() initSCVars := synchronizer.SCVariables{

@@ -150,16 +151,16 @@ )

// TODO: Get (maxL1UserTxs, maxL1OperatorTxs, maxTxs) from the smart contract txSelector, err := txselector.NewTxSelector(coordCfg.TxSelector.Path, stateDB, l2DB, 10, 10, 10) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // TODO: Get (configCircuits []ConfigCircuit, batchNum common.BatchNum, nLevels uint64) from smart contract nLevels := uint64(32) //nolint:gomnd batchBuilder, err := batchbuilder.NewBatchBuilder(coordCfg.BatchBuilder.Path, stateDB, nil, 0, nLevels) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } serverProofs := make([]coordinator.ServerProofInterface, len(coordCfg.ServerProofs)) for i, serverProofCfg := range coordCfg.ServerProofs {

@@ -180,18 +181,18 @@ &scConsts,

&initSCVars, ) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } } var nodeAPI *NodeAPI if cfg.API.Address != "" { if cfg.API.UpdateMetricsInterval.Duration == 0 { - return nil, fmt.Errorf("invalid cfg.API.UpdateMetricsInterval: %v", - cfg.API.UpdateMetricsInterval.Duration) + return nil, tracerr.Wrap(fmt.Errorf("invalid cfg.API.UpdateMetricsInterval: %v", + cfg.API.UpdateMetricsInterval.Duration)) } if cfg.API.UpdateRecommendedFeeInterval.Duration == 0 { - return nil, fmt.Errorf("invalid cfg.API.UpdateRecommendedFeeInterval: %v", - cfg.API.UpdateRecommendedFeeInterval.Duration) + return nil, tracerr.Wrap(fmt.Errorf("invalid cfg.API.UpdateRecommendedFeeInterval: %v", + cfg.API.UpdateRecommendedFeeInterval.Duration)) } server := gin.Default() coord := false

@@ -213,7 +214,7 @@ WDelayerConstants: scConsts.WDelayer,

}, ) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } nodeAPI.api.SetRollupVariables(initSCVars.Rollup) nodeAPI.api.SetAuctionVariables(initSCVars.Auction)

@@ -273,7 +274,7 @@ l2db,

config, ) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &NodeAPI{ addr: addr,

@@ -295,8 +296,7 @@ MaxHeaderBytes: 1 << 20, //nolint:gomnd

} go func() { log.Infof("NodeAPI is ready at %v", a.addr) - if err := server.ListenAndServe(); err != nil && - err != http.ErrServerClosed { + if err := server.ListenAndServe(); err != nil && tracerr.Unwrap(err) != http.ErrServerClosed { log.Fatalf("Listen: %s\n", err) } }()

@@ -306,7 +306,7 @@ log.Info("Stopping NodeAPI...")

ctxTimeout, cancel := context.WithTimeout(context.Background(), 10*time.Second) //nolint:gomnd defer cancel() if err := server.Shutdown(ctxTimeout); err != nil { - return err + return tracerr.Wrap(err) } log.Info("NodeAPI done") return nil
M priceupdater/priceupdater.go → priceupdater/priceupdater.go

@@ -8,6 +8,7 @@

"github.com/dghubble/sling" "github.com/hermeznetwork/hermez-node/db/historydb" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" ) const (

@@ -66,7 +67,7 @@ // UpdateTokenList get the registered token symbols from HistoryDB

func (p *PriceUpdater) UpdateTokenList() error { tokenSymbols, err := p.db.GetTokenSymbols() if err != nil { - return err + return tracerr.Wrap(err) } p.tokenSymbols = tokenSymbols return nil
M synchronizer/synchronizer.go → synchronizer/synchronizer.go

@@ -14,6 +14,7 @@ "github.com/hermeznetwork/hermez-node/db/historydb"

"github.com/hermeznetwork/hermez-node/db/statedb" "github.com/hermeznetwork/hermez-node/eth" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" ) var (

@@ -122,11 +123,11 @@ }

lastBlock, err := ethClient.EthBlockByNumber(context.TODO(), -1) if err != nil { - return err + return tracerr.Wrap(err) } lastBatch, err := ethClient.RollupLastForgedBatch() if err != nil { - return err + return tracerr.Wrap(err) } s.rw.Lock() s.Eth.Updated = now

@@ -218,17 +219,17 @@ stateDB *statedb.StateDB, cfg Config) (*Synchronizer, error) {

auctionConstants, err := ethClient.AuctionConstants() if err != nil { log.Errorw("NewSynchronizer ethClient.AuctionConstants()", "err", err) - return nil, err + return nil, tracerr.Wrap(err) } rollupConstants, err := ethClient.RollupConstants() if err != nil { log.Errorw("NewSynchronizer ethClient.RollupConstants()", "err", err) - return nil, err + return nil, tracerr.Wrap(err) } wDelayerConstants, err := ethClient.WDelayerConstants() if err != nil { log.Errorw("NewSynchronizer ethClient.WDelayerConstants()", "err", err) - return nil, err + return nil, tracerr.Wrap(err) } // Set startBlockNum to the minimum between Auction, Rollup and

@@ -296,7 +297,7 @@ dbBatchesLen, err := s.historyDB.GetBatchesLen(slotNum)

// fmt.Printf("DBG -1 from: %v, to: %v, len: %v\n", from, to, dbBatchesLen) if err != nil { log.Errorw("historyDB.GetBatchesLen", "err", err) - return err + return tracerr.Wrap(err) } slot.BatchesLen = dbBatchesLen } else if slotNum > slot.SlotNum {

@@ -311,10 +312,10 @@ slot.StartBlock, slot.EndBlock = s.consts.Auction.SlotBlocks(slot.SlotNum)

// If Synced, update the current coordinator if s.stats.Synced() { bidCoord, err := s.historyDB.GetBestBidCoordinator(slot.SlotNum) - if err != nil && err != sql.ErrNoRows { - return err + if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows { + return tracerr.Wrap(err) } - if err == sql.ErrNoRows { + if tracerr.Unwrap(err) == sql.ErrNoRows { slot.BootCoord = true slot.Forger = s.vars.Auction.BootCoordinator slot.URL = "???"

@@ -339,11 +340,11 @@ // TODO: Remove this SANITY CHECK once this code is tested enough

// BEGIN SANITY CHECK canForge, err := s.ethClient.AuctionCanForge(slot.Forger, blockNum) if err != nil { - return err + return tracerr.Wrap(err) } if !canForge { - return fmt.Errorf("Synchronized value of forger address for closed slot "+ - "differs from smart contract: %+v", slot) + return tracerr.Wrap(fmt.Errorf("Synchronized value of forger address for closed slot "+ + "differs from smart contract: %+v", slot)) } // END SANITY CHECK }

@@ -355,24 +356,24 @@ func (s *Synchronizer) init() error {

// Update stats parameters so that they have valid values before the // first Sync call if err := s.stats.UpdateEth(s.ethClient); err != nil { - return err + return tracerr.Wrap(err) } lastBlock := &common.Block{} lastSavedBlock, err := s.historyDB.GetLastBlock() - if err != nil && err != sql.ErrNoRows { - return err + if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows { + return tracerr.Wrap(err) } // If there's no block in the DB (or we only have the default block 0), // make sure that the stateDB is clean - if err == sql.ErrNoRows || lastSavedBlock.Num == 0 { + if tracerr.Unwrap(err) == sql.ErrNoRows || lastSavedBlock.Num == 0 { if err := s.stateDB.Reset(0); err != nil { - return err + return tracerr.Wrap(err) } } else { lastBlock = lastSavedBlock } if err := s.resetState(lastBlock); err != nil { - return err + return tracerr.Wrap(err) } log.Infow("Sync init block",

@@ -401,12 +402,12 @@ if lastSavedBlock == nil {

var err error // Get lastSavedBlock from History DB lastSavedBlock, err = s.historyDB.GetLastBlock() - if err != nil && err != sql.ErrNoRows { - return nil, nil, err + if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows { + return nil, nil, tracerr.Wrap(err) } // If we don't have any stored block, we must do a full sync // starting from the startBlockNum - if err == sql.ErrNoRows || lastSavedBlock.Num == 0 { + if tracerr.Unwrap(err) == sql.ErrNoRows || lastSavedBlock.Num == 0 { nextBlockNum = s.startBlockNum lastSavedBlock = nil }

@@ -416,16 +417,16 @@ nextBlockNum = lastSavedBlock.Num + 1

} ethBlock, err := s.ethClient.EthBlockByNumber(ctx, nextBlockNum) - if err == ethereum.NotFound { + if tracerr.Unwrap(err) == ethereum.NotFound { return nil, nil, nil } else if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } log.Debugf("ethBlock: num: %v, parent: %v, hash: %v", ethBlock.Num, ethBlock.ParentHash.String(), ethBlock.Hash.String()) if err := s.stats.UpdateEth(s.ethClient); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } log.Debugw("Syncing...",

@@ -442,7 +443,7 @@ "blockNum", ethBlock.Num,

"block.parent(got)", ethBlock.ParentHash, "parent.hash(exp)", lastSavedBlock.Hash) lastDBBlockNum, err := s.reorg(lastSavedBlock) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } discarded := lastSavedBlock.Num - lastDBBlockNum return nil, &discarded, nil

@@ -452,19 +453,19 @@

// Get data from the rollup contract rollupData, err := s.rollupSync(ethBlock) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } // Get data from the auction contract auctionData, err := s.auctionSync(ethBlock) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } // Get data from the WithdrawalDelayer contract wDelayerData, err := s.wdelayerSync(ethBlock) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } for i := range rollupData.Withdrawals {

@@ -472,8 +473,8 @@ withdrawal := &rollupData.Withdrawals[i]

if !withdrawal.InstantWithdraw { wDelayerTransfers := wDelayerData.DepositsByTxHash[withdrawal.TxHash] if len(wDelayerTransfers) == 0 { - return nil, nil, fmt.Errorf("WDelayer deposit corresponding to " + - "non-instant rollup withdrawal not found") + return nil, nil, tracerr.Wrap(fmt.Errorf("WDelayer deposit corresponding to " + + "non-instant rollup withdrawal not found")) } // Pop the first wDelayerTransfer to consume them in chronological order wDelayerTransfer := wDelayerTransfers[0]

@@ -500,7 +501,7 @@ // return err

// } err = s.historyDB.AddBlockSCData(&blockData) if err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } batchesLen := len(rollupData.Batches)

@@ -517,7 +518,7 @@ s.stats.UpdateSync(ethBlock,

&rollupData.Batches[batchesLen-1].Batch.BatchNum, lastL1BatchBlock) } if err := s.updateCurrentSlotIfSync(len(rollupData.Batches)); err != nil { - return nil, nil, err + return nil, nil, tracerr.Wrap(err) } log.Debugw("Synced block",

@@ -549,13 +550,13 @@ for blockNum >= s.startBlockNum {

ethBlock, err := s.ethClient.EthBlockByNumber(context.Background(), blockNum) if err != nil { log.Errorw("ethClient.EthBlockByNumber", "err", err) - return 0, err + return 0, tracerr.Wrap(err) } block, err = s.historyDB.GetBlock(blockNum) if err != nil { log.Errorw("historyDB.GetBlock", "err", err) - return 0, err + return 0, tracerr.Wrap(err) } if block.Hash == ethBlock.Hash { log.Debugf("Found valid block: %v", blockNum)

@@ -569,11 +570,11 @@

// Set History DB and State DB to the correct state err := s.historyDB.Reorg(block.Num) if err != nil { - return 0, err + return 0, tracerr.Wrap(err) } if err := s.resetState(block); err != nil { - return 0, err + return 0, tracerr.Wrap(err) } return block.Num, nil

@@ -583,14 +584,14 @@ func (s *Synchronizer) resetState(block *common.Block) error {

rollup, auction, wDelayer, err := s.historyDB.GetSCVars() // If SCVars are not in the HistoryDB, this is probably the first run // of the Synchronizer: store the initial vars taken from config - if err == sql.ErrNoRows { + if tracerr.Unwrap(err) == sql.ErrNoRows { rollup = &s.cfg.InitialVariables.Rollup auction = &s.cfg.InitialVariables.Auction wDelayer = &s.cfg.InitialVariables.WDelayer log.Info("Setting initial SCVars in HistoryDB") if err = s.historyDB.SetInitialSCVars(rollup, auction, wDelayer); err != nil { log.Errorw("historyDB.SetInitialSCVars", "err", err) - return err + return tracerr.Wrap(err) } } s.vars.Rollup = *rollup

@@ -598,33 +599,33 @@ s.vars.Auction = *auction

s.vars.WDelayer = *wDelayer batchNum, err := s.historyDB.GetLastBatchNum() - if err != nil && err != sql.ErrNoRows { + if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows { log.Errorw("historyDB.GetLastBatchNum", "err", err) - return err + return tracerr.Wrap(err) } - if err == sql.ErrNoRows { + if tracerr.Unwrap(err) == sql.ErrNoRows { batchNum = 0 } lastL1BatchBlockNum, err := s.historyDB.GetLastL1BatchBlockNum() - if err != nil && err != sql.ErrNoRows { + if err != nil && tracerr.Unwrap(err) != sql.ErrNoRows { log.Errorw("historyDB.GetLastL1BatchBlockNum", "err", err) - return err + return tracerr.Wrap(err) } - if err == sql.ErrNoRows { + if tracerr.Unwrap(err) == sql.ErrNoRows { lastL1BatchBlockNum = 0 } err = s.stateDB.Reset(batchNum) if err != nil { log.Errorw("stateDB.Reset", "err", err) - return err + return tracerr.Wrap(err) } s.stats.UpdateSync(block, &batchNum, &lastL1BatchBlockNum) // TODO if err := s.updateCurrentSlotIfSync(-1); err != nil { - return err + return tracerr.Wrap(err) } return nil }

@@ -685,7 +686,7 @@ // Get rollup events in the block, and make sure the block hash matches

// the expected one. rollupEvents, blockHash, err := s.ethClient.RollupEventsByBlock(blockNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // No events in this block if blockHash == nil {

@@ -694,13 +695,13 @@ }

if *blockHash != ethBlock.Hash { log.Errorw("Block hash mismatch in Rollup events", "expected", ethBlock.Hash.String(), "got", blockHash.String()) - return nil, eth.ErrBlockHashMismatchEvent + return nil, tracerr.Wrap(eth.ErrBlockHashMismatchEvent) } var nextForgeL1TxsNum int64 // forgeL1TxsNum for the next L1Batch nextForgeL1TxsNumPtr, err := s.historyDB.GetLastL1TxsNum() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if nextForgeL1TxsNumPtr != nil { nextForgeL1TxsNum = *nextForgeL1TxsNumPtr + 1

@@ -711,7 +712,7 @@

// Get L1UserTX rollupData.L1UserTxs, err = getL1UserTx(rollupEvents.L1UserTx, blockNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // Get ForgeBatch events to get the L1CoordinatorTxs

@@ -722,7 +723,7 @@

// Get the input for each Tx forgeBatchArgs, sender, err := s.ethClient.RollupForgeBatchArgs(evtForgeBatch.EthTxHash) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } batchNum := common.BatchNum(evtForgeBatch.BatchNum)

@@ -736,7 +737,7 @@

// First try to find them in HistoryDB. l1UserTxs, err = s.historyDB.GetL1UserTxs(nextForgeL1TxsNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // Apart from the DB, try to find them in this block. // This could happen because in a block there could be

@@ -763,7 +764,7 @@ l1CoordinatorTx.EthBlockNum = blockNum

l1CoordinatorTx.BatchNum = &batchNum l1Tx, err := common.NewL1Tx(&l1CoordinatorTx) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } batchData.L1CoordinatorTxs = append(batchData.L1CoordinatorTxs, *l1Tx)

@@ -787,7 +788,7 @@ }

processTxsOut, err := s.stateDB.ProcessTxs(ptc, forgeBatchArgs.FeeIdxCoordinator, l1UserTxs, batchData.L1CoordinatorTxs, poolL2Txs) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // Set batchNum in exits

@@ -799,7 +800,7 @@ batchData.ExitTree = processTxsOut.ExitInfos

l2Txs, err := common.PoolL2TxsToL2Txs(poolL2Txs) // NOTE: This is a big uggly, find a better way if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } for i := range l2Txs {

@@ -809,7 +810,7 @@ tx.EthBlockNum = blockNum

tx.BatchNum = batchNum nTx, err := common.NewL2Tx(tx) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } batchData.L2Txs = append(batchData.L2Txs, *nTx)

@@ -923,7 +924,7 @@

// Get auction events in the block auctionEvents, blockHash, err := s.ethClient.AuctionEventsByBlock(blockNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // No events in this block if blockHash == nil {

@@ -932,7 +933,7 @@ }

if *blockHash != ethBlock.Hash { log.Errorw("Block hash mismatch in Auction events", "expected", ethBlock.Hash.String(), "got", blockHash.String()) - return nil, eth.ErrBlockHashMismatchEvent + return nil, tracerr.Wrap(eth.ErrBlockHashMismatchEvent) } // Get bids

@@ -988,8 +989,8 @@ varsUpdate = true

} for _, evt := range auctionEvents.NewDefaultSlotSetBid { if evt.SlotSet > 6 { //nolint:gomnd - return nil, fmt.Errorf("unexpected SlotSet in "+ - "auctionEvents.NewDefaultSlotSetBid: %v", evt.SlotSet) + return nil, tracerr.Wrap(fmt.Errorf("unexpected SlotSet in "+ + "auctionEvents.NewDefaultSlotSetBid: %v", evt.SlotSet)) } s.vars.Auction.DefaultSlotSetBid[evt.SlotSet] = evt.NewInitialMinBid s.vars.Auction.DefaultSlotSetBidSlotNum = s.consts.Auction.SlotNum(blockNum) +

@@ -1017,7 +1018,7 @@

// Get wDelayer events in the block wDelayerEvents, blockHash, err := s.ethClient.WDelayerEventsByBlock(blockNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // No events in this block if blockHash == nil {

@@ -1026,7 +1027,7 @@ }

if *blockHash != ethBlock.Hash { log.Errorw("Block hash mismatch in WDelayer events", "expected", ethBlock.Hash.String(), "got", blockHash.String()) - return nil, eth.ErrBlockHashMismatchEvent + return nil, tracerr.Wrap(eth.ErrBlockHashMismatchEvent) } for _, evt := range wDelayerEvents.Deposit {

@@ -1086,7 +1087,7 @@ eventsL1UserTx[i].L1UserTx.EthBlockNum = blockNum

// Check validity of L1UserTx l1Tx, err := common.NewL1Tx(&eventsL1UserTx[i].L1UserTx) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } l1Txs[i] = *l1Tx }
M test/debugapi/debugapi.go → test/debugapi/debugapi.go

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

"github.com/hermeznetwork/hermez-node/db/statedb" "github.com/hermeznetwork/hermez-node/log" "github.com/hermeznetwork/hermez-node/synchronizer" + "github.com/hermeznetwork/tracerr" ) func handleNoRoute(c *gin.Context) {

@@ -118,8 +119,7 @@ MaxHeaderBytes: 1 << 20, //nolint:gomnd

} go func() { log.Infof("DebugAPI is ready at %v", a.addr) - if err := debugAPIServer.ListenAndServe(); err != nil && - err != http.ErrServerClosed { + if err := debugAPIServer.ListenAndServe(); err != nil && tracerr.Unwrap(err) != http.ErrServerClosed { log.Fatalf("Listen: %s\n", err) } }()

@@ -129,7 +129,7 @@ log.Info("Stopping DebugAPI...")

ctxTimeout, cancel := context.WithTimeout(context.Background(), 10*time.Second) //nolint:gomnd defer cancel() if err := debugAPIServer.Shutdown(ctxTimeout); err != nil { - return err + return tracerr.Wrap(err) } log.Info("DebugAPI done") return nil
M test/ethclient.go → test/ethclient.go

@@ -16,6 +16,7 @@ "github.com/ethereum/go-ethereum/core/types"

"github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/eth" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/mitchellh/copystructure" )

@@ -111,7 +112,7 @@ }

func (a *AuctionBlock) getMinBidBySlot(slot int64) (*big.Int, error) { if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) { - return nil, errBidClosed + return nil, tracerr.Wrap(errBidClosed) } slotSet := a.getSlotSet(slot)

@@ -140,9 +141,9 @@ }

func (a *AuctionBlock) forge(forger ethCommon.Address) error { if ok, err := a.canForge(forger, a.Eth.BlockNum); err != nil { - return err + return tracerr.Wrap(err) } else if !ok { - return fmt.Errorf("Can't forge") + return tracerr.Wrap(fmt.Errorf("Can't forge")) } slotToForge := a.getSlotNumber(a.Eth.BlockNum)

@@ -162,7 +163,7 @@ }

func (a *AuctionBlock) canForge(forger ethCommon.Address, blockNum int64) (bool, error) { if blockNum < a.Constants.GenesisBlockNum { - return false, fmt.Errorf("Auction has not started yet") + return false, tracerr.Wrap(fmt.Errorf("Auction has not started yet")) } slotToForge := a.getSlotNumber(blockNum)

@@ -616,7 +617,7 @@ e := currentBlock.Eth

if constants, ok := e.Tokens[tokenAddr]; ok { return &constants, nil } - return nil, fmt.Errorf("tokenAddr not found") + return nil, tracerr.Wrap(fmt.Errorf("tokenAddr not found")) } // func newHeader(number *big.Int) *types.Header {

@@ -656,7 +657,7 @@

// EthAddress returns the ethereum address of the account loaded into the Client func (c *Client) EthAddress() (*ethCommon.Address, error) { if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } return c.addr, nil }

@@ -697,7 +698,7 @@

// RollupL1UserTxERC20Permit is the interface to call the smart contract function func (c *Client) RollupL1UserTxERC20Permit(fromBJJ *babyjub.PublicKey, fromIdx int64, loadAmount *big.Int, amount *big.Int, tokenID uint32, toIdx int64, deadline *big.Int) (tx *types.Transaction, err error) { log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // RollupL1UserTxERC20ETH sends an L1UserTx to the Rollup.

@@ -716,11 +717,11 @@ defer func() { c.revertIfErr(err, cpy) }()

_, err = common.NewFloat16(amount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } _, err = common.NewFloat16(loadAmount) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } nextBlock := c.nextBlock()

@@ -751,7 +752,7 @@ Position: len(queue.L1TxQueue),

UserOrigin: true, }) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } queue.L1TxQueue = append(queue.L1TxQueue, *l1Tx)

@@ -770,7 +771,7 @@

// RollupRegisterTokensCount is the interface to call the smart contract function func (c *Client) RollupRegisterTokensCount() (*big.Int, error) { log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // RollupLastForgedBatch is the interface to call the smart contract function

@@ -786,7 +787,7 @@

// RollupWithdrawCircuit is the interface to call the smart contract function func (c *Client) RollupWithdrawCircuit(proofA, proofC [2]*big.Int, proofB [2][2]*big.Int, tokenID uint32, numExitRoot, idx int64, amount *big.Int, instantWithdraw bool) (*types.Transaction, error) { log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // RollupWithdrawMerkleProof is the interface to call the smart contract function

@@ -800,10 +801,10 @@ nextBlock := c.nextBlock()

r := nextBlock.Rollup if int(numExitRoot) >= len(r.State.ExitRoots) { - return nil, fmt.Errorf("numExitRoot >= len(r.State.ExitRoots)") + return nil, tracerr.Wrap(fmt.Errorf("numExitRoot >= len(r.State.ExitRoots)")) } if _, ok := r.State.ExitNullifierMap[numExitRoot][idx]; ok { - return nil, fmt.Errorf("exit already withdrawn") + return nil, tracerr.Wrap(fmt.Errorf("exit already withdrawn")) } r.State.ExitNullifierMap[numExitRoot][idx] = true

@@ -860,16 +861,16 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } a := c.nextBlock().Auction ok, err := a.canForge(*c.addr, a.Eth.BlockNum) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if !ok { - return nil, fmt.Errorf("incorrect slot") + return nil, tracerr.Wrap(fmt.Errorf("incorrect slot")) } // TODO: Verify proof

@@ -877,7 +878,7 @@

// Auction err = a.forge(*c.addr) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } // TODO: If successful, store the tx in a successful array.

@@ -902,7 +903,7 @@ nextBlock := c.nextBlock()

r := nextBlock.Rollup r.State.StateRoot = args.NewStRoot if args.NewLastIdx < r.State.CurrentIdx { - return nil, fmt.Errorf("args.NewLastIdx < r.State.CurrentIdx") + return nil, tracerr.Wrap(fmt.Errorf("args.NewLastIdx < r.State.CurrentIdx")) } r.State.CurrentIdx = args.NewLastIdx r.State.ExitNullifierMap[int64(len(r.State.ExitRoots))] = make(map[int64]bool)

@@ -938,16 +939,16 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } nextBlock := c.nextBlock() r := nextBlock.Rollup if _, ok := r.State.TokenMap[tokenAddress]; ok { - return nil, fmt.Errorf("Token %v already registered", tokenAddress) + return nil, tracerr.Wrap(fmt.Errorf("Token %v already registered", tokenAddress)) } if feeAddToken.Cmp(r.Vars.FeeAddToken) != 0 { - return nil, fmt.Errorf("Expected fee: %v but got: %v", r.Vars.FeeAddToken, feeAddToken) + return nil, tracerr.Wrap(fmt.Errorf("Expected fee: %v but got: %v", r.Vars.FeeAddToken, feeAddToken)) } r.State.TokenMap[tokenAddress] = true

@@ -963,7 +964,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // RollupUpdateForgeL1L2BatchTimeout is the interface to call the smart contract function

@@ -973,7 +974,7 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } nextBlock := c.nextBlock()

@@ -992,11 +993,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // RollupUpdateTokensHEZ is the interface to call the smart contract function

@@ -1030,7 +1031,7 @@ defer c.rw.RUnlock()

block, ok := c.blocks[blockNum] if !ok { - return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum) + return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum)) } return &block.Rollup.Events, &block.Eth.Hash, nil }

@@ -1042,7 +1043,7 @@ defer c.rw.RUnlock()

batch, ok := c.forgeBatchArgs[ethTxHash] if !ok { - return nil, nil, fmt.Errorf("transaction not found") + return nil, nil, tracerr.Wrap(fmt.Errorf("transaction not found")) } return &batch.ForgeBatchArgs, &batch.Sender, nil }

@@ -1058,11 +1059,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetSlotDeadline is the interface to call the smart contract function

@@ -1071,7 +1072,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return 0, errTODO + return 0, tracerr.Wrap(errTODO) } // AuctionSetOpenAuctionSlots is the interface to call the smart contract function

@@ -1081,7 +1082,7 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } nextBlock := c.nextBlock()

@@ -1099,7 +1100,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return 0, errTODO + return 0, tracerr.Wrap(errTODO) } // AuctionSetClosedAuctionSlots is the interface to call the smart contract function

@@ -1109,11 +1110,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetClosedAuctionSlots is the interface to call the smart contract function

@@ -1122,7 +1123,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return 0, errTODO + return 0, tracerr.Wrap(errTODO) } // AuctionSetOutbidding is the interface to call the smart contract function

@@ -1132,11 +1133,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetOutbidding is the interface to call the smart contract function

@@ -1145,7 +1146,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return 0, errTODO + return 0, tracerr.Wrap(errTODO) } // AuctionSetAllocationRatio is the interface to call the smart contract function

@@ -1155,11 +1156,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetAllocationRatio is the interface to call the smart contract function

@@ -1168,7 +1169,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return [3]uint16{}, errTODO + return [3]uint16{}, tracerr.Wrap(errTODO) } // AuctionSetDonationAddress is the interface to call the smart contract function

@@ -1178,11 +1179,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetDonationAddress is the interface to call the smart contract function

@@ -1191,7 +1192,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionSetBootCoordinator is the interface to call the smart contract function

@@ -1201,11 +1202,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetBootCoordinator is the interface to call the smart contract function

@@ -1226,11 +1227,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionSetCoordinator is the interface to call the smart contract function

@@ -1240,7 +1241,7 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } nextBlock := c.nextBlock()

@@ -1272,7 +1273,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return false, errTODO + return false, tracerr.Wrap(errTODO) } // AuctionUpdateCoordinatorInfo is the interface to call the smart contract function

@@ -1282,11 +1283,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetSlotNumber is the interface to call the smart contract function

@@ -1305,7 +1306,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return 0, errTODO + return 0, tracerr.Wrap(errTODO) } // AuctionGetMinBidBySlot is the interface to call the smart contract function

@@ -1314,7 +1315,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetDefaultSlotSetBid is the interface to call the smart contract function

@@ -1323,7 +1324,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetSlotSet is the interface to call the smart contract function

@@ -1332,7 +1333,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionTokensReceived is the interface to call the smart contract function

@@ -1354,30 +1355,30 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { func() { c.revertIfErr(err, cpy) }() }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } nextBlock := c.nextBlock() a := nextBlock.Auction if slot < a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots) { - return nil, errBidClosed + return nil, tracerr.Wrap(errBidClosed) } if slot >= a.getCurrentSlotNumber()+int64(a.Vars.ClosedAuctionSlots)+int64(a.Vars.OpenAuctionSlots) { - return nil, errBidNotOpen + return nil, tracerr.Wrap(errBidNotOpen) } minBid, err := a.getMinBidBySlot(slot) if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if bidAmount.Cmp(minBid) == -1 { - return nil, errBidBelowMin + return nil, tracerr.Wrap(errBidBelowMin) } if _, ok := a.State.Coordinators[*c.addr]; !ok { - return nil, errCoordNotReg + return nil, tracerr.Wrap(errCoordNotReg) } slotState, ok := a.State.Slots[slot]

@@ -1408,11 +1409,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionCanForge is the interface to call the smart contract function

@@ -1432,11 +1433,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionClaimHEZ is the interface to call the smart contract function

@@ -1446,11 +1447,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionGetClaimableHEZ is the interface to call the smart contract function

@@ -1459,7 +1460,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // AuctionConstants returns the Constants of the Auction Smart Contract

@@ -1477,7 +1478,7 @@ defer c.rw.RUnlock()

block, ok := c.blocks[blockNum] if !ok { - return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum) + return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum)) } return &block.Auction.Events, &block.Eth.Hash, nil }

@@ -1492,7 +1493,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerSetHermezGovernanceDAOAddress is the interface to call the smart contract function

@@ -1502,11 +1503,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerGetHermezKeeperAddress is the interface to call the smart contract function

@@ -1515,7 +1516,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerSetHermezKeeperAddress is the interface to call the smart contract function

@@ -1525,11 +1526,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerGetWhiteHackGroupAddress is the interface to call the smart contract function

@@ -1538,7 +1539,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerSetWhiteHackGroupAddress is the interface to call the smart contract function

@@ -1548,11 +1549,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerIsEmergencyMode is the interface to call the smart contract function

@@ -1561,7 +1562,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return false, errTODO + return false, tracerr.Wrap(errTODO) } // WDelayerGetWithdrawalDelay is the interface to call the smart contract function

@@ -1570,7 +1571,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerGetEmergencyModeStartingTime is the interface to call the smart contract function

@@ -1579,7 +1580,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerEnableEmergencyMode is the interface to call the smart contract function

@@ -1589,11 +1590,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerChangeWithdrawalDelay is the interface to call the smart contract function

@@ -1603,7 +1604,7 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } nextBlock := c.nextBlock()

@@ -1621,7 +1622,7 @@ c.rw.RLock()

defer c.rw.RUnlock() log.Error("TODO") - return eth.DepositState{}, errTODO + return eth.DepositState{}, tracerr.Wrap(errTODO) } // WDelayerDeposit is the interface to call the smart contract function

@@ -1631,11 +1632,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerWithdrawal is the interface to call the smart contract function

@@ -1645,11 +1646,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerEscapeHatchWithdrawal is the interface to call the smart contract function

@@ -1659,11 +1660,11 @@ defer c.rw.Unlock()

cpy := c.nextBlock().copy() defer func() { c.revertIfErr(err, cpy) }() if c.addr == nil { - return nil, eth.ErrAccountNil + return nil, tracerr.Wrap(eth.ErrAccountNil) } log.Error("TODO") - return nil, errTODO + return nil, tracerr.Wrap(errTODO) } // WDelayerEventsByBlock returns the events in a block that happened in the WDelayer Contract

@@ -1673,7 +1674,7 @@ defer c.rw.RUnlock()

block, ok := c.blocks[blockNum] if !ok { - return nil, nil, fmt.Errorf("Block %v doesn't exist", blockNum) + return nil, nil, tracerr.Wrap(fmt.Errorf("Block %v doesn't exist", blockNum)) } return &block.WDelayer.Events, &block.Eth.Hash, nil }
M test/ethclient_test.go → test/ethclient_test.go

@@ -12,6 +12,7 @@ ethCommon "github.com/ethereum/go-ethereum/common"

ethCrypto "github.com/ethereum/go-ethereum/crypto" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/eth" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"

@@ -95,20 +96,20 @@

// Check several cases in which bid doesn't succed, and also do 2 successful bids. _, err := c.AuctionBidSimple(0, big.NewInt(1)) - assert.Equal(t, errBidClosed, err) + assert.Equal(t, errBidClosed, tracerr.Unwrap(err)) _, err = c.AuctionBidSimple(4322, big.NewInt(1)) - assert.Equal(t, errBidNotOpen, err) + assert.Equal(t, errBidNotOpen, tracerr.Unwrap(err)) // 101 % 6 = 5; defaultSlotSetBid[5] = 1500; 1500 + 10% = 1650 _, err = c.AuctionBidSimple(101, big.NewInt(1650)) - assert.Equal(t, errCoordNotReg, err) + assert.Equal(t, errCoordNotReg, tracerr.Unwrap(err)) _, err = c.AuctionSetCoordinator(addrForge, "https://foo.bar") assert.Nil(t, err) _, err = c.AuctionBidSimple(3, big.NewInt(1)) - assert.Equal(t, errBidBelowMin, err) + assert.Equal(t, errBidBelowMin, tracerr.Unwrap(err)) _, err = c.AuctionBidSimple(3, big.NewInt(1650)) assert.Nil(t, err)

@@ -118,7 +119,7 @@ _, err = c.AuctionSetCoordinator(addrForge2, "https://foo2.bar")

assert.Nil(t, err) _, err = c.AuctionBidSimple(3, big.NewInt(16)) - assert.Equal(t, errBidBelowMin, err) + assert.Equal(t, errBidBelowMin, tracerr.Unwrap(err)) // 1650 + 10% = 1815 _, err = c.AuctionBidSimple(3, big.NewInt(1815))
M test/historydb.go → test/historydb.go

@@ -8,6 +8,7 @@ "time"

ethCommon "github.com/ethereum/go-ethereum/common" "github.com/hermeznetwork/hermez-node/common" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" "github.com/iden3/go-merkletree" )

@@ -425,7 +426,7 @@ }

i++ i = i % len(accs) if i == firstI { - return &acc, errors.New("Didnt found any account matchinng the criteria") + return &acc, tracerr.Wrap(errors.New("Didnt found any account matchinng the criteria")) } } }
M test/til/lang.go → test/til/lang.go

@@ -11,6 +11,7 @@ "strconv"

"github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" ) var eof = rune(0)

@@ -272,7 +273,7 @@ func (p *parser) parseLine(setType setType) (*instruction, error) {

c := &instruction{} tok, lit := p.scanIgnoreWhitespace() if tok == EOF { - return nil, errof + return nil, tracerr.Wrap(errof) } c.literal += lit if lit == "/" {

@@ -280,7 +281,7 @@ _, _ = p.s.r.ReadString('\n')

return nil, commentLine } else if lit == ">" { if setType == setTypePoolL2 { - return c, fmt.Errorf("Unexpected '>' at PoolL2Txs set") + return c, tracerr.Wrap(fmt.Errorf("Unexpected '>' at PoolL2Txs set")) } _, lit = p.scanIgnoreWhitespace() if lit == "batch" {

@@ -293,11 +294,11 @@ } else if lit == "block" {

_, _ = p.s.r.ReadString('\n') return &instruction{typ: typeNewBlock}, newEventLine } else { - return c, fmt.Errorf("Unexpected '> %s', expected '> batch' or '> block'", lit) + return c, tracerr.Wrap(fmt.Errorf("Unexpected '> %s', expected '> batch' or '> block'", lit)) } } else if lit == "Type" { if err := p.expectChar(c, ":"); err != nil { - return c, err + return c, tracerr.Wrap(err) } _, lit = p.scanIgnoreWhitespace() if lit == "Blockchain" {

@@ -305,11 +306,11 @@ return &instruction{typ: "Blockchain"}, setTypeLine

} else if lit == "PoolL2" { return &instruction{typ: "PoolL2"}, setTypeLine } else { - return c, fmt.Errorf("Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", lit) + return c, tracerr.Wrap(fmt.Errorf("Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", lit)) } } else if lit == "AddToken" { if err := p.expectChar(c, "("); err != nil { - return c, err + return c, tracerr.Wrap(err) } _, lit = p.scanIgnoreWhitespace() c.literal += lit

@@ -317,11 +318,11 @@ tidI, err := strconv.Atoi(lit)

if err != nil { line, _ := p.s.r.ReadString('\n') c.literal += line - return c, err + return c, tracerr.Wrap(err) } c.tokenID = common.TokenID(tidI) if err := p.expectChar(c, ")"); err != nil { - return c, err + return c, tracerr.Wrap(err) } c.typ = typeAddToken line, _ := p.s.r.ReadString('\n')

@@ -330,7 +331,7 @@ return c, newEventLine

} if setType == "" { - return c, fmt.Errorf("Set type not defined") + return c, tracerr.Wrap(fmt.Errorf("Set type not defined")) } transferring := false fee := false

@@ -363,7 +364,7 @@ transferring = true

case "ForceExit": c.typ = common.TxTypeForceExit default: - return c, fmt.Errorf("Unexpected Blockchain tx type: %s", lit) + return c, tracerr.Wrap(fmt.Errorf("Unexpected Blockchain tx type: %s", lit)) } } else if setType == setTypePoolL2 { switch lit {

@@ -383,14 +384,14 @@ case "PoolExit":

c.typ = common.TxTypeExit fee = true default: - return c, fmt.Errorf("Unexpected PoolL2 tx type: %s", lit) + return c, tracerr.Wrap(fmt.Errorf("Unexpected PoolL2 tx type: %s", lit)) } } else { - return c, fmt.Errorf("Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", setType) + return c, tracerr.Wrap(fmt.Errorf("Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", setType)) } if err := p.expectChar(c, "("); err != nil { - return c, err + return c, tracerr.Wrap(err) } _, lit = p.scanIgnoreWhitespace() c.literal += lit

@@ -398,11 +399,11 @@ tidI, err := strconv.Atoi(lit)

if err != nil { line, _ := p.s.r.ReadString('\n') c.literal += line - return c, err + return c, tracerr.Wrap(err) } c.tokenID = common.TokenID(tidI) if err := p.expectChar(c, ")"); err != nil { - return c, err + return c, tracerr.Wrap(err) } _, lit = p.scanIgnoreWhitespace() c.literal += lit

@@ -416,7 +417,7 @@ _, lit = p.scanIgnoreWhitespace()

c.literal += lit if transferring { if lit != "-" { - return c, fmt.Errorf("Expected '-', found '%s'", lit) + return c, tracerr.Wrap(fmt.Errorf("Expected '-', found '%s'", lit)) } _, lit = p.scanIgnoreWhitespace() c.literal += lit

@@ -427,7 +428,7 @@ }

if lit != ":" { line, _ := p.s.r.ReadString('\n') c.literal += line - return c, fmt.Errorf("Expected ':', found '%s'", lit) + return c, tracerr.Wrap(fmt.Errorf("Expected ':', found '%s'", lit)) } if c.typ == common.TxTypeDepositTransfer || c.typ == common.TxTypeCreateAccountDepositTransfer {

@@ -438,11 +439,11 @@ loadAmount, ok := new(big.Int).SetString(lit, 10)

if !ok { line, _ := p.s.r.ReadString('\n') c.literal += line - return c, fmt.Errorf("Can not parse number for LoadAmount") + return c, tracerr.Wrap(fmt.Errorf("Can not parse number for LoadAmount")) } c.loadAmount = loadAmount if err := p.expectChar(c, ","); err != nil { - return c, err + return c, tracerr.Wrap(err) } } _, lit = p.scanIgnoreWhitespace()

@@ -451,7 +452,7 @@ amount, ok := new(big.Int).SetString(lit, 10)

if !ok { line, _ := p.s.r.ReadString('\n') c.literal += line - return c, fmt.Errorf("Can not parse number for Amount: %s", lit) + return c, tracerr.Wrap(fmt.Errorf("Can not parse number for Amount: %s", lit)) } if c.typ == common.TxTypeDeposit || c.typ == common.TxTypeCreateAccountDeposit {

@@ -461,7 +462,7 @@ c.amount = amount

} if fee { if err := p.expectChar(c, "("); err != nil { - return c, err + return c, tracerr.Wrap(err) } _, lit = p.scanIgnoreWhitespace() c.literal += lit

@@ -469,22 +470,22 @@ fee, err := strconv.Atoi(lit)

if err != nil { line, _ := p.s.r.ReadString('\n') c.literal += line - return c, err + return c, tracerr.Wrap(err) } if fee > common.MaxFeePlan-1 { line, _ := p.s.r.ReadString('\n') c.literal += line - return c, fmt.Errorf("Fee %d can not be bigger than 255", fee) + return c, tracerr.Wrap(fmt.Errorf("Fee %d can not be bigger than 255", fee)) } c.fee = uint8(fee) if err := p.expectChar(c, ")"); err != nil { - return c, err + return c, tracerr.Wrap(err) } } if tok == EOF { - return nil, errof + return nil, tracerr.Wrap(errof) } return c, nil }

@@ -495,7 +496,7 @@ c.literal += lit

if lit != ch { line, _ := p.s.r.ReadString('\n') c.literal += line - return fmt.Errorf("Expected '%s', found '%s'", ch, lit) + return tracerr.Wrap(fmt.Errorf("Expected '%s', found '%s'", ch, lit)) } return nil }

@@ -512,12 +513,12 @@ users := make(map[string]bool)

for { i++ instruction, err := p.parseLine(ps.typ) - if err == errof { + if tracerr.Unwrap(err) == errof { break } - if err == setTypeLine { + if tracerr.Unwrap(err) == setTypeLine { if ps.typ != "" { - return ps, fmt.Errorf("Line %d: Instruction of 'Type: %s' when there is already a previous instruction 'Type: %s' defined", i, instruction.typ, ps.typ) + return ps, tracerr.Wrap(fmt.Errorf("Line %d: Instruction of 'Type: %s' when there is already a previous instruction 'Type: %s' defined", i, instruction.typ, ps.typ)) } if instruction.typ == "PoolL2" { ps.typ = setTypePoolL2

@@ -528,22 +529,22 @@ log.Fatalf("Line %d: Invalid set type: '%s'. Valid set types: 'Blockchain', 'PoolL2'", i, instruction.typ)

} continue } - if err == commentLine { + if tracerr.Unwrap(err) == commentLine { continue } instruction.lineNum = i - if err == newEventLine { + if tracerr.Unwrap(err) == newEventLine { if instruction.typ == typeAddToken && instruction.tokenID == common.TokenID(0) { - return ps, fmt.Errorf("Line %d: AddToken can not register TokenID 0", i) + return ps, tracerr.Wrap(fmt.Errorf("Line %d: AddToken can not register TokenID 0", i)) } ps.instructions = append(ps.instructions, *instruction) continue } if err != nil { - return ps, fmt.Errorf("Line %d: %s, err: %s", i, instruction.literal, err.Error()) + return ps, tracerr.Wrap(fmt.Errorf("Line %d: %s, err: %s", i, instruction.literal, err.Error())) } if ps.typ == "" { - return ps, fmt.Errorf("Line %d: Set type not defined", i) + return ps, tracerr.Wrap(fmt.Errorf("Line %d: Set type not defined", i)) } ps.instructions = append(ps.instructions, *instruction) users[instruction.from] = true
M test/til/txs.go → test/til/txs.go

@@ -12,6 +12,7 @@ ethCommon "github.com/ethereum/go-ethereum/common"

ethCrypto "github.com/ethereum/go-ethereum/crypto" "github.com/hermeznetwork/hermez-node/common" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -151,10 +152,10 @@ func (tc *Context) GenerateBlocks(set string) ([]common.BlockData, error) {

parser := newParser(strings.NewReader(set)) parsedSet, err := parser.parse() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if parsedSet.typ != setTypeBlockchain { - return nil, fmt.Errorf("Expected set type: %s, found: %s", setTypeBlockchain, parsedSet.typ) + return nil, tracerr.Wrap(fmt.Errorf("Expected set type: %s, found: %s", setTypeBlockchain, parsedSet.typ)) } tc.Instructions = parsedSet.instructions

@@ -168,7 +169,7 @@ switch inst.typ {

case txTypeCreateAccountDepositCoordinator: // tx source: L1CoordinatorTx if err := tc.checkIfTokenIsRegistered(inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx := common.L1Tx{ FromEthAddr: tc.Users[inst.from].Addr,

@@ -188,7 +189,7 @@ tc.currBatchTest.l1CoordinatorTxs = append(tc.currBatchTest.l1CoordinatorTxs, testTx)

case common.TxTypeCreateAccountDeposit, common.TxTypeCreateAccountDepositTransfer: // tx source: L1UserTx if err := tc.checkIfTokenIsRegistered(inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx := common.L1Tx{ FromEthAddr: tc.Users[inst.from].Addr,

@@ -208,16 +209,16 @@ toIdxName: inst.to,

L1Tx: tx, } if err := tc.addToL1UserQueue(testTx); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } case common.TxTypeDeposit, common.TxTypeDepositTransfer: // tx source: L1UserTx if err := tc.checkIfTokenIsRegistered(inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } if err := tc.checkIfAccountExists(inst.from, inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx := common.L1Tx{ TokenID: inst.tokenID,

@@ -235,12 +236,12 @@ toIdxName: inst.to,

L1Tx: tx, } if err := tc.addToL1UserQueue(testTx); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } case common.TxTypeTransfer: // L2Tx if err := tc.checkIfTokenIsRegistered(inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx := common.L2Tx{ Amount: inst.amount,

@@ -260,7 +261,7 @@ tc.currBatchTest.l2Txs = append(tc.currBatchTest.l2Txs, testTx)

case common.TxTypeForceTransfer: // tx source: L1UserTx if err := tc.checkIfTokenIsRegistered(inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx := common.L1Tx{ TokenID: inst.tokenID,

@@ -275,12 +276,12 @@ toIdxName: inst.to,

L1Tx: tx, } if err := tc.addToL1UserQueue(testTx); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } case common.TxTypeExit: // tx source: L2Tx if err := tc.checkIfTokenIsRegistered(inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx := common.L2Tx{ ToIdx: common.Idx(1), // as is an Exit

@@ -301,7 +302,7 @@ tc.currBatchTest.l2Txs = append(tc.currBatchTest.l2Txs, testTx)

case common.TxTypeForceExit: // tx source: L1UserTx if err := tc.checkIfTokenIsRegistered(inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx := common.L1Tx{ ToIdx: common.Idx(1), // as is an Exit

@@ -317,28 +318,28 @@ toIdxName: inst.to,

L1Tx: tx, } if err := tc.addToL1UserQueue(testTx); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } case typeNewBatch: if err = tc.calculateIdxForL1Txs(true, tc.currBatchTest.l1CoordinatorTxs); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if err = tc.setIdxs(); err != nil { log.Error(err) - return nil, err + return nil, tracerr.Wrap(err) } case typeNewBatchL1: // for each L1UserTx of the Queues[ToForgeNum], calculate the Idx if err = tc.calculateIdxForL1Txs(false, tc.Queues[tc.ToForgeNum]); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if err = tc.calculateIdxForL1Txs(true, tc.currBatchTest.l1CoordinatorTxs); err != nil { - return nil, err + return nil, tracerr.Wrap(err) } tc.currBatch.L1Batch = true if err = tc.setIdxs(); err != nil { log.Error(err) - return nil, err + return nil, tracerr.Wrap(err) } toForgeL1TxsNum := int64(tc.openToForge) tc.currBatch.Batch.ForgeL1TxsNum = &toForgeL1TxsNum

@@ -363,12 +364,12 @@ TokenID: inst.tokenID,

EthBlockNum: tc.blockNum, } if inst.tokenID != tc.LastRegisteredTokenID+1 { - return nil, fmt.Errorf("Line %d: AddToken TokenID should be sequential, expected TokenID: %d, defined TokenID: %d", inst.lineNum, tc.LastRegisteredTokenID+1, inst.tokenID) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: AddToken TokenID should be sequential, expected TokenID: %d, defined TokenID: %d", inst.lineNum, tc.LastRegisteredTokenID+1, inst.tokenID)) } tc.LastRegisteredTokenID++ tc.currBlock.Rollup.AddedTokens = append(tc.currBlock.Rollup.AddedTokens, newToken) default: - return nil, fmt.Errorf("Line %d: Unexpected type: %s", inst.lineNum, inst.typ) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: Unexpected type: %s", inst.lineNum, inst.typ)) } }

@@ -383,7 +384,7 @@ for i := 0; i < len(txs); i++ {

tx := txs[i] if tx.L1Tx.Type == common.TxTypeCreateAccountDeposit || tx.L1Tx.Type == common.TxTypeCreateAccountDepositTransfer { if tc.Users[tx.fromIdxName].Accounts[tx.L1Tx.TokenID] != nil { // if account already exists, return error - return fmt.Errorf("Can not create same account twice (same User (%s) & same TokenID (%d)) (this is a design property of Til)", tx.fromIdxName, tx.L1Tx.TokenID) + return tracerr.Wrap(fmt.Errorf("Can not create same account twice (same User (%s) & same TokenID (%d)) (this is a design property of Til)", tx.fromIdxName, tx.L1Tx.TokenID)) } tc.Users[tx.fromIdxName].Accounts[tx.L1Tx.TokenID] = &Account{ Idx: common.Idx(tc.idx),

@@ -410,11 +411,11 @@ for i := 0; i < len(tc.currBatchTest.l2Txs); i++ {

testTx := &tc.currBatchTest.l2Txs[i] if tc.Users[testTx.fromIdxName].Accounts[testTx.tokenID] == nil { - return fmt.Errorf("Line %d: %s from User %s for TokenID %d while account not created yet", testTx.lineNum, testTx.L2Tx.Type, testTx.fromIdxName, testTx.tokenID) + return tracerr.Wrap(fmt.Errorf("Line %d: %s from User %s for TokenID %d while account not created yet", testTx.lineNum, testTx.L2Tx.Type, testTx.fromIdxName, testTx.tokenID)) } if testTx.L2Tx.Type == common.TxTypeTransfer { if _, ok := tc.l1CreatedAccounts[idxTokenIDToString(testTx.toIdxName, testTx.tokenID)]; !ok { - return fmt.Errorf("Line %d: Can not create Transfer for a non existing account. Batch %d, ToIdx name: %s, TokenID: %d", testTx.lineNum, tc.currBatchNum, testTx.toIdxName, testTx.tokenID) + return tracerr.Wrap(fmt.Errorf("Line %d: Can not create Transfer for a non existing account. Batch %d, ToIdx name: %s, TokenID: %d", testTx.lineNum, tc.currBatchNum, testTx.toIdxName, testTx.tokenID)) } } tc.Users[testTx.fromIdxName].Accounts[testTx.tokenID].Nonce++

@@ -433,7 +434,7 @@ // GenerateBlocks main switch inside TxTypeExit case

nTx, err := common.NewL2Tx(&testTx.L2Tx) if err != nil { - return fmt.Errorf("Line %d: %s", testTx.lineNum, err.Error()) + return tracerr.Wrap(fmt.Errorf("Line %d: %s", testTx.lineNum, err.Error())) } testTx.L2Tx = *nTx

@@ -476,8 +477,8 @@ tx.L1Tx.ToIdx = common.Idx(0)

} else { account, ok := tc.Users[tx.toIdxName].Accounts[tx.L1Tx.TokenID] if !ok { - return fmt.Errorf("Line %d: Transfer to User: %s, for TokenID: %d, "+ - "while account not created yet", tx.lineNum, tx.toIdxName, tx.L1Tx.TokenID) + return tracerr.Wrap(fmt.Errorf("Line %d: Transfer to User: %s, for TokenID: %d, "+ + "while account not created yet", tx.lineNum, tx.toIdxName, tx.L1Tx.TokenID)) } tx.L1Tx.ToIdx = account.Idx }

@@ -486,7 +487,7 @@ tx.L1Tx.ToIdx = common.Idx(1)

} nTx, err := common.NewL1Tx(&tx.L1Tx) if err != nil { - return fmt.Errorf("Line %d: %s", tx.lineNum, err.Error()) + return tracerr.Wrap(fmt.Errorf("Line %d: %s", tx.lineNum, err.Error())) } tx.L1Tx = *nTx

@@ -498,13 +499,13 @@ }

func (tc *Context) checkIfAccountExists(tf string, inst instruction) error { if tc.Users[tf].Accounts[inst.tokenID] == nil { - return fmt.Errorf("%s at User: %s, for TokenID: %d, while account not created yet", inst.typ, tf, inst.tokenID) + return tracerr.Wrap(fmt.Errorf("%s at User: %s, for TokenID: %d, while account not created yet", inst.typ, tf, inst.tokenID)) } return nil } func (tc *Context) checkIfTokenIsRegistered(inst instruction) error { if inst.tokenID > tc.LastRegisteredTokenID { - return fmt.Errorf("Can not process %s: TokenID %d not registered, last registered TokenID: %d", inst.typ, inst.tokenID, tc.LastRegisteredTokenID) + return tracerr.Wrap(fmt.Errorf("Can not process %s: TokenID %d not registered, last registered TokenID: %d", inst.typ, inst.tokenID, tc.LastRegisteredTokenID)) } return nil }

@@ -515,10 +516,10 @@ func (tc *Context) GeneratePoolL2Txs(set string) ([]common.PoolL2Tx, error) {

parser := newParser(strings.NewReader(set)) parsedSet, err := parser.parse() if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } if parsedSet.typ != setTypePoolL2 { - return nil, fmt.Errorf("Expected set type: %s, found: %s", setTypePoolL2, parsedSet.typ) + return nil, tracerr.Wrap(fmt.Errorf("Expected set type: %s, found: %s", setTypePoolL2, parsedSet.typ)) } tc.Instructions = parsedSet.instructions

@@ -532,13 +533,13 @@ switch inst.typ {

case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ: if err := tc.checkIfAccountExists(inst.from, inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } if inst.typ == common.TxTypeTransfer { // if TxTypeTransfer, need to exist the ToIdx account if err := tc.checkIfAccountExists(inst.to, inst); err != nil { log.Error(err) - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } } tc.Users[inst.from].Accounts[inst.tokenID].Nonce++

@@ -570,13 +571,13 @@ tx.ToBJJ = tc.Users[inst.to].BJJ.Public()

} nTx, err := common.NewPoolL2Tx(&tx) if err != nil { - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx = *nTx // perform signature and set it to tx.Signature toSign, err := tx.HashToSign() if err != nil { - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } sig := tc.Users[inst.from].BJJ.SignPoseidon(toSign) tx.Signature = sig.Compress()

@@ -596,19 +597,19 @@ Type: common.TxTypeExit,

} nTx, err := common.NewPoolL2Tx(&tx) if err != nil { - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } tx = *nTx // perform signature and set it to tx.Signature toSign, err := tx.HashToSign() if err != nil { - return nil, fmt.Errorf("Line %d: %s", inst.lineNum, err.Error()) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: %s", inst.lineNum, err.Error())) } sig := tc.Users[inst.from].BJJ.SignPoseidon(toSign) tx.Signature = sig.Compress() txs = append(txs, tx) default: - return nil, fmt.Errorf("Line %d: instruction type unrecognized: %s", inst.lineNum, inst.typ) + return nil, tracerr.Wrap(fmt.Errorf("Line %d: instruction type unrecognized: %s", inst.lineNum, inst.typ)) } }

@@ -750,7 +751,7 @@ if tx.Type == common.TxTypeCreateAccountDeposit ||

tx.Type == common.TxTypeCreateAccountDepositTransfer { user, ok := tc.UsersByIdx[tc.extra.idx] if !ok { - return fmt.Errorf("Created account with idx: %v not found", tc.extra.idx) + return tracerr.Wrap(fmt.Errorf("Created account with idx: %v not found", tc.extra.idx)) } batch.CreatedAccounts = append(batch.CreatedAccounts, common.Account{

@@ -785,7 +786,7 @@ tx.EffectiveAmount = big.NewInt(0)

tx.EffectiveLoadAmount = big.NewInt(0) nTx, err := common.NewL1Tx(tx) if err != nil { - return err + return tracerr.Wrap(err) } *tx = *nTx }

@@ -797,7 +798,7 @@ tc.extra.nonces[tx.FromIdx]++

tx.Nonce = tc.extra.nonces[tx.FromIdx] nTx, err := common.NewL2Tx(tx) if err != nil { - return err + return tracerr.Wrap(err) } *tx = *nTx }

@@ -834,13 +835,13 @@ })

} fee, err := common.CalcFeeAmount(tx.Amount, tx.Fee) if err != nil { - return err + return tracerr.Wrap(err) } // Find the TokenID of the tx fromAcc, ok := tc.accountsByIdx[int(tx.FromIdx)] if !ok { - return fmt.Errorf("L2tx.FromIdx idx: %v not found", tx.FromIdx) + return tracerr.Wrap(fmt.Errorf("L2tx.FromIdx idx: %v not found", tx.FromIdx)) } // Find the idx of the CoordUser for the
M txselector/txselector.go → txselector/txselector.go

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

"github.com/hermeznetwork/hermez-node/db/l2db" "github.com/hermeznetwork/hermez-node/db/statedb" "github.com/hermeznetwork/hermez-node/log" + "github.com/hermeznetwork/tracerr" "github.com/iden3/go-iden3-crypto/babyjub" )

@@ -45,7 +46,7 @@ // NewTxSelector returns a *TxSelector

func NewTxSelector(dbpath string, synchronizerStateDB *statedb.StateDB, l2 *l2db.L2DB, maxL1UserTxs, maxL1OperatorTxs, maxTxs uint64) (*TxSelector, error) { localAccountsDB, err := statedb.NewLocalStateDB(dbpath, synchronizerStateDB, statedb.TypeTxSelector, 0) // without merkletree if err != nil { - return nil, err + return nil, tracerr.Wrap(err) } return &TxSelector{

@@ -62,7 +63,7 @@ // from the required `batchNum`

func (txsel *TxSelector) Reset(batchNum common.BatchNum) error { err := txsel.localAccountsDB.Reset(batchNum, true) if err != nil { - return err + return tracerr.Wrap(err) } return nil }

@@ -71,7 +72,7 @@ // GetL2TxSelection returns the L1CoordinatorTxs and a selection of the L2Txs

// for the next batch, from the L2DB pool func (txsel *TxSelector) GetL2TxSelection(coordIdxs []common.Idx, batchNum common.BatchNum) ([]common.L1Tx, []common.PoolL2Tx, error) { _, l1CoordinatorTxs, l2Txs, err := txsel.GetL1L2TxSelection(coordIdxs, batchNum, []common.L1Tx{}) - return l1CoordinatorTxs, l2Txs, err + return l1CoordinatorTxs, l2Txs, tracerr.Wrap(err) } // GetL1L2TxSelection returns the selection of L1 + L2 txs

@@ -84,7 +85,7 @@

// get pending l2-tx from tx-pool l2TxsRaw, err := txsel.l2db.GetPendingTxs() // (batchID) if err != nil { - return nil, nil, nil, err + return nil, nil, nil, tracerr.Wrap(err) } var validTxs txs

@@ -224,11 +225,11 @@ }

// process the txs in the local AccountsDB _, err = txsel.localAccountsDB.ProcessTxs(ptc, coordIdxs, l1Txs, l1CoordinatorTxs, l2Txs) if err != nil { - return nil, nil, nil, err + return nil, nil, nil, tracerr.Wrap(err) } err = txsel.localAccountsDB.MakeCheckpoint() if err != nil { - return nil, nil, nil, err + return nil, nil, nil, tracerr.Wrap(err) } return l1Txs, l1CoordinatorTxs, l2Txs, nil