diff --git a/client/lib.go b/client/lib.go index 87e81896994b0e943b802e1b43e3e04d5f7fd70a..ed2884bab40a29d4d12e0c29835539ef644405a5 100644 --- a/client/lib.go +++ b/client/lib.go @@ -4,11 +4,11 @@ package goshimmer import ( "bytes" "encoding/json" + "errors" "fmt" "io/ioutil" "net/http" - "github.com/iotaledger/goshimmer/packages/errors" webapi_broadcastData "github.com/iotaledger/goshimmer/plugins/webapi/broadcastData" webapi_findTransactions "github.com/iotaledger/goshimmer/plugins/webapi/findTransactions" webapi_getNeighbors "github.com/iotaledger/goshimmer/plugins/webapi/getNeighbors" @@ -59,7 +59,7 @@ type errorresponse struct { func interpretBody(res *http.Response, decodeTo interface{}) error { resBody, err := ioutil.ReadAll(res.Body) if err != nil { - return errors.Wrap(err, "unable to read response body") + return fmt.Errorf("unable to read response body: %w", err) } defer res.Body.Close() @@ -69,23 +69,24 @@ func interpretBody(res *http.Response, decodeTo interface{}) error { errRes := &errorresponse{} if err := json.Unmarshal(resBody, errRes); err != nil { - return errors.Wrap(err, "unable to read error from response body") + return fmt.Errorf("unable to read error from response body: %w", err) } switch res.StatusCode { case http.StatusInternalServerError: - return errors.Wrap(ErrInternalServerError, errRes.Error) + return fmt.Errorf("%w: %s", ErrInternalServerError, errRes.Error) case http.StatusNotFound: - return errors.Wrap(ErrNotFound, errRes.Error) + return fmt.Errorf("%w: %s", ErrNotFound, errRes.Error) case http.StatusBadRequest: - return errors.Wrap(ErrBadRequest, errRes.Error) + return fmt.Errorf("%w: %s", ErrBadRequest, errRes.Error) } - return errors.Wrap(ErrUnknownError, errRes.Error) + + return fmt.Errorf("%w: %s", ErrUnknownError, errRes.Error) } func (api *GoShimmerAPI) BroadcastData(targetAddress trinary.Trytes, data string) (trinary.Hash, error) { if !guards.IsHash(targetAddress) { - return "", errors.Wrapf(consts.ErrInvalidHash, "invalid address: %s", targetAddress) + return "", fmt.Errorf("%w: invalid address: %s", consts.ErrInvalidHash, targetAddress) } reqBytes, err := json.Marshal(&webapi_broadcastData.Request{Address: targetAddress, Data: data}) @@ -109,7 +110,7 @@ func (api *GoShimmerAPI) BroadcastData(targetAddress trinary.Trytes, data string func (api *GoShimmerAPI) GetTrytes(txHashes trinary.Hashes) ([]trinary.Trytes, error) { for _, hash := range txHashes { if !guards.IsTrytes(hash) { - return nil, errors.Wrapf(consts.ErrInvalidHash, "invalid hash: %s", hash) + return nil, fmt.Errorf("%w: invalid hash: %s", consts.ErrInvalidHash, hash) } } @@ -134,7 +135,7 @@ func (api *GoShimmerAPI) GetTrytes(txHashes trinary.Hashes) ([]trinary.Trytes, e func (api *GoShimmerAPI) GetTransactions(txHashes trinary.Hashes) ([]webapi_getTransactions.Transaction, error) { for _, hash := range txHashes { if !guards.IsTrytes(hash) { - return nil, errors.Wrapf(consts.ErrInvalidHash, "invalid hash: %s", hash) + return nil, fmt.Errorf("%w: invalid hash: %s", consts.ErrInvalidHash, hash) } } @@ -159,7 +160,7 @@ func (api *GoShimmerAPI) GetTransactions(txHashes trinary.Hashes) ([]webapi_getT func (api *GoShimmerAPI) FindTransactions(query *webapi_findTransactions.Request) ([]trinary.Hashes, error) { for _, hash := range query.Addresses { if !guards.IsTrytes(hash) { - return nil, errors.Wrapf(consts.ErrInvalidHash, "invalid hash: %s", hash) + return nil, fmt.Errorf("%w: invalid hash: %s", consts.ErrInvalidHash, hash) } } diff --git a/go.mod b/go.mod index 10d4c4c4cc928a127415ba96617b5f5cb9434135..0564d83750563587252c4c190bc10c030a072a58 100644 --- a/go.mod +++ b/go.mod @@ -23,7 +23,7 @@ require ( github.com/mattn/go-isatty v0.0.11 // indirect github.com/mattn/go-runewidth v0.0.7 // indirect github.com/pelletier/go-toml v1.6.0 // indirect - github.com/pkg/errors v0.9.1 + github.com/pkg/errors v0.9.1 // indirect github.com/rivo/tview v0.0.0-20191229165609-1ee8d9874dcf github.com/spf13/afero v1.2.2 // indirect github.com/spf13/cast v1.3.1 // indirect diff --git a/packages/autopeering/discover/protocol.go b/packages/autopeering/discover/protocol.go index 242016f7b45feb4fd4c303707f94a86ebc1e3417..756f5fe1c25e842df22c4ddc9d3386ea3a04cc7e 100644 --- a/packages/autopeering/discover/protocol.go +++ b/packages/autopeering/discover/protocol.go @@ -2,6 +2,7 @@ package discover import ( "bytes" + "fmt" "sync" "time" @@ -12,7 +13,6 @@ import ( "github.com/iotaledger/goshimmer/packages/autopeering/peer/service" "github.com/iotaledger/goshimmer/packages/autopeering/server" "github.com/iotaledger/hive.go/logger" - "github.com/pkg/errors" ) // The Protocol handles the peer discovery. @@ -104,7 +104,7 @@ func (p *Protocol) HandleMessage(s *server.Server, fromAddr string, fromID peer. case pb.MPing: m := new(pb.Ping) if err := proto.Unmarshal(data[1:], m); err != nil { - return true, errors.Wrap(err, "invalid message") + return true, fmt.Errorf("invalid message: %w", err) } if p.validatePing(s, fromAddr, m) { p.handlePing(s, fromAddr, fromID, fromKey, data) @@ -114,7 +114,7 @@ func (p *Protocol) HandleMessage(s *server.Server, fromAddr string, fromID peer. case pb.MPong: m := new(pb.Pong) if err := proto.Unmarshal(data[1:], m); err != nil { - return true, errors.Wrap(err, "invalid message") + return true, fmt.Errorf("invalid message: %w", err) } if p.validatePong(s, fromAddr, fromID, m) { p.handlePong(fromAddr, fromID, fromKey, m) @@ -124,7 +124,7 @@ func (p *Protocol) HandleMessage(s *server.Server, fromAddr string, fromID peer. case pb.MDiscoveryRequest: m := new(pb.DiscoveryRequest) if err := proto.Unmarshal(data[1:], m); err != nil { - return true, errors.Wrap(err, "invalid message") + return true, fmt.Errorf("invalid message: %w", err) } if p.validateDiscoveryRequest(s, fromAddr, fromID, m) { p.handleDiscoveryRequest(s, fromAddr, data) @@ -134,7 +134,7 @@ func (p *Protocol) HandleMessage(s *server.Server, fromAddr string, fromID peer. case pb.MDiscoveryResponse: m := new(pb.DiscoveryResponse) if err := proto.Unmarshal(data[1:], m); err != nil { - return true, errors.Wrap(err, "invalid message") + return true, fmt.Errorf("invalid message: %w", err) } p.validateDiscoveryResponse(s, fromAddr, fromID, m) // DiscoveryResponse messages are handled in the handleReply function of the validation diff --git a/packages/autopeering/peer/peer.go b/packages/autopeering/peer/peer.go index 30a1882f2fdc9da398af2a28754f9df627a72093..768511caf2cd39b9a241284b1e098b762ea010fc 100644 --- a/packages/autopeering/peer/peer.go +++ b/packages/autopeering/peer/peer.go @@ -12,6 +12,11 @@ import ( "github.com/iotaledger/goshimmer/packages/autopeering/peer/service" ) +var ( + ErrNeedsPeeringService = errors.New("needs peering service") + ErrInvalidSignature = errors.New("invalid signature") +) + // PublicKey is the type of Ed25519 public keys used for peers. type PublicKey ed25519.PublicKey @@ -100,7 +105,7 @@ func FromProto(in *pb.Peer) (*Peer, error) { return nil, err } if services.Get(service.PeeringKey) == nil { - return nil, errors.New("need peering service") + return nil, ErrNeedsPeeringService } return NewPeer(in.GetPublicKey(), services), nil @@ -122,13 +127,13 @@ func Unmarshal(data []byte) (*Peer, error) { func recoverKey(key, data, sig []byte) (PublicKey, error) { if l := len(key); l != ed25519.PublicKeySize { - return nil, fmt.Errorf("invalid key length: %d, need %d", l, ed25519.PublicKeySize) + return nil, fmt.Errorf("%w: invalid key length: %d, need %d", ErrInvalidSignature, l, ed25519.PublicKeySize) } if l := len(sig); l != ed25519.SignatureSize { - return nil, fmt.Errorf("invalid signature length: %d, need %d", l, ed25519.SignatureSize) + return nil, fmt.Errorf("%w: invalid signature length: %d, need %d", ErrInvalidSignature, l, ed25519.SignatureSize) } if !ed25519.Verify(key, data, sig) { - return nil, errors.New("invalid signature") + return nil, ErrInvalidSignature } publicKey := make([]byte, ed25519.PublicKeySize) diff --git a/packages/autopeering/selection/protocol.go b/packages/autopeering/selection/protocol.go index dd92c1f2f77fe68b7ef0857dc10784e4288c2e24..f82697afd88be5cf25c0e14ecb98ec3833fa2d8a 100644 --- a/packages/autopeering/selection/protocol.go +++ b/packages/autopeering/selection/protocol.go @@ -2,6 +2,7 @@ package selection import ( "bytes" + "fmt" "sync" "time" @@ -11,7 +12,6 @@ import ( pb "github.com/iotaledger/goshimmer/packages/autopeering/selection/proto" "github.com/iotaledger/goshimmer/packages/autopeering/server" "github.com/iotaledger/hive.go/logger" - "github.com/pkg/errors" ) // DiscoverProtocol specifies the methods from the peer discovery that are required. @@ -101,7 +101,7 @@ func (p *Protocol) HandleMessage(s *server.Server, fromAddr string, fromID peer. case pb.MPeeringRequest: m := new(pb.PeeringRequest) if err := proto.Unmarshal(data[1:], m); err != nil { - return true, errors.Wrap(err, "invalid message") + return true, fmt.Errorf("invalid message: %w", err) } if p.validatePeeringRequest(s, fromAddr, fromID, m) { p.handlePeeringRequest(s, fromAddr, fromID, data, m) @@ -111,7 +111,7 @@ func (p *Protocol) HandleMessage(s *server.Server, fromAddr string, fromID peer. case pb.MPeeringResponse: m := new(pb.PeeringResponse) if err := proto.Unmarshal(data[1:], m); err != nil { - return true, errors.Wrap(err, "invalid message") + return true, fmt.Errorf("invalid message: %w", err) } p.validatePeeringResponse(s, fromAddr, fromID, m) // PeeringResponse messages are handled in the handleReply function of the validation @@ -120,7 +120,7 @@ func (p *Protocol) HandleMessage(s *server.Server, fromAddr string, fromID peer. case pb.MPeeringDrop: m := new(pb.PeeringDrop) if err := proto.Unmarshal(data[1:], m); err != nil { - return true, errors.Wrap(err, "invalid message") + return true, fmt.Errorf("invalid message: %w", err) } if p.validatePeeringDrop(s, fromAddr, m) { p.handlePeeringDrop(fromID) diff --git a/packages/autopeering/server/errors.go b/packages/autopeering/server/errors.go index 54c5d51a35778daa3459ad3cf94f8765fb04d8f2..c278c2f5058fe0944af9a73506b7abcfd02ae62e 100644 --- a/packages/autopeering/server/errors.go +++ b/packages/autopeering/server/errors.go @@ -1,6 +1,6 @@ package server -import "github.com/pkg/errors" +import "errors" var ( // ErrTimeout is returned when an expected response was not received in time. diff --git a/packages/autopeering/server/server.go b/packages/autopeering/server/server.go index 2c6303e573912c03aa055fc7e208e09ddabd723e..bd3d65da1323192b9018b8ac8d4cc6436053f31a 100644 --- a/packages/autopeering/server/server.go +++ b/packages/autopeering/server/server.go @@ -2,6 +2,7 @@ package server import ( "container/list" + "fmt" "io" "net" "sync" @@ -12,7 +13,6 @@ import ( pb "github.com/iotaledger/goshimmer/packages/autopeering/server/proto" "github.com/iotaledger/goshimmer/packages/autopeering/transport" "github.com/iotaledger/hive.go/logger" - "github.com/pkg/errors" ) const ( @@ -288,7 +288,7 @@ func (s *Server) readLoop() { func (s *Server) handlePacket(pkt *pb.Packet, fromAddr string) error { data, key, err := decode(pkt) if err != nil { - return errors.Wrap(err, "invalid packet") + return fmt.Errorf("invalid packet: %w", err) } fromID := key.ID() diff --git a/packages/database/badger_instance.go b/packages/database/badger_instance.go index 3f6fd82fdc4d9efd675c6e040fc00e2da83e76e3..439aa4727db7bd7f56c29bbc46896cbba7ae7b7e 100644 --- a/packages/database/badger_instance.go +++ b/packages/database/badger_instance.go @@ -1,13 +1,13 @@ package database import ( + "fmt" "os" "sync" "github.com/dgraph-io/badger" "github.com/dgraph-io/badger/options" "github.com/iotaledger/goshimmer/packages/parameter" - "github.com/pkg/errors" ) var instance *badger.DB @@ -40,7 +40,7 @@ func checkDir(dir string) error { func createDB() (*badger.DB, error) { directory := parameter.NodeConfig.GetString(CFG_DIRECTORY) if err := checkDir(directory); err != nil { - return nil, errors.Wrap(err, "Could not check directory") + return nil, fmt.Errorf("could not check directory: %w", err) } opts := badger.DefaultOptions(directory) @@ -50,7 +50,7 @@ func createDB() (*badger.DB, error) { db, err := badger.Open(opts) if err != nil { - return nil, errors.Wrap(err, "Could not open new DB") + return nil, fmt.Errorf("could not open new DB: %w", err) } return db, nil diff --git a/packages/datastructure/doubly_linked_list.go b/packages/datastructure/doubly_linked_list.go index 91d2e067e6b7cb4a3f2a0aae850ec52a65b34ba3..bc511e3f0fd126afe40879a964d5cc00f521072a 100644 --- a/packages/datastructure/doubly_linked_list.go +++ b/packages/datastructure/doubly_linked_list.go @@ -1,9 +1,8 @@ package datastructure import ( + "fmt" "sync" - - "github.com/iotaledger/goshimmer/packages/errors" ) type DoublyLinkedList struct { @@ -66,7 +65,7 @@ func (list *DoublyLinkedList) Clear() { list.clear() } -func (list *DoublyLinkedList) GetFirst() (interface{}, errors.IdentifiableError) { +func (list *DoublyLinkedList) GetFirst() (interface{}, error) { if firstEntry, err := list.GetFirstEntry(); err != nil { return nil, err } else { @@ -74,14 +73,14 @@ func (list *DoublyLinkedList) GetFirst() (interface{}, errors.IdentifiableError) } } -func (list *DoublyLinkedList) GetFirstEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) GetFirstEntry() (*DoublyLinkedListEntry, error) { list.mutex.RLock() defer list.mutex.RUnlock() return list.getFirstEntry() } -func (list *DoublyLinkedList) GetLast() (interface{}, errors.IdentifiableError) { +func (list *DoublyLinkedList) GetLast() (interface{}, error) { if lastEntry, err := list.GetLastEntry(); err != nil { return nil, err } else { @@ -89,14 +88,14 @@ func (list *DoublyLinkedList) GetLast() (interface{}, errors.IdentifiableError) } } -func (list *DoublyLinkedList) GetLastEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) GetLastEntry() (*DoublyLinkedListEntry, error) { list.mutex.RLock() defer list.mutex.RUnlock() return list.getLastEntry() } -func (list *DoublyLinkedList) RemoveFirst() (interface{}, errors.IdentifiableError) { +func (list *DoublyLinkedList) RemoveFirst() (interface{}, error) { if firstEntry, err := list.RemoveFirstEntry(); err != nil { return nil, err } else { @@ -104,14 +103,14 @@ func (list *DoublyLinkedList) RemoveFirst() (interface{}, errors.IdentifiableErr } } -func (list *DoublyLinkedList) RemoveFirstEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) RemoveFirstEntry() (*DoublyLinkedListEntry, error) { list.mutex.Lock() defer list.mutex.Unlock() return list.removeFirstEntry() } -func (list *DoublyLinkedList) RemoveLast() (interface{}, errors.IdentifiableError) { +func (list *DoublyLinkedList) RemoveLast() (interface{}, error) { if lastEntry, err := list.RemoveLastEntry(); err != nil { return nil, err } else { @@ -119,14 +118,14 @@ func (list *DoublyLinkedList) RemoveLast() (interface{}, errors.IdentifiableErro } } -func (list *DoublyLinkedList) RemoveLastEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) RemoveLastEntry() (*DoublyLinkedListEntry, error) { list.mutex.Lock() defer list.mutex.Unlock() return list.removeLastEntry() } -func (list *DoublyLinkedList) Remove(value interface{}) errors.IdentifiableError { +func (list *DoublyLinkedList) Remove(value interface{}) error { list.mutex.RLock() currentEntry := list.head for currentEntry != nil { @@ -144,10 +143,10 @@ func (list *DoublyLinkedList) Remove(value interface{}) errors.IdentifiableError } list.mutex.RUnlock() - return ErrNoSuchElement.Derive("the entry is not part of the list") + return fmt.Errorf("%w: the entry is not part of the list", ErrNoSuchElement) } -func (list *DoublyLinkedList) RemoveEntry(entry *DoublyLinkedListEntry) errors.IdentifiableError { +func (list *DoublyLinkedList) RemoveEntry(entry *DoublyLinkedListEntry) error { list.mutex.Lock() defer list.mutex.Unlock() @@ -195,23 +194,23 @@ func (list *DoublyLinkedList) clear() { list.count = 0 } -func (list *DoublyLinkedList) getFirstEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) getFirstEntry() (*DoublyLinkedListEntry, error) { if list.head == nil { - return nil, ErrNoSuchElement.Derive("the list is empty") + return nil, fmt.Errorf("%w: the list is empty", ErrNoSuchElement) } return list.head, nil } -func (list *DoublyLinkedList) getLastEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) getLastEntry() (*DoublyLinkedListEntry, error) { if list.tail == nil { - return nil, ErrNoSuchElement.Derive("the list is empty") + return nil, fmt.Errorf("%w: the list is empty", ErrNoSuchElement) } return list.tail, nil } -func (list *DoublyLinkedList) removeFirstEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) removeFirstEntry() (*DoublyLinkedListEntry, error) { entryToRemove := list.head if err := list.removeEntry(entryToRemove); err != nil { return nil, err @@ -220,7 +219,7 @@ func (list *DoublyLinkedList) removeFirstEntry() (*DoublyLinkedListEntry, errors return entryToRemove, nil } -func (list *DoublyLinkedList) removeLastEntry() (*DoublyLinkedListEntry, errors.IdentifiableError) { +func (list *DoublyLinkedList) removeLastEntry() (*DoublyLinkedListEntry, error) { entryToRemove := list.tail if err := list.removeEntry(entryToRemove); err != nil { return nil, err @@ -229,13 +228,13 @@ func (list *DoublyLinkedList) removeLastEntry() (*DoublyLinkedListEntry, errors. return entryToRemove, nil } -func (list *DoublyLinkedList) removeEntry(entry *DoublyLinkedListEntry) errors.IdentifiableError { +func (list *DoublyLinkedList) removeEntry(entry *DoublyLinkedListEntry) error { if entry == nil { - return ErrInvalidArgument.Derive("the entry must not be nil") + return fmt.Errorf("%w: the entry must not be nil", ErrInvalidArgument) } if list.head == nil { - return ErrNoSuchElement.Derive("the entry is not part of the list") + return fmt.Errorf("%w: the entry is not part of the list", ErrNoSuchElement) } prevEntry := entry.GetPrev() diff --git a/packages/datastructure/errors.go b/packages/datastructure/errors.go index bd52cc1cf5406ef4da3b5422b2e94abafc17322e..757c2ef93eb188a3c6eac6410f948f84c6625070 100644 --- a/packages/datastructure/errors.go +++ b/packages/datastructure/errors.go @@ -1,7 +1,7 @@ package datastructure import ( - "github.com/iotaledger/goshimmer/packages/errors" + "errors" ) var ( diff --git a/packages/errors/errors.go b/packages/errors/errors.go deleted file mode 100644 index 738ed629704070ce452d025deebb90905098128d..0000000000000000000000000000000000000000 --- a/packages/errors/errors.go +++ /dev/null @@ -1,365 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which when applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// together with the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required, the errors.WithStack and -// errors.WithMessage functions destructure errors.Wrap into its component -// operations: annotating an error with a stack trace and with a message, -// respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error that does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// Although the causer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported: -// -// %s print the error. If the error has a Cause it will be -// printed recursively. -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface: -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// The returned errors.StackTrace type is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d\n", f, f) -// } -// } -// -// Although the stackTracer interface is not exported by this package, it is -// considered a part of its stable public interface. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -var idCounter = 0 - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) *fundamental { - idCounter++ - - return &fundamental{ - id: idCounter, - msg: message, - stack: Callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) IdentifiableError { - idCounter++ - - return &fundamental{ - id: idCounter, - msg: fmt.Sprintf(format, args...), - stack: Callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - id int - msg string - *stack -} - -func (f *fundamental) Derive(msg string) *fundamental { - return &fundamental{ - id: f.id, - msg: msg, - stack: Callers(), - } -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Equals(err IdentifiableError) bool { - return f.id == err.Id() -} - -func (f *fundamental) Id() int { - return f.id -} - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) IdentifiableError { - if err == nil { - return nil - } - - idCounter++ - - return &withStack{ - idCounter, - err, - Callers(), - } -} - -type withStack struct { - int - error - *stack -} - -func (w *withStack) Equals(err IdentifiableError) bool { - return w.int == err.Id() -} - -func (w *withStack) Id() int { - return w.int -} - -func (w *withStack) Derive(err error, message string) *withStack { - if err == nil { - return nil - } - return &withStack{ - w.int, - &withMessage{ - cause: err, - msg: message, - }, - Callers(), - } -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) *withStack { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - - idCounter++ - - return &withStack{ - idCounter, - err, - Callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is called, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) IdentifiableError { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - - idCounter++ - - return &withStack{ - idCounter, - err, - Callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) IdentifiableError { - if err == nil { - return nil - } - - idCounter++ - - return &withMessage{ - id: idCounter, - cause: err, - msg: message, - } -} - -// WithMessagef annotates err with the format specifier. -// If err is nil, WithMessagef returns nil. -func WithMessagef(err error, format string, args ...interface{}) IdentifiableError { - if err == nil { - return nil - } - - idCounter++ - - return &withMessage{ - id: idCounter, - cause: err, - msg: fmt.Sprintf(format, args...), - } -} - -type withMessage struct { - id int - cause error - msg string -} - -func (w *withMessage) Equals(err IdentifiableError) bool { - return w.id == err.Id() -} - -func (w *withMessage) Id() int { - return w.id -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} - -type IdentifiableError interface { - Error() string - Equals(identifiableError IdentifiableError) bool - Id() int -} diff --git a/packages/errors/stack.go b/packages/errors/stack.go deleted file mode 100644 index 875216879918d050cf26196e1fb6581a4d7768c3..0000000000000000000000000000000000000000 --- a/packages/errors/stack.go +++ /dev/null @@ -1,177 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strconv" - "strings" -) - -// Frame represents a program counter inside a stack frame. -// For historical reasons if Frame is interpreted as a uintptr -// its value represents the program counter + 1. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// name returns the name of this function, if known. -func (f Frame) name() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - return fn.Name() -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (<funcname>\n\t<path>) -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - io.WriteString(s, f.name()) - io.WriteString(s, "\n\t") - io.WriteString(s, f.file()) - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - io.WriteString(s, strconv.Itoa(f.line())) - case 'n': - io.WriteString(s, funcname(f.name())) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// MarshalText formats a stacktrace Frame as a text string. The output is the -// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. -func (f Frame) MarshalText() ([]byte, error) { - name := f.name() - if name == "unknown" { - return []byte(name), nil - } - return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -// Format formats the stack of Frames according to the fmt.Formatter interface. -// -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+v Prints filename, function, and line number for each Frame in the stack. -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - io.WriteString(s, "\n") - f.Format(s, verb) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - st.formatSlice(s, verb) - } - case 's': - st.formatSlice(s, verb) - } -} - -// formatSlice will format this StackTrace into the given buffer as a slice of -// Frame, only valid when called with '%s' or '%v'. -func (st StackTrace) formatSlice(s fmt.State, verb rune) { - io.WriteString(s, "[") - for i, f := range st { - if i > 0 { - io.WriteString(s, " ") - } - f.Format(s, verb) - } - io.WriteString(s, "]") -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func Callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} diff --git a/packages/gossip/errors.go b/packages/gossip/errors.go index e32a15305c2bb607d7ab74bd4d6b8cd4a3f65090..85e43340fe2f4be0cf91f95de18b21b378d0bb61 100644 --- a/packages/gossip/errors.go +++ b/packages/gossip/errors.go @@ -1,6 +1,6 @@ package gossip -import "github.com/pkg/errors" +import "errors" var ( ErrNotStarted = errors.New("manager not started") diff --git a/packages/gossip/manager.go b/packages/gossip/manager.go index 1050243f82a22b7e430c73e0273869603f70e361..03bcb475025475996c3b494bc862981099ba9b71 100644 --- a/packages/gossip/manager.go +++ b/packages/gossip/manager.go @@ -1,6 +1,7 @@ package gossip import ( + "fmt" "net" "sync" @@ -10,7 +11,6 @@ import ( pb "github.com/iotaledger/goshimmer/packages/gossip/proto" "github.com/iotaledger/goshimmer/packages/gossip/server" "github.com/iotaledger/hive.go/events" - "github.com/pkg/errors" "go.uber.org/zap" ) @@ -225,7 +225,7 @@ func (m *Manager) handlePacket(data []byte, p *peer.Peer) error { case pb.MTransaction: msg := new(pb.Transaction) if err := proto.Unmarshal(data[1:], msg); err != nil { - return errors.Wrap(err, "invalid packet") + return fmt.Errorf("invalid packet: %w", err) } m.log.Debugw("Received Transaction", "data", msg.GetData()) Events.TransactionReceived.Trigger(&TransactionReceivedEvent{Data: msg.GetData(), Peer: p}) @@ -234,7 +234,7 @@ func (m *Manager) handlePacket(data []byte, p *peer.Peer) error { case pb.MTransactionRequest: msg := new(pb.TransactionRequest) if err := proto.Unmarshal(data[1:], msg); err != nil { - return errors.Wrap(err, "invalid packet") + return fmt.Errorf("invalid packet: %w", err) } m.log.Debugw("Received Tx Req", "data", msg.GetHash()) // do something diff --git a/packages/gossip/server/server.go b/packages/gossip/server/server.go index 7723d4ee39baaf6a3445da3845b5ae7366fbdb2e..8cbab0e37cb9194601b4eac4cc1309fc569388b0 100644 --- a/packages/gossip/server/server.go +++ b/packages/gossip/server/server.go @@ -3,6 +3,7 @@ package server import ( "bytes" "container/list" + "errors" "fmt" "io" "net" @@ -14,7 +15,6 @@ import ( "github.com/iotaledger/goshimmer/packages/autopeering/peer" "github.com/iotaledger/goshimmer/packages/autopeering/peer/service" pb "github.com/iotaledger/goshimmer/packages/autopeering/server/proto" - "github.com/pkg/errors" "go.uber.org/zap" ) @@ -141,12 +141,12 @@ func (t *TCP) DialPeer(p *peer.Peer) (net.Conn, error) { conn, err := net.DialTimeout(gossipAddr.Network(), gossipAddr.String(), acceptTimeout) if err != nil { - return nil, errors.Wrap(err, "dial peer failed") + return nil, fmt.Errorf("dial peer failed: %w", err) } err = t.doHandshake(p.PublicKey(), gossipAddr.String(), conn) if err != nil { - return nil, errors.Wrap(err, "outgoing handshake failed") + return nil, fmt.Errorf("outgoing handshake failed: %w", err) } t.log.Debugw("outgoing connection established", @@ -166,7 +166,7 @@ func (t *TCP) AcceptPeer(p *peer.Peer) (net.Conn, error) { // wait for the connection connected := <-t.acceptPeer(p) if connected.err != nil { - return nil, errors.Wrap(connected.err, "accept peer failed") + return nil, fmt.Errorf("accept peer failed: %w", connected.err) } t.log.Debugw("incoming connection established", @@ -269,7 +269,7 @@ func (t *TCP) matchAccept(m *acceptMatcher, req []byte, conn net.Conn) { defer t.wg.Done() if err := t.writeHandshakeResponse(req, conn); err != nil { - m.connected <- connect{nil, errors.Wrap(err, "incoming handshake failed")} + m.connected <- connect{nil, fmt.Errorf("incoming handshake failed: %w", err)} t.closeConnection(conn) return } @@ -375,7 +375,7 @@ func (t *TCP) readHandshakeRequest(conn net.Conn) (peer.PublicKey, []byte, error b := make([]byte, maxHandshakePacketSize) n, err := conn.Read(b) if err != nil { - return nil, nil, errors.Wrap(err, ErrInvalidHandshake.Error()) + return nil, nil, fmt.Errorf("%w: %s", ErrInvalidHandshake, err.Error()) } pkt := &pb.Packet{} diff --git a/packages/model/approvers/approvers.go b/packages/model/approvers/approvers.go index 1c98156dcda57532bb11a5a3c61de591ddc015f4..d84e02216ebea3066095ed4c70884afee86dca5a 100644 --- a/packages/model/approvers/approvers.go +++ b/packages/model/approvers/approvers.go @@ -2,10 +2,10 @@ package approvers import ( "encoding/binary" - "strconv" + "fmt" "sync" - "github.com/iotaledger/goshimmer/packages/errors" + "github.com/iotaledger/goshimmer/packages/model" "github.com/iotaledger/hive.go/typeutils" "github.com/iotaledger/iota.go/trinary" ) @@ -86,17 +86,17 @@ func (approvers *Approvers) Marshal() (result []byte) { return } -func (approvers *Approvers) Unmarshal(data []byte) (err errors.IdentifiableError) { +func (approvers *Approvers) Unmarshal(data []byte) error { dataLen := len(data) if dataLen < MARSHALED_APPROVERS_MIN_SIZE { - return ErrMarshallFailed.Derive(errors.New("unmarshall failed"), "marshaled approvers are too short") + return fmt.Errorf("%w: marshaled approvers are too short", model.ErrMarshalFailed) } hashesCount := binary.BigEndian.Uint64(data[MARSHALED_APPROVERS_HASHES_COUNT_START:MARSHALED_APPROVERS_HASHES_COUNT_END]) if dataLen < MARSHALED_APPROVERS_MIN_SIZE+int(hashesCount)*MARSHALED_APPROVERS_HASH_SIZE { - return ErrMarshallFailed.Derive(errors.New("unmarshall failed"), "marshaled approvers are too short for "+strconv.FormatUint(hashesCount, 10)+" approvers") + return fmt.Errorf("%w: marshaled approvers are too short for %d approvers", model.ErrMarshalFailed, hashesCount) } approvers.hashesMutex.Lock() @@ -112,7 +112,7 @@ func (approvers *Approvers) Unmarshal(data []byte) (err errors.IdentifiableError approvers.hashesMutex.Unlock() - return + return nil } // endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/packages/model/approvers/errors.go b/packages/model/approvers/errors.go deleted file mode 100644 index 81e5d9e1c23ded899ef41f90d99c22ca9f056bba..0000000000000000000000000000000000000000 --- a/packages/model/approvers/errors.go +++ /dev/null @@ -1,8 +0,0 @@ -package approvers - -import "github.com/iotaledger/goshimmer/packages/errors" - -var ( - ErrUnmarshalFailed = errors.Wrap(errors.New("unmarshall failed"), "input data is corrupted") - ErrMarshallFailed = errors.Wrap(errors.New("marshal failed"), "the source object contains invalid values") -) diff --git a/packages/model/bundle/bundle.go b/packages/model/bundle/bundle.go index 977592c4c77afa16c7793b56b979e5fa1713aaa5..d54092ed0ebd37649781360f745ec91268550da7 100644 --- a/packages/model/bundle/bundle.go +++ b/packages/model/bundle/bundle.go @@ -2,11 +2,11 @@ package bundle import ( "encoding/binary" - "strconv" + "fmt" "sync" "unsafe" - "github.com/iotaledger/goshimmer/packages/errors" + "github.com/iotaledger/goshimmer/packages/model" "github.com/iotaledger/hive.go/bitmask" "github.com/iotaledger/hive.go/typeutils" "github.com/iotaledger/iota.go/trinary" @@ -140,17 +140,17 @@ func (bundle *Bundle) Marshal() (result []byte) { return } -func (bundle *Bundle) Unmarshal(data []byte) (err errors.IdentifiableError) { +func (bundle *Bundle) Unmarshal(data []byte) error { dataLen := len(data) if dataLen < MARSHALED_MIN_SIZE { - return ErrMarshallFailed.Derive(errors.New("unmarshall failed"), "marshaled bundle is too short") + return fmt.Errorf("%w: marshaled bundle is too short", model.ErrMarshalFailed) } hashesCount := binary.BigEndian.Uint64(data[MARSHALED_TRANSACTIONS_COUNT_START:MARSHALED_TRANSACTIONS_COUNT_END]) if dataLen < MARSHALED_MIN_SIZE+int(hashesCount)*MARSHALED_TRANSACTION_HASH_SIZE { - return ErrMarshallFailed.Derive(errors.New("unmarshall failed"), "marshaled bundle is too short for "+strconv.FormatUint(hashesCount, 10)+" transactions") + return fmt.Errorf("%w: marshaled bundle is too short for %d transactions", model.ErrMarshalFailed, hashesCount) } bundle.hashMutex.Lock() @@ -179,5 +179,5 @@ func (bundle *Bundle) Unmarshal(data []byte) (err errors.IdentifiableError) { bundle.bundleEssenceHashMutex.Unlock() bundle.hashMutex.Unlock() - return + return nil } diff --git a/packages/model/bundle/errors.go b/packages/model/bundle/errors.go deleted file mode 100644 index c4805e6bb6c70d420a1cccc764c97a8a2d5cd036..0000000000000000000000000000000000000000 --- a/packages/model/bundle/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package bundle - -import ( - "github.com/iotaledger/goshimmer/packages/errors" -) - -var ( - ErrUnmarshalFailed = errors.Wrap(errors.New("unmarshall failed"), "input data is corrupted") - ErrMarshallFailed = errors.Wrap(errors.New("marshal failed"), "the source object contains invalid values") -) diff --git a/packages/model/error.go b/packages/model/error.go new file mode 100644 index 0000000000000000000000000000000000000000..b060d2d30bcc10c7a327b936e38d2d3287b89e74 --- /dev/null +++ b/packages/model/error.go @@ -0,0 +1,8 @@ +package model + +import "errors" + +var ( + ErrUnmarshalFailed = errors.New("unmarshal failed") + ErrMarshalFailed = errors.New("marshal failed") +) diff --git a/packages/model/meta_transaction/meta_transaction.go b/packages/model/meta_transaction/meta_transaction.go index 1ed461447c98cf1612a216a27efc5663421c04ac..45550786ca7383277ca6d194aa06629477658a7c 100644 --- a/packages/model/meta_transaction/meta_transaction.go +++ b/packages/model/meta_transaction/meta_transaction.go @@ -1,6 +1,7 @@ package meta_transaction import ( + "errors" "fmt" "sync" @@ -8,7 +9,10 @@ import ( "github.com/iotaledger/iota.go/curl" "github.com/iotaledger/iota.go/pow" "github.com/iotaledger/iota.go/trinary" - "github.com/pkg/errors" +) + +var ( + ErrInvalidWeightMagnitude = errors.New("insufficient weight magnitude") ) type MetaTransaction struct { @@ -552,7 +556,7 @@ func (this *MetaTransaction) DoProofOfWork(mwm int) error { this.hasherMutex.Unlock() if err != nil { - return errors.Wrap(err, "PoW failed") + return fmt.Errorf("PoW failed: %w", err) } this.SetNonce(nonce) @@ -563,7 +567,7 @@ func (this *MetaTransaction) Validate() error { // check that the weight magnitude is valid weightMagnitude := this.GetWeightMagnitude() if weightMagnitude < MIN_WEIGHT_MAGNITUDE { - return fmt.Errorf("insufficient weight magnitude: got=%d, want=%d", weightMagnitude, MIN_WEIGHT_MAGNITUDE) + return fmt.Errorf("%w: got=%d, want=%d", ErrInvalidWeightMagnitude, weightMagnitude, MIN_WEIGHT_MAGNITUDE) } return nil diff --git a/packages/model/transactionmetadata/errors.go b/packages/model/transactionmetadata/errors.go deleted file mode 100644 index b8cfc2239971e878bf9943290b83194bb7972a2a..0000000000000000000000000000000000000000 --- a/packages/model/transactionmetadata/errors.go +++ /dev/null @@ -1,12 +0,0 @@ -package transactionmetadata - -import "github.com/iotaledger/goshimmer/packages/errors" - -// region errors /////////////////////////////////////////////////////////////////////////////////////////////////////// - -var ( - ErrUnmarshalFailed = errors.Wrap(errors.New("unmarshall failed"), "input data is corrupted") - ErrMarshallFailed = errors.Wrap(errors.New("marshal failed"), "the source object contains invalid values") -) - -// endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/packages/model/transactionmetadata/transactionmetadata.go b/packages/model/transactionmetadata/transactionmetadata.go index daf4a2342ed5b586e806134927756e8e32f1a568..66a2796601db9d236556d2d079340f0954c163a0 100644 --- a/packages/model/transactionmetadata/transactionmetadata.go +++ b/packages/model/transactionmetadata/transactionmetadata.go @@ -1,10 +1,11 @@ package transactionmetadata import ( + "fmt" "sync" "time" - "github.com/iotaledger/goshimmer/packages/errors" + "github.com/iotaledger/goshimmer/packages/model" "github.com/iotaledger/hive.go/bitmask" "github.com/iotaledger/hive.go/typeutils" "github.com/iotaledger/iota.go/trinary" @@ -206,7 +207,7 @@ func (metadata *TransactionMetadata) SetModified(modified bool) { // region marshaling functions ///////////////////////////////////////////////////////////////////////////////////////// -func (metadata *TransactionMetadata) Marshal() ([]byte, errors.IdentifiableError) { +func (metadata *TransactionMetadata) Marshal() ([]byte, error) { marshaledMetadata := make([]byte, MARSHALED_TOTAL_SIZE) metadata.receivedTimeMutex.RLock() @@ -222,7 +223,7 @@ func (metadata *TransactionMetadata) Marshal() ([]byte, errors.IdentifiableError marshaledReceivedTime, err := metadata.receivedTime.MarshalBinary() if err != nil { - return nil, ErrMarshallFailed.Derive(err, "failed to marshal received time") + return nil, fmt.Errorf("%w: failed to marshal received time: %s", model.ErrMarshalFailed, err.Error()) } copy(marshaledMetadata[MARSHALED_RECEIVED_TIME_START:MARSHALED_RECEIVED_TIME_END], marshaledReceivedTime) @@ -241,7 +242,7 @@ func (metadata *TransactionMetadata) Marshal() ([]byte, errors.IdentifiableError return marshaledMetadata, nil } -func (metadata *TransactionMetadata) Unmarshal(data []byte) errors.IdentifiableError { +func (metadata *TransactionMetadata) Unmarshal(data []byte) error { metadata.hashMutex.Lock() defer metadata.hashMutex.Unlock() metadata.receivedTimeMutex.Lock() @@ -253,10 +254,10 @@ func (metadata *TransactionMetadata) Unmarshal(data []byte) errors.IdentifiableE metadata.finalizedMutex.Lock() defer metadata.finalizedMutex.Unlock() - metadata.hash = trinary.Trytes(typeutils.BytesToString(data[MARSHALED_HASH_START:MARSHALED_HASH_END])) + metadata.hash = typeutils.BytesToString(data[MARSHALED_HASH_START:MARSHALED_HASH_END]) if err := metadata.receivedTime.UnmarshalBinary(data[MARSHALED_RECEIVED_TIME_START:MARSHALED_RECEIVED_TIME_END]); err != nil { - return ErrUnmarshalFailed.Derive(err, "could not unmarshal the received time") + return fmt.Errorf("%w: could not unmarshal the received time: %s", model.ErrUnmarshalFailed, err.Error()) } booleanFlags := bitmask.BitMask(data[MARSHALED_FLAGS_START]) diff --git a/plugins/analysis/server/plugin.go b/plugins/analysis/server/plugin.go index a46f4c2fe96001b05d8ccb24d8172bd110edd566..ab1b14453cc5e4b0c5daf20a40b6c7d1f053b6f6 100644 --- a/plugins/analysis/server/plugin.go +++ b/plugins/analysis/server/plugin.go @@ -2,6 +2,7 @@ package server import ( "encoding/hex" + "errors" "math" "github.com/iotaledger/goshimmer/packages/network" @@ -17,12 +18,14 @@ import ( "github.com/iotaledger/hive.go/events" "github.com/iotaledger/hive.go/logger" "github.com/iotaledger/hive.go/node" - "github.com/pkg/errors" ) -var server *tcp.Server - -var log *logger.Logger +var ( + ErrInvalidPackageHeader = errors.New("invalid package header") + ErrExpectedInitialAddNodePackage = errors.New("expected initial add node package") + server *tcp.Server + log *logger.Logger +) func Configure(plugin *node.Plugin) { log = logger.NewLogger("Analysis-Server") @@ -136,7 +139,7 @@ func processIncomingPacket(connectionState *byte, receiveBuffer *[]byte, conn *n if firstPackage { if *connectionState != STATE_ADD_NODE { - Events.Error.Trigger(errors.New("expected initial add node package")) + Events.Error.Trigger(ErrExpectedInitialAddNodePackage) } else { *connectionState = STATE_INITIAL_ADDNODE } @@ -194,7 +197,7 @@ func parsePackageHeader(data []byte) (ConnectionState, []byte, error) { connectionState = STATE_REMOVE_NODE default: - return 0, nil, errors.New("invalid package header") + return 0, nil, ErrInvalidPackageHeader } return connectionState, receiveBuffer, nil diff --git a/plugins/analysis/types/addnode/packet.go b/plugins/analysis/types/addnode/packet.go index 79d0274db22a87a6125fb00ea009d4fbf019a916..da2ba9925b765ba15835f694d9d8c287f0c0a361 100644 --- a/plugins/analysis/types/addnode/packet.go +++ b/plugins/analysis/types/addnode/packet.go @@ -1,6 +1,10 @@ package addnode -import "github.com/pkg/errors" +import "errors" + +var ( + ErrMalformedAddNodePacket = errors.New("malformed add node packet") +) type Packet struct { NodeId []byte @@ -8,7 +12,7 @@ type Packet struct { func Unmarshal(data []byte) (*Packet, error) { if len(data) < MARSHALED_TOTAL_SIZE || data[0] != MARSHALED_PACKET_HEADER { - return nil, errors.New("malformed add node packet") + return nil, ErrMalformedAddNodePacket } unmarshaledPackage := &Packet{ diff --git a/plugins/analysis/types/connectnodes/packet.go b/plugins/analysis/types/connectnodes/packet.go index 7d9c05a8150da41bec26c53485ed6c442e6cf32b..1e672c3ad4a5714ca390f2289155b1cc39585f04 100644 --- a/plugins/analysis/types/connectnodes/packet.go +++ b/plugins/analysis/types/connectnodes/packet.go @@ -1,6 +1,10 @@ package connectnodes -import "github.com/pkg/errors" +import "errors" + +var ( + ErrMalformedConnectNodesPacket = errors.New("malformed connect nodes packet") +) type Packet struct { SourceId []byte @@ -9,7 +13,7 @@ type Packet struct { func Unmarshal(data []byte) (*Packet, error) { if len(data) < MARSHALED_TOTAL_SIZE || data[0] != MARSHALED_PACKET_HEADER { - return nil, errors.New("malformed connect nodes packet") + return nil, ErrMalformedConnectNodesPacket } unmarshaledPackage := &Packet{ diff --git a/plugins/analysis/types/disconnectnodes/packet.go b/plugins/analysis/types/disconnectnodes/packet.go index 9193312e412eff118f3b209ba912ee2f10bf2bcf..b810fa8fefa0a53d56facc09c03a3e2d48805f84 100644 --- a/plugins/analysis/types/disconnectnodes/packet.go +++ b/plugins/analysis/types/disconnectnodes/packet.go @@ -1,6 +1,10 @@ package disconnectnodes -import "github.com/pkg/errors" +import "errors" + +var ( + ErrMalformedDisconnectNodesPacket = errors.New("malformed disconnect nodes packet") +) type Packet struct { SourceId []byte @@ -9,7 +13,7 @@ type Packet struct { func Unmarshal(data []byte) (*Packet, error) { if len(data) < MARSHALED_TOTAL_SIZE || data[0] != MARSHALED_PACKET_HEADER { - return nil, errors.New("malformed disconnect nodes packet") + return nil, ErrMalformedDisconnectNodesPacket } unmarshaledPackage := &Packet{ diff --git a/plugins/analysis/types/ping/packet.go b/plugins/analysis/types/ping/packet.go index 6325771df3a49621fb44a14141b703e94d2e8ad4..68193e5153630da265a8776b527356cf4a34e1fb 100644 --- a/plugins/analysis/types/ping/packet.go +++ b/plugins/analysis/types/ping/packet.go @@ -1,12 +1,16 @@ package ping -import "github.com/pkg/errors" +import "errors" + +var ( + ErrMalformedPingPacket = errors.New("malformed ping packet") +) type Packet struct{} func Unmarshal(data []byte) (*Packet, error) { if len(data) < MARSHALED_TOTAL_SIZE || data[MARSHALED_PACKET_HEADER_START] != MARSHALED_PACKET_HEADER { - return nil, errors.New("malformed ping packet") + return nil, ErrMalformedPingPacket } unmarshaledPacket := &Packet{} diff --git a/plugins/analysis/types/removenode/packet.go b/plugins/analysis/types/removenode/packet.go index c44bf94b4bed6688f41dadcf6109384993877cc2..aeb890357109db49775d45fe0b52cfe08748e3a0 100644 --- a/plugins/analysis/types/removenode/packet.go +++ b/plugins/analysis/types/removenode/packet.go @@ -1,6 +1,10 @@ package removenode -import "github.com/pkg/errors" +import "errors" + +var ( + ErrMalformedRemovePacket = errors.New("malformed remove node packet") +) type Packet struct { NodeId []byte @@ -8,7 +12,7 @@ type Packet struct { func Unmarshal(data []byte) (*Packet, error) { if len(data) < MARSHALED_TOTAL_SIZE || data[0] != MARSHALED_PACKET_HEADER { - return nil, errors.New("malformed remove node packet") + return nil, ErrMalformedRemovePacket } unmarshaledPackage := &Packet{ diff --git a/plugins/autopeering/autopeering.go b/plugins/autopeering/autopeering.go index ff21679ca532c3925c979d5fb3814f23695575e7..f2cac97dd1aef4c7ba304f8159860e7ff4e5382f 100644 --- a/plugins/autopeering/autopeering.go +++ b/plugins/autopeering/autopeering.go @@ -2,6 +2,7 @@ package autopeering import ( "encoding/base64" + "errors" "fmt" "net" "strings" @@ -17,7 +18,6 @@ import ( "github.com/iotaledger/goshimmer/plugins/gossip" "github.com/iotaledger/hive.go/logger" "github.com/iotaledger/hive.go/node" - "github.com/pkg/errors" ) var ( @@ -26,6 +26,8 @@ var ( // Selection is the peer selection protocol. Selection *selection.Protocol + ErrParsingMasterNode = errors.New("can't parse master node") + log *logger.Logger ) @@ -111,11 +113,11 @@ func parseEntryNodes() (result []*peer.Peer, err error) { parts := strings.Split(entryNodeDefinition, "@") if len(parts) != 2 { - return nil, fmt.Errorf("parseMaster") + return nil, fmt.Errorf("%w: master node parts must be 2, is %d", ErrParsingMasterNode, len(parts)) } pubKey, err := base64.StdEncoding.DecodeString(parts[0]) if err != nil { - return nil, errors.Wrap(err, "parseMaster") + return nil, fmt.Errorf("%w: can't decode public key: %s", ErrParsingMasterNode, err) } services := service.New() diff --git a/plugins/bundleprocessor/bundleprocessor.go b/plugins/bundleprocessor/bundleprocessor.go index a09fabf2c9b5804b3e9b39ed4eabbd0895f73617..6085e2a97dfe54457ee630c7064f51a6d03c9f7f 100644 --- a/plugins/bundleprocessor/bundleprocessor.go +++ b/plugins/bundleprocessor/bundleprocessor.go @@ -4,7 +4,6 @@ import ( "fmt" "runtime" - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/bundle" "github.com/iotaledger/goshimmer/packages/model/transactionmetadata" "github.com/iotaledger/goshimmer/packages/model/value_transaction" @@ -23,12 +22,12 @@ var workerPool = workerpool.New(func(task workerpool.Task) { var WORKER_COUNT = runtime.NumCPU() -func ProcessSolidBundleHead(headTransaction *value_transaction.ValueTransaction) errors.IdentifiableError { +func ProcessSolidBundleHead(headTransaction *value_transaction.ValueTransaction) error { // only process the bundle if we didn't process it, yet - _, err := tangle.GetBundle(headTransaction.GetHash(), func(headTransactionHash trinary.Trytes) (*bundle.Bundle, errors.IdentifiableError) { + _, err := tangle.GetBundle(headTransaction.GetHash(), func(headTransactionHash trinary.Trytes) (*bundle.Bundle, error) { // abort if bundle syntax is wrong if !headTransaction.IsHead() { - return nil, ErrProcessBundleFailed.Derive(errors.New("invalid parameter"), "transaction needs to be head of bundle") + return nil, fmt.Errorf("%w: transaction needs to be the head of the bundle", ErrProcessBundleFailed) } // initialize event variables @@ -43,17 +42,16 @@ func ProcessSolidBundleHead(headTransaction *value_transaction.ValueTransaction) newBundle.SetTransactionHashes(mapTransactionsToTransactionHashes(bundleTransactions)) Events.InvalidBundle.Trigger(newBundle, bundleTransactions) - - return nil, ErrProcessBundleFailed.Derive(errors.New("invalid bundle found"), "missing bundle tail") + return nil, fmt.Errorf("%w: missing bundle tail", ErrProcessBundleFailed) } // update bundle transactions bundleTransactions = append(bundleTransactions, currentTransaction) // retrieve & update metadata - currentTransactionMetadata, dbErr := tangle.GetTransactionMetadata(currentTransaction.GetHash(), transactionmetadata.New) - if dbErr != nil { - return nil, ErrProcessBundleFailed.Derive(dbErr, "failed to retrieve transaction metadata") + currentTransactionMetadata, err := tangle.GetTransactionMetadata(currentTransaction.GetHash(), transactionmetadata.New) + if err != nil { + return nil, fmt.Errorf("%w: failed to retrieve transaction metadata: %s", ErrProcessBundleFailed, err) } currentTransactionMetadata.SetBundleHeadHash(headTransactionHash) @@ -79,10 +77,11 @@ func ProcessSolidBundleHead(headTransaction *value_transaction.ValueTransaction) // try to iterate to next turn if nextTransaction, err := tangle.GetTransaction(currentTransaction.GetTrunkTransactionHash()); err != nil { - return nil, ErrProcessBundleFailed.Derive(err, "failed to retrieve trunk while processing bundle") + return nil, fmt.Errorf("%w: failed to retrieve trunk while processing bundle: %s", ErrProcessBundleFailed, err) } else if nextTransaction == nil { - fmt.Println(ErrProcessBundleFailed.Derive(errors.New("missing transaction "+currentTransaction.GetTrunkTransactionHash()), "failed to retrieve trunk while processing bundle")) - return nil, ErrProcessBundleFailed.Derive(err, "failed to retrieve trunk while processing bundle") + err := fmt.Errorf("%w: failed to retrieve trunk while processing bundle: missing trunk transaction %s\n", ErrProcessBundleFailed, currentTransaction.GetTrunkTransactionHash()) + fmt.Println(err) + return nil, err } else { currentTransaction = nextTransaction } diff --git a/plugins/bundleprocessor/errors.go b/plugins/bundleprocessor/errors.go index 214b5859117f21079a1e1a6e7fad7437e8ca8cbd..7b488de18a26dca073df29488a5a00d0d54d9d21 100644 --- a/plugins/bundleprocessor/errors.go +++ b/plugins/bundleprocessor/errors.go @@ -1,7 +1,7 @@ package bundleprocessor -import "github.com/iotaledger/goshimmer/packages/errors" +import "errors" var ( - ErrProcessBundleFailed = errors.Wrap(errors.New("bundle processing error"), "failed to process bundle") + ErrProcessBundleFailed = errors.New("failed to process bundle") ) diff --git a/plugins/bundleprocessor/events.go b/plugins/bundleprocessor/events.go index 7fcfb2d3e742a081312bc8d6d5afd9c41d2fc4f9..46eeaa5ca6ee676b4e28b692fad037d5cdf7be9d 100644 --- a/plugins/bundleprocessor/events.go +++ b/plugins/bundleprocessor/events.go @@ -1,7 +1,6 @@ package bundleprocessor import ( - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/bundle" "github.com/iotaledger/goshimmer/packages/model/value_transaction" "github.com/iotaledger/hive.go/events" @@ -20,7 +19,7 @@ type pluginEvents struct { } func errorCaller(handler interface{}, params ...interface{}) { - handler.(func(errors.IdentifiableError))(params[0].(errors.IdentifiableError)) + handler.(func(error))(params[0].(error)) } func bundleEventCaller(handler interface{}, params ...interface{}) { diff --git a/plugins/bundleprocessor/plugin.go b/plugins/bundleprocessor/plugin.go index 822a2952df50aa39ce8c224bea3839918ec9071f..d8a6303dfe71ab83d96c0dcd6a151dfb113828ee 100644 --- a/plugins/bundleprocessor/plugin.go +++ b/plugins/bundleprocessor/plugin.go @@ -1,7 +1,6 @@ package bundleprocessor import ( - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/value_transaction" "github.com/iotaledger/goshimmer/packages/shutdown" "github.com/iotaledger/goshimmer/plugins/tangle" @@ -23,8 +22,8 @@ func configure(*node.Plugin) { } })) - Events.Error.Attach(events.NewClosure(func(err errors.IdentifiableError) { - log.Error(err.Error()) + Events.Error.Attach(events.NewClosure(func(err error) { + log.Error(err) })) } diff --git a/plugins/bundleprocessor/valuebundleprocessor.go b/plugins/bundleprocessor/valuebundleprocessor.go index 1ab5c7792817b90fb188b66e36d3489b0842f9fd..984c2b244b354abfc26562859b69d82eae5810e2 100644 --- a/plugins/bundleprocessor/valuebundleprocessor.go +++ b/plugins/bundleprocessor/valuebundleprocessor.go @@ -1,7 +1,6 @@ package bundleprocessor import ( - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/bundle" "github.com/iotaledger/goshimmer/packages/model/value_transaction" "github.com/iotaledger/hive.go/workerpool" @@ -18,7 +17,7 @@ var valueBundleProcessorWorkerPool = workerpool.New(func(task workerpool.Task) { task.Return(nil) }, workerpool.WorkerCount(WORKER_COUNT), workerpool.QueueSize(2*WORKER_COUNT)) -func ProcessSolidValueBundle(bundle *bundle.Bundle, bundleTransactions []*value_transaction.ValueTransaction) errors.IdentifiableError { +func ProcessSolidValueBundle(bundle *bundle.Bundle, bundleTransactions []*value_transaction.ValueTransaction) error { bundle.SetBundleEssenceHash(CalculateBundleHash(bundleTransactions)) Events.BundleSolid.Trigger(bundle, bundleTransactions) diff --git a/plugins/gossip/gossip.go b/plugins/gossip/gossip.go index 0c793d556890f179975df33177c82c51abbb8a57..2e53b3364dd654e0778fea70cdf42a6b1d797dee 100644 --- a/plugins/gossip/gossip.go +++ b/plugins/gossip/gossip.go @@ -6,7 +6,6 @@ import ( "strconv" "github.com/iotaledger/goshimmer/packages/autopeering/peer/service" - "github.com/iotaledger/goshimmer/packages/errors" gp "github.com/iotaledger/goshimmer/packages/gossip" "github.com/iotaledger/goshimmer/packages/gossip/server" "github.com/iotaledger/goshimmer/packages/parameter" @@ -62,7 +61,7 @@ func loadTransaction(hash []byte) ([]byte, error) { tx, err := tangle.GetTransaction(typeutils.BytesToString(hash)) if err != nil { - return nil, errors.Wrap(err, "could not get transaction") + return nil, fmt.Errorf("could not get transaction: %w", err) } if tx == nil { return nil, fmt.Errorf("transaction not found: hash=%s", hash) diff --git a/plugins/tangle/approvers.go b/plugins/tangle/approvers.go index 166b1a7ed0e8b969017c84855ce98ade6db8d419..10073c39435df28a04fefc943518312582ab5eee 100644 --- a/plugins/tangle/approvers.go +++ b/plugins/tangle/approvers.go @@ -1,8 +1,9 @@ package tangle import ( + "fmt" + "github.com/iotaledger/goshimmer/packages/database" - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/approvers" "github.com/iotaledger/hive.go/lru_cache" "github.com/iotaledger/hive.go/typeutils" @@ -12,7 +13,7 @@ import ( // region global public api //////////////////////////////////////////////////////////////////////////////////////////// // GetApprovers retrieves approvers from the database. -func GetApprovers(transactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) *approvers.Approvers) (result *approvers.Approvers, err errors.IdentifiableError) { +func GetApprovers(transactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) *approvers.Approvers) (result *approvers.Approvers, err error) { if cacheResult := approversCache.ComputeIfAbsent(transactionHash, func() interface{} { if dbApprovers, dbErr := getApproversFromDatabase(transactionHash); dbErr != nil { err = dbErr @@ -34,7 +35,7 @@ func GetApprovers(transactionHash trinary.Trytes, computeIfAbsent ...func(trinar return } -func ContainsApprovers(transactionHash trinary.Trytes) (result bool, err errors.IdentifiableError) { +func ContainsApprovers(transactionHash trinary.Trytes) (result bool, err error) { if approversCache.Contains(transactionHash) { result = true } else { @@ -88,10 +89,10 @@ func configureApproversDatabase() { } } -func storeApproversInDatabase(approvers *approvers.Approvers) errors.IdentifiableError { +func storeApproversInDatabase(approvers *approvers.Approvers) error { if approvers.GetModified() { if err := approversDatabase.Set(typeutils.StringToBytes(approvers.GetHash()), approvers.Marshal()); err != nil { - return ErrDatabaseError.Derive(err, "failed to store approvers") + return fmt.Errorf("%w: failed to store approvers: %s", ErrDatabaseError, err) } approvers.SetModified(false) @@ -100,14 +101,13 @@ func storeApproversInDatabase(approvers *approvers.Approvers) errors.Identifiabl return nil } -func getApproversFromDatabase(transactionHash trinary.Trytes) (*approvers.Approvers, errors.IdentifiableError) { +func getApproversFromDatabase(transactionHash trinary.Trytes) (*approvers.Approvers, error) { approversData, err := approversDatabase.Get(typeutils.StringToBytes(transactionHash)) if err != nil { if err == database.ErrKeyNotFound { return nil, nil } - - return nil, ErrDatabaseError.Derive(err, "failed to retrieve approvers") + return nil, fmt.Errorf("%w: failed to retrieve approvers: %s", ErrDatabaseError, err) } var result approvers.Approvers @@ -118,9 +118,9 @@ func getApproversFromDatabase(transactionHash trinary.Trytes) (*approvers.Approv return &result, nil } -func databaseContainsApprovers(transactionHash trinary.Trytes) (bool, errors.IdentifiableError) { +func databaseContainsApprovers(transactionHash trinary.Trytes) (bool, error) { if contains, err := approversDatabase.Contains(typeutils.StringToBytes(transactionHash)); err != nil { - return false, ErrDatabaseError.Derive(err, "failed to check if the approvers exists") + return false, fmt.Errorf("%w: failed to check if the approvers exist: %s", ErrDatabaseError, err) } else { return contains, nil } diff --git a/plugins/tangle/bundle.go b/plugins/tangle/bundle.go index ca7208a932492d1cbfaa43bff98c4596353d5edc..55411764a2eacc04b73122a86b119352bc0d1cbd 100644 --- a/plugins/tangle/bundle.go +++ b/plugins/tangle/bundle.go @@ -1,8 +1,9 @@ package tangle import ( + "fmt" + "github.com/iotaledger/goshimmer/packages/database" - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/bundle" "github.com/iotaledger/hive.go/lru_cache" "github.com/iotaledger/hive.go/typeutils" @@ -12,7 +13,7 @@ import ( // region global public api //////////////////////////////////////////////////////////////////////////////////////////// // GetBundle retrieves bundle from the database. -func GetBundle(headerTransactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) (*bundle.Bundle, errors.IdentifiableError)) (result *bundle.Bundle, err errors.IdentifiableError) { +func GetBundle(headerTransactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) (*bundle.Bundle, error)) (result *bundle.Bundle, err error) { if cacheResult := bundleCache.ComputeIfAbsent(headerTransactionHash, func() interface{} { if dbBundle, dbErr := getBundleFromDatabase(headerTransactionHash); dbErr != nil { err = dbErr @@ -38,7 +39,7 @@ func GetBundle(headerTransactionHash trinary.Trytes, computeIfAbsent ...func(tri return } -func ContainsBundle(headerTransactionHash trinary.Trytes) (result bool, err errors.IdentifiableError) { +func ContainsBundle(headerTransactionHash trinary.Trytes) (result bool, err error) { if bundleCache.Contains(headerTransactionHash) { result = true } else { @@ -92,10 +93,10 @@ func configureBundleDatabase() { } } -func storeBundleInDatabase(bundle *bundle.Bundle) errors.IdentifiableError { +func storeBundleInDatabase(bundle *bundle.Bundle) error { if bundle.GetModified() { if err := bundleDatabase.Set(typeutils.StringToBytes(bundle.GetHash()), bundle.Marshal()); err != nil { - return ErrDatabaseError.Derive(err, "failed to store bundle") + return fmt.Errorf("%w: failed to store bundle: %s", ErrDatabaseError, err) } bundle.SetModified(false) @@ -104,14 +105,14 @@ func storeBundleInDatabase(bundle *bundle.Bundle) errors.IdentifiableError { return nil } -func getBundleFromDatabase(transactionHash trinary.Trytes) (*bundle.Bundle, errors.IdentifiableError) { +func getBundleFromDatabase(transactionHash trinary.Trytes) (*bundle.Bundle, error) { bundleData, err := bundleDatabase.Get(typeutils.StringToBytes(transactionHash)) if err != nil { if err == database.ErrKeyNotFound { return nil, nil } - return nil, ErrDatabaseError.Derive(err, "failed to retrieve bundle") + return nil, fmt.Errorf("%w: failed to retrieve bundle: %s", ErrDatabaseError, err) } var result bundle.Bundle @@ -122,9 +123,9 @@ func getBundleFromDatabase(transactionHash trinary.Trytes) (*bundle.Bundle, erro return &result, nil } -func databaseContainsBundle(transactionHash trinary.Trytes) (bool, errors.IdentifiableError) { +func databaseContainsBundle(transactionHash trinary.Trytes) (bool, error) { if contains, err := bundleDatabase.Contains(typeutils.StringToBytes(transactionHash)); err != nil { - return false, ErrDatabaseError.Derive(err, "failed to check if the bundle exists") + return false, fmt.Errorf("%w: failed to check if the bundle exists: %s", ErrDatabaseError, err) } else { return contains, nil } diff --git a/plugins/tangle/errors.go b/plugins/tangle/errors.go index ffde1bcc9d30ac5d6e22f2d6806c17be41973af6..5ca8797f9ff4f5d0c08e7a744988108b6605b1d7 100644 --- a/plugins/tangle/errors.go +++ b/plugins/tangle/errors.go @@ -1,9 +1,7 @@ package tangle -import "github.com/iotaledger/goshimmer/packages/errors" +import "errors" var ( - ErrDatabaseError = errors.Wrap(errors.New("database error"), "failed to access the database") - ErrUnmarshalFailed = errors.Wrap(errors.New("unmarshall failed"), "input data is corrupted") - ErrMarshallFailed = errors.Wrap(errors.New("marshal failed"), "the source object contains invalid values") + ErrDatabaseError = errors.New("database error") ) diff --git a/plugins/tangle/solidifier.go b/plugins/tangle/solidifier.go index 014a20db15068ca68be1c582d21cbf6642962c60..cfcb3da5f649a72afe0d2b49def62e342f8a9a94 100644 --- a/plugins/tangle/solidifier.go +++ b/plugins/tangle/solidifier.go @@ -4,7 +4,6 @@ import ( "runtime" "time" - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/gossip" "github.com/iotaledger/goshimmer/packages/model/approvers" "github.com/iotaledger/goshimmer/packages/model/meta_transaction" @@ -69,7 +68,7 @@ func runSolidifier() { // endregion /////////////////////////////////////////////////////////////////////////////////////////////////////////// // Checks and updates the solid flag of a single transaction. -func checkSolidity(transaction *value_transaction.ValueTransaction) (result bool, err errors.IdentifiableError) { +func checkSolidity(transaction *value_transaction.ValueTransaction) (result bool, err error) { // abort if transaction is solid already txMetadata, metaDataErr := GetTransactionMetadata(transaction.GetHash(), transactionmetadata.New) if metaDataErr != nil { @@ -140,7 +139,7 @@ func checkSolidity(transaction *value_transaction.ValueTransaction) (result bool } // Checks and updates the solid flag of a transaction and its approvers (future cone). -func IsSolid(transaction *value_transaction.ValueTransaction) (bool, errors.IdentifiableError) { +func IsSolid(transaction *value_transaction.ValueTransaction) (bool, error) { if isSolid, err := checkSolidity(transaction); err != nil { return false, err } else if isSolid { @@ -154,7 +153,7 @@ func IsSolid(transaction *value_transaction.ValueTransaction) (bool, errors.Iden return false, nil } -func propagateSolidity(transactionHash trinary.Trytes) errors.IdentifiableError { +func propagateSolidity(transactionHash trinary.Trytes) error { if transactionApprovers, err := GetApprovers(transactionHash, approvers.New); err != nil { return err } else { diff --git a/plugins/tangle/transaction.go b/plugins/tangle/transaction.go index 0de47154fd96b64915ef689e14e23e660b9a0fbe..fc2e2f02dd7cd3b18739eeb232f6b27b4bd791ae 100644 --- a/plugins/tangle/transaction.go +++ b/plugins/tangle/transaction.go @@ -1,8 +1,9 @@ package tangle import ( + "fmt" + "github.com/iotaledger/goshimmer/packages/database" - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/value_transaction" "github.com/iotaledger/hive.go/lru_cache" "github.com/iotaledger/hive.go/typeutils" @@ -11,7 +12,7 @@ import ( // region public api /////////////////////////////////////////////////////////////////////////////////////////////////// -func GetTransaction(transactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) *value_transaction.ValueTransaction) (result *value_transaction.ValueTransaction, err errors.IdentifiableError) { +func GetTransaction(transactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) *value_transaction.ValueTransaction) (result *value_transaction.ValueTransaction, err error) { if cacheResult := transactionCache.ComputeIfAbsent(transactionHash, func() interface{} { if transaction, dbErr := getTransactionFromDatabase(transactionHash); dbErr != nil { err = dbErr @@ -33,7 +34,7 @@ func GetTransaction(transactionHash trinary.Trytes, computeIfAbsent ...func(trin return } -func ContainsTransaction(transactionHash trinary.Trytes) (result bool, err errors.IdentifiableError) { +func ContainsTransaction(transactionHash trinary.Trytes) (result bool, err error) { if transactionCache.Contains(transactionHash) { result = true } else { @@ -89,10 +90,10 @@ func configureTransactionDatabase() { } } -func storeTransactionInDatabase(transaction *value_transaction.ValueTransaction) errors.IdentifiableError { +func storeTransactionInDatabase(transaction *value_transaction.ValueTransaction) error { if transaction.GetModified() { if err := transactionDatabase.Set(typeutils.StringToBytes(transaction.GetHash()), transaction.MetaTransaction.GetBytes()); err != nil { - return ErrDatabaseError.Derive(err, "failed to store transaction") + return fmt.Errorf("%w: failed to store transaction: %s", ErrDatabaseError, err.Error()) } transaction.SetModified(false) @@ -101,22 +102,21 @@ func storeTransactionInDatabase(transaction *value_transaction.ValueTransaction) return nil } -func getTransactionFromDatabase(transactionHash trinary.Trytes) (*value_transaction.ValueTransaction, errors.IdentifiableError) { +func getTransactionFromDatabase(transactionHash trinary.Trytes) (*value_transaction.ValueTransaction, error) { txData, err := transactionDatabase.Get(typeutils.StringToBytes(transactionHash)) if err != nil { if err == database.ErrKeyNotFound { return nil, nil - } else { - return nil, ErrDatabaseError.Derive(err, "failed to retrieve transaction") } + return nil, fmt.Errorf("%w: failed to retrieve transaction: %s", ErrDatabaseError, err) } return value_transaction.FromBytes(txData), nil } -func databaseContainsTransaction(transactionHash trinary.Trytes) (bool, errors.IdentifiableError) { +func databaseContainsTransaction(transactionHash trinary.Trytes) (bool, error) { if contains, err := transactionDatabase.Contains(typeutils.StringToBytes(transactionHash)); err != nil { - return contains, ErrDatabaseError.Derive(err, "failed to check if the transaction exists") + return contains, fmt.Errorf("%w: failed to check if the transaction exists: %s", ErrDatabaseError, err) } else { return contains, nil } diff --git a/plugins/tangle/transaction_metadata.go b/plugins/tangle/transaction_metadata.go index 0ea3c9828c7dda77375dcc319a4fc317fc571030..94d6177af989c666a75d2b1c1e75bd1c252166bc 100644 --- a/plugins/tangle/transaction_metadata.go +++ b/plugins/tangle/transaction_metadata.go @@ -1,8 +1,9 @@ package tangle import ( + "fmt" + "github.com/iotaledger/goshimmer/packages/database" - "github.com/iotaledger/goshimmer/packages/errors" "github.com/iotaledger/goshimmer/packages/model/transactionmetadata" "github.com/iotaledger/hive.go/lru_cache" "github.com/iotaledger/hive.go/typeutils" @@ -11,7 +12,7 @@ import ( // region public api /////////////////////////////////////////////////////////////////////////////////////////////////// -func GetTransactionMetadata(transactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) *transactionmetadata.TransactionMetadata) (result *transactionmetadata.TransactionMetadata, err errors.IdentifiableError) { +func GetTransactionMetadata(transactionHash trinary.Trytes, computeIfAbsent ...func(trinary.Trytes) *transactionmetadata.TransactionMetadata) (result *transactionmetadata.TransactionMetadata, err error) { if cacheResult := transactionMetadataCache.ComputeIfAbsent(transactionHash, func() interface{} { if transactionMetadata, dbErr := getTransactionMetadataFromDatabase(transactionHash); dbErr != nil { err = dbErr @@ -33,7 +34,7 @@ func GetTransactionMetadata(transactionHash trinary.Trytes, computeIfAbsent ...f return } -func ContainsTransactionMetadata(transactionHash trinary.Trytes) (result bool, err errors.IdentifiableError) { +func ContainsTransactionMetadata(transactionHash trinary.Trytes) (result bool, err error) { if transactionMetadataCache.Contains(transactionHash) { result = true } else { @@ -89,13 +90,13 @@ func configureTransactionMetaDataDatabase() { } } -func storeTransactionMetadataInDatabase(metadata *transactionmetadata.TransactionMetadata) errors.IdentifiableError { +func storeTransactionMetadataInDatabase(metadata *transactionmetadata.TransactionMetadata) error { if metadata.GetModified() { if marshaledMetadata, err := metadata.Marshal(); err != nil { return err } else { if err := transactionMetadataDatabase.Set(typeutils.StringToBytes(metadata.GetHash()), marshaledMetadata); err != nil { - return ErrDatabaseError.Derive(err, "failed to store transaction metadata") + return fmt.Errorf("%w: failed to store transaction metadata: %s", ErrDatabaseError, err) } metadata.SetModified(false) @@ -105,14 +106,13 @@ func storeTransactionMetadataInDatabase(metadata *transactionmetadata.Transactio return nil } -func getTransactionMetadataFromDatabase(transactionHash trinary.Trytes) (*transactionmetadata.TransactionMetadata, errors.IdentifiableError) { +func getTransactionMetadataFromDatabase(transactionHash trinary.Trytes) (*transactionmetadata.TransactionMetadata, error) { txMetadata, err := transactionMetadataDatabase.Get(typeutils.StringToBytes(transactionHash)) if err != nil { if err == database.ErrKeyNotFound { return nil, nil - } else { - return nil, ErrDatabaseError.Derive(err, "failed to retrieve transaction") } + return nil, fmt.Errorf("%w: failed to retrieve transaction: %s", ErrDatabaseError, err) } var result transactionmetadata.TransactionMetadata @@ -123,9 +123,9 @@ func getTransactionMetadataFromDatabase(transactionHash trinary.Trytes) (*transa return &result, nil } -func databaseContainsTransactionMetadata(transactionHash trinary.Trytes) (bool, errors.IdentifiableError) { +func databaseContainsTransactionMetadata(transactionHash trinary.Trytes) (bool, error) { if contains, err := transactionMetadataDatabase.Contains(typeutils.StringToBytes(transactionHash)); err != nil { - return contains, ErrDatabaseError.Derive(err, "failed to check if the transaction metadata exists") + return contains, fmt.Errorf("%w: failed to check if the transaction metadata exists: %s", ErrDatabaseError, err) } else { return contains, nil } diff --git a/plugins/tangle/tx_per_address.go b/plugins/tangle/tx_per_address.go index c6bb03cdce9c63b63a0d388483b8dd2430b85b48..1ab4950e6c79405e99e4acf3242f4ebc6591eb94 100644 --- a/plugins/tangle/tx_per_address.go +++ b/plugins/tangle/tx_per_address.go @@ -1,6 +1,8 @@ package tangle import ( + "fmt" + "github.com/iotaledger/goshimmer/packages/database" "github.com/iotaledger/hive.go/typeutils" "github.com/iotaledger/iota.go/trinary" @@ -28,7 +30,7 @@ func StoreTransactionHashForAddressInDatabase(address *TxHashForAddress) error { databaseKeyForHashPrefixedHash(address.Address, address.TxHash), []byte{}, ); err != nil { - return ErrDatabaseError.Derive(err, "failed to store tx for address in database") + return fmt.Errorf("%w: failed to store tx for address in database: %s", ErrDatabaseError, err) } return nil } @@ -37,7 +39,7 @@ func DeleteTransactionHashForAddressInDatabase(address *TxHashForAddress) error if err := transactionsHashesForAddressDatabase.Delete( databaseKeyForHashPrefixedHash(address.Address, address.TxHash), ); err != nil { - return ErrDatabaseError.Derive(err, "failed to delete tx for address") + return fmt.Errorf("%w: failed to delete tx for address: %s", ErrDatabaseError, err) } return nil @@ -53,8 +55,7 @@ func ReadTransactionHashesForAddressFromDatabase(address trinary.Hash) ([]trinar }) if err != nil { - return nil, ErrDatabaseError.Derive(err, "failed to read tx per address from database") - } else { - return transactionHashes, nil + return nil, fmt.Errorf("%w: failed to read tx per address from database: %s", ErrDatabaseError, err) } + return transactionHashes, nil }