From d2504d8eda42e93d2512104f4d9544c519c7200e Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Tue, 12 Mar 2024 16:32:53 +0800 Subject: [PATCH 01/19] Fix wrap order and improve errors in components --- components/dashboard/explorer_routes.go | 18 +++++++++--------- components/inx/server_blocks.go | 2 +- components/inx/server_commitments.go | 6 +++--- components/inx/server_issuance.go | 7 +++++-- components/inx/server_transactions.go | 2 +- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/components/dashboard/explorer_routes.go b/components/dashboard/explorer_routes.go index 1af8a1dfe..6766c26d6 100644 --- a/components/dashboard/explorer_routes.go +++ b/components/dashboard/explorer_routes.go @@ -28,12 +28,12 @@ func setupExplorerRoutes(routeGroup *echo.Group) { routeGroup.GET("/block/:"+api.ParameterBlockID, func(c echo.Context) (err error) { blockID, err := httpserver.ParseBlockIDParam(c, api.ParameterBlockID) if err != nil { - return ierrors.Errorf("parse block ID error: %w", err) + return ierrors.Wrap(err, "failed to parse block ID") } t, err := findBlock(blockID) if err != nil { - return ierrors.Errorf("find block error: %w", err) + return err } return c.JSON(http.StatusOK, t) @@ -53,12 +53,12 @@ func setupExplorerRoutes(routeGroup *echo.Group) { blockID, err := iotago.BlockIDFromHexString(search) if err != nil { - return ierrors.Wrapf(ErrInvalidParameter, "search ID %s", search) + return ierrors.WithMessagef(ErrInvalidParameter, "search ID %s", search) } blk, err := findBlock(blockID) if err != nil { - return ierrors.Errorf("can't find block %s: %w", search, err) + return err } result.Block = blk @@ -75,14 +75,14 @@ func setupExplorerRoutes(routeGroup *echo.Group) { func findBlock(blockID iotago.BlockID) (explorerBlk *ExplorerBlock, err error) { block, exists := deps.Protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.Errorf("block not found: %s", blockID.ToHex()) + return nil, ierrors.Errorf("block %s not found", blockID.ToHex()) } cachedBlock, _ := deps.Protocol.Engines.Main.Get().BlockCache.Block(blockID) blockMetadata, err := deps.Protocol.Engines.Main.Get().BlockRetainer.BlockMetadata(blockID) if err != nil { - return nil, ierrors.Wrapf(err, "block metadata %s", blockID.ToHex()) + return nil, ierrors.Wrapf(err, "failed to get block metadata for block %s", blockID.ToHex()) } return createExplorerBlock(block, cachedBlock, blockMetadata), nil @@ -201,12 +201,12 @@ func getTransaction(c echo.Context) error { block, exists := deps.Protocol.Engines.Main.Get().Block(output.BlockID()) if !exists { - return ierrors.Errorf("block not found: %s", output.BlockID().ToHex()) + return ierrors.Errorf("block %s not found", output.BlockID().ToHex()) } iotaTX, isTX := block.SignedTransaction() if !isTX { - return ierrors.Errorf("payload is not a signed transaction: %s", output.BlockID().ToHex()) + return ierrors.Errorf("block payload of block %s is not a signed transaction", output.BlockID().ToHex()) } return httpserver.JSONResponse(c, http.StatusOK, NewTransaction(iotaTX)) @@ -223,7 +223,7 @@ func getTransactionMetadata(c echo.Context) error { copy(outputID[:], txID[:]) txMetadata, exists := deps.Protocol.Engines.Main.Get().Ledger.MemPool().TransactionMetadata(txID) if !exists { - return ierrors.Errorf("tx metadata not found: %s", txID.ToHex()) + return ierrors.Errorf("transaction metadata for transaction %s not found", txID.ToHex()) } conflicts, _ := deps.Protocol.Engines.Main.Get().Ledger.SpendDAG().ConflictingSpenders(txID) diff --git a/components/inx/server_blocks.go b/components/inx/server_blocks.go index 7ed7ca157..71f79981a 100644 --- a/components/inx/server_blocks.go +++ b/components/inx/server_blocks.go @@ -197,7 +197,7 @@ func (s *Server) attachBlock(ctx context.Context, block *iotago.Block) (*inx.Blo func getINXBlockMetadata(blockID iotago.BlockID) (*inx.BlockMetadata, error) { blockMetadata, err := deps.Protocol.Engines.Main.Get().BlockRetainer.BlockMetadata(blockID) if err != nil { - return nil, ierrors.Errorf("failed to get BlockMetadata: %v", err) + return nil, ierrors.Wrap(err, "failed to get BlockMetadata") } return inx.WrapBlockMetadata(blockMetadata) diff --git a/components/inx/server_commitments.go b/components/inx/server_commitments.go index c69bf74a8..3f504e15d 100644 --- a/components/inx/server_commitments.go +++ b/components/inx/server_commitments.go @@ -40,7 +40,7 @@ func (s *Server) ListenToCommitments(req *inx.SlotRangeRequest, srv inx.INX_List } if err := srv.Send(inxCommitment(commitment)); err != nil { - return ierrors.Errorf("send error: %w", err) + return ierrors.Wrap(err, "send error") } return nil @@ -108,7 +108,7 @@ func (s *Server) ListenToCommitments(req *inx.SlotRangeRequest, srv inx.INX_List catchUpFunc := func(start iotago.SlotIndex, end iotago.SlotIndex) error { err := sendSlotsRange(start, end) if err != nil { - err := ierrors.Errorf("sendSlotsRange error: %w", err) + err := ierrors.Wrap(err, "sendSlotsRange error") Component.LogError(err.Error()) return err @@ -119,7 +119,7 @@ func (s *Server) ListenToCommitments(req *inx.SlotRangeRequest, srv inx.INX_List sendFunc := func(_ iotago.SlotIndex, payload *inx.Commitment) error { if err := srv.Send(payload); err != nil { - err := ierrors.Errorf("send error: %w", err) + err := ierrors.Wrap(err, "send error") Component.LogError(err.Error()) return err diff --git a/components/inx/server_issuance.go b/components/inx/server_issuance.go index 50d43f2ae..4f1433db9 100644 --- a/components/inx/server_issuance.go +++ b/components/inx/server_issuance.go @@ -3,7 +3,6 @@ package inx import ( "context" - "github.com/iotaledger/hive.go/ierrors" "github.com/iotaledger/hive.go/lo" "github.com/iotaledger/hive.go/serializer/v2/serix" inx "github.com/iotaledger/inx/go" @@ -58,8 +57,12 @@ func (s *Server) ValidatePayload(_ context.Context, payload *inx.RawPayload) (*i // TaggedData is always valid if serix decoding was successful return nil + case *iotago.CandidacyAnnouncement: + panic("TODO: implement me") default: - return ierrors.Errorf("unsupported payload type: %T", typedPayload) + // We're switching on the Go payload type here, so we can only run into the default case + // if we added a new payload type and have not handled it above. In this case we want to panic. + panic("all supported payload types should be handled above") } }(); err != nil { //nolint:nilerr // this is expected behavior diff --git a/components/inx/server_transactions.go b/components/inx/server_transactions.go index bcf678a29..3e2063523 100644 --- a/components/inx/server_transactions.go +++ b/components/inx/server_transactions.go @@ -20,7 +20,7 @@ func (s *Server) ReadTransactionMetadata(_ context.Context, transactionID *inx.T return nil, status.Errorf(codes.NotFound, "transaction metadata not found: %s", txID.ToHex()) } - return nil, ierrors.WithMessagef(err, "error when retrieving transaction metadata: %s", txID.ToHex()) + return nil, ierrors.Wrapf(err, "error when retrieving transaction metadata: %s", txID.ToHex()) } return inx.WrapTransactionMetadata(txMetadata), nil From 20cc73713e60c95e9f12082d0e1d0abe74c63802 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 10:34:01 +0800 Subject: [PATCH 02/19] Fix error wrapping order in components --- components/p2p/component.go | 2 +- components/p2p/utils.go | 2 +- components/prometheus/metrics_scheduler.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/components/p2p/component.go b/components/p2p/component.go index 681857ae2..c328ee3a7 100644 --- a/components/p2p/component.go +++ b/components/p2p/component.go @@ -331,7 +331,7 @@ func getMultiAddrsFromString(peers []string) ([]multiaddr.Multiaddr, error) { for _, peer := range peers { peerMultiAddr, err := multiaddr.NewMultiaddr(peer) if err != nil { - return nil, ierrors.Errorf("invalid peer multiaddr \"%s\": %w", peer, err) + return nil, ierrors.Wrapf(err, "invalid peer multiaddr \"%s\"", peer) } peersMultiAddresses = append(peersMultiAddresses, peerMultiAddr) } diff --git a/components/p2p/utils.go b/components/p2p/utils.go index 238cda833..33c8ba802 100644 --- a/components/p2p/utils.go +++ b/components/p2p/utils.go @@ -18,7 +18,7 @@ func initPeerDB() (peerDB *network.DB, peerDBKVStore kvstore.KVStore, err error) db, err := database.NewRocksDB(ParamsP2P.Database.Path) if err != nil { - return nil, nil, ierrors.Wrap(err, "error creating peer database") + return nil, nil, ierrors.Wrap(err, "failed to create peer database") } peerDBKVStore = rocksdb.New(db) diff --git a/components/prometheus/metrics_scheduler.go b/components/prometheus/metrics_scheduler.go index b4801dddf..5d8a01f18 100644 --- a/components/prometheus/metrics_scheduler.go +++ b/components/prometheus/metrics_scheduler.go @@ -126,7 +126,7 @@ var SchedulerMetrics = collector.NewCollection(schedulerNamespace, deps.Protocol.Events.Engine.Scheduler.BlockEnqueued.Hook(func(block *blocks.Block) { mana, err := deps.Protocol.Engines.Main.Get().Ledger.ManaManager().GetManaOnAccount(block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot()) if err != nil { - deps.Protocol.Engines.Main.Get().ErrorHandler("metrics")(ierrors.Wrapf(err, "failed to retrieve mana on account %s for slot %d", block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot())) + deps.Protocol.Engines.Main.Get().ErrorHandler("metrics")(ierrors.Wrapf(err, "failed to retrieve mana on account %s for slot %d", block.ProtocolBlock().Header.IssuerID.ToHex(), block.SlotCommitmentID().Slot())) return } From 9d33251a91548c52a5a05d8feba899c9323b19c3 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 10:43:46 +0800 Subject: [PATCH 03/19] Fix error wrapping order in restapi --- components/restapi/core/blocks.go | 2 +- components/restapi/core/component.go | 2 +- components/restapi/core/transaction.go | 4 ++-- components/restapi/management/pruning.go | 14 +++++++------- components/restapi/management/snapshots.go | 4 ++-- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/components/restapi/core/blocks.go b/components/restapi/core/blocks.go index 097dd1709..2292b9c0e 100644 --- a/components/restapi/core/blocks.go +++ b/components/restapi/core/blocks.go @@ -44,7 +44,7 @@ func sendBlock(c echo.Context) (*api.BlockCreatedResponse, error) { blockID, err := deps.RequestHandler.AttachBlock(c.Request().Context(), iotaBlock) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to attach block: %w", err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to attach block: %w", err) } return &api.BlockCreatedResponse{ diff --git a/components/restapi/core/component.go b/components/restapi/core/component.go index cb887c005..4cc1f113c 100644 --- a/components/restapi/core/component.go +++ b/components/restapi/core/component.go @@ -312,7 +312,7 @@ func checkNodeSynced() echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if !deps.RequestHandler.IsNodeSynced() { - return ierrors.Wrap(echo.ErrServiceUnavailable, "node is not synced") + return ierrors.WithMessage(echo.ErrServiceUnavailable, "node is not synced") } return next(c) diff --git a/components/restapi/core/transaction.go b/components/restapi/core/transaction.go index d3ed3ee91..bde1d95f5 100644 --- a/components/restapi/core/transaction.go +++ b/components/restapi/core/transaction.go @@ -21,7 +21,7 @@ func blockIDFromTransactionID(c echo.Context) (iotago.BlockID, error) { func blockFromTransactionID(c echo.Context) (*iotago.Block, error) { blockID, err := blockIDFromTransactionID(c) if err != nil { - return nil, ierrors.Wrapf(echo.ErrBadRequest, "failed to get block ID by transaction ID: %s", err) + return nil, ierrors.WithMessagef(echo.ErrBadRequest, "failed to get block ID by transaction ID: %w", err) } block, err := deps.RequestHandler.BlockByID(blockID) @@ -35,7 +35,7 @@ func blockFromTransactionID(c echo.Context) (*iotago.Block, error) { func blockMetadataFromTransactionID(c echo.Context) (*api.BlockMetadataResponse, error) { blockID, err := blockIDFromTransactionID(c) if err != nil { - return nil, ierrors.Wrapf(echo.ErrBadRequest, "failed to get block ID by transaction ID: %s", err) + return nil, ierrors.WithMessagef(echo.ErrBadRequest, "failed to get block ID by transaction ID: %w", err) } return deps.RequestHandler.BlockMetadataByBlockID(blockID) diff --git a/components/restapi/management/pruning.go b/components/restapi/management/pruning.go index 88bf1f8a5..5d5acc03b 100644 --- a/components/restapi/management/pruning.go +++ b/components/restapi/management/pruning.go @@ -11,12 +11,12 @@ import ( func pruneDatabase(c echo.Context) (*api.PruneDatabaseResponse, error) { if deps.Protocol.Engines.Main.Get().Storage.IsPruning() { - return nil, ierrors.Wrapf(echo.ErrServiceUnavailable, "node is already pruning") + return nil, ierrors.WithMessage(echo.ErrServiceUnavailable, "node is already pruning") } request := &api.PruneDatabaseRequest{} if err := c.Bind(request); err != nil { - return nil, ierrors.Wrapf(httpserver.ErrInvalidParameter, "invalid request, error: %s", err) + return nil, ierrors.WithMessagef(httpserver.ErrInvalidParameter, "invalid request, error: %w", err) } // only allow one type of pruning at a time @@ -24,7 +24,7 @@ func pruneDatabase(c echo.Context) (*api.PruneDatabaseResponse, error) { (request.Epoch != 0 && request.Depth != 0) || (request.Epoch != 0 && request.TargetDatabaseSize != "") || (request.Depth != 0 && request.TargetDatabaseSize != "") { - return nil, ierrors.Wrapf(httpserver.ErrInvalidParameter, "either epoch, depth or size has to be specified") + return nil, ierrors.WithMessage(httpserver.ErrInvalidParameter, "either epoch, depth or size has to be specified") } var err error @@ -32,26 +32,26 @@ func pruneDatabase(c echo.Context) (*api.PruneDatabaseResponse, error) { if request.Epoch != 0 { err = deps.Protocol.Engines.Main.Get().Storage.PruneByEpochIndex(request.Epoch) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err) } } if request.Depth != 0 { _, _, err := deps.Protocol.Engines.Main.Get().Storage.PruneByDepth(request.Depth) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err) } } if request.TargetDatabaseSize != "" { pruningTargetDatabaseSizeBytes, err := bytes.Parse(request.TargetDatabaseSize) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err) } err = deps.Protocol.Engines.Main.Get().Storage.PruneBySize(pruningTargetDatabaseSizeBytes) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "pruning database failed: %s", err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "pruning database failed: %w", err) } } diff --git a/components/restapi/management/snapshots.go b/components/restapi/management/snapshots.go index e23fa3629..eb4215259 100644 --- a/components/restapi/management/snapshots.go +++ b/components/restapi/management/snapshots.go @@ -14,7 +14,7 @@ func createSnapshots(_ echo.Context) (*api.CreateSnapshotResponse, error) { request := &createSnapshotsRequest{} if err := c.Bind(request); err != nil { - return nil, ierrors.WithMessagef(httpserver.ErrInvalidParameter, "invalid request, error: %s", err) + return nil, ierrors.WithMessagef(httpserver.ErrInvalidParameter, "invalid request: %w", err) } if request.Slot == 0 { @@ -23,7 +23,7 @@ func createSnapshots(_ echo.Context) (*api.CreateSnapshotResponse, error) { filePath := filepath.Join(filepath.Dir(deps.SnapshotsFullPath), fmt.Sprintf("full_snapshot_%d.bin", request.Slot)) if err := deps.SnapshotManager.CreateFullSnapshot(Component.Daemon().ContextStopped(), request.Slot, filePath, false); err != nil { - return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "creating snapshot failed: %s", err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "creating snapshot failed: %w", err) } return &createSnapshotsResponse{ From 891b0b9b7ffdbb6760c48602389184bd991f385b Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 11:46:14 +0800 Subject: [PATCH 04/19] Fix errors in models --- pkg/jwt/jwt.go | 6 +++--- pkg/model/block.go | 2 +- pkg/model/commitment.go | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pkg/jwt/jwt.go b/pkg/jwt/jwt.go index 812793914..698339dc3 100644 --- a/pkg/jwt/jwt.go +++ b/pkg/jwt/jwt.go @@ -33,7 +33,7 @@ func NewAuth(subject string, sessionTimeout time.Duration, nodeID string, secret secretBytes, err := crypto.MarshalPrivateKey(secret) if err != nil { - return nil, ierrors.Errorf("unable to convert private key: %w", err) + return nil, ierrors.Wrap(err, "unable to convert private key") } return &Auth{ @@ -98,7 +98,7 @@ func (j *Auth) Middleware(skipper middleware.Skipper, allow func(c echo.Context, // validate the signing method we expect if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return ierrors.Errorf("unexpected signing method: %v", token.Header["alg"]) + return ierrors.Errorf("unexpected signing method: %s", token.Method.Alg()) } // read the claims set by the JWT middleware on the context @@ -154,7 +154,7 @@ func (j *Auth) VerifyJWT(token string, allow func(claims *AuthClaims) bool) bool t, err := jwt.ParseWithClaims(token, &AuthClaims{}, func(token *jwt.Token) (interface{}, error) { // validate the signing method we expect if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, ierrors.Errorf("unexpected signing method: %v", token.Header["alg"]) + return nil, ierrors.Errorf("unexpected signing method: %s", token.Method.Alg()) } return j.secret, nil diff --git a/pkg/model/block.go b/pkg/model/block.go index 9729aaef7..5e21b6e94 100644 --- a/pkg/model/block.go +++ b/pkg/model/block.go @@ -129,7 +129,7 @@ func (blk *Block) String() string { panic(err) } var out bytes.Buffer - if json.Indent(&out, encode, "", " ") != nil { + if err = json.Indent(&out, encode, "", " "); err != nil { panic(err) } diff --git a/pkg/model/commitment.go b/pkg/model/commitment.go index 673116ab1..32e66774b 100644 --- a/pkg/model/commitment.go +++ b/pkg/model/commitment.go @@ -126,7 +126,7 @@ func (c *Commitment) String() string { panic(err) } var out bytes.Buffer - if json.Indent(&out, encode, "", " ") != nil { + if err = json.Indent(&out, encode, "", " "); err != nil { panic(err) } From a804f44ab1ae5b8c86b0307e2b7e2eb3f92f8196 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 11:57:00 +0800 Subject: [PATCH 05/19] Improve errors in p2p --- pkg/network/p2p/manager.go | 38 +++++++++---------- .../p2p/manualpeering/manualpeering.go | 4 +- pkg/network/p2p/neighbor.go | 14 +++---- pkg/network/protocols/core/protocol.go | 2 +- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/pkg/network/p2p/manager.go b/pkg/network/p2p/manager.go index 3149d3883..2785a614e 100644 --- a/pkg/network/p2p/manager.go +++ b/pkg/network/p2p/manager.go @@ -113,11 +113,11 @@ func (m *Manager) DialPeer(ctx context.Context, peer *network.Peer) error { } if m.NeighborExists(peer.ID) { - return ierrors.Wrapf(network.ErrDuplicatePeer, "peer %s already exists", peer.ID) + return ierrors.Wrapf(network.ErrDuplicatePeer, "peer %s already exists", peer.ID.String()) } if !m.allowPeer(peer.ID) { - return ierrors.Wrapf(network.ErrMaxAutopeeringPeersReached, "peer %s is not allowed", peer.ID) + return ierrors.Wrapf(network.ErrMaxAutopeeringPeersReached, "peer %s is not allowed", peer.ID.String()) } // Adds the peer's multiaddresses to the peerstore, so that they can be used for dialing. @@ -126,14 +126,14 @@ func (m *Manager) DialPeer(ctx context.Context, peer *network.Peer) error { stream, err := m.P2PHost().NewStream(cancelCtx, peer.ID, network.CoreProtocolID) if err != nil { - return ierrors.Wrapf(err, "dial %s / %s failed to open stream for proto %s", peer.PeerAddresses, peer.ID, network.CoreProtocolID) + return ierrors.Wrapf(err, "dial %s / %s failed to open stream for proto %s", peer.PeerAddresses, peer.ID.String(), network.CoreProtocolID) } ps := NewPacketsStream(stream, m.protocolHandler.PacketFactory) if err := ps.sendNegotiation(); err != nil { m.closeStream(stream) - return ierrors.Wrapf(err, "dial %s / %s failed to send negotiation for proto %s", peer.PeerAddresses, peer.ID, network.CoreProtocolID) + return ierrors.Wrapf(err, "dial %s / %s failed to send negotiation for proto %s", peer.PeerAddresses, peer.ID.String(), network.CoreProtocolID) } m.logger.LogDebugf("outgoing stream negotiated, id: %s, addr: %s, proto: %s", peer.ID, ps.Conn().RemoteMultiaddr(), network.CoreProtocolID) @@ -141,13 +141,13 @@ func (m *Manager) DialPeer(ctx context.Context, peer *network.Peer) error { if err := m.peerDB.UpdatePeer(peer); err != nil { m.closeStream(stream) - return ierrors.Wrapf(err, "failed to update peer %s", peer.ID) + return ierrors.Wrapf(err, "failed to update peer %s", peer.ID.String()) } if err := m.addNeighbor(ctx, peer, ps); err != nil { m.closeStream(stream) - return ierrors.Errorf("failed to add neighbor %s: %s", peer.ID, err) + return ierrors.Errorf("failed to add neighbor %s: %s", peer.ID.String(), err.Error()) } return nil @@ -177,11 +177,11 @@ func (m *Manager) Shutdown() { m.isShutdown = true if err := m.autoPeering.Stop(); err != nil { - m.logger.LogErrorf("failed to stop autopeering: %s", err) + m.logger.LogErrorf("failed to stop autopeering: %s", err.Error()) } if err := m.manualPeering.Stop(); err != nil { - m.logger.LogErrorf("failed to stop manualpeering: %s", err) + m.logger.LogErrorf("failed to stop manualpeering: %s", err.Error()) } m.dropAllNeighbors() @@ -189,7 +189,7 @@ func (m *Manager) Shutdown() { m.UnregisterProtocol() if err := m.libp2pHost.Close(); err != nil { - m.logger.LogErrorf("failed to close libp2p host: %s", err) + m.logger.LogErrorf("failed to close libp2p host: %s", err.Error()) } } @@ -290,7 +290,7 @@ func (m *Manager) handleStream(stream p2pnetwork.Stream) { peerID := stream.Conn().RemotePeer() if !m.allowPeer(peerID) { - m.logger.LogDebugf("peer %s is not allowed", peerID) + m.logger.LogDebugf("peer %s is not allowed", peerID.String()) m.closeStream(stream) return @@ -311,14 +311,14 @@ func (m *Manager) handleStream(stream p2pnetwork.Stream) { networkPeer := network.NewPeerFromAddrInfo(peerAddrInfo) if err := m.peerDB.UpdatePeer(networkPeer); err != nil { - m.logger.LogErrorf("failed to update peer in peer database, peerID: %s, error: %s", peerID, err) + m.logger.LogErrorf("failed to update peer in peer database, peerID: %s, error: %s", peerID.String(), err.Error()) m.closeStream(stream) return } if err := m.addNeighbor(m.ctx, networkPeer, ps); err != nil { - m.logger.LogErrorf("failed to add neighbor, peerID: %s, error: %s", peerID, err) + m.logger.LogErrorf("failed to add neighbor, peerID: %s, error: %s", peerID.String(), err.Error()) m.closeStream(stream) return @@ -327,7 +327,7 @@ func (m *Manager) handleStream(stream p2pnetwork.Stream) { func (m *Manager) closeStream(s p2pnetwork.Stream) { if err := s.Reset(); err != nil { - m.logger.LogWarnf("close error, error: %s", err) + m.logger.LogWarnf("close error, error: %s", err.Error()) } } @@ -367,10 +367,10 @@ func (m *Manager) addNeighbor(ctx context.Context, peer *network.Peer, ps *Packe return } if err := m.protocolHandler.PacketHandler(nbr.Peer().ID, packet); err != nil { - nbr.logger.LogDebugf("Can't handle packet, error: %s", err) + nbr.logger.LogDebugf("Can't handle packet, error: %s", err.Error()) } }, func(nbr *neighbor) { - nbr.logger.LogInfof("Neighbor connected: %s", nbr.Peer().ID) + nbr.logger.LogInfof("Neighbor connected: %s", nbr.Peer().ID.String()) nbr.Peer().SetConnStatus(network.ConnStatusConnected) firstPacketReceivedCancel() m.neighborAdded.Trigger(nbr) @@ -380,7 +380,7 @@ func (m *Manager) addNeighbor(ctx context.Context, peer *network.Peer, ps *Packe }) if err := m.setNeighbor(nbr); err != nil { if resetErr := ps.Reset(); resetErr != nil { - nbr.logger.LogErrorf("error closing stream, error: %s", resetErr) + nbr.logger.LogErrorf("error closing stream, error: %s", resetErr.Error()) } return ierrors.WithStack(err) @@ -437,19 +437,19 @@ func (m *Manager) dropAllNeighbors() { func (m *Manager) allowPeer(id peer.ID) (allow bool) { // Always allow manual peers if m.manualPeering.IsPeerKnown(id) { - m.logger.LogDebugf("Allow manual peer %s", id) + m.logger.LogDebugf("Allow manual peer %s", id.String()) return true } // Only allow up to the maximum number of autopeered neighbors autopeeredNeighborsCount := len(m.AutopeeringNeighbors()) if autopeeredNeighborsCount < m.autoPeering.MaxNeighbors() { - m.logger.LogDebugf("Allow autopeered peer %s. Max %d has not been reached: %d", id, m.autoPeering.MaxNeighbors(), autopeeredNeighborsCount) + m.logger.LogDebugf("Allow autopeered peer %s. Max %d has not been reached: %d", id.String(), m.autoPeering.MaxNeighbors(), autopeeredNeighborsCount) return true } // Don't allow new peers - m.logger.LogDebugf("Disallow autopeered peer %s. Max %d has been reached", id, m.autoPeering.MaxNeighbors()) + m.logger.LogDebugf("Disallow autopeered peer %s. Max %d has been reached", id.String(), m.autoPeering.MaxNeighbors()) return false } diff --git a/pkg/network/p2p/manualpeering/manualpeering.go b/pkg/network/p2p/manualpeering/manualpeering.go index 672572177..cbc547bec 100644 --- a/pkg/network/p2p/manualpeering/manualpeering.go +++ b/pkg/network/p2p/manualpeering/manualpeering.go @@ -88,7 +88,7 @@ func (m *Manager) RemovePeer(peerID peer.ID) error { m.networkManager.P2PHost().ConnManager().Unprotect(peerID, manualPeerProtectionTag) if err := m.networkManager.DropNeighbor(peerID); err != nil && !ierrors.Is(err, network.ErrUnknownPeer) { - return ierrors.Wrapf(err, "failed to drop known peer %s in the gossip layer", peerID) + return ierrors.Wrapf(err, "failed to drop known peer %s in the gossip layer", peerID.String()) } return nil @@ -252,7 +252,7 @@ func (m *Manager) keepPeerConnected(peer *network.Peer) { var err error if err = m.networkManager.DialPeer(ctx, peer); err != nil && !ierrors.Is(err, network.ErrDuplicatePeer) && !ierrors.Is(err, context.Canceled) { - m.logger.LogErrorf("Failed to connect a neighbor in the gossip layer, peerID: %s, error: %s", peer.ID, err) + m.logger.LogErrorf("Failed to connect a neighbor in the gossip layer, peerID: %s, error: %s", peer.ID.String(), err.Error()) } } select { diff --git a/pkg/network/p2p/neighbor.go b/pkg/network/p2p/neighbor.go index c54e2eb2e..27a8d58ce 100644 --- a/pkg/network/p2p/neighbor.go +++ b/pkg/network/p2p/neighbor.go @@ -69,7 +69,7 @@ func newNeighbor(parentLogger log.Logger, p *network.Peer, stream *PacketsStream sendQueue: make(chan *queuedPacket, NeighborsSendQueueSize), } - n.logger.LogInfo("created", "ID", n.Peer().ID) + n.logger.LogInfo("created", "ID", n.Peer().ID.String()) return n } @@ -120,9 +120,9 @@ func (n *neighbor) readLoop() { packet := stream.packetFactory() err := stream.ReadPacket(packet) if err != nil { - n.logger.LogInfof("Stream read packet error: %s", err) + n.logger.LogInfof("Stream read packet error: %s", err.Error()) if disconnectErr := n.disconnect(); disconnectErr != nil { - n.logger.LogWarnf("Failed to disconnect, error: %s", disconnectErr) + n.logger.LogWarnf("Failed to disconnect, error: %s", disconnectErr.Error()) } return @@ -148,15 +148,15 @@ func (n *neighbor) writeLoop() { if n.stream == nil { n.logger.LogWarnf("send error, no stream for protocol, peerID: %s, protocol: %s", n.Peer().ID, sendPacket.protocolID) if disconnectErr := n.disconnect(); disconnectErr != nil { - n.logger.LogWarnf("Failed to disconnect, error: %s", disconnectErr) + n.logger.LogWarnf("Failed to disconnect, error: %s", disconnectErr.Error()) } return } if err := n.stream.WritePacket(sendPacket.packet); err != nil { - n.logger.LogWarnf("send error, peerID: %s, error: %s", n.Peer().ID, err) + n.logger.LogWarnf("send error, peerID: %s, error: %s", n.Peer().ID.String(), err.Error()) if disconnectErr := n.disconnect(); disconnectErr != nil { - n.logger.LogWarnf("Failed to disconnect, error: %s", disconnectErr) + n.logger.LogWarnf("Failed to disconnect, error: %s", disconnectErr.Error()) } return @@ -169,7 +169,7 @@ func (n *neighbor) writeLoop() { // Close closes the connection with the neighbor. func (n *neighbor) Close() { if err := n.disconnect(); err != nil { - n.logger.LogErrorf("Failed to disconnect the neighbor, error: %s", err) + n.logger.LogErrorf("Failed to disconnect the neighbor, error: %s", err.Error()) } n.wg.Wait() n.logger.UnsubscribeFromParentLogger() diff --git a/pkg/network/protocols/core/protocol.go b/pkg/network/protocols/core/protocol.go index 7f49e88b6..f6c9454ae 100644 --- a/pkg/network/protocols/core/protocol.go +++ b/pkg/network/protocols/core/protocol.go @@ -257,7 +257,7 @@ func (p *Protocol) onAttestations(commitmentBytes []byte, attestationsBytes []by attestationsCount, err := stream.PeekSize(reader, serializer.SeriLengthPrefixTypeAsUint32) if err != nil { - p.Events.Error.Trigger(ierrors.Errorf("failed peek attestations count"), id) + p.Events.Error.Trigger(ierrors.Errorf("failed to peek attestations count"), id) return } From 235646354090cd70aa2fdc27e2657596ea331a84 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 13:23:54 +0800 Subject: [PATCH 06/19] Fix errors and panics in protocol --- pkg/protocol/commitment_verifier.go | 4 +++- pkg/protocol/engines.go | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/pkg/protocol/commitment_verifier.go b/pkg/protocol/commitment_verifier.go index ed176efb6..12014fa2c 100644 --- a/pkg/protocol/commitment_verifier.go +++ b/pkg/protocol/commitment_verifier.go @@ -165,7 +165,9 @@ func (c *CommitmentVerifier) verifyAttestations(attestations []*iotago.Attestati } default: - return nil, 0, ierrors.Errorf("only ed25519 signatures supported, got %s", att.Signature.Type()) + // We're switching on the Go signature type here, so we can only run into the default case + // if we added a new signature type and have not handled it above. In this case we want to panic. + panic("all supported signature types should be handled above") } // 2. Verify the signature of the attestation. diff --git a/pkg/protocol/engines.go b/pkg/protocol/engines.go index c6edf6740..5458c5933 100644 --- a/pkg/protocol/engines.go +++ b/pkg/protocol/engines.go @@ -149,7 +149,7 @@ func (e *Engines) ForkAtSlot(slot iotago.SlotIndex) (*engine.Engine, error) { func (e *Engines) loadMainEngine(snapshotPath string) (*engine.Engine, error) { info := &engineInfo{} if err := ioutils.ReadJSONFromFile(e.infoFilePath(), info); err != nil && !ierrors.Is(err, os.ErrNotExist) { - return nil, ierrors.Errorf("unable to read engine info file: %w", err) + return nil, ierrors.Wrap(err, "unable to read engine info file") } //nolint:revive From 1ebcb5a1f70bffdfcfac307b11f6c4b19d84e9f3 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 13:40:08 +0800 Subject: [PATCH 07/19] Fix error wrapping order in requesthandler --- pkg/requesthandler/accounts.go | 20 ++++++++++---------- pkg/requesthandler/blockissuance.go | 6 +++--- pkg/requesthandler/blocks.go | 10 +++++----- pkg/requesthandler/commitments.go | 14 +++++++------- pkg/requesthandler/transaction.go | 6 +++--- pkg/requesthandler/utxo.go | 12 ++++++------ 6 files changed, 34 insertions(+), 34 deletions(-) diff --git a/pkg/requesthandler/accounts.go b/pkg/requesthandler/accounts.go index 1d463cf15..5d8a74b96 100644 --- a/pkg/requesthandler/accounts.go +++ b/pkg/requesthandler/accounts.go @@ -18,10 +18,10 @@ func (r *RequestHandler) CongestionByAccountAddress(accountAddress *iotago.Accou accountID := accountAddress.AccountID() acc, exists, err := r.protocol.Engines.Main.Get().Ledger.Account(accountID, commitment.Slot()) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get account %s from the Ledger: %s", accountID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get account %s from the Ledger: %w", accountID.ToHex(), err) } if !exists { - return nil, ierrors.Wrapf(echo.ErrNotFound, "account not found: %s", accountID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "account %s not found", accountID.ToHex()) } return &api.CongestionResponse{ @@ -41,14 +41,14 @@ func (r *RequestHandler) Validators(slotRange, cursorIndex, pageSize uint32) (*a //if !exists { // registeredValidators, err := r.protocol.Engines.Main.Get().SybilProtection.OrderedRegisteredCandidateValidatorsList(latestEpoch) // if err != nil { - // return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get ordered registered validators list for epoch %d : %s", latestEpoch, err) + // return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get ordered registered validators list for epoch %d: %w", latestEpoch, err) // } // r.protocol.Engines.Main.Get().BlockRetainer.RetainRegisteredValidatorsCache(slotRange, registeredValidators) //} registeredValidators, err := r.protocol.Engines.Main.Get().SybilProtection.OrderedRegisteredCandidateValidatorsList(latestEpoch) if err != nil { - return nil, ierrors.Join(echo.ErrInternalServerError, ierrors.Wrapf(err, "failed to get ordered registered validators list for epoch %d", latestEpoch)) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get ordered registered validators list for epoch %d: %w", latestEpoch, err) } page := registeredValidators[cursorIndex:lo.Min(cursorIndex+pageSize, uint32(len(registeredValidators)))] @@ -72,10 +72,10 @@ func (r *RequestHandler) ValidatorByAccountAddress(accountAddress *iotago.Accoun accountID := accountAddress.AccountID() accountData, exists, err := r.protocol.Engines.Main.Get().Ledger.Account(accountID, latestCommittedSlot) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get account %s from the Ledger: %s", accountID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get account %s from the Ledger: %s", accountID.ToHex(), err) } if !exists { - return nil, ierrors.Wrapf(echo.ErrNotFound, "account %s not found for latest committedSlot %d", accountID.ToHex(), latestCommittedSlot) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "account %s not found for latest committedSlot %d", accountID.ToHex(), latestCommittedSlot) } epoch := r.protocol.APIForSlot(latestCommittedSlot).TimeProvider().EpochFromSlot(latestCommittedSlot) @@ -100,7 +100,7 @@ func (r *RequestHandler) ValidatorByAccountAddress(accountAddress *iotago.Accoun func (r *RequestHandler) RewardsByOutputID(outputID iotago.OutputID, slot iotago.SlotIndex) (*api.ManaRewardsResponse, error) { utxoOutput, err := r.protocol.Engines.Main.Get().Ledger.Output(outputID) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get output %s from ledger: %s", outputID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get output %s from ledger: %w", outputID.ToHex(), err) } var stakingPoolValidatorAccountID iotago.AccountID @@ -115,7 +115,7 @@ func (r *RequestHandler) RewardsByOutputID(outputID iotago.OutputID, slot iotago accountOutput := utxoOutput.Output().(*iotago.AccountOutput) feature, exists := accountOutput.FeatureSet()[iotago.FeatureStaking] if !exists { - return nil, ierrors.Wrapf(echo.ErrBadRequest, "account %s is not a validator", outputID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrBadRequest, "account %s is not a validator", outputID.ToHex()) } //nolint:forcetypeassert @@ -158,13 +158,13 @@ func (r *RequestHandler) RewardsByOutputID(outputID iotago.OutputID, slot iotago ) } if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to calculate reward for output %s: %s", outputID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to calculate reward for output %s: %w", outputID.ToHex(), err) } latestCommittedEpochPoolRewards, poolRewardExists, err := r.protocol.Engines.Main.Get().SybilProtection.PoolRewardsForAccount(stakingPoolValidatorAccountID) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to retrieve pool rewards for account %s: %s", stakingPoolValidatorAccountID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to retrieve pool rewards for account %s: %w", stakingPoolValidatorAccountID.ToHex(), err) } if !poolRewardExists { latestCommittedEpochPoolRewards = 0 diff --git a/pkg/requesthandler/blockissuance.go b/pkg/requesthandler/blockissuance.go index ed6e163ec..21b9be3a9 100644 --- a/pkg/requesthandler/blockissuance.go +++ b/pkg/requesthandler/blockissuance.go @@ -71,15 +71,15 @@ func (r *RequestHandler) SubmitBlockAndAwaitEvent(ctx context.Context, block *mo defer lo.BatchReverse(evtUnhook, prefilteredUnhook, postfilteredUnhook)() if err := r.submitBlock(block); err != nil { - return ierrors.Wrapf(err, "failed to issue block %s", blockID) + return ierrors.Wrapf(err, "failed to issue block %s", blockID.ToHex()) } select { case <-processingCtx.Done(): - return ierrors.Errorf("context canceled whilst waiting for event on block %s", blockID) + return ierrors.Errorf("context canceled whilst waiting for event on block %s", blockID.ToHex()) case err := <-filtered: if err != nil { - return ierrors.Wrapf(err, "block filtered %s", blockID) + return ierrors.Wrapf(err, "block filtered %s", blockID.ToHex()) } return nil diff --git a/pkg/requesthandler/blocks.go b/pkg/requesthandler/blocks.go index 1838848d9..4109ac7c8 100644 --- a/pkg/requesthandler/blocks.go +++ b/pkg/requesthandler/blocks.go @@ -14,7 +14,7 @@ import ( func (r *RequestHandler) BlockByID(blockID iotago.BlockID) (*iotago.Block, error) { block, exists := r.protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.Wrapf(echo.ErrNotFound, "block not found: %s", blockID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "block %s not found", blockID.ToHex()) } return block.ProtocolBlock(), nil @@ -23,7 +23,7 @@ func (r *RequestHandler) BlockByID(blockID iotago.BlockID) (*iotago.Block, error func (r *RequestHandler) BlockMetadataByBlockID(blockID iotago.BlockID) (*api.BlockMetadataResponse, error) { blockMetadata, err := r.protocol.Engines.Main.Get().BlockRetainer.BlockMetadata(blockID) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get block metadata %s: %s", blockID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get block metadata %s: %w", blockID.ToHex(), err) } return blockMetadata, nil @@ -41,7 +41,7 @@ func (r *RequestHandler) BlockMetadataByID(c echo.Context) (*api.BlockMetadataRe func (r *RequestHandler) BlockWithMetadataByID(blockID iotago.BlockID) (*api.BlockWithMetadataResponse, error) { block, exists := r.protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.Wrapf(echo.ErrNotFound, "no transaction found for block ID %s", blockID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "no transaction found for block ID %s", blockID.ToHex()) } blockMetadata, err := r.BlockMetadataByBlockID(blockID) @@ -58,7 +58,7 @@ func (r *RequestHandler) BlockWithMetadataByID(blockID iotago.BlockID) (*api.Blo func (r *RequestHandler) BlockIssuance() (*api.IssuanceBlockHeaderResponse, error) { references := r.protocol.Engines.Main.Get().TipSelection.SelectTips(iotago.BasicBlockMaxParents) if len(references[iotago.StrongParentType]) == 0 { - return nil, ierrors.Wrap(echo.ErrServiceUnavailable, "no strong parents available") + return nil, ierrors.WithMessage(echo.ErrServiceUnavailable, "no strong parents available") } // get the latest parent block issuing time @@ -67,7 +67,7 @@ func (r *RequestHandler) BlockIssuance() (*api.IssuanceBlockHeaderResponse, erro for _, blockID := range references[parentType] { block, exists := r.protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.Wrapf(echo.ErrNotFound, "no block found for parent, block ID: %s", blockID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "failed to retrieve parents: no block found for block ID %s", blockID.ToHex()) } if latestParentBlockIssuingTime.Before(block.ProtocolBlock().Header.IssuingTime) { diff --git a/pkg/requesthandler/commitments.go b/pkg/requesthandler/commitments.go index 5cdcf6abc..c8f5117db 100644 --- a/pkg/requesthandler/commitments.go +++ b/pkg/requesthandler/commitments.go @@ -14,12 +14,12 @@ func (r *RequestHandler) GetCommitmentBySlot(slot iotago.SlotIndex) (*model.Comm latest := r.protocol.Engines.Main.Get().SyncManager.LatestCommitment() if slot > latest.Slot() { - return nil, ierrors.Wrapf(echo.ErrBadRequest, "commitment is from a future slot (%d > %d)", slot, latest.Slot()) + return nil, ierrors.WithMessagef(echo.ErrBadRequest, "commitment is from a future slot (%d > %d)", slot, latest.Slot()) } commitment, err := r.protocol.Engines.Main.Get().Storage.Commitments().Load(slot) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to load commitment, slot: %d, error: %w", slot, err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to load commitment, slot: %d, error: %w", slot, err) } return commitment, nil @@ -33,16 +33,16 @@ func (r *RequestHandler) GetCommitmentByID(commitmentID iotago.CommitmentID) (*m } if commitmentID.Slot() > latest.Slot() { - return nil, ierrors.Wrapf(echo.ErrBadRequest, "commitment ID (%s) is from a future slot (%d > %d)", commitmentID, commitmentID.Slot(), latest.Slot()) + return nil, ierrors.WithMessagef(echo.ErrBadRequest, "commitment ID (%s) is from a future slot (%d > %d)", commitmentID, commitmentID.Slot(), latest.Slot()) } commitment, err := r.protocol.Engines.Main.Get().Storage.Commitments().Load(commitmentID.Slot()) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to load commitment, commitmentID: %s, slot: %d, error: %w", commitmentID, commitmentID.Slot(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to load commitment, commitmentID: %s, slot: %d, error: %w", commitmentID, commitmentID.Slot(), err) } if commitment.ID() != commitmentID { - return nil, ierrors.Wrapf(echo.ErrBadRequest, "commitment in the store for slot %d does not match the given commitmentID (%s != %s)", commitmentID.Slot(), commitment.ID(), commitmentID) + return nil, ierrors.WithMessagef(echo.ErrBadRequest, "commitment in the store for slot %d does not match the given commitmentID (%s != %s)", commitmentID.Slot(), commitment.ID(), commitmentID) } return commitment, nil @@ -55,7 +55,7 @@ func (r *RequestHandler) GetLatestCommitment() *model.Commitment { func (r *RequestHandler) GetUTXOChanges(commitmentID iotago.CommitmentID) (*api.UTXOChangesResponse, error) { diffs, err := r.protocol.Engines.Main.Get().Ledger.SlotDiffs(commitmentID.Slot()) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get slot diffs, commitmentID: %s, slot: %d, error: %w", commitmentID, commitmentID.Slot(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get slot diffs, commitmentID: %s, slot: %d, error: %w", commitmentID, commitmentID.Slot(), err) } createdOutputs := make(iotago.OutputIDs, len(diffs.Outputs)) @@ -79,7 +79,7 @@ func (r *RequestHandler) GetUTXOChanges(commitmentID iotago.CommitmentID) (*api. func (r *RequestHandler) GetUTXOChangesFull(commitmentID iotago.CommitmentID) (*api.UTXOChangesFullResponse, error) { diffs, err := r.protocol.Engines.Main.Get().Ledger.SlotDiffs(commitmentID.Slot()) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get slot diffs, commitmentID: %s, slot: %d, error: %w", commitmentID, commitmentID.Slot(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get slot diffs, commitmentID: %s, slot: %d, error: %w", commitmentID, commitmentID.Slot(), err) } createdOutputs := make([]*api.OutputWithID, len(diffs.Outputs)) diff --git a/pkg/requesthandler/transaction.go b/pkg/requesthandler/transaction.go index 290c17d63..7b454782a 100644 --- a/pkg/requesthandler/transaction.go +++ b/pkg/requesthandler/transaction.go @@ -16,7 +16,7 @@ func (r *RequestHandler) BlockIDFromTransactionID(transactionID iotago.Transacti output, spent, err := r.protocol.Engines.Main.Get().Ledger.OutputOrSpent(outputID) if err != nil { - return iotago.EmptyBlockID, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get output %s: %s", outputID.ToHex(), err) + return iotago.EmptyBlockID, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get output %s: %w", outputID.ToHex(), err) } if output != nil { @@ -30,10 +30,10 @@ func (r *RequestHandler) TransactionMetadataByID(txID iotago.TransactionID) (*ap txMetadata, err := r.protocol.Engines.Main.Get().TxRetainer.TransactionMetadata(txID) if err != nil { if ierrors.Is(err, txretainer.ErrEntryNotFound) { - return nil, ierrors.WithMessagef(echo.ErrNotFound, "transaction metadata not found: %s", txID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "transaction metadata for transaction %s not found", txID.ToHex()) } - return nil, ierrors.Join(echo.ErrInternalServerError, ierrors.Wrapf(err, "error when retrieving transaction metadata: %s", txID.ToHex())) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to retrieve transaction metadata for transaction %s: %w", txID.ToHex(), err) } return txMetadata, nil diff --git a/pkg/requesthandler/utxo.go b/pkg/requesthandler/utxo.go index c9bd951df..cff57956e 100644 --- a/pkg/requesthandler/utxo.go +++ b/pkg/requesthandler/utxo.go @@ -12,7 +12,7 @@ import ( func (r *RequestHandler) OutputFromOutputID(outputID iotago.OutputID) (*api.OutputResponse, error) { output, err := r.protocol.Engines.Main.Get().Ledger.Output(outputID) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get output %s from the Ledger: %s", outputID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get output %s from the Ledger: %w", outputID.ToHex(), err) } return &api.OutputResponse{ @@ -24,7 +24,7 @@ func (r *RequestHandler) OutputFromOutputID(outputID iotago.OutputID) (*api.Outp func (r *RequestHandler) OutputMetadataFromOutputID(outputID iotago.OutputID) (*api.OutputMetadata, error) { output, spent, err := r.protocol.Engines.Main.Get().Ledger.OutputOrSpent(outputID) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get output %s from the Ledger: %s", outputID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get output %s from the Ledger: %w", outputID.ToHex(), err) } if spent != nil { @@ -37,13 +37,13 @@ func (r *RequestHandler) OutputMetadataFromOutputID(outputID iotago.OutputID) (* func (r *RequestHandler) OutputWithMetadataFromOutputID(outputID iotago.OutputID) (*api.OutputWithMetadataResponse, error) { output, spent, err := r.protocol.Engines.Main.Get().Ledger.OutputOrSpent(outputID) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to get output %s from the Ledger: %s", outputID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get output %s from the Ledger: %w", outputID.ToHex(), err) } if spent != nil { metadata, err := r.newSpentMetadataResponse(spent) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to load spent output metadata: %s", err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to load spent output metadata: %w", err) } return &api.OutputWithMetadataResponse{ @@ -75,7 +75,7 @@ func (r *RequestHandler) newOutputMetadataResponse(output *utxoledger.Output) (* includedSlot >= r.protocol.Engines.Main.Get().CommittedAPI().ProtocolParameters().GenesisSlot() { includedCommitment, err := r.protocol.Engines.Main.Get().Storage.Commitments().Load(includedSlot) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to load commitment with index %d: %s", includedSlot, err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to load commitment with index %d: %s", includedSlot, err) } includedCommitmentID = includedCommitment.ID() } @@ -105,7 +105,7 @@ func (r *RequestHandler) newSpentMetadataResponse(spent *utxoledger.Spent) (*api spentSlot >= r.protocol.Engines.Main.Get().CommittedAPI().ProtocolParameters().GenesisSlot() { spentCommitment, err := r.protocol.Engines.Main.Get().Storage.Commitments().Load(spentSlot) if err != nil { - return nil, ierrors.Wrapf(echo.ErrInternalServerError, "failed to load commitment with index %d: %s", spentSlot, err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to load commitment with index %d: %w", spentSlot, err) } spentCommitmentID = spentCommitment.ID() } From ebc5e4f7ced35ece13e55e1fbd57a7406362a588 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 14:44:23 +0800 Subject: [PATCH 08/19] Make error formatting consistent --- .../engine/accounts/accountsledger/manager.go | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/pkg/protocol/engine/accounts/accountsledger/manager.go b/pkg/protocol/engine/accounts/accountsledger/manager.go index 8e9f031c5..8a4aaa715 100644 --- a/pkg/protocol/engine/accounts/accountsledger/manager.go +++ b/pkg/protocol/engine/accounts/accountsledger/manager.go @@ -216,7 +216,7 @@ func (m *Manager) account(accountID iotago.AccountID, targetSlot iotago.SlotInde // read initial account data at the latest committed slot loadedAccount, exists, err := m.accountsTree.Get(accountID) if err != nil { - return nil, false, ierrors.Wrapf(err, "can't retrieve account, could not load account (%s) from accounts tree", accountID) + return nil, false, ierrors.Wrapf(err, "can't retrieve account, could not load account %s from accounts tree", accountID) } if !exists { @@ -247,7 +247,7 @@ func (m *Manager) PastAccounts(accountIDs iotago.AccountIDs, targetSlot iotago.S // read initial account data at the latest committed slot loadedAccount, exists, err := m.accountsTree.Get(accountID) if err != nil { - return nil, ierrors.Wrapf(err, "can't retrieve account, could not load account (%s) from accounts tree", accountID) + return nil, ierrors.Wrapf(err, "can't retrieve account, could not load account %s from accounts tree", accountID) } if !exists { @@ -344,11 +344,11 @@ func (m *Manager) AddAccount(output *utxoledger.Output, blockIssuanceCredits iot ) if err := m.accountsTree.Set(accountOutput.AccountID, accountData); err != nil { - return ierrors.Wrapf(err, "can't add account, could not set account (%s) in accounts tree", accountOutput.AccountID) + return ierrors.Wrapf(err, "can't add account, could not set account %s in accounts tree", accountOutput.AccountID) } if err := m.accountsTree.Commit(); err != nil { - return ierrors.Wrapf(err, "can't add account (%s), could not commit accounts tree", accountOutput.AccountID) + return ierrors.Wrapf(err, "can't add account %s, could not commit accounts tree", accountOutput.AccountID) } return nil @@ -368,12 +368,12 @@ func (m *Manager) rollbackAccountTo(accountData *accounts.AccountData, targetSlo for diffSlot := m.latestCommittedSlot; diffSlot > targetSlot; diffSlot-- { diffStore, err := m.slotDiff(diffSlot) if err != nil { - return false, ierrors.Errorf("can't retrieve account, could not find diff store for slot (%d)", diffSlot) + return false, ierrors.Errorf("can't retrieve account, could not find diff store for slot %d", diffSlot) } found, err := diffStore.Has(accountData.ID) if err != nil { - return false, ierrors.Wrapf(err, "can't retrieve account, could not check if diff store for slot (%d) has account (%s)", diffSlot, accountData.ID) + return false, ierrors.Wrapf(err, "can't retrieve account, could not check if diff store for slot %d has account %s", diffSlot, accountData.ID) } // no changes for this account in this slot @@ -383,7 +383,7 @@ func (m *Manager) rollbackAccountTo(accountData *accounts.AccountData, targetSlo diffChange, destroyed, err := diffStore.Load(accountData.ID) if err != nil { - return false, ierrors.Wrapf(err, "can't retrieve account, could not load diff for account (%s) in slot (%d)", accountData.ID, diffSlot) + return false, ierrors.Wrapf(err, "can't retrieve account, could not load diff for account %s in slot %d", accountData.ID, diffSlot) } // update the account data with the diff @@ -401,25 +401,25 @@ func (m *Manager) rollbackAccountTo(accountData *accounts.AccountData, targetSlo validatorStake, err := safemath.SafeSub(int64(accountData.ValidatorStake), diffChange.ValidatorStakeChange) if err != nil { - return false, ierrors.Wrapf(err, "can't retrieve account, validator stake underflow for account (%s) in slot (%d): %d - %d", accountData.ID, diffSlot, accountData.ValidatorStake, diffChange.ValidatorStakeChange) + return false, ierrors.Wrapf(err, "can't retrieve account, validator stake underflow for account %s in slot %d: %d - %d", accountData.ID, diffSlot, accountData.ValidatorStake, diffChange.ValidatorStakeChange) } accountData.ValidatorStake = iotago.BaseToken(validatorStake) delegationStake, err := safemath.SafeSub(int64(accountData.DelegationStake), diffChange.DelegationStakeChange) if err != nil { - return false, ierrors.Wrapf(err, "can't retrieve account, delegation stake underflow for account (%s) in slot (%d): %d - %d", accountData.ID, diffSlot, accountData.DelegationStake, diffChange.DelegationStakeChange) + return false, ierrors.Wrapf(err, "can't retrieve account, delegation stake underflow for account %s in slot %d: %d - %d", accountData.ID, diffSlot, accountData.DelegationStake, diffChange.DelegationStakeChange) } accountData.DelegationStake = iotago.BaseToken(delegationStake) stakeEpochEnd, err := safemath.SafeSub(int64(accountData.StakeEndEpoch), diffChange.StakeEndEpochChange) if err != nil { - return false, ierrors.Wrapf(err, "can't retrieve account, stake end epoch underflow for account (%s) in slot (%d): %d - %d", accountData.ID, diffSlot, accountData.StakeEndEpoch, diffChange.StakeEndEpochChange) + return false, ierrors.Wrapf(err, "can't retrieve account, stake end epoch underflow for account %s in slot %d: %d - %d", accountData.ID, diffSlot, accountData.StakeEndEpoch, diffChange.StakeEndEpochChange) } accountData.StakeEndEpoch = iotago.EpochIndex(stakeEpochEnd) fixedCost, err := safemath.SafeSub(int64(accountData.FixedCost), diffChange.FixedCostChange) if err != nil { - return false, ierrors.Wrapf(err, "can't retrieve account, fixed cost underflow for account (%s) in slot (%d): %d - %d", accountData.ID, diffSlot, accountData.FixedCost, diffChange.FixedCostChange) + return false, ierrors.Wrapf(err, "can't retrieve account, fixed cost underflow for account %s in slot %d: %d - %d", accountData.ID, diffSlot, accountData.FixedCost, diffChange.FixedCostChange) } accountData.FixedCost = iotago.Mana(fixedCost) if diffChange.PrevLatestSupportedVersionAndHash != diffChange.NewLatestSupportedVersionAndHash { @@ -437,7 +437,7 @@ func (m *Manager) preserveDestroyedAccountData(accountID iotago.AccountID) (acco // if any data is left on the account, we need to store in the diff, to be able to rollback accountData, exists, err := m.accountsTree.Get(accountID) if err != nil { - return nil, ierrors.Wrapf(err, "can't retrieve account, could not load account (%s) from accounts tree", accountID) + return nil, ierrors.Wrapf(err, "can't retrieve account, could not load account %s from accounts tree", accountID) } if !exists { @@ -509,7 +509,7 @@ func (m *Manager) commitAccountTree(slot iotago.SlotIndex, accountDiffChanges ma // remove a destroyed account, no need to update with diffs if destroyedAccounts.Has(accountID) { if _, err := m.accountsTree.Delete(accountID); err != nil { - return ierrors.Wrapf(err, "could not delete account (%s) from accounts tree", accountID) + return ierrors.Wrapf(err, "could not delete account %s from accounts tree", accountID) } continue @@ -517,7 +517,7 @@ func (m *Manager) commitAccountTree(slot iotago.SlotIndex, accountDiffChanges ma accountData, exists, err := m.accountsTree.Get(accountID) if err != nil { - return ierrors.Wrapf(err, "can't retrieve account, could not load account (%s) from accounts tree", accountID) + return ierrors.Wrapf(err, "can't retrieve account, could not load account %s from accounts tree", accountID) } if !exists { @@ -529,7 +529,7 @@ func (m *Manager) commitAccountTree(slot iotago.SlotIndex, accountDiffChanges ma if exists { decayedPreviousCredits, err := m.apiProvider.APIForSlot(slot).ManaDecayProvider().DecayManaBySlots(iotago.Mana(accountData.Credits.Value), accountData.Credits.UpdateSlot, slot) if err != nil { - return ierrors.Wrapf(err, "can't retrieve account, could not decay credits for account (%s) in slot (%d)", accountData.ID, slot) + return ierrors.Wrapf(err, "can't retrieve account, could not decay credits for account %s in slot %d", accountData.ID, slot) } // update the account data diff taking into account the decay, the modified diff will be stored in the calling @@ -555,25 +555,25 @@ func (m *Manager) commitAccountTree(slot iotago.SlotIndex, accountDiffChanges ma validatorStake, err := safemath.SafeAdd(int64(accountData.ValidatorStake), diffChange.ValidatorStakeChange) if err != nil { - return ierrors.Wrapf(err, "can't retrieve account, validator stake overflow for account (%s) in slot (%d): %d + %d", accountData.ID, slot, accountData.ValidatorStake, diffChange.ValidatorStakeChange) + return ierrors.Wrapf(err, "can't retrieve account, validator stake overflow for account %s in slot %d: %d + %d", accountData.ID, slot, accountData.ValidatorStake, diffChange.ValidatorStakeChange) } accountData.ValidatorStake = iotago.BaseToken(validatorStake) delegationStake, err := safemath.SafeAdd(int64(accountData.DelegationStake), diffChange.DelegationStakeChange) if err != nil { - return ierrors.Wrapf(err, "can't retrieve account, delegation stake overflow for account (%s) in slot (%d): %d + %d", accountData.ID, slot, accountData.DelegationStake, diffChange.DelegationStakeChange) + return ierrors.Wrapf(err, "can't retrieve account, delegation stake overflow for account %s in slot %d: %d + %d", accountData.ID, slot, accountData.DelegationStake, diffChange.DelegationStakeChange) } accountData.DelegationStake = iotago.BaseToken(delegationStake) stakeEndEpoch, err := safemath.SafeAdd(int64(accountData.StakeEndEpoch), diffChange.StakeEndEpochChange) if err != nil { - return ierrors.Wrapf(err, "can't retrieve account, stake end epoch overflow for account (%s) in slot (%d): %d + %d", accountData.ID, slot, accountData.StakeEndEpoch, diffChange.StakeEndEpochChange) + return ierrors.Wrapf(err, "can't retrieve account, stake end epoch overflow for account %s in slot %d: %d + %d", accountData.ID, slot, accountData.StakeEndEpoch, diffChange.StakeEndEpochChange) } accountData.StakeEndEpoch = iotago.EpochIndex(stakeEndEpoch) fixedCost, err := safemath.SafeAdd(int64(accountData.FixedCost), diffChange.FixedCostChange) if err != nil { - return ierrors.Wrapf(err, "can't retrieve account, validator fixed cost overflow for account (%s) in slot (%d): %d + %d", accountData.ID, slot, accountData.FixedCost, diffChange.FixedCostChange) + return ierrors.Wrapf(err, "can't retrieve account, validator fixed cost overflow for account %s in slot %d: %d + %d", accountData.ID, slot, accountData.FixedCost, diffChange.FixedCostChange) } accountData.FixedCost = iotago.Mana(fixedCost) @@ -582,7 +582,7 @@ func (m *Manager) commitAccountTree(slot iotago.SlotIndex, accountDiffChanges ma } if err := m.accountsTree.Set(accountID, accountData); err != nil { - return ierrors.Wrapf(err, "could not set account (%s) in accounts tree", accountID) + return ierrors.Wrapf(err, "could not set account %s in accounts tree", accountID) } } @@ -610,7 +610,7 @@ func (m *Manager) updateSlotDiffWithBurns(slot iotago.SlotIndex, accountDiffs ma accountDiff = model.NewAccountDiff() accountData, exists, err := m.account(id, slot-1) if err != nil { - panic(ierrors.Errorf("error loading account %s in slot %d: %w", id, slot-1, err)) + panic(ierrors.Wrapf(err, "error loading account %s in slot %d", id, slot-1)) } if !exists { panic(ierrors.Errorf("trying to burn Mana from account %s which is not present in slot %d", id, slot-1)) @@ -638,7 +638,7 @@ func (m *Manager) updateSlotDiffWithVersionSignals(slot iotago.SlotIndex, accoun for id, signaledBlock := range signalsStorage.AsMap() { accountData, exists, err := m.accountsTree.Get(id) if err != nil { - return ierrors.Wrapf(err, "can't retrieve account, could not load account (%s) from accounts tree", id) + return ierrors.Wrapf(err, "can't retrieve account, could not load account %s from accounts tree", id) } if !exists { From 25bd8147d3b8c24672a0949d2a4fb241a01a93f9 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 15:53:15 +0800 Subject: [PATCH 09/19] Fix error wrapping order in engine and booker --- pkg/protocol/engine/accounts/mana/manager.go | 8 ++++---- pkg/protocol/engine/booker/inmemorybooker/booker.go | 4 ++-- pkg/protocol/engine/commitment_api.go | 12 ++++++------ .../congestioncontrol/scheduler/drr/scheduler.go | 2 +- pkg/protocol/engine/engine.go | 2 +- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/pkg/protocol/engine/accounts/mana/manager.go b/pkg/protocol/engine/accounts/mana/manager.go index 8716d1d2b..9355987b5 100644 --- a/pkg/protocol/engine/accounts/mana/manager.go +++ b/pkg/protocol/engine/accounts/mana/manager.go @@ -53,12 +53,12 @@ func (m *Manager) GetManaOnAccount(accountID iotago.AccountID, slot iotago.SlotI if !exists || mana.UpdateTime() > slot { output, err := m.accountOutputResolveFunc(accountID, slot) if err != nil { - return 0, ierrors.Wrapf(err, "failed to resolve AccountOutput for %s in slot %s", accountID, slot) + return 0, ierrors.Wrapf(err, "failed to resolve AccountOutput %s in slot %s", accountID, slot) } mana, err = m.getMana(accountID, output, slot) if err != nil { - return 0, ierrors.Wrapf(err, "failed to calculate mana for %s in slot %s", accountID, slot) + return 0, ierrors.Wrapf(err, "failed to calculate mana for account %s in slot %s", accountID, slot) } // If it did not exist in cache, then add an entry to cache. @@ -191,7 +191,7 @@ func (m *Manager) ApplyDiff(slot iotago.SlotIndex, destroyedAccounts ds.Set[iota } else if accountDiff.BICChange != 0 { var err error if accountOutput, err = m.accountOutputResolveFunc(accountID, slot); err != nil { - return ierrors.Errorf("failed to resolve AccountOutput for %s in slot %s: %w", accountID, slot, err) + return ierrors.Wrapf(err, "failed to resolve AccountOutput %s in slot %s", accountID, slot) } } @@ -199,7 +199,7 @@ func (m *Manager) ApplyDiff(slot iotago.SlotIndex, destroyedAccounts ds.Set[iota if accountOutput != nil { mana, err := m.getMana(accountID, accountOutput, slot) if err != nil { - return ierrors.Wrapf(err, "failed to calculate mana on an account %s", accountID) + return ierrors.Wrapf(err, "failed to calculate mana on account %s", accountID) } m.manaVectorCache.Put(accountID, mana) diff --git a/pkg/protocol/engine/booker/inmemorybooker/booker.go b/pkg/protocol/engine/booker/inmemorybooker/booker.go index 56ca12b29..60a0d3098 100644 --- a/pkg/protocol/engine/booker/inmemorybooker/booker.go +++ b/pkg/protocol/engine/booker/inmemorybooker/booker.go @@ -89,7 +89,7 @@ func (b *Booker) Queue(block *blocks.Block) error { } if signedTransactionMetadata == nil { - return ierrors.Errorf("transaction in %s was not attached", block.ID()) + return ierrors.Errorf("transaction in block %s was not attached", block.ID()) } // Based on the assumption that we always fork and the UTXO and Tangle past cones are always fully known. @@ -150,7 +150,7 @@ func (b *Booker) setupBlock(block *blocks.Block) { parentBlock.Invalid().OnUpdateOnce(func(_ bool, _ bool) { if block.SetInvalid() { - b.events.BlockInvalid.Trigger(block, ierrors.Errorf("block marked as invalid in Booker because parent block is invalid %s", parentBlock.ID())) + b.events.BlockInvalid.Trigger(block, ierrors.Errorf("block marked as invalid in Booker because parent block %s is invalid", parentBlock.ID())) } }) }) diff --git a/pkg/protocol/engine/commitment_api.go b/pkg/protocol/engine/commitment_api.go index 6ad955b20..38caa5b1a 100644 --- a/pkg/protocol/engine/commitment_api.go +++ b/pkg/protocol/engine/commitment_api.go @@ -87,19 +87,19 @@ func (c *CommitmentAPI) Mutations() (acceptedBlocksBySlotCommitment map[iotago.C // Roots returns the roots of the slot. func (c *CommitmentAPI) Roots() (committedRoots *iotago.Roots, err error) { if c.engine.SyncManager.LatestCommitment().Slot() < c.CommitmentID.Slot() { - return nil, ierrors.Errorf("slot %d is not committed yet", c.CommitmentID) + return nil, ierrors.Errorf("slot %d is not committed yet", c.CommitmentID.Slot()) } rootsStorage, err := c.engine.Storage.Roots(c.CommitmentID.Slot()) if err != nil { - return nil, ierrors.Errorf("no roots storage for slot %d", c.CommitmentID) + return nil, ierrors.Errorf("no roots storage for slot %d", c.CommitmentID.Slot()) } roots, _, err := rootsStorage.Load(c.CommitmentID) if err != nil { - return nil, ierrors.Wrapf(err, "failed to load roots for slot %d", c.CommitmentID) + return nil, ierrors.Wrapf(err, "failed to load roots for slot %d", c.CommitmentID.Slot()) } else if roots == nil { - return nil, ierrors.Errorf("roots for slot %d are not known, yet", c.CommitmentID) + return nil, ierrors.Errorf("roots for slot %d are not known, yet", c.CommitmentID.Slot()) } return roots, nil @@ -108,7 +108,7 @@ func (c *CommitmentAPI) Roots() (committedRoots *iotago.Roots, err error) { // BlocksIDsBySlotCommitmentID returns the accepted block IDs of the slot grouped by their SlotCommitmentID. func (c *CommitmentAPI) BlocksIDsBySlotCommitmentID() (map[iotago.CommitmentID]iotago.BlockIDs, error) { if c.engine.SyncManager.LatestCommitment().Slot() < c.CommitmentID.Slot() { - return nil, ierrors.Errorf("slot %d is not committed yet", c.CommitmentID) + return nil, ierrors.Errorf("slot %d is not committed yet", c.CommitmentID.Slot()) } store, err := c.engine.Storage.Blocks(c.CommitmentID.Slot()) @@ -129,7 +129,7 @@ func (c *CommitmentAPI) BlocksIDsBySlotCommitmentID() (map[iotago.CommitmentID]i func (c *CommitmentAPI) TransactionIDs() (iotago.TransactionIDs, error) { if c.engine.SyncManager.LatestCommitment().Slot() < c.CommitmentID.Slot() { - return nil, ierrors.Errorf("slot %d is not committed yet", c.CommitmentID) + return nil, ierrors.Errorf("slot %d is not committed yet", c.CommitmentID.Slot()) } store, err := c.engine.Storage.Mutations(c.CommitmentID.Slot()) diff --git a/pkg/protocol/engine/congestioncontrol/scheduler/drr/scheduler.go b/pkg/protocol/engine/congestioncontrol/scheduler/drr/scheduler.go index 85a8bc2eb..4735ef524 100644 --- a/pkg/protocol/engine/congestioncontrol/scheduler/drr/scheduler.go +++ b/pkg/protocol/engine/congestioncontrol/scheduler/drr/scheduler.go @@ -277,7 +277,7 @@ func (s *Scheduler) enqueueBasicBlock(block *blocks.Block) { func(issuerID iotago.AccountID) Deficit { quantum, quantumErr := s.quantumFunc(issuerID, slot) if quantumErr != nil { - s.errorHandler(ierrors.Wrapf(quantumErr, "failed to retrieve deficit for issuerID %d in slot %d when submitting a block", issuerID, slot)) + s.errorHandler(ierrors.Wrapf(quantumErr, "failed to retrieve deficit for issuerID %s in slot %d when submitting a block", issuerID, slot)) return 0 } diff --git a/pkg/protocol/engine/engine.go b/pkg/protocol/engine/engine.go index fd6fd45da..d6e7162a4 100644 --- a/pkg/protocol/engine/engine.go +++ b/pkg/protocol/engine/engine.go @@ -455,7 +455,7 @@ func (e *Engine) setupBlockStorage() { e.Events.BlockGadget.BlockAccepted.Hook(func(block *blocks.Block) { store, err := e.Storage.Blocks(block.ID().Slot()) if err != nil { - e.errorHandler(ierrors.Errorf("failed to store block with %s, storage with given index does not exist", block.ID())) + e.errorHandler(ierrors.Errorf("failed to store block %s, storage at block's slot does not exist", block.ID())) return } From 7dccb4ff9338b178164448a2ecd3363a7ea45762 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Wed, 13 Mar 2024 17:24:24 +0800 Subject: [PATCH 10/19] Fix error wrapping in filters --- .../post_solid_block_filter.go | 24 +++++++++---------- .../pre_solid_block_filter.go | 6 ++--- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/pkg/protocol/engine/filter/postsolidfilter/postsolidblockfilter/post_solid_block_filter.go b/pkg/protocol/engine/filter/postsolidfilter/postsolidblockfilter/post_solid_block_filter.go index cc5a66338..47c1c1fe5 100644 --- a/pkg/protocol/engine/filter/postsolidfilter/postsolidblockfilter/post_solid_block_filter.go +++ b/pkg/protocol/engine/filter/postsolidfilter/postsolidblockfilter/post_solid_block_filter.go @@ -62,7 +62,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if !exists { c.filterBlock( block, - ierrors.Join(iotago.ErrBlockParentNotFound, ierrors.Errorf("parent %s of block %s is not known", parentID, block.ID())), + ierrors.WithMessagef(iotago.ErrBlockParentNotFound, "parent %s of block %s is not known", parentID, block.ID()), ) return @@ -71,7 +71,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if !block.IssuingTime().After(parent.IssuingTime()) { c.filterBlock( block, - ierrors.Join(iotago.ErrBlockIssuingTimeNonMonotonic, ierrors.Errorf("block %s issuing time %s not greater than parent's %s issuing time %s", block.ID(), block.IssuingTime(), parentID, parent.IssuingTime())), + ierrors.WithMessagef(iotago.ErrBlockIssuingTimeNonMonotonic, "block %s's issuing time %s is not greater than parent's %s issuing time %s", block.ID(), block.IssuingTime(), parentID, parent.IssuingTime()), ) return @@ -86,7 +86,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if err != nil { c.filterBlock( block, - ierrors.Join(iotago.ErrIssuerAccountNotFound, ierrors.Wrapf(err, "could not retrieve account information for block issuer %s", block.ProtocolBlock().Header.IssuerID)), + ierrors.WithMessagef(iotago.ErrIssuerAccountNotFound, "could not retrieve account information for block issuer %s: %w", block.ProtocolBlock().Header.IssuerID, err), ) return @@ -94,7 +94,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if !exists { c.filterBlock( block, - ierrors.Join(iotago.ErrIssuerAccountNotFound, ierrors.Errorf("block issuer account %s does not exist in slot commitment %s", block.ProtocolBlock().Header.IssuerID, block.ProtocolBlock().Header.SlotCommitmentID.Slot())), + ierrors.WithMessagef(iotago.ErrIssuerAccountNotFound, "block issuer account %s does not exist in slot commitment %s", block.ProtocolBlock().Header.IssuerID, block.ProtocolBlock().Header.SlotCommitmentID.Slot()), ) return @@ -107,7 +107,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if err != nil { c.filterBlock( block, - ierrors.Join(iotago.ErrRMCNotFound, ierrors.Wrapf(err, "could not retrieve RMC for slot commitment %s", rmcSlot)), + ierrors.WithMessagef(iotago.ErrRMCNotFound, "could not retrieve RMC for slot commitment %s: %w", rmcSlot, err), ) return @@ -117,13 +117,13 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if err != nil { c.filterBlock( block, - ierrors.Join(iotago.ErrFailedToCalculateManaCost, ierrors.Wrapf(err, "could not calculate Mana cost for block")), + ierrors.WithMessagef(iotago.ErrFailedToCalculateManaCost, "could not calculate Mana cost for block: %w", err), ) } if basicBlock.MaxBurnedMana < manaCost { c.filterBlock( block, - ierrors.Join(iotago.ErrBurnedInsufficientMana, ierrors.Errorf("block issuer account %s burned insufficient Mana, required %d, burned %d", block.ProtocolBlock().Header.IssuerID, manaCost, basicBlock.MaxBurnedMana)), + ierrors.WithMessagef(iotago.ErrBurnedInsufficientMana, "block issuer account %s burned insufficient Mana, required %d, burned %d", block.ProtocolBlock().Header.IssuerID, manaCost, basicBlock.MaxBurnedMana), ) return @@ -136,7 +136,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if accountData.Credits.Value < 0 { c.filterBlock( block, - ierrors.Wrapf(iotago.ErrAccountLocked, "block issuer account %s", block.ProtocolBlock().Header.IssuerID), + ierrors.WithMessagef(iotago.ErrAccountLocked, "block issuer account %s", block.ProtocolBlock().Header.IssuerID), ) return @@ -148,7 +148,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if accountData.ExpirySlot < block.ProtocolBlock().Header.SlotCommitmentID.Slot() { c.filterBlock( block, - ierrors.Wrapf(iotago.ErrAccountExpired, "block issuer account %s is expired, expiry slot %d in commitment %d", block.ProtocolBlock().Header.IssuerID, accountData.ExpirySlot, block.ProtocolBlock().Header.SlotCommitmentID.Slot()), + ierrors.WithMessagef(iotago.ErrAccountExpired, "block issuer account %s is expired, expiry slot %d in commitment %d", block.ProtocolBlock().Header.IssuerID, accountData.ExpirySlot, block.ProtocolBlock().Header.SlotCommitmentID.Slot()), ) return @@ -164,7 +164,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if !accountData.BlockIssuerKeys.Has(expectedBlockIssuerKey) { c.filterBlock( block, - ierrors.Wrapf(iotago.ErrInvalidSignature, "block issuer account %s does not have block issuer key corresponding to public key %s in slot %d", block.ProtocolBlock().Header.IssuerID, hexutil.EncodeHex(signature.PublicKey[:]), block.ProtocolBlock().Header.SlotCommitmentID.Index()), + ierrors.WithMessagef(iotago.ErrInvalidSignature, "block issuer account %s does not have block issuer key corresponding to public key %s in slot %d", block.ProtocolBlock().Header.IssuerID, hexutil.EncodeHex(signature.PublicKey[:]), block.ProtocolBlock().Header.SlotCommitmentID.Index()), ) return @@ -174,7 +174,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { if err != nil { c.filterBlock( block, - ierrors.Wrapf(iotago.ErrInvalidSignature, "error: %s", err.Error()), + ierrors.WithMessagef(iotago.ErrInvalidSignature, "%w", err), ) return @@ -190,7 +190,7 @@ func (c *PostSolidBlockFilter) ProcessSolidBlock(block *blocks.Block) { default: c.filterBlock( block, - ierrors.Wrapf(iotago.ErrInvalidSignature, "only ed25519 signatures supported, got %s", block.ProtocolBlock().Signature.Type()), + ierrors.WithMessagef(iotago.ErrInvalidSignature, "only ed25519 signatures supported, got %s", block.ProtocolBlock().Signature.Type()), ) return diff --git a/pkg/protocol/engine/filter/presolidfilter/presolidblockfilter/pre_solid_block_filter.go b/pkg/protocol/engine/filter/presolidfilter/presolidblockfilter/pre_solid_block_filter.go index ee1c0edc3..07eed7c7e 100644 --- a/pkg/protocol/engine/filter/presolidfilter/presolidblockfilter/pre_solid_block_filter.go +++ b/pkg/protocol/engine/filter/presolidfilter/presolidblockfilter/pre_solid_block_filter.go @@ -66,7 +66,7 @@ func (f *PreSolidBlockFilter) ProcessReceivedBlock(block *model.Block, source pe if apiForSlot.Version() != block.ProtocolBlock().Header.ProtocolVersion { f.events.BlockPreFiltered.Trigger(&presolidfilter.BlockPreFilteredEvent{ Block: block, - Reason: ierrors.Wrapf(ErrInvalidBlockVersion, "invalid protocol version %d (expected %d) for epoch %d", block.ProtocolBlock().Header.ProtocolVersion, apiForSlot.Version(), apiForSlot.TimeProvider().EpochFromSlot(block.ID().Slot())), + Reason: ierrors.WithMessagef(ErrInvalidBlockVersion, "invalid protocol version %d (expected %d) for epoch %d", block.ProtocolBlock().Header.ProtocolVersion, apiForSlot.Version(), apiForSlot.TimeProvider().EpochFromSlot(block.ID().Slot())), Source: source, }) @@ -79,7 +79,7 @@ func (f *PreSolidBlockFilter) ProcessReceivedBlock(block *model.Block, source pe if !exists { f.events.BlockPreFiltered.Trigger(&presolidfilter.BlockPreFilteredEvent{ Block: block, - Reason: ierrors.Wrapf(ErrValidatorNotInCommittee, "no committee for slot %d", blockSlot), + Reason: ierrors.WithMessagef(ErrValidatorNotInCommittee, "no committee for slot %d", blockSlot), Source: source, }) @@ -89,7 +89,7 @@ func (f *PreSolidBlockFilter) ProcessReceivedBlock(block *model.Block, source pe if !committee.HasAccount(block.ProtocolBlock().Header.IssuerID) { f.events.BlockPreFiltered.Trigger(&presolidfilter.BlockPreFilteredEvent{ Block: block, - Reason: ierrors.Wrapf(ErrValidatorNotInCommittee, "validation block issuer %s is not part of the committee for slot %d", block.ProtocolBlock().Header.IssuerID, blockSlot), + Reason: ierrors.WithMessagef(ErrValidatorNotInCommittee, "validation block issuer %s is not part of the committee for slot %d", block.ProtocolBlock().Header.IssuerID, blockSlot), Source: source, }) From 3e099115c023e7072357cee67d902b9d26c791fd Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Thu, 14 Mar 2024 12:31:34 +0800 Subject: [PATCH 11/19] Improve errors in ledger --- pkg/protocol/engine/ledger/ledger/ledger.go | 42 +++++++++--------- pkg/protocol/engine/ledger/ledger/vm.go | 49 ++++++++++----------- 2 files changed, 44 insertions(+), 47 deletions(-) diff --git a/pkg/protocol/engine/ledger/ledger/ledger.go b/pkg/protocol/engine/ledger/ledger/ledger.go index 22fc3b200..c500a2927 100644 --- a/pkg/protocol/engine/ledger/ledger/ledger.go +++ b/pkg/protocol/engine/ledger/ledger/ledger.go @@ -123,7 +123,7 @@ func (l *Ledger) AttachTransaction(block *blocks.Block) (attachedTransaction mem if signedTransaction, hasTransaction := block.SignedTransaction(); hasTransaction { signedTransactionMetadata, err := l.memPool.AttachSignedTransaction(signedTransaction, signedTransaction.Transaction, block.ID()) if err != nil { - l.errorHandler(ierrors.Wrapf(err, "failed to attach transaction %s to block %s", signedTransaction.Transaction.MustID(), block.ID())) + l.errorHandler(ierrors.Wrapf(err, "failed to attach signed transaction %s to block %s", signedTransaction.Transaction.MustID(), block.ID())) return nil, true } @@ -146,7 +146,7 @@ func (l *Ledger) CommitSlot(slot iotago.SlotIndex) (stateRoot iotago.Identifier, stateDiff, err := l.memPool.CommitStateDiff(slot) if err != nil { - return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Errorf("failed to retrieve state diff for slot %d: %w", slot, err) + return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Wrapf(err, "failed to retrieve state diff for slot %d", slot) } // collect outputs and allotments from the "uncompacted" stateDiff @@ -154,7 +154,7 @@ func (l *Ledger) CommitSlot(slot iotago.SlotIndex) (stateRoot iotago.Identifier, // and retrieve intermediate outputs to show to the user spenders, outputs, accountDiffs, err := l.processStateDiffTransactions(stateDiff) if err != nil { - return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Errorf("failed to process state diff transactions in slot %d: %w", slot, err) + return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Wrapf(err, "failed to process state diff transactions in slot %d", slot) } // Now we process the collected account changes, for that we consume the "compacted" state diff to get the overall @@ -163,7 +163,7 @@ func (l *Ledger) CommitSlot(slot iotago.SlotIndex) (stateRoot iotago.Identifier, // output side createdAccounts, consumedAccounts, destroyedAccounts, err := l.processCreatedAndConsumedAccountOutputs(stateDiff, accountDiffs) if err != nil { - return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Errorf("failed to process outputs consumed and created in slot %d: %w", slot, err) + return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Wrapf(err, "failed to process outputs consumed and created in slot %d", slot) } l.prepareAccountDiffs(accountDiffs, slot, consumedAccounts, createdAccounts) @@ -171,7 +171,7 @@ func (l *Ledger) CommitSlot(slot iotago.SlotIndex) (stateRoot iotago.Identifier, // Commit the changes // Update the UTXO ledger if err = l.utxoLedger.ApplyDiff(slot, outputs, spenders); err != nil { - return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Errorf("failed to apply diff to UTXO ledger for slot %d: %w", slot, err) + return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Wrapf(err, "failed to apply diff to UTXO ledger for slot %d", slot) } // Update the Accounts ledger @@ -183,15 +183,15 @@ func (l *Ledger) CommitSlot(slot iotago.SlotIndex) (stateRoot iotago.Identifier, } rmcForSlot, err := l.rmcManager.RMC(rmcSlot) if err != nil { - return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Errorf("ledger failed to get RMC for slot %d: %w", rmcSlot, err) + return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Wrapf(err, "ledger failed to get RMC for slot %d", rmcSlot) } if err = l.accountsLedger.ApplyDiff(slot, rmcForSlot, accountDiffs, destroyedAccounts); err != nil { - return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Errorf("failed to apply diff to Accounts ledger for slot %d: %w", slot, err) + return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Wrapf(err, "failed to apply diff to Accounts ledger for slot %d", slot) } // Update the mana manager's cache if err = l.manaManager.ApplyDiff(slot, destroyedAccounts, createdAccounts, accountDiffs); err != nil { - return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Errorf("failed to apply diff to mana manager for slot %d: %w", slot, err) + return iotago.Identifier{}, iotago.Identifier{}, iotago.Identifier{}, nil, nil, nil, ierrors.Wrapf(err, "failed to apply diff to mana manager for slot %d", slot) } // Mark each transaction as committed so the mempool can evict it @@ -382,7 +382,7 @@ func (l *Ledger) prepareAccountDiffs(accountDiffs map[iotago.AccountID]*model.Ac // Obtain account state at the current latest committed slot, which is slot-1 accountData, exists, err := l.accountsLedger.Account(consumedAccountID, slot-1) if err != nil { - panic(ierrors.Errorf("error loading account %s in slot %d: %w", consumedAccountID, slot-1, err)) + panic(ierrors.Wrapf(err, "error loading account %s in slot %d", consumedAccountID, slot-1)) } if !exists { panic(ierrors.Errorf("could not find destroyed account %s in slot %d", consumedAccountID, slot-1)) @@ -538,7 +538,7 @@ func (l *Ledger) processCreatedAndConsumedAccountOutputs(stateDiff mempool.State }) if err != nil { - return nil, nil, nil, ierrors.Errorf("error while processing created states: %w", err) + return nil, nil, nil, ierrors.Wrap(err, "error while processing created states") } // input side @@ -596,7 +596,7 @@ func (l *Ledger) processCreatedAndConsumedAccountOutputs(stateDiff mempool.State } if err != nil { - return nil, nil, nil, ierrors.Errorf("error while processing created states: %w", err) + return nil, nil, nil, ierrors.Wrap(err, "error while processing created states") } return createdAccounts, consumedAccounts, destroyedAccounts, nil @@ -620,7 +620,7 @@ func (l *Ledger) processStateDiffTransactions(stateDiff mempool.StateDiff) (spen for _, inputRef := range lo.Map(inputRefs, mempool.UTXOInputStateRefFromInput) { stateWithMetadata, stateError := l.memPool.StateMetadata(inputRef) if stateError != nil { - err = ierrors.Wrapf(stateError, "failed to retrieve outputs of %s", txID) + err = ierrors.Wrapf(stateError, "failed to retrieve outputs of transaction %s", txID) return false } spent := utxoledger.NewSpent(l.outputFromState(stateWithMetadata.State()), txWithMeta.ID(), stateDiff.Slot()) @@ -653,7 +653,7 @@ func (l *Ledger) processStateDiffTransactions(stateDiff mempool.StateDiff) (spen accountData, exists, accountErr := l.accountsLedger.Account(allotment.AccountID, stateDiff.Slot()-1) if accountErr != nil { - panic(ierrors.Errorf("error loading account %s in slot %d: %w", allotment.AccountID, stateDiff.Slot()-1, accountErr)) + panic(ierrors.Wrapf(accountErr, "error loading account %s in slot %d", allotment.AccountID, stateDiff.Slot()-1)) } // if the account does not exist in our AccountsLedger it means it doesn't have a BIC feature, so // we burn this allotment. @@ -683,10 +683,10 @@ func (l *Ledger) processStateDiffTransactions(stateDiff mempool.StateDiff) (spen func (l *Ledger) resolveAccountOutput(accountID iotago.AccountID, slot iotago.SlotIndex) (*utxoledger.Output, error) { accountMetadata, exists, err := l.accountsLedger.Account(accountID, slot) if err != nil { - return nil, ierrors.Errorf("could not get account information for account %s in slot %d: %w", accountID, slot, err) + return nil, ierrors.Wrapf(err, "could not get account information for account %s in slot %d", accountID, slot) } if !exists { - return nil, ierrors.Errorf("account %s does not exist in slot %d: %w", accountID, slot, mempool.ErrStateNotFound) + return nil, ierrors.WithMessagef(mempool.ErrStateNotFound, "account %s does not exist in slot %d", accountID, slot) } l.utxoLedger.ReadLockLedger() @@ -694,15 +694,15 @@ func (l *Ledger) resolveAccountOutput(accountID iotago.AccountID, slot iotago.Sl isUnspent, err := l.utxoLedger.IsOutputIDUnspentWithoutLocking(accountMetadata.OutputID) if err != nil { - return nil, ierrors.Errorf("error while checking account output %s is unspent: %w", accountMetadata.OutputID, err) + return nil, ierrors.Wrapf(err, "error while checking whether account with output id %s is unspent", accountMetadata.OutputID.ToHex()) } if !isUnspent { - return nil, ierrors.Errorf("unspent account output %s not found: %w", accountMetadata.OutputID, mempool.ErrStateNotFound) + return nil, ierrors.WithMessagef(mempool.ErrStateNotFound, "unspent account with output id %s not found", accountMetadata.OutputID.ToHex()) } accountOutput, err := l.utxoLedger.ReadOutputByOutputIDWithoutLocking(accountMetadata.OutputID) if err != nil { - return nil, ierrors.Errorf("error while retrieving account output %s: %w", accountMetadata.OutputID, err) + return nil, ierrors.Wrapf(err, "error while retrieving account with output id %s", accountMetadata.OutputID.ToHex()) } return accountOutput, nil @@ -720,17 +720,17 @@ func (l *Ledger) resolveState(stateRef mempool.StateReference) *promise.Promise[ utxoInput := stateRef.(mempool.UTXOInputStateRef).Input isUnspent, err := l.utxoLedger.IsOutputIDUnspentWithoutLocking(utxoInput.OutputID()) if err != nil { - return p.Reject(ierrors.Wrapf(iotago.ErrUTXOInputInvalid, "error while retrieving output %s: %w", utxoInput.OutputID(), err)) + return p.Reject(ierrors.Join(iotago.ErrUTXOInputInvalid, ierrors.Wrapf(err, "error while retrieving output %s", utxoInput.OutputID()))) } if !isUnspent { - return p.Reject(ierrors.Join(iotago.ErrInputAlreadySpent, ierrors.Wrapf(mempool.ErrStateNotFound, "unspent output %s not found", utxoInput.OutputID()))) + return p.Reject(ierrors.Join(iotago.ErrInputAlreadySpent, ierrors.WithMessagef(mempool.ErrStateNotFound, "unspent output %s not found", utxoInput.OutputID()))) } // possible to cast `stateRef` to more specialized interfaces here, e.g. for DustOutput output, err := l.utxoLedger.ReadOutputByOutputIDWithoutLocking(utxoInput.OutputID()) if err != nil { - return p.Reject(ierrors.Wrapf(iotago.ErrUTXOInputInvalid, "output %s not found: %w", utxoInput.OutputID(), mempool.ErrStateNotFound)) + return p.Reject(ierrors.Join(iotago.ErrUTXOInputInvalid, ierrors.WithMessagef(mempool.ErrStateNotFound, "output %s not found", utxoInput.OutputID()))) } return p.Resolve(output) diff --git a/pkg/protocol/engine/ledger/ledger/vm.go b/pkg/protocol/engine/ledger/ledger/vm.go index a26152e8e..97d4db578 100644 --- a/pkg/protocol/engine/ledger/ledger/vm.go +++ b/pkg/protocol/engine/ledger/ledger/vm.go @@ -28,31 +28,31 @@ func (v *VM) Inputs(transaction mempool.Transaction) (inputReferences []mempool. } for _, input := range iotagoTransaction.TransactionEssence.Inputs { - switch input.Type() { - case iotago.InputUTXO: - //nolint:forcetypeassert // we can safely assume that this is a UTXOInput + switch castedInput := input.(type) { + case *iotago.UTXOInput: inputReferences = append(inputReferences, mempool.UTXOInputStateRefFromInput( - input.(*iotago.UTXOInput), + castedInput, )) default: - return nil, ierrors.Errorf("unrecognized input type %d", input.Type()) + // We're switching on the Go input type here, so we can only run into the default case + // if we added a new input type and have not handled it above. In this case we want to panic. + panic("all supported input types should be handled above") } } for _, contextInput := range iotagoTransaction.TransactionEssence.ContextInputs { - switch contextInput.Type() { - case iotago.ContextInputCommitment: - //nolint:forcetypeassert // we can safely assume that this is a CommitmentInput + switch castedContextInput := contextInput.(type) { + case *iotago.CommitmentInput: inputReferences = append(inputReferences, mempool.CommitmentInputStateRefFromInput( - contextInput.(*iotago.CommitmentInput), + castedContextInput, )) // These context inputs do not need to be resolved. - case iotago.ContextInputBlockIssuanceCredit: - continue - case iotago.ContextInputReward: + case *iotago.BlockIssuanceCreditInput, *iotago.RewardInput: continue default: - return nil, ierrors.Errorf("unrecognized context input type %d", contextInput.Type()) + // We're switching on the Go context input type here, so we can only run into the default case + // if we added a new context input type and have not handled it above. In this case we want to panic. + panic("all supported context input types should be handled above") } } @@ -100,7 +100,7 @@ func (v *VM) ValidateSignatures(signedTransaction mempool.SignedTransaction, res return nil, ierrors.Join(iotago.ErrBICInputReferenceInvalid, ierrors.Wrapf(accountErr, "could not get BIC input for account %s in slot %d", inp.AccountID, commitmentInput.Slot)) } if !exists { - return nil, ierrors.Join(iotago.ErrBICInputReferenceInvalid, ierrors.Errorf("BIC input does not exist for account %s in slot %d", inp.AccountID, commitmentInput.Slot)) + return nil, ierrors.WithMessagef(iotago.ErrBICInputReferenceInvalid, "BIC input does not exist for account %s in slot %d", inp.AccountID, commitmentInput.Slot) } bicInputSet[inp.AccountID] = accountData.Credits.Value @@ -110,7 +110,7 @@ func (v *VM) ValidateSignatures(signedTransaction mempool.SignedTransaction, res for _, inp := range rewardInputs { output, ok := resolvedInputStates[inp.Index].(*utxoledger.Output) if !ok { - return nil, ierrors.Wrapf(iotago.ErrRewardInputReferenceInvalid, "input at index %d is not an UTXO output", inp.Index) + return nil, ierrors.WithMessagef(iotago.ErrRewardInputReferenceInvalid, "input at index %d is not a UTXO output", inp.Index) } outputID := output.OutputID() @@ -118,7 +118,7 @@ func (v *VM) ValidateSignatures(signedTransaction mempool.SignedTransaction, res case *iotago.AccountOutput: stakingFeature := castOutput.FeatureSet().Staking() if stakingFeature == nil { - return nil, ierrors.Wrapf(iotago.ErrRewardInputReferenceInvalid, "cannot claim rewards from an AccountOutput %s at index %d without staking feature", outputID, inp.Index) + return nil, ierrors.Wrapf(iotago.ErrRewardInputReferenceInvalid, "cannot claim rewards from a Account with output id %s at index %d without a staking feature", outputID.ToHex(), inp.Index) } accountID := castOutput.AccountID if accountID.Empty() { @@ -131,7 +131,7 @@ func (v *VM) ValidateSignatures(signedTransaction mempool.SignedTransaction, res reward, _, _, rewardErr := v.ledger.sybilProtection.ValidatorReward(accountID, stakingFeature, claimingEpoch) if rewardErr != nil { - return nil, ierrors.Wrapf(iotago.ErrStakingRewardCalculationFailure, "failed to get Validator reward for AccountOutput %s at index %d (StakedAmount: %d, StartEpoch: %d, EndEpoch: %d, claimingEpoch: %d", outputID, inp.Index, stakingFeature.StakedAmount, stakingFeature.StartEpoch, stakingFeature.EndEpoch, claimingEpoch) + return nil, ierrors.Join(iotago.ErrStakingRewardCalculationFailure, ierrors.Wrapf(rewardErr, "failed to get validator reward for account with output id %s at index %d (StakedAmount: %d, StartEpoch: %d, EndEpoch: %d, claimingEpoch: %d)", outputID.ToHex(), inp.Index, stakingFeature.StakedAmount, stakingFeature.StartEpoch, stakingFeature.EndEpoch, claimingEpoch)) } rewardInputSet[accountID] = reward @@ -154,12 +154,12 @@ func (v *VM) ValidateSignatures(signedTransaction mempool.SignedTransaction, res reward, _, _, rewardErr := v.ledger.sybilProtection.DelegatorReward(castOutput.ValidatorAddress.AccountID(), castOutput.DelegatedAmount, castOutput.StartEpoch, delegationEnd, claimingEpoch) if rewardErr != nil { - return nil, ierrors.Wrapf(iotago.ErrDelegationRewardCalculationFailure, "failed to get Delegator reward for DelegationOutput %s at index %d (StakedAmount: %d, StartEpoch: %d, EndEpoch: %d", outputID, inp.Index, castOutput.DelegatedAmount, castOutput.StartEpoch, castOutput.EndEpoch) + return nil, ierrors.Join(iotago.ErrDelegationRewardCalculationFailure, ierrors.Wrapf(rewardErr, "failed to get delegator reward for DelegationOutput with output id %s at index %d (DelegatedAmount: %d, StartEpoch: %d, EndEpoch: %d)", outputID, inp.Index, castOutput.DelegatedAmount, castOutput.StartEpoch, castOutput.EndEpoch)) } rewardInputSet[delegationID] = reward default: - return nil, ierrors.Wrapf(iotago.ErrRewardInputReferenceInvalid, "reward input cannot point to %s", output.Output().Type()) + return nil, ierrors.WithMessagef(iotago.ErrRewardInputReferenceInvalid, "reward input cannot point to %s", output.Output().Type()) } } @@ -172,7 +172,7 @@ func (v *VM) ValidateSignatures(signedTransaction mempool.SignedTransaction, res unlockedAddresses, err := nova.NewVirtualMachine().ValidateUnlocks(iotagoSignedTransaction, resolvedInputs) if err != nil { - return nil, err + return nil, ierrors.Wrap(err, "failed to validate unlocks in signed transaction") } executionContext = context.Background() @@ -188,19 +188,16 @@ func (v *VM) Execute(executionContext context.Context, transaction mempool.Trans return nil, iotago.ErrTxTypeInvalid } - transactionID, err := iotagoTransaction.ID() - if err != nil { - return nil, err - } + transactionID := iotagoTransaction.MustID() unlockedAddresses, ok := executionContext.Value(ExecutionContextKeyUnlockedAddresses).(iotagovm.UnlockedAddresses) if !ok { - return nil, ierrors.Errorf("unlockedAddresses not found in execution context") + panic("unlockedAddresses should be present in execution context") } resolvedInputs, ok := executionContext.Value(ExecutionContextKeyResolvedInputs).(iotagovm.ResolvedInputs) if !ok { - return nil, ierrors.Errorf("resolvedInputs not found in execution context") + panic("resolvedInputs should be present in execution context") } createdOutputs, err := nova.NewVirtualMachine().Execute(iotagoTransaction, resolvedInputs, unlockedAddresses) From 1ff28353b303b5dffead91fe89e92d7dc04f9fb8 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Thu, 14 Mar 2024 12:48:56 +0800 Subject: [PATCH 12/19] Fix error order in mempool --- .../mempool/spenddag/spenddagv1/spenddag.go | 18 +++++++++--------- .../mempool/spenddag/spenddagv1/spender.go | 2 +- pkg/protocol/engine/mempool/v1/mempool.go | 6 +++--- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/pkg/protocol/engine/mempool/spenddag/spenddagv1/spenddag.go b/pkg/protocol/engine/mempool/spenddag/spenddagv1/spenddag.go index 3ef7a4406..ee42e7989 100644 --- a/pkg/protocol/engine/mempool/spenddag/spenddagv1/spenddag.go +++ b/pkg/protocol/engine/mempool/spenddag/spenddagv1/spenddag.go @@ -113,7 +113,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) UpdateSpentResources(id Spen spender, exists := c.spendersByID.Get(id) if !exists { - return nil, ierrors.Errorf("spender already evicted: %w", spenddag.ErrEntityEvicted) + return nil, ierrors.WithMessage(spenddag.ErrEntityEvicted, "spender already evicted") } existingSpendSets := c.spendSets(resourceIDs) @@ -122,7 +122,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) UpdateSpentResources(id Spen }() if err != nil { - return ierrors.Errorf("spender %s failed to join spend sets: %w", id, err) + return ierrors.Wrapf(err, "spender %s failed to join spend sets", id) } if !joinedSpendSets.IsEmpty() { @@ -152,7 +152,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) UpdateSpenderParents(spender currentSpender, currentSpendExists := c.spendersByID.Get(spenderID) if !currentSpendExists { - return false, ierrors.Errorf("tried to modify evicted spend with %s: %w", spenderID, spenddag.ErrEntityEvicted) + return false, ierrors.WithMessagef(spenddag.ErrEntityEvicted, "tried to modify evicted spend with %s", spenderID) } addedParents := ds.NewSet[*Spender[SpenderID, ResourceID, VoteRank]]() @@ -170,7 +170,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) UpdateSpenderParents(spender removedParents, err := c.spenders(removedParentIDs, !currentSpender.IsRejected()) if err != nil { - return false, ierrors.Errorf("failed to update spend parents: %w", err) + return false, ierrors.Wrap(err, "failed to update spend parents") } updated := currentSpender.UpdateParents(addedParents, removedParents) @@ -326,7 +326,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) CastVotes(vote *vote.Vote[Vo supportedSpenders, revokedSpenders, err := c.determineVotes(spenderIDs) if err != nil { - return ierrors.Errorf("failed to determine votes: %w", err) + return ierrors.Wrap(err, "failed to determine votes") } for supportedSpender := supportedSpenders.Iterator(); supportedSpender.HasNext(); { @@ -345,7 +345,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) AcceptanceState(spenderIDs d if err := spenderIDs.ForEach(func(spenderID SpenderID) error { spender, exists := c.spendersByID.Get(spenderID) if !exists { - return ierrors.Errorf("tried to retrieve non-existing spend: %w", spenddag.ErrFatal) + return ierrors.WithMessage(spenddag.ErrFatal, "tried to retrieve non-existing spend") } if spender.IsRejected() { @@ -435,7 +435,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) spenders(ids ds.Set[SpenderI spenders.Add(existingSpend) } - return lo.Cond(exists || ignoreMissing, nil, ierrors.Errorf("tried to retrieve a non-existing spend with %s: %w", id, spenddag.ErrEntityEvicted)) + return lo.Cond(exists || ignoreMissing, nil, ierrors.WithMessagef(spenddag.ErrEntityEvicted, "tried to retrieve a non-existing spend with %s", id)) }) } @@ -473,7 +473,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) determineVotes(spenderIDs ds supportSpender := func(supportedSpender *Spender[SpenderID, ResourceID, VoteRank]) error { if supportedSpenders.Add(supportedSpender) { if err := supportedSpender.ConflictingSpenders.ForEach(revokeSpend); err != nil { - return ierrors.Errorf("failed to collect conflicting spenders: %w", err) + return ierrors.Wrap(err, "failed to collect conflicting spenders") } supportedWalker.PushAll(supportedSpender.Parents.ToSlice()...) @@ -484,7 +484,7 @@ func (c *SpendDAG[SpenderID, ResourceID, VoteRank]) determineVotes(spenderIDs ds for supportedWalker.PushAll(lo.Return1(c.spenders(spenderIDs, true)).ToSlice()...); supportedWalker.HasNext(); { if err := supportSpender(supportedWalker.Next()); err != nil { - return nil, nil, ierrors.Errorf("failed to collect supported spenders: %w", err) + return nil, nil, ierrors.Wrap(err, "failed to collect supported spenders") } } diff --git a/pkg/protocol/engine/mempool/spenddag/spenddagv1/spender.go b/pkg/protocol/engine/mempool/spenddag/spenddagv1/spender.go index 09e7de7bd..fc432b021 100644 --- a/pkg/protocol/engine/mempool/spenddag/spenddagv1/spender.go +++ b/pkg/protocol/engine/mempool/spenddag/spenddagv1/spender.go @@ -135,7 +135,7 @@ func (c *Spender[SpenderID, ResourceID, VoteRank]) JoinSpendSets(spendSets ds.Se } if c.evicted.Load() { - return nil, ierrors.Errorf("tried to join spend sets of evicted spender: %w", spenddag.ErrEntityEvicted) + return nil, ierrors.WithMessage(spenddag.ErrEntityEvicted, "tried to join spend sets of evicted spender") } registerConflictingSpender := func(c *Spender[SpenderID, ResourceID, VoteRank], spender *Spender[SpenderID, ResourceID, VoteRank]) { diff --git a/pkg/protocol/engine/mempool/v1/mempool.go b/pkg/protocol/engine/mempool/v1/mempool.go index 0620d5524..3be5ff71a 100644 --- a/pkg/protocol/engine/mempool/v1/mempool.go +++ b/pkg/protocol/engine/mempool/v1/mempool.go @@ -352,7 +352,7 @@ func (m *MemPool[VoteRank]) storeTransaction(signedTransaction mempool.SignedTra if m.lastCommittedSlot >= blockID.Slot() { // block will be retained as invalid, we do not store tx failure as it was block's fault - return nil, false, false, ierrors.Errorf("blockID %d is older than last evicted slot %d", blockID.Slot(), m.lastCommittedSlot) + return nil, false, false, ierrors.Errorf("blockID %d is older than last evicted slot %d", blockID, m.lastCommittedSlot) } inputReferences, err := m.vm.Inputs(transaction) @@ -362,7 +362,7 @@ func (m *MemPool[VoteRank]) storeTransaction(signedTransaction mempool.SignedTra newTransaction, err := NewTransactionMetadata(transaction, inputReferences) if err != nil { - return nil, false, false, ierrors.Errorf("failed to create transaction metadata: %w", err) + return nil, false, false, ierrors.Wrap(err, "failed to create transaction metadata") } storedTransaction, isNewTransaction := m.cachedTransactions.GetOrCreate(newTransaction.ID(), func() *TransactionMetadata { return newTransaction }) @@ -372,7 +372,7 @@ func (m *MemPool[VoteRank]) storeTransaction(signedTransaction mempool.SignedTra newSignedTransaction, err := NewSignedTransactionMetadata(signedTransaction, storedTransaction) if err != nil { - return nil, false, false, ierrors.Errorf("failed to create signedTransaction metadata: %w", err) + return nil, false, false, ierrors.Wrap(err, "failed to create signedTransaction metadata") } storedSignedTransaction, isNewSignedTransaction = m.cachedSignedTransactions.GetOrCreate(signedTransaction.MustID(), func() *SignedTransactionMetadata { return newSignedTransaction }) From f70c33b4bed6c58e80737c8742cca89aa4d4138c Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Thu, 14 Mar 2024 12:51:49 +0800 Subject: [PATCH 13/19] Use MustID for signed and regular tx --- pkg/protocol/engine/mempool/v1/mempool.go | 10 ++-------- .../engine/mempool/v1/signed_transaction_metadata.go | 10 +++------- pkg/protocol/engine/mempool/v1/transaction_metadata.go | 10 +++------- .../engine/mempool/v1/transaction_metadata_test.go | 6 ++---- 4 files changed, 10 insertions(+), 26 deletions(-) diff --git a/pkg/protocol/engine/mempool/v1/mempool.go b/pkg/protocol/engine/mempool/v1/mempool.go index 3be5ff71a..a003894cb 100644 --- a/pkg/protocol/engine/mempool/v1/mempool.go +++ b/pkg/protocol/engine/mempool/v1/mempool.go @@ -360,20 +360,14 @@ func (m *MemPool[VoteRank]) storeTransaction(signedTransaction mempool.SignedTra return nil, false, false, ierrors.Wrap(err, "failed to get input references of transaction") } - newTransaction, err := NewTransactionMetadata(transaction, inputReferences) - if err != nil { - return nil, false, false, ierrors.Wrap(err, "failed to create transaction metadata") - } + newTransaction := NewTransactionMetadata(transaction, inputReferences) storedTransaction, isNewTransaction := m.cachedTransactions.GetOrCreate(newTransaction.ID(), func() *TransactionMetadata { return newTransaction }) if isNewTransaction { m.setupTransaction(storedTransaction) } - newSignedTransaction, err := NewSignedTransactionMetadata(signedTransaction, storedTransaction) - if err != nil { - return nil, false, false, ierrors.Wrap(err, "failed to create signedTransaction metadata") - } + newSignedTransaction := NewSignedTransactionMetadata(signedTransaction, storedTransaction) storedSignedTransaction, isNewSignedTransaction = m.cachedSignedTransactions.GetOrCreate(signedTransaction.MustID(), func() *SignedTransactionMetadata { return newSignedTransaction }) if isNewSignedTransaction { diff --git a/pkg/protocol/engine/mempool/v1/signed_transaction_metadata.go b/pkg/protocol/engine/mempool/v1/signed_transaction_metadata.go index 72e94b1c7..40f073c9b 100644 --- a/pkg/protocol/engine/mempool/v1/signed_transaction_metadata.go +++ b/pkg/protocol/engine/mempool/v1/signed_transaction_metadata.go @@ -2,7 +2,6 @@ package mempoolv1 import ( "github.com/iotaledger/hive.go/ds/reactive" - "github.com/iotaledger/hive.go/ierrors" "github.com/iotaledger/hive.go/runtime/syncutils" "github.com/iotaledger/iota-core/pkg/protocol/engine/mempool" iotago "github.com/iotaledger/iota.go/v4" @@ -19,11 +18,8 @@ type SignedTransactionMetadata struct { evicted reactive.Event } -func NewSignedTransactionMetadata(signedTransaction mempool.SignedTransaction, transactionMetadata *TransactionMetadata) (*SignedTransactionMetadata, error) { - signedID, signedIDErr := signedTransaction.ID() - if signedIDErr != nil { - return nil, ierrors.Errorf("failed to retrieve signed transaction ID: %w", signedIDErr) - } +func NewSignedTransactionMetadata(signedTransaction mempool.SignedTransaction, transactionMetadata *TransactionMetadata) *SignedTransactionMetadata { + signedID := signedTransaction.MustID() return &SignedTransactionMetadata{ id: signedID, @@ -33,7 +29,7 @@ func NewSignedTransactionMetadata(signedTransaction mempool.SignedTransaction, t signaturesInvalid: reactive.NewVariable[error](), signaturesValid: reactive.NewEvent(), evicted: reactive.NewEvent(), - }, nil + } } func (s *SignedTransactionMetadata) ID() iotago.SignedTransactionID { diff --git a/pkg/protocol/engine/mempool/v1/transaction_metadata.go b/pkg/protocol/engine/mempool/v1/transaction_metadata.go index cd9b98a6d..24dc01fe9 100644 --- a/pkg/protocol/engine/mempool/v1/transaction_metadata.go +++ b/pkg/protocol/engine/mempool/v1/transaction_metadata.go @@ -7,7 +7,6 @@ import ( "github.com/iotaledger/hive.go/ds" "github.com/iotaledger/hive.go/ds/reactive" "github.com/iotaledger/hive.go/ds/shrinkingmap" - "github.com/iotaledger/hive.go/ierrors" "github.com/iotaledger/hive.go/lo" "github.com/iotaledger/hive.go/runtime/syncutils" "github.com/iotaledger/iota-core/pkg/protocol/engine/mempool" @@ -58,11 +57,8 @@ func (t *TransactionMetadata) ValidAttachments() []iotago.BlockID { return t.validAttachments.Keys() } -func NewTransactionMetadata(transaction mempool.Transaction, referencedInputs []mempool.StateReference) (*TransactionMetadata, error) { - transactionID, transactionIDErr := transaction.ID() - if transactionIDErr != nil { - return nil, ierrors.Errorf("failed to retrieve transaction ID: %w", transactionIDErr) - } +func NewTransactionMetadata(transaction mempool.Transaction, referencedInputs []mempool.StateReference) *TransactionMetadata { + transactionID := transaction.MustID() return (&TransactionMetadata{ id: transactionID, @@ -92,7 +88,7 @@ func NewTransactionMetadata(transaction mempool.Transaction, referencedInputs [] allValidAttachmentsEvicted: reactive.NewVariable[iotago.SlotIndex](), inclusionFlags: newInclusionFlags(), - }).setup(), nil + }).setup() } func (t *TransactionMetadata) ID() iotago.TransactionID { diff --git a/pkg/protocol/engine/mempool/v1/transaction_metadata_test.go b/pkg/protocol/engine/mempool/v1/transaction_metadata_test.go index ce592069d..a15837d10 100644 --- a/pkg/protocol/engine/mempool/v1/transaction_metadata_test.go +++ b/pkg/protocol/engine/mempool/v1/transaction_metadata_test.go @@ -15,10 +15,8 @@ func TestAttachments(t *testing.T) { "2": iotago.BlockIDRepresentingData(2, []byte("block2")), } - transactionMetadata, err := NewTransactionMetadata(mempooltests.NewTransaction(2), nil) - require.NoError(t, err) - - signedTransactionMetadata, err := NewSignedTransactionMetadata(mempooltests.NewSignedTransaction(transactionMetadata.Transaction()), transactionMetadata) + transactionMetadata := NewTransactionMetadata(mempooltests.NewTransaction(2), nil) + signedTransactionMetadata := NewSignedTransactionMetadata(mempooltests.NewSignedTransaction(transactionMetadata.Transaction()), transactionMetadata) require.True(t, signedTransactionMetadata.addAttachment(blockIDs["1"])) require.True(t, signedTransactionMetadata.addAttachment(blockIDs["2"])) From 541cc78d8b4389ba79bac251e1984bd8e1c7f26b Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Thu, 14 Mar 2024 13:06:43 +0800 Subject: [PATCH 14/19] Improve errors in utxoledger --- .../notarization/slotnotarization/slotmutations.go | 2 +- .../signalingupgradeorchestrator/snapshot.go | 4 +--- pkg/protocol/engine/utxoledger/manager.go | 14 +++++++------- pkg/protocol/engine/utxoledger/slot_diff.go | 4 ++-- pkg/protocol/engine/utxoledger/snapshot.go | 6 +++--- pkg/protocol/engine/utxoledger/state_tree.go | 2 +- 6 files changed, 15 insertions(+), 17 deletions(-) diff --git a/pkg/protocol/engine/notarization/slotnotarization/slotmutations.go b/pkg/protocol/engine/notarization/slotnotarization/slotmutations.go index af17fa755..c8663054a 100644 --- a/pkg/protocol/engine/notarization/slotnotarization/slotmutations.go +++ b/pkg/protocol/engine/notarization/slotnotarization/slotmutations.go @@ -41,7 +41,7 @@ func (m *SlotMutations) AddAcceptedBlock(block *blocks.Block) (err error) { } if err := m.acceptedBlocks(blockID.Slot(), true).Add(blockID); err != nil { - return ierrors.Wrapf(err, "failed to add block to accepted blocks, blockID: %s", blockID.ToHex()) + return ierrors.Wrapf(err, "failed to add block %s to accepted blocks", blockID) } return diff --git a/pkg/protocol/engine/upgrade/signalingupgradeorchestrator/snapshot.go b/pkg/protocol/engine/upgrade/signalingupgradeorchestrator/snapshot.go index c9400b2ca..9197dd914 100644 --- a/pkg/protocol/engine/upgrade/signalingupgradeorchestrator/snapshot.go +++ b/pkg/protocol/engine/upgrade/signalingupgradeorchestrator/snapshot.go @@ -127,9 +127,7 @@ func (o *Orchestrator) Export(writer io.WriteSeeker, targetSlot iotago.SlotIndex for epoch := o.signalingWindowStart(currentEpoch, apiForSlot); epoch <= currentEpoch; epoch++ { versionAndHash, err := o.decidedUpgradeSignals.Load(epoch) if err != nil { - if err != nil { - return 0, ierrors.Wrapf(err, "failed to get permanent upgrade signals for epoch %d", epoch) - } + return 0, ierrors.Wrapf(err, "failed to get permanent upgrade signals for epoch %d", epoch) } if versionAndHash.Version == 0 { // We don't write anything to the storage if no supermajority was reached (or no signaling was going on). diff --git a/pkg/protocol/engine/utxoledger/manager.go b/pkg/protocol/engine/utxoledger/manager.go index 6fc850cab..c107608e1 100644 --- a/pkg/protocol/engine/utxoledger/manager.go +++ b/pkg/protocol/engine/utxoledger/manager.go @@ -136,7 +136,7 @@ func (m *Manager) ReadLedgerIndexWithoutLocking() (iotago.SlotIndex, error) { return m.apiProvider.CommittedAPI().ProtocolParameters().GenesisSlot(), nil } - return 0, ierrors.Errorf("failed to load ledger milestone index: %w", err) + return 0, ierrors.Wrap(err, "failed to load ledger milestone index") } return lo.DropCount(iotago.SlotIndexFromBytes(value)) @@ -200,12 +200,12 @@ func (m *Manager) ApplyDiffWithoutLocking(slot iotago.SlotIndex, newOutputs Outp for _, output := range newOutputs { if err := m.stateTree.Set(output.OutputID(), newStateMetadata(output)); err != nil { - return ierrors.Wrapf(err, "failed to set new oputput in state tree, outputID: %s", output.OutputID()) + return ierrors.Wrapf(err, "failed to set new oputput in state tree, outputID: %s", output.OutputID().ToHex()) } } for _, spent := range newSpents { if _, err := m.stateTree.Delete(spent.OutputID()); err != nil { - return ierrors.Wrapf(err, "failed to delete spent output from state tree, outputID: %s", spent.OutputID()) + return ierrors.Wrapf(err, "failed to delete spent output from state tree, outputID: %s", spent.OutputID().ToHex()) } } @@ -276,12 +276,12 @@ func (m *Manager) RollbackDiffWithoutLocking(slot iotago.SlotIndex, newOutputs O for _, spent := range newSpents { if err := m.stateTree.Set(spent.OutputID(), newStateMetadata(spent.Output())); err != nil { - return ierrors.Wrapf(err, "failed to set new spent output in state tree, outputID: %s", spent.OutputID()) + return ierrors.Wrapf(err, "failed to set new spent output in state tree, outputID: %s", spent.OutputID().ToHex()) } } for _, output := range newOutputs { if _, err := m.stateTree.Delete(output.OutputID()); err != nil { - return ierrors.Wrapf(err, "failed to delete new output from state tree, outputID: %s", output.OutputID()) + return ierrors.Wrapf(err, "failed to delete new output from state tree, outputID: %s", output.OutputID().ToHex()) } } @@ -314,7 +314,7 @@ func (m *Manager) CheckLedgerState(tokenSupply iotago.BaseToken) error { func (m *Manager) AddGenesisUnspentOutputWithoutLocking(unspentOutput *Output) error { if err := m.importUnspentOutputWithoutLocking(unspentOutput); err != nil { - return ierrors.Wrapf(err, "failed to import unspent output, outputID: %s", unspentOutput.OutputID()) + return ierrors.Wrapf(err, "failed to import unspent output, outputID: %s", unspentOutput.OutputID().ToHex()) } if err := m.stateTree.Commit(); err != nil { @@ -347,7 +347,7 @@ func (m *Manager) importUnspentOutputWithoutLocking(unspentOutput *Output) error } if err := m.stateTree.Set(unspentOutput.OutputID(), newStateMetadata(unspentOutput)); err != nil { - return ierrors.Wrapf(err, "failed to set state tree entry for output, outputID: %s", unspentOutput.OutputID()) + return ierrors.Wrapf(err, "failed to set state tree entry for output, outputID: %s", unspentOutput.OutputID().ToHex()) } return nil diff --git a/pkg/protocol/engine/utxoledger/slot_diff.go b/pkg/protocol/engine/utxoledger/slot_diff.go index be304e321..b4f985a34 100644 --- a/pkg/protocol/engine/utxoledger/slot_diff.go +++ b/pkg/protocol/engine/utxoledger/slot_diff.go @@ -146,11 +146,11 @@ func (sd *SlotDiff) SHA256Sum() ([]byte, error) { sdDiffHash := sha256.New() if err := stream.WriteBytes(sdDiffHash, sd.KVStorableKey()); err != nil { - return nil, ierrors.Errorf("unable to serialize slot diff: %w", err) + return nil, ierrors.Wrap(err, "unable to serialize slot diff") } if err := stream.WriteBytes(sdDiffHash, sd.KVStorableValue()); err != nil { - return nil, ierrors.Errorf("unable to serialize slot diff: %w", err) + return nil, ierrors.Wrap(err, "unable to serialize slot diff") } // calculate sha256 hash diff --git a/pkg/protocol/engine/utxoledger/snapshot.go b/pkg/protocol/engine/utxoledger/snapshot.go index a6af13e95..53af5f0a5 100644 --- a/pkg/protocol/engine/utxoledger/snapshot.go +++ b/pkg/protocol/engine/utxoledger/snapshot.go @@ -199,7 +199,7 @@ func (m *Manager) Import(reader io.ReadSeeker) error { } if slotDiff.Slot != snapshotLedgerIndex-iotago.SlotIndex(i) { - return ierrors.Errorf("invalid LS slot index. %d vs %d", slotDiff.Slot, snapshotLedgerIndex-iotago.SlotIndex(i)) + return ierrors.Errorf("invalid LS slot index, %d vs %d", slotDiff.Slot, snapshotLedgerIndex-iotago.SlotIndex(i)) } if err := m.RollbackDiffWithoutLocking(slotDiff.Slot, slotDiff.Outputs, slotDiff.Spents); err != nil { @@ -243,11 +243,11 @@ func (m *Manager) Export(writer io.WriteSeeker, targetIndex iotago.SlotIndex) er for _, outputID := range outputIDs.RemoveDupsAndSort() { output, err := m.ReadOutputByOutputIDWithoutLocking(outputID) if err != nil { - return 0, ierrors.Wrapf(err, "error while retrieving output %s", outputID) + return 0, ierrors.Wrapf(err, "error while retrieving output with ID %s", outputID.ToHex()) } if err := stream.WriteBytes(writer, output.SnapshotBytes()); err != nil { - return 0, ierrors.Wrapf(err, "unable to write output with ID %s", outputID) + return 0, ierrors.Wrapf(err, "unable to write output with ID %s", outputID.ToHex()) } outputCount++ diff --git a/pkg/protocol/engine/utxoledger/state_tree.go b/pkg/protocol/engine/utxoledger/state_tree.go index 1e5f3af3f..9a5ea3553 100644 --- a/pkg/protocol/engine/utxoledger/state_tree.go +++ b/pkg/protocol/engine/utxoledger/state_tree.go @@ -52,7 +52,7 @@ func (m *Manager) CheckStateTree() bool { if err := m.ForEachUnspentOutput(func(output *Output) bool { if err := comparisonTree.Set(output.OutputID(), newStateMetadata(output)); err != nil { - panic(ierrors.Wrapf(err, "failed to set output in comparison tree, outputID: %s", output.OutputID())) + panic(ierrors.Wrapf(err, "failed to set output in comparison tree, outputID: %s", output.OutputID().ToHex())) } return true From 489e3249fdc4c2f180471e15bfb80806092dbe5a Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Thu, 14 Mar 2024 13:22:01 +0800 Subject: [PATCH 15/19] Fix errors in sybilprotection --- .../sybilprotectionv1/performance/rewards.go | 10 +++++----- .../sybilprotectionv1/performance/testsuite_test.go | 4 +--- .../sybilprotectionv1/sybilprotection.go | 6 +++--- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/pkg/protocol/sybilprotection/sybilprotectionv1/performance/rewards.go b/pkg/protocol/sybilprotection/sybilprotectionv1/performance/rewards.go index 505de8d5f..8b6529371 100644 --- a/pkg/protocol/sybilprotection/sybilprotectionv1/performance/rewards.go +++ b/pkg/protocol/sybilprotection/sybilprotectionv1/performance/rewards.go @@ -320,27 +320,27 @@ func (t *Tracker) calculatePoolCoefficient(poolStake iotago.BaseToken, totalStak poolCoeffExponent := t.apiProvider.APIForSlot(slot).ProtocolParameters().RewardsParameters().PoolCoefficientExponent scaledUpPoolStake, err := safemath.SafeLeftShift(poolStake, poolCoeffExponent) if err != nil { - return 0, ierrors.Wrapf(err, "failed to calculate pool coefficient due to overflow for slot %d", slot) + return 0, ierrors.Wrapf(err, "failed in step 1 of pool coefficient calculation due to overflow for slot %d", slot) } result1, err := safemath.SafeDiv(scaledUpPoolStake, totalStake) if err != nil { - return 0, ierrors.Wrapf(err, "failed to calculate pool coefficient due to overflow for slot %d", slot) + return 0, ierrors.Wrapf(err, "failed in step 2 of pool coefficient calculation due to overflow for slot %d", slot) } scaledUpValidatorStake, err := safemath.SafeLeftShift(validatorStake, poolCoeffExponent) if err != nil { - return 0, ierrors.Wrapf(err, "failed to calculate pool coefficient due to overflow for slot %d", slot) + return 0, ierrors.Wrapf(err, "failed in step 3 of pool coefficient calculation due to overflow for slot %d", slot) } result2, err := safemath.SafeDiv(scaledUpValidatorStake, totalValidatorStake) if err != nil { - return 0, ierrors.Wrapf(err, "failed to calculate pool coefficient due to overflow for slot %d", slot) + return 0, ierrors.Wrapf(err, "failed in step 4 of pool coefficient calculation due to overflow for slot %d", slot) } poolCoeff, err := safemath.SafeAdd(result1, result2) if err != nil { - return 0, ierrors.Wrapf(err, "failed to calculate pool coefficient due to overflow for slot %d", slot) + return 0, ierrors.Wrapf(err, "failed in step 5 of pool coefficient calculation due to overflow for slot %d", slot) } return uint64(poolCoeff), nil diff --git a/pkg/protocol/sybilprotection/sybilprotectionv1/performance/testsuite_test.go b/pkg/protocol/sybilprotection/sybilprotectionv1/performance/testsuite_test.go index c8f223fa9..99c3d9b08 100644 --- a/pkg/protocol/sybilprotection/sybilprotectionv1/performance/testsuite_test.go +++ b/pkg/protocol/sybilprotection/sybilprotectionv1/performance/testsuite_test.go @@ -22,7 +22,6 @@ import ( type TestSuite struct { T *testing.T - stores map[iotago.SlotIndex]kvstore.KVStore accounts map[string]iotago.AccountID poolRewards map[iotago.EpochIndex]map[string]*model.PoolRewards epochStats map[iotago.EpochIndex]*model.PoolsStats @@ -30,8 +29,7 @@ type TestSuite struct { api iotago.API - Instance *Tracker - performanceFactorFunc func(iotago.SlotIndex) *model.ValidatorPerformance + Instance *Tracker } func NewTestSuite(t *testing.T) *TestSuite { diff --git a/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go b/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go index ca6531202..c0bc29969 100644 --- a/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go +++ b/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go @@ -111,7 +111,7 @@ func (o *SybilProtection) TrackBlock(block *blocks.Block) { accountData, exists, err := o.ledger.Account(block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot()) if err != nil { - o.errHandler(ierrors.Wrapf(err, "error while retrieving account from account %s in slot %d from accounts ledger", block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot())) + o.errHandler(ierrors.Wrapf(err, "error while retrieving account %s in slot %d from accounts ledger", block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot())) return } @@ -314,7 +314,7 @@ func (o *SybilProtection) EligibleValidators(epoch iotago.EpochIndex) (accounts. return ierrors.Wrapf(err, "failed to load account data for candidate %s", candidate) } if !exists { - return ierrors.Errorf("account of committee candidate does not exist: %s", candidate) + return ierrors.Errorf("account of committee candidate %s does not exist", candidate) } // if `End Epoch` is the current one or has passed, validator is no longer considered for validator selection if accountData.StakeEndEpoch <= epoch { @@ -349,7 +349,7 @@ func (o *SybilProtection) OrderedRegisteredCandidateValidatorsList(epoch iotago. return ierrors.Wrapf(err, "failed to get account %s", candidate) } if !exists { - return ierrors.Errorf("account of committee candidate does not exist: %s", candidate) + return ierrors.Errorf("account of committee candidate %s does not exist", candidate) } // if `End Epoch` is the current one or has passed, validator is no longer considered for validator selection if accountData.StakeEndEpoch <= epoch { From 1f50524b3bc2d4311c6fb61dbd413ccdba95d576 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Thu, 14 Mar 2024 13:39:13 +0800 Subject: [PATCH 16/19] Fix error order in storage and retainer --- pkg/restapi/utils.go | 2 +- pkg/retainer/blockretainer/block_retainer.go | 2 +- pkg/retainer/txretainer/tx_retainer_database.go | 2 +- pkg/storage/prunable/bucket_manager.go | 8 ++++---- pkg/storage/prunable/epochstore/base_store.go | 4 ++-- pkg/storage/prunable/epochstore/epoch_kv.go | 2 +- pkg/storage/prunable/prunable_slot.go | 16 ++++++++-------- pkg/storage/storage_pruning.go | 14 +++++++------- 8 files changed, 25 insertions(+), 25 deletions(-) diff --git a/pkg/restapi/utils.go b/pkg/restapi/utils.go index c5cda4fbf..f4bd2ad3a 100644 --- a/pkg/restapi/utils.go +++ b/pkg/restapi/utils.go @@ -30,7 +30,7 @@ func CompileRoutesAsRegexes(routes []string) ([]*regexp.Regexp, error) { for i, route := range routes { reg := CompileRouteAsRegex(route) if reg == nil { - return nil, ierrors.Errorf("Invalid route in config: %s", route) + return nil, ierrors.Errorf("invalid route in config: %s", route) } regexes[i] = reg } diff --git a/pkg/retainer/blockretainer/block_retainer.go b/pkg/retainer/blockretainer/block_retainer.go index 27363bd06..929b7a8e2 100644 --- a/pkg/retainer/blockretainer/block_retainer.go +++ b/pkg/retainer/blockretainer/block_retainer.go @@ -116,7 +116,7 @@ func (r *BlockRetainer) getBlockMetadata(blockID iotago.BlockID) (*slotstore.Blo func (r *BlockRetainer) BlockMetadata(blockID iotago.BlockID) (*api.BlockMetadataResponse, error) { blockStatus, err := r.blockState(blockID) if err != nil { - return nil, ierrors.Wrapf(err, "block %s not found", blockID.ToHex()) + return nil, ierrors.Wrapf(err, "block %s not found", blockID) } // we do not expose accepted flag diff --git a/pkg/retainer/txretainer/tx_retainer_database.go b/pkg/retainer/txretainer/tx_retainer_database.go index 5cb68e49e..5ff1203a5 100644 --- a/pkg/retainer/txretainer/tx_retainer_database.go +++ b/pkg/retainer/txretainer/tx_retainer_database.go @@ -119,7 +119,7 @@ func (r *transactionRetainerDatabase) TransactionMetadataByID(transactionID iota Take(txMeta).Error }); err != nil { if !ierrors.Is(err, gorm.ErrRecordNotFound) { - return nil, ierrors.Wrapf(err, "failed to query transaction metadata for transaction ID %s", transactionID.ToHex()) + return nil, ierrors.Wrapf(err, "failed to query transaction metadata for transaction ID %s", transactionID) } // no entry found diff --git a/pkg/storage/prunable/bucket_manager.go b/pkg/storage/prunable/bucket_manager.go index 40e955d03..c557e2903 100644 --- a/pkg/storage/prunable/bucket_manager.go +++ b/pkg/storage/prunable/bucket_manager.go @@ -64,7 +64,7 @@ func (b *BucketManager) IsTooOld(epoch iotago.EpochIndex) (isTooOld bool) { func (b *BucketManager) Get(epoch iotago.EpochIndex, realm kvstore.Realm) (kvstore.KVStore, error) { if b.IsTooOld(epoch) { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "epoch %d", epoch) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "epoch %d", epoch) } kv := b.getDBInstance(epoch).KVStore() @@ -132,7 +132,7 @@ func (b *BucketManager) TotalSize() int64 { b.openDBs.ForEach(func(key iotago.EpochIndex, _ *database.DBInstance) bool { size, err := dbPrunableDirectorySize(b.dbConfig.Directory, key) if err != nil { - b.errorHandler(ierrors.Wrapf(err, "dbPrunableDirectorySize failed for key %s: %s", b.dbConfig.Directory, key)) + b.errorHandler(ierrors.Wrapf(err, "dbPrunableDirectorySize failed for epoch %d in directory %s", key, b.dbConfig.Directory)) } sum += size @@ -157,7 +157,7 @@ func (b *BucketManager) BucketSize(epoch iotago.EpochIndex) (int64, error) { size, err := dbPrunableDirectorySize(b.dbConfig.Directory, epoch) if err != nil { - return 0, ierrors.Wrapf(err, "dbPrunableDirectorySize failed for epoch %s: %s", b.dbConfig.Directory, epoch) + return 0, ierrors.Wrapf(err, "dbPrunableDirectorySize failed for epoch %d in directory %s", epoch, b.dbConfig.Directory) } return size, nil @@ -247,7 +247,7 @@ func (b *BucketManager) Prune(epoch iotago.EpochIndex) error { defer b.lastPrunedMutex.Unlock() if epoch < lo.Return1(b.lastPrunedEpoch.Index()) { - return ierrors.Wrapf(database.ErrNoPruningNeeded, "epoch %d is already pruned", epoch) + return ierrors.WithMessagef(database.ErrNoPruningNeeded, "epoch %d is already pruned", epoch) } b.DeleteBucket(epoch) diff --git a/pkg/storage/prunable/epochstore/base_store.go b/pkg/storage/prunable/epochstore/base_store.go index 6d398a48f..9335e6793 100644 --- a/pkg/storage/prunable/epochstore/base_store.go +++ b/pkg/storage/prunable/epochstore/base_store.go @@ -53,7 +53,7 @@ func (s *BaseStore[V]) Load(epoch iotago.EpochIndex) (V, error) { var zeroValue V if s.isTooOld(epoch) { - return zeroValue, ierrors.Wrapf(database.ErrEpochPruned, "epoch %d is too old", epoch) + return zeroValue, ierrors.WithMessagef(database.ErrEpochPruned, "epoch %d is too old", epoch) } value, err := s.kv.Get(epoch) @@ -79,7 +79,7 @@ func (s *BaseStore[V]) Store(epoch iotago.EpochIndex, value V) error { }) if s.isTooOld(epoch) { - return ierrors.Wrapf(database.ErrEpochPruned, "epoch %d is too old", epoch) + return ierrors.WithMessagef(database.ErrEpochPruned, "epoch %d is too old", epoch) } return s.kv.Set(epoch, value) diff --git a/pkg/storage/prunable/epochstore/epoch_kv.go b/pkg/storage/prunable/epochstore/epoch_kv.go index 4f42f6518..1c106b28a 100644 --- a/pkg/storage/prunable/epochstore/epoch_kv.go +++ b/pkg/storage/prunable/epochstore/epoch_kv.go @@ -65,7 +65,7 @@ func (e *EpochKVStore) GetEpoch(epoch iotago.EpochIndex) (kvstore.KVStore, error }) if e.isTooOld(epoch) { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "epoch %d is too old", epoch) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "epoch %d is too old", epoch) } return lo.PanicOnErr(e.kv.WithExtendedRealm(epoch.MustBytes())), nil diff --git a/pkg/storage/prunable/prunable_slot.go b/pkg/storage/prunable/prunable_slot.go index 6a6c788bd..431a84dbf 100644 --- a/pkg/storage/prunable/prunable_slot.go +++ b/pkg/storage/prunable/prunable_slot.go @@ -33,7 +33,7 @@ func (p *Prunable) getKVStoreFromSlot(slot iotago.SlotIndex, prefix kvstore.Real func (p *Prunable) Blocks(slot iotago.SlotIndex) (*slotstore.Blocks, error) { kv, err := p.getKVStoreFromSlot(slot, kvstore.Realm{slotPrefixBlocks}) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get blocks with slot %d", slot) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get blocks with slot %d", slot) } return slotstore.NewBlocks(slot, kv, p.apiProvider.APIForSlot(slot)), nil @@ -42,7 +42,7 @@ func (p *Prunable) Blocks(slot iotago.SlotIndex) (*slotstore.Blocks, error) { func (p *Prunable) RootBlocks(slot iotago.SlotIndex) (*slotstore.Store[iotago.BlockID, iotago.CommitmentID], error) { kv, err := p.getKVStoreFromSlot(slot, kvstore.Realm{slotPrefixRootBlocks}) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get root blocks with slot %d", slot) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get root blocks with slot %d", slot) } return slotstore.NewStore(slot, kv, @@ -58,7 +58,7 @@ func (p *Prunable) CommitteeCandidates(epoch iotago.EpochIndex) (*kvstore.TypedS // Candidates belong to an epoch, but we store them here so that they're pruned more quickly and easily without unnecessary key iteration. kv, err := p.prunableSlotStore.Get(epoch, byteutils.ConcatBytes(p.apiProvider.APIForEpoch(epoch).TimeProvider().EpochStart(epoch).MustBytes(), kvstore.Realm{epochPrefixCommitteeCandidates})) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get committee candidates with epoch %d", epoch) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get committee candidates with epoch %d", epoch) } return kvstore.NewTypedStore(kv, @@ -80,7 +80,7 @@ func (p *Prunable) Attestations(slot iotago.SlotIndex) (kvstore.KVStore, error) func (p *Prunable) AccountDiffs(slot iotago.SlotIndex) (*slotstore.AccountDiffs, error) { kv, err := p.getKVStoreFromSlot(slot, kvstore.Realm{slotPrefixAccountDiffs}) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get account diffs with slot %d", slot) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get account diffs with slot %d", slot) } return slotstore.NewAccountDiffs(slot, kv, p.apiProvider.APIForSlot(slot)), nil @@ -89,7 +89,7 @@ func (p *Prunable) AccountDiffs(slot iotago.SlotIndex) (*slotstore.AccountDiffs, func (p *Prunable) ValidatorPerformances(slot iotago.SlotIndex) (*slotstore.Store[iotago.AccountID, *model.ValidatorPerformance], error) { kv, err := p.getKVStoreFromSlot(slot, kvstore.Realm{slotPrefixPerformanceFactors}) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get performance factors with slot %d", slot) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get performance factors with slot %d", slot) } return slotstore.NewStore(slot, kv, @@ -103,7 +103,7 @@ func (p *Prunable) ValidatorPerformances(slot iotago.SlotIndex) (*slotstore.Stor func (p *Prunable) UpgradeSignals(slot iotago.SlotIndex) (*slotstore.Store[account.SeatIndex, *model.SignaledBlock], error) { kv, err := p.getKVStoreFromSlot(slot, kvstore.Realm{slotPrefixUpgradeSignals}) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get upgrade signals with slot %d", slot) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get upgrade signals with slot %d", slot) } apiForSlot := p.apiProvider.APIForSlot(slot) @@ -121,7 +121,7 @@ func (p *Prunable) UpgradeSignals(slot iotago.SlotIndex) (*slotstore.Store[accou func (p *Prunable) Roots(slot iotago.SlotIndex) (*slotstore.Store[iotago.CommitmentID, *iotago.Roots], error) { kv, err := p.getKVStoreFromSlot(slot, kvstore.Realm{slotPrefixRoots}) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get roots with slot %d", slot) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get roots with slot %d", slot) } apiForSlot := p.apiProvider.APIForSlot(slot) @@ -149,7 +149,7 @@ func (p *Prunable) Roots(slot iotago.SlotIndex) (*slotstore.Store[iotago.Commitm func (p *Prunable) BlockMetadata(slot iotago.SlotIndex) (*slotstore.BlockMetadataStore, error) { kv, err := p.getKVStoreFromSlot(slot, kvstore.Realm{slotPrefixBlockMetadata}) if err != nil { - return nil, ierrors.Wrapf(database.ErrEpochPruned, "could not get block metadata store with slot %d", slot) + return nil, ierrors.WithMessagef(database.ErrEpochPruned, "could not get block metadata store with slot %d", slot) } return slotstore.NewBlockMetadataStore(slot, kv), nil diff --git a/pkg/storage/storage_pruning.go b/pkg/storage/storage_pruning.go index 10a30a9d5..f2f28dd45 100644 --- a/pkg/storage/storage_pruning.go +++ b/pkg/storage/storage_pruning.go @@ -88,7 +88,7 @@ func (s *Storage) PruneByDepth(epochDepth iotago.EpochIndex) (firstPruned iotago latestPrunableEpoch := s.latestPrunableEpoch() if epochDepth > latestPrunableEpoch { - return 0, 0, ierrors.Wrapf(database.ErrNoPruningNeeded, "epochDepth %d is too big, latest prunable epoch is %d", epochDepth, latestPrunableEpoch) + return 0, 0, ierrors.WithMessagef(database.ErrNoPruningNeeded, "epochDepth %d is too big, latest prunable epoch is %d", epochDepth, latestPrunableEpoch) } // We need to do (epochDepth-1) because latestPrunableEpoch is already making sure that we keep at least one full epoch. @@ -100,7 +100,7 @@ func (s *Storage) PruneByDepth(epochDepth iotago.EpochIndex) (firstPruned iotago // Make sure epoch is not already pruned. start, canPrune := s.getPruningStart(end) if !canPrune { - return 0, 0, ierrors.Wrapf(database.ErrEpochPruned, "epochDepth %d is too big, want to prune until %d but pruned epoch is already %d", epochDepth, end, lo.Return1(s.lastPrunedEpoch.Index())) + return 0, 0, ierrors.WithMessagef(database.ErrEpochPruned, "epochDepth %d is too big, want to prune until %d but pruned epoch is already %d", epochDepth, end, lo.Return1(s.lastPrunedEpoch.Index())) } s.setIsPruning(true) @@ -123,7 +123,7 @@ func (s *Storage) PruneBySize(targetSizeMaxBytes ...int64) error { defer s.pruningLock.Unlock() if time.Since(s.lastPrunedSizeTime) < s.optsPruningSizeCooldownTime { - return ierrors.Wrapf(database.ErrNoPruningNeeded, "last pruning by size was %s ago, cooldown time is %s", time.Since(s.lastPrunedSizeTime), s.optsPruningSizeCooldownTime) + return ierrors.WithMessagef(database.ErrNoPruningNeeded, "last pruning by size was %s ago, cooldown time is %s", time.Since(s.lastPrunedSizeTime), s.optsPruningSizeCooldownTime) } // The target size is the maximum size of the database after pruning. @@ -147,7 +147,7 @@ func (s *Storage) PruneBySize(targetSizeMaxBytes ...int64) error { // Make sure epoch is not already pruned. start, canPrune := s.getPruningStart(latestPrunableEpoch) if !canPrune { - return ierrors.Wrapf(database.ErrEpochPruned, "can't prune any more data: latest prunable epoch is %d but pruned epoch is already %d", latestPrunableEpoch, lo.Return1(s.lastPrunedEpoch.Index())) + return ierrors.WithMessagef(database.ErrEpochPruned, "can't prune any more data: latest prunable epoch is %d but pruned epoch is already %d", latestPrunableEpoch, lo.Return1(s.lastPrunedEpoch.Index())) } s.setIsPruning(true) @@ -181,7 +181,7 @@ func (s *Storage) PruneBySize(targetSizeMaxBytes ...int64) error { // If the size of the database is still bigger than the max size, after we tried to prune everything possible, // we return an error so that the user can be notified about a potentially full disk. if currentDBSize = s.Size(); currentDBSize > dbMaxSize { - return ierrors.Wrapf(database.ErrDatabaseFull, "database size is still bigger than the start threshold size after pruning: %d > %d", currentDBSize, dbMaxSize) + return ierrors.WithMessagef(database.ErrDatabaseFull, "database size is still bigger than the start threshold size after pruning: %d > %d", currentDBSize, dbMaxSize) } return nil @@ -213,11 +213,11 @@ func (s *Storage) latestPrunableEpoch() iotago.EpochIndex { func (s *Storage) pruneUntilEpoch(startEpoch iotago.EpochIndex, targetEpoch iotago.EpochIndex, pruningDelay iotago.EpochIndex) error { for currentEpoch := startEpoch; currentEpoch <= targetEpoch; currentEpoch++ { if err := s.prunable.Prune(currentEpoch, pruningDelay); err != nil { - return ierrors.Wrapf(err, "failed to prune epoch in prunable %d", currentEpoch) + return ierrors.Wrapf(err, "failed to prune epoch %d in prunable", currentEpoch) } if err := s.permanent.PruneUTXOLedger(currentEpoch); err != nil { - return ierrors.Wrapf(err, "failed to prune epoch in permanent %d", currentEpoch) + return ierrors.Wrapf(err, "failed to prune epoch %d in permanent", currentEpoch) } } From 98a6fe9b1f3b0c7895de8b2a2ab8df6b5551e1aa Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Thu, 14 Mar 2024 13:53:52 +0800 Subject: [PATCH 17/19] Replace fmt.Errorf with ierrors --- components/inx/server_utxo.go | 11 +++++------ pkg/toolset/ed25519.go | 4 ++-- pkg/toolset/jwt.go | 19 ++++++++++--------- pkg/toolset/p2p_identity_extract.go | 9 +++++---- pkg/toolset/p2p_identity_gen.go | 23 ++++++++++++----------- pkg/toolset/toolset.go | 2 +- 6 files changed, 35 insertions(+), 33 deletions(-) diff --git a/components/inx/server_utxo.go b/components/inx/server_utxo.go index 7d922a4a1..6c4324295 100644 --- a/components/inx/server_utxo.go +++ b/components/inx/server_utxo.go @@ -2,7 +2,6 @@ package inx import ( "context" - "fmt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -189,7 +188,7 @@ func (s *Server) ReadUnspentOutputs(_ *inx.NoParams, srv inx.INX_ReadUnspentOutp } if err := srv.Send(payload); err != nil { - innerErr = fmt.Errorf("send error: %w", err) + innerErr = ierrors.Wrap(err, "send error") return false } @@ -212,7 +211,7 @@ func (s *Server) ListenToLedgerUpdates(req *inx.SlotRangeRequest, srv inx.INX_Li // Send Begin if err := srv.Send(NewLedgerUpdateBatchBegin(commitment.ID(), len(outputs), len(spents))); err != nil { - return fmt.Errorf("send error: %w", err) + return ierrors.Wrap(err, "send error") } // Send consumed @@ -223,7 +222,7 @@ func (s *Server) ListenToLedgerUpdates(req *inx.SlotRangeRequest, srv inx.INX_Li } if err := srv.Send(payload); err != nil { - return fmt.Errorf("send error: %w", err) + return ierrors.Wrap(err, "send error") } } @@ -235,13 +234,13 @@ func (s *Server) ListenToLedgerUpdates(req *inx.SlotRangeRequest, srv inx.INX_Li } if err := srv.Send(payload); err != nil { - return fmt.Errorf("send error: %w", err) + return ierrors.Wrap(err, "send error") } } // Send End if err := srv.Send(NewLedgerUpdateBatchEnd(commitment.ID(), len(outputs), len(spents))); err != nil { - return fmt.Errorf("send error: %w", err) + return ierrors.Wrap(err, "send error") } return nil diff --git a/pkg/toolset/ed25519.go b/pkg/toolset/ed25519.go index 4cb8ab8fb..a6d061682 100644 --- a/pkg/toolset/ed25519.go +++ b/pkg/toolset/ed25519.go @@ -82,11 +82,11 @@ func generateEd25519Key(args []string) error { } if len(*hrpFlag) == 0 { - return fmt.Errorf("'%s' not specified", FlagToolHRP) + return ierrors.Errorf("'%s' not specified", FlagToolHRP) } if len(*bip32Path) == 0 { - return fmt.Errorf("'%s' not specified", FlagToolBIP32Path) + return ierrors.Errorf("'%s' not specified", FlagToolBIP32Path) } var err error diff --git a/pkg/toolset/jwt.go b/pkg/toolset/jwt.go index 9585eee8c..a0c062cf2 100644 --- a/pkg/toolset/jwt.go +++ b/pkg/toolset/jwt.go @@ -11,6 +11,7 @@ import ( "github.com/iotaledger/hive.go/app/configuration" hivep2p "github.com/iotaledger/hive.go/crypto/p2p" "github.com/iotaledger/hive.go/crypto/pem" + "github.com/iotaledger/hive.go/ierrors" "github.com/iotaledger/iota-core/components/p2p" "github.com/iotaledger/iota-core/pkg/jwt" ) @@ -38,10 +39,10 @@ func generateJWTApiToken(args []string) error { } if len(*databasePathFlag) == 0 { - return fmt.Errorf("'%s' not specified", FlagToolDatabasePath) + return ierrors.Errorf("'%s' not specified", FlagToolDatabasePath) } if len(*apiJWTSaltFlag) == 0 { - return fmt.Errorf("'%s' not specified", FlagToolSalt) + return ierrors.Errorf("'%s' not specified", FlagToolSalt) } databasePath := *databasePathFlag @@ -53,28 +54,28 @@ func generateJWTApiToken(args []string) error { switch { case os.IsNotExist(err): // private key does not exist - return fmt.Errorf("private key file (%s) does not exist", privKeyFilePath) + return ierrors.Errorf("private key file (%s) does not exist", privKeyFilePath) case err == nil || os.IsExist(err): // private key file exists default: - return fmt.Errorf("unable to check private key file (%s): %w", privKeyFilePath, err) + return ierrors.Wrapf(err, "unable to check private key file (%s)", privKeyFilePath) } privKey, err := pem.ReadEd25519PrivateKeyFromPEMFile(privKeyFilePath) if err != nil { - return fmt.Errorf("reading private key file for peer identity failed: %w", err) + return ierrors.Wrap(err, "reading private key file for peer identity failed") } libp2pPrivKey, err := hivep2p.Ed25519PrivateKeyToLibp2pPrivateKey(privKey) if err != nil { - return fmt.Errorf("reading private key file for peer identity failed: %w", err) + return ierrors.Wrap(err, "reading private key file for peer identity failed") } peerID, err := peer.IDFromPublicKey(libp2pPrivKey.GetPublic()) if err != nil { - return fmt.Errorf("unable to get peer identity from public key: %w", err) + return ierrors.Wrap(err, "unable to get peer identity from public key") } // API tokens do not expire. @@ -84,12 +85,12 @@ func generateJWTApiToken(args []string) error { libp2pPrivKey, ) if err != nil { - return fmt.Errorf("JWT auth initialization failed: %w", err) + return ierrors.Wrap(err, "JWT auth initialization failed") } jwtToken, err := jwtAuth.IssueJWT() if err != nil { - return fmt.Errorf("issuing JWT token failed: %w", err) + return ierrors.Wrap(err, "issuing JWT token failed") } if *outputJSONFlag { diff --git a/pkg/toolset/p2p_identity_extract.go b/pkg/toolset/p2p_identity_extract.go index 45a364d10..84e9c053e 100644 --- a/pkg/toolset/p2p_identity_extract.go +++ b/pkg/toolset/p2p_identity_extract.go @@ -10,6 +10,7 @@ import ( "github.com/iotaledger/hive.go/app/configuration" hivep2p "github.com/iotaledger/hive.go/crypto/p2p" "github.com/iotaledger/hive.go/crypto/pem" + "github.com/iotaledger/hive.go/ierrors" "github.com/iotaledger/iota-core/components/p2p" ) @@ -33,7 +34,7 @@ func extractP2PIdentity(args []string) error { } if len(*databasePathFlag) == 0 { - return fmt.Errorf("'%s' not specified", FlagToolDatabasePath) + return ierrors.Errorf("'%s' not specified", FlagToolDatabasePath) } databasePath := *databasePathFlag @@ -43,18 +44,18 @@ func extractP2PIdentity(args []string) error { switch { case os.IsNotExist(err): // private key does not exist - return fmt.Errorf("private key file (%s) does not exist", privKeyFilePath) + return ierrors.Errorf("private key file (%s) does not exist", privKeyFilePath) case err == nil || os.IsExist(err): // private key file exists default: - return fmt.Errorf("unable to check private key file (%s): %w", privKeyFilePath, err) + return ierrors.Wrapf(err, "unable to check private key file (%s)", privKeyFilePath) } privKey, err := pem.ReadEd25519PrivateKeyFromPEMFile(privKeyFilePath) if err != nil { - return fmt.Errorf("reading private key file for peer identity failed: %w", err) + return ierrors.Wrap(err, "reading private key file for peer identity failed") } libp2pPrivKey, err := hivep2p.Ed25519PrivateKeyToLibp2pPrivateKey(privKey) diff --git a/pkg/toolset/p2p_identity_gen.go b/pkg/toolset/p2p_identity_gen.go index b376fd5e8..6086a4500 100644 --- a/pkg/toolset/p2p_identity_gen.go +++ b/pkg/toolset/p2p_identity_gen.go @@ -15,6 +15,7 @@ import ( "github.com/iotaledger/hive.go/app/configuration" hivecrypto "github.com/iotaledger/hive.go/crypto" "github.com/iotaledger/hive.go/crypto/pem" + "github.com/iotaledger/hive.go/ierrors" "github.com/iotaledger/iota-core/components/p2p" "github.com/iotaledger/iota.go/v4/hexutil" ) @@ -43,50 +44,50 @@ func generateP2PIdentity(args []string) error { } if len(*databasePathFlag) == 0 { - return fmt.Errorf("'%s' not specified", FlagToolDatabasePath) + return ierrors.Errorf("'%s' not specified", FlagToolDatabasePath) } databasePath := *databasePathFlag privKeyFilePath := filepath.Join(databasePath, p2p.IdentityPrivateKeyFileName) if err := os.MkdirAll(databasePath, 0700); err != nil { - return fmt.Errorf("could not create peer store database dir '%s': %w", databasePath, err) + return ierrors.Wrapf(err, "could not create peer store database dir '%s'", databasePath) } _, err := os.Stat(privKeyFilePath) switch { case err == nil || os.IsExist(err): // private key file already exists - return fmt.Errorf("private key file (%s) already exists", privKeyFilePath) + return ierrors.Errorf("private key file (%s) already exists", privKeyFilePath) case os.IsNotExist(err): // private key file does not exist, create a new one default: - return fmt.Errorf("unable to check private key file (%s): %w", privKeyFilePath, err) + return ierrors.Wrapf(err, "unable to check private key file (%s)", privKeyFilePath) } var privKey ed25519.PrivateKey if privateKeyFlag != nil && len(*privateKeyFlag) > 0 { privKey, err = hivecrypto.ParseEd25519PrivateKeyFromString(*privateKeyFlag) if err != nil { - return fmt.Errorf("invalid private key given '%s': %w", *privateKeyFlag, err) + return ierrors.Wrapf(err, "invalid private key given '%s'", *privateKeyFlag) } } else { // create identity _, privKey, err = ed25519.GenerateKey(nil) if err != nil { - return fmt.Errorf("unable to generate Ed25519 private key for peer identity: %w", err) + return ierrors.Wrap(err, "unable to generate Ed25519 private key for peer identity") } } libp2pPrivKey, libp2pPubKey, err := crypto.KeyPairFromStdKey(&privKey) if err != nil { - return fmt.Errorf("unable to convert given private key '%s': %w", hexutil.EncodeHex(privKey), err) + return ierrors.Wrapf(err, "unable to convert given private key '%s'", hexutil.EncodeHex(privKey)) } if err := pem.WriteEd25519PrivateKeyToPEMFile(privKeyFilePath, privKey); err != nil { - return fmt.Errorf("writing private key file for peer identity failed: %w", err) + return ierrors.Wrap(err, "writing private key file for peer identity failed") } return printP2PIdentity(libp2pPrivKey, libp2pPubKey, *outputJSONFlag) @@ -103,17 +104,17 @@ func printP2PIdentity(libp2pPrivKey crypto.PrivKey, libp2pPubKey crypto.PubKey, privKeyBytes, err := libp2pPrivKey.Raw() if err != nil { - return fmt.Errorf("unable to get raw private key bytes: %w", err) + return ierrors.Wrap(err, "unable to get raw private key bytes") } pubKeyBytes, err := libp2pPubKey.Raw() if err != nil { - return fmt.Errorf("unable to get raw public key bytes: %w", err) + return ierrors.Wrap(err, "unable to get raw public key bytes") } peerID, err := peer.IDFromPublicKey(libp2pPubKey) if err != nil { - return fmt.Errorf("unable to get peer identity from public key: %w", err) + return ierrors.Wrap(err, "unable to get peer identity from public key") } identity := P2PIdentity{ diff --git a/pkg/toolset/toolset.go b/pkg/toolset/toolset.go index cad18b14e..6721f92e1 100644 --- a/pkg/toolset/toolset.go +++ b/pkg/toolset/toolset.go @@ -148,7 +148,7 @@ func loadConfigFile(filePath string, parameters map[string]any) error { } if err := config.LoadFile(filePath); err != nil { - return fmt.Errorf("loading config file failed: %w", err) + return ierrors.Wrap(err, "loading config file failed") } config.UpdateBoundParameters() From e6b771b32a2ea2a17b6bd8d682463373f4c39758 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Fri, 15 Mar 2024 11:22:14 +0800 Subject: [PATCH 18/19] Prefer `blockID` over `blockID.ToHex()` in errors --- components/dashboard/explorer_routes.go | 4 ++-- components/debugapi/blocks.go | 2 +- pkg/protocol/engine/mempool/v1/mempool.go | 2 +- pkg/requesthandler/blockissuance.go | 6 +++--- pkg/requesthandler/blocks.go | 10 +++++----- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/components/dashboard/explorer_routes.go b/components/dashboard/explorer_routes.go index 6766c26d6..0598222f0 100644 --- a/components/dashboard/explorer_routes.go +++ b/components/dashboard/explorer_routes.go @@ -75,14 +75,14 @@ func setupExplorerRoutes(routeGroup *echo.Group) { func findBlock(blockID iotago.BlockID) (explorerBlk *ExplorerBlock, err error) { block, exists := deps.Protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.Errorf("block %s not found", blockID.ToHex()) + return nil, ierrors.Errorf("block %s not found", blockID) } cachedBlock, _ := deps.Protocol.Engines.Main.Get().BlockCache.Block(blockID) blockMetadata, err := deps.Protocol.Engines.Main.Get().BlockRetainer.BlockMetadata(blockID) if err != nil { - return nil, ierrors.Wrapf(err, "failed to get block metadata for block %s", blockID.ToHex()) + return nil, ierrors.Wrapf(err, "failed to get block metadata for block %s", blockID) } return createExplorerBlock(block, cachedBlock, blockMetadata), nil diff --git a/components/debugapi/blocks.go b/components/debugapi/blocks.go index b12b577e2..963116fdd 100644 --- a/components/debugapi/blocks.go +++ b/components/debugapi/blocks.go @@ -27,7 +27,7 @@ func getSlotBlockIDs(index iotago.SlotIndex) (*BlockChangesResponse, error) { _ = blocksForSlot.StreamKeys(func(blockID iotago.BlockID) error { includedBlocks = append(includedBlocks, blockID.String()) if err := tangleTree.Add(blockID); err != nil { - return ierrors.Wrapf(err, "failed to add block to tangle tree, blockID: %s", blockID.ToHex()) + return ierrors.Wrapf(err, "failed to add block to tangle tree, blockID: %s", blockID) } return nil diff --git a/pkg/protocol/engine/mempool/v1/mempool.go b/pkg/protocol/engine/mempool/v1/mempool.go index a003894cb..cd44e046c 100644 --- a/pkg/protocol/engine/mempool/v1/mempool.go +++ b/pkg/protocol/engine/mempool/v1/mempool.go @@ -352,7 +352,7 @@ func (m *MemPool[VoteRank]) storeTransaction(signedTransaction mempool.SignedTra if m.lastCommittedSlot >= blockID.Slot() { // block will be retained as invalid, we do not store tx failure as it was block's fault - return nil, false, false, ierrors.Errorf("blockID %d is older than last evicted slot %d", blockID, m.lastCommittedSlot) + return nil, false, false, ierrors.Errorf("blockID %s is older than last evicted slot %d", blockID, m.lastCommittedSlot) } inputReferences, err := m.vm.Inputs(transaction) diff --git a/pkg/requesthandler/blockissuance.go b/pkg/requesthandler/blockissuance.go index 21b9be3a9..ed6e163ec 100644 --- a/pkg/requesthandler/blockissuance.go +++ b/pkg/requesthandler/blockissuance.go @@ -71,15 +71,15 @@ func (r *RequestHandler) SubmitBlockAndAwaitEvent(ctx context.Context, block *mo defer lo.BatchReverse(evtUnhook, prefilteredUnhook, postfilteredUnhook)() if err := r.submitBlock(block); err != nil { - return ierrors.Wrapf(err, "failed to issue block %s", blockID.ToHex()) + return ierrors.Wrapf(err, "failed to issue block %s", blockID) } select { case <-processingCtx.Done(): - return ierrors.Errorf("context canceled whilst waiting for event on block %s", blockID.ToHex()) + return ierrors.Errorf("context canceled whilst waiting for event on block %s", blockID) case err := <-filtered: if err != nil { - return ierrors.Wrapf(err, "block filtered %s", blockID.ToHex()) + return ierrors.Wrapf(err, "block filtered %s", blockID) } return nil diff --git a/pkg/requesthandler/blocks.go b/pkg/requesthandler/blocks.go index 12c72e205..ba0491dac 100644 --- a/pkg/requesthandler/blocks.go +++ b/pkg/requesthandler/blocks.go @@ -15,7 +15,7 @@ import ( func (r *RequestHandler) BlockByID(blockID iotago.BlockID) (*iotago.Block, error) { block, exists := r.protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.WithMessagef(echo.ErrNotFound, "block %s not found", blockID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "block %s not found", blockID) } return block.ProtocolBlock(), nil @@ -25,10 +25,10 @@ func (r *RequestHandler) BlockMetadataByBlockID(blockID iotago.BlockID) (*api.Bl blockMetadata, err := r.protocol.Engines.Main.Get().BlockRetainer.BlockMetadata(blockID) if err != nil { if ierrors.Is(err, kvstore.ErrKeyNotFound) { - return nil, ierrors.WithMessagef(echo.ErrNotFound, "block %s not found", blockID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "block %s not found", blockID) } - return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get block metadata %s: %w", blockID.ToHex(), err) + return nil, ierrors.WithMessagef(echo.ErrInternalServerError, "failed to get block metadata %s: %w", blockID, err) } return blockMetadata, nil @@ -46,7 +46,7 @@ func (r *RequestHandler) BlockMetadataByID(c echo.Context) (*api.BlockMetadataRe func (r *RequestHandler) BlockWithMetadataByID(blockID iotago.BlockID) (*api.BlockWithMetadataResponse, error) { block, exists := r.protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.WithMessagef(echo.ErrNotFound, "no transaction found for block ID %s", blockID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "no transaction found for block ID %s", blockID) } blockMetadata, err := r.BlockMetadataByBlockID(blockID) @@ -72,7 +72,7 @@ func (r *RequestHandler) BlockIssuance() (*api.IssuanceBlockHeaderResponse, erro for _, blockID := range references[parentType] { block, exists := r.protocol.Engines.Main.Get().Block(blockID) if !exists { - return nil, ierrors.WithMessagef(echo.ErrNotFound, "failed to retrieve parents: no block found for block ID %s", blockID.ToHex()) + return nil, ierrors.WithMessagef(echo.ErrNotFound, "failed to retrieve parents: no block found for block ID %s", blockID) } if latestParentBlockIssuingTime.Before(block.ProtocolBlock().Header.IssuingTime) { From f87ad11bf58643c2526800ed10489e58e6eea990 Mon Sep 17 00:00:00 2001 From: Philipp Gackstatter Date: Fri, 15 Mar 2024 11:22:30 +0800 Subject: [PATCH 19/19] Fix incorrect error order and Errorf usage --- pkg/network/p2p/manager.go | 6 +++--- .../sybilprotection/sybilprotectionv1/sybilprotection.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/network/p2p/manager.go b/pkg/network/p2p/manager.go index 2785a614e..da232ef00 100644 --- a/pkg/network/p2p/manager.go +++ b/pkg/network/p2p/manager.go @@ -113,11 +113,11 @@ func (m *Manager) DialPeer(ctx context.Context, peer *network.Peer) error { } if m.NeighborExists(peer.ID) { - return ierrors.Wrapf(network.ErrDuplicatePeer, "peer %s already exists", peer.ID.String()) + return ierrors.WithMessagef(network.ErrDuplicatePeer, "peer %s already exists", peer.ID.String()) } if !m.allowPeer(peer.ID) { - return ierrors.Wrapf(network.ErrMaxAutopeeringPeersReached, "peer %s is not allowed", peer.ID.String()) + return ierrors.WithMessagef(network.ErrMaxAutopeeringPeersReached, "peer %s is not allowed", peer.ID.String()) } // Adds the peer's multiaddresses to the peerstore, so that they can be used for dialing. @@ -147,7 +147,7 @@ func (m *Manager) DialPeer(ctx context.Context, peer *network.Peer) error { if err := m.addNeighbor(ctx, peer, ps); err != nil { m.closeStream(stream) - return ierrors.Errorf("failed to add neighbor %s: %s", peer.ID.String(), err.Error()) + return ierrors.Wrapf(err, "failed to add neighbor %s", peer.ID.String()) } return nil diff --git a/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go b/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go index c1d10cfd6..49b7132b5 100644 --- a/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go +++ b/pkg/protocol/sybilprotection/sybilprotectionv1/sybilprotection.go @@ -110,7 +110,7 @@ func (o *SybilProtection) TrackBlock(block *blocks.Block) { accountData, exists, err := o.ledger.Account(block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot()) if err != nil { - o.errHandler(ierrors.Wrapf(err, "error while retrieving account %s in slot %d from accounts ledger", block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot())) + o.errHandler(ierrors.Wrapf(err, "error while retrieving data for account %s in slot %d from accounts ledger", block.ProtocolBlock().Header.IssuerID, block.SlotCommitmentID().Slot())) return }