From c4fd64c1123e42238e4990f5225cb2c564e9ede1 Mon Sep 17 00:00:00 2001 From: Fedor Partanskiy Date: Tue, 21 May 2024 20:54:01 +0300 Subject: [PATCH] refactoring for delete archived package github.com/pkg/errors Signed-off-by: Fedor Partanskiy --- go.mod | 1 - go.sum | 2 - internal/bft/controller_test.go | 2 +- internal/bft/requestpool.go | 18 +- internal/bft/requestpool_test.go | 2 +- internal/bft/state.go | 14 +- internal/bft/statecollector.go | 3 +- internal/bft/util.go | 4 +- internal/bft/view.go | 18 +- internal/bft/viewchanger.go | 29 ++- internal/bft/viewchanger_test.go | 2 +- pkg/consensus/consensus.go | 15 +- pkg/types/config.go | 49 ++-- pkg/wal/util.go | 2 +- pkg/wal/writeaheadlog.go | 22 +- vendor/github.com/pkg/errors/.gitignore | 24 -- vendor/github.com/pkg/errors/.travis.yml | 10 - vendor/github.com/pkg/errors/LICENSE | 23 -- vendor/github.com/pkg/errors/Makefile | 44 ---- vendor/github.com/pkg/errors/README.md | 59 ----- vendor/github.com/pkg/errors/appveyor.yml | 32 --- vendor/github.com/pkg/errors/errors.go | 288 ---------------------- vendor/github.com/pkg/errors/go113.go | 38 --- vendor/github.com/pkg/errors/stack.go | 177 ------------- vendor/modules.txt | 3 - 25 files changed, 84 insertions(+), 797 deletions(-) delete mode 100644 vendor/github.com/pkg/errors/.gitignore delete mode 100644 vendor/github.com/pkg/errors/.travis.yml delete mode 100644 vendor/github.com/pkg/errors/LICENSE delete mode 100644 vendor/github.com/pkg/errors/Makefile delete mode 100644 vendor/github.com/pkg/errors/README.md delete mode 100644 vendor/github.com/pkg/errors/appveyor.yml delete mode 100644 vendor/github.com/pkg/errors/errors.go delete mode 100644 vendor/github.com/pkg/errors/go113.go delete mode 100644 vendor/github.com/pkg/errors/stack.go diff --git a/go.mod b/go.mod index 4671c199..88f8a7a6 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,6 @@ go 1.22.3 require ( github.com/golang/protobuf v1.5.4 - github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.9.0 go.uber.org/zap v1.27.0 golang.org/x/sync v0.7.0 diff --git a/go.sum b/go.sum index 6ccccf0c..59d9f6d8 100644 --- a/go.sum +++ b/go.sum @@ -4,8 +4,6 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= diff --git a/internal/bft/controller_test.go b/internal/bft/controller_test.go index 85f2f816..fad05e1c 100644 --- a/internal/bft/controller_test.go +++ b/internal/bft/controller_test.go @@ -6,6 +6,7 @@ package bft_test import ( + "errors" "os" "sync" "sync/atomic" @@ -20,7 +21,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/pkg/types" "github.com/hyperledger-labs/SmartBFT/pkg/wal" protos "github.com/hyperledger-labs/SmartBFT/smartbftprotos" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "go.uber.org/zap" diff --git a/internal/bft/requestpool.go b/internal/bft/requestpool.go index 477efa6c..5b4242cc 100644 --- a/internal/bft/requestpool.go +++ b/internal/bft/requestpool.go @@ -8,6 +8,7 @@ package bft import ( "container/list" "context" + "errors" "fmt" "sync" "time" @@ -15,7 +16,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/pkg/api" "github.com/hyperledger-labs/SmartBFT/pkg/metrics/disabled" "github.com/hyperledger-labs/SmartBFT/pkg/types" - "github.com/pkg/errors" "golang.org/x/sync/semaphore" ) @@ -27,10 +27,10 @@ const ( ) var ( - ErrReqAlreadyExists = fmt.Errorf("request already exists") - ErrReqAlreadyProcessed = fmt.Errorf("request already processed") - ErrRequestTooBig = fmt.Errorf("submitted request is too big") - ErrSubmitTimeout = fmt.Errorf("timeout submitting to request pool") + ErrReqAlreadyExists = errors.New("request already exists") + ErrReqAlreadyProcessed = errors.New("request already processed") + ErrRequestTooBig = errors.New("submitted request is too big") + ErrSubmitTimeout = errors.New("timeout submitting to request pool") ) //go:generate mockery -dir . -name RequestTimeoutHandler -case underscore -output ./mocks/ @@ -191,7 +191,7 @@ func (rp *Pool) isClosed() bool { func (rp *Pool) Submit(request []byte) error { reqInfo := rp.inspector.RequestID(request) if rp.isClosed() { - return errors.Errorf("pool closed, request rejected: %s", reqInfo) + return fmt.Errorf("pool closed, request rejected: %s", reqInfo) } if uint64(len(request)) > rp.options.RequestMaxBytes { @@ -227,7 +227,7 @@ func (rp *Pool) Submit(request []byte) error { rp.metrics.CountOfFailAddRequestToPool.With( rp.metrics.LabelsForWith("reason", api.ReasonSemaphoreAcquireFail)..., ).Add(1) - return errors.Wrapf(err, "acquiring semaphore for request: %s", reqInfo) + return fmt.Errorf("acquiring semaphore for request: %s: %w", reqInfo, err) } reqCopy := append(make([]byte, 0), request...) @@ -308,7 +308,7 @@ func (rp *Pool) NextRequests(maxCount int, maxSizeBytes uint64, check bool) (bat var totalSize uint64 batch = make([][]byte, 0, count) element := rp.fifo.Front() - for i := 0; i < count; i++ { + for range count { req := element.Value.(*requestItem).request reqLen := uint64(len(req)) if totalSize+reqLen > maxSizeBytes { @@ -380,7 +380,7 @@ func (rp *Pool) RemoveRequest(requestInfo types.RequestInfo) error { rp.moveToDelSlice(requestInfo) errStr := fmt.Sprintf("request %s is not in the pool at remove time", requestInfo) rp.logger.Debugf(errStr) - return fmt.Errorf(errStr) + return errors.New(errStr) } rp.deleteRequest(element, requestInfo) diff --git a/internal/bft/requestpool_test.go b/internal/bft/requestpool_test.go index cf54fd10..6d125ecb 100644 --- a/internal/bft/requestpool_test.go +++ b/internal/bft/requestpool_test.go @@ -9,6 +9,7 @@ import ( "bytes" "crypto/rand" "encoding/binary" + "errors" "fmt" "sync" "testing" @@ -17,7 +18,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/internal/bft" "github.com/hyperledger-labs/SmartBFT/internal/bft/mocks" "github.com/hyperledger-labs/SmartBFT/pkg/types" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "go.uber.org/zap" diff --git a/internal/bft/state.go b/internal/bft/state.go index e0dba836..b45d9347 100644 --- a/internal/bft/state.go +++ b/internal/bft/state.go @@ -6,13 +6,13 @@ package bft import ( + "errors" "fmt" "github.com/golang/protobuf/proto" "github.com/hyperledger-labs/SmartBFT/pkg/api" "github.com/hyperledger-labs/SmartBFT/pkg/types" protos "github.com/hyperledger-labs/SmartBFT/smartbftprotos" - "github.com/pkg/errors" ) type StateRecorder struct { @@ -84,7 +84,7 @@ func (ps *PersistedState) LoadNewViewIfApplicable() (*types.ViewAndSeq, error) { lastPersistedMessage := &protos.SavedMessage{} if err := proto.Unmarshal(lastEntry, lastPersistedMessage); err != nil { ps.Logger.Errorf("Failed unmarshaling last entry from WAL: %v", err) - return nil, errors.Wrap(err, "failed unmarshaling last entry from WAL") + return nil, fmt.Errorf("failed unmarshaling last entry from WAL: %w", err) } if newViewMsg := lastPersistedMessage.GetNewView(); newViewMsg != nil { ps.Logger.Infof("last entry in WAL is a newView record") @@ -103,7 +103,7 @@ func (ps *PersistedState) LoadViewChangeIfApplicable() (*protos.ViewChange, erro lastPersistedMessage := &protos.SavedMessage{} if err := proto.Unmarshal(lastEntry, lastPersistedMessage); err != nil { ps.Logger.Errorf("Failed unmarshaling last entry from WAL: %v", err) - return nil, errors.Wrap(err, "failed unmarshaling last entry from WAL") + return nil, fmt.Errorf("failed unmarshaling last entry from WAL: %w", err) } if viewChangeMsg := lastPersistedMessage.GetViewChange(); viewChangeMsg != nil { ps.Logger.Infof("last entry in WAL is a viewChange message") @@ -128,7 +128,7 @@ func (ps *PersistedState) Restore(v *View) error { lastPersistedMessage := &protos.SavedMessage{} if err := proto.Unmarshal(lastEntry, lastPersistedMessage); err != nil { ps.Logger.Errorf("Failed unmarshaling last entry from WAL: %v", err) - return errors.Wrap(err, "failed unmarshaling last entry from WAL") + return fmt.Errorf("failed unmarshaling last entry from WAL: %w", err) } if proposed := lastPersistedMessage.GetProposedRecord(); proposed != nil { @@ -149,7 +149,7 @@ func (ps *PersistedState) Restore(v *View) error { return nil } - return errors.Errorf("unrecognized record: %v", lastPersistedMessage) + return fmt.Errorf("unrecognized record: %v", lastPersistedMessage) } func (ps *PersistedState) recoverProposed(lastPersistedMessage *protos.ProposedRecord, v *View) error { @@ -184,12 +184,12 @@ func (ps *PersistedState) recoverProposed(lastPersistedMessage *protos.ProposedR func (ps *PersistedState) recoverPrepared(lastPersistedMessage *protos.Message, v *View, entries [][]byte) error { // Last entry is a commit, so we should have not pruned the previous pre-prepare if len(entries) < 2 { - return fmt.Errorf("last message is a commit, but expected to also have a matching pre-prepare") + return errors.New("last message is a commit, but expected to also have a matching pre-prepare") } prePrepareMsg := &protos.SavedMessage{} if err := proto.Unmarshal(entries[len(entries)-2], prePrepareMsg); err != nil { ps.Logger.Errorf("Failed unmarshaling second last entry from WAL: %v", err) - return errors.Wrap(err, "failed unmarshaling last entry from WAL") + return fmt.Errorf("failed unmarshaling last entry from WAL: %w", err) } prePrepareFromWAL := prePrepareMsg.GetProposedRecord().GetPrePrepare() diff --git a/internal/bft/statecollector.go b/internal/bft/statecollector.go index 065c044e..649a6581 100644 --- a/internal/bft/statecollector.go +++ b/internal/bft/statecollector.go @@ -105,8 +105,7 @@ func (s *StateCollector) collectedEnoughEqualVotes() *types.ViewAndSeq { return nil } votesMap := make(map[types.ViewAndSeq]uint64) - num := len(s.responses.votes) - for i := 0; i < num; i++ { + for range len(s.responses.votes) { vote := <-s.responses.votes response := vote.GetStateTransferResponse() if response == nil { diff --git a/internal/bft/util.go b/internal/bft/util.go index 584813cb..e1b7b027 100644 --- a/internal/bft/util.go +++ b/internal/bft/util.go @@ -94,7 +94,7 @@ func getLeaderID( return nodes[view%n] } - for i := 0; i < len(nodes); i++ { + for i := range len(nodes) { index := (view + (decisionsInView / decisionsPerLeader)) + uint64(i) node := nodes[index%n] _, exists := blackListed[node] @@ -552,7 +552,7 @@ func equalIntLists(a, b []uint64) bool { return false } - for i := 0; i < len(a); i++ { + for i := range len(a) { if a[i] != b[i] { return false } diff --git a/internal/bft/view.go b/internal/bft/view.go index 8fb5cf68..234cbcdd 100644 --- a/internal/bft/view.go +++ b/internal/bft/view.go @@ -7,6 +7,7 @@ package bft import ( "bytes" + "errors" "fmt" "sync" "sync/atomic" @@ -16,7 +17,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/pkg/api" "github.com/hyperledger-labs/SmartBFT/pkg/types" protos "github.com/hyperledger-labs/SmartBFT/smartbftprotos" - "github.com/pkg/errors" ) // Phase indicates the status of the view @@ -597,7 +597,7 @@ func (v *View) verifyProposal(proposal types.Proposal, prevCommits []*protos.Sig // Check that the metadata contains a digest of the previous commit signatures prevCommitDigest := CommitSignaturesDigest(prevCommits) if !bytes.Equal(prevCommitDigest, md.PrevCommitSignatureDigest) && v.DecisionsPerLeader > 0 { - return nil, errors.Errorf("prev commit signatures received from leader mismatches the metadata digest") + return nil, errors.New("prev commit signatures received from leader mismatches the metadata digest") } return requests, nil @@ -634,11 +634,11 @@ func (v *View) verifyPrevCommitSignatures(prevCommitSignatures []*protos.Signatu Value: sig.Value, }, prevProp) if err != nil { - return nil, errors.Errorf("failed verifying consenter signature of %d: %v", sig.Signer, err) + return nil, fmt.Errorf("failed verifying consenter signature of %d: %w", sig.Signer, err) } prpf := &protos.PreparesFrom{} if err = proto.Unmarshal(aux, prpf); err != nil { - return nil, errors.Errorf("failed unmarshaling auxiliary input from %d: %v", sig.Signer, err) + return nil, fmt.Errorf("failed unmarshaling auxiliary input from %d: %w", sig.Signer, err) } prepareAcknowledgements[sig.Signer] = prpf } @@ -651,7 +651,7 @@ func (v *View) verifyBlacklist(prevCommitSignatures []*protos.Signature, currVer v.Logger.Debugf("DecisionsPerLeader is 0, hence leader rotation is inactive") if len(pendingBlacklist) > 0 { v.Logger.Warnf("Blacklist cannot be non-empty (%v) if rotation is inactive", pendingBlacklist) - return errors.Errorf("rotation is inactive but blacklist is not empty: %v", pendingBlacklist) + return fmt.Errorf("rotation is inactive but blacklist is not empty: %v", pendingBlacklist) } return nil } @@ -666,7 +666,7 @@ func (v *View) verifyBlacklist(prevCommitSignatures []*protos.Signature, currVer if prevPropRaw.VerificationSequence != currVerificationSeq { // If there has been a reconfiguration, black list should remain the same if !equalIntLists(prevProposalMetadata.BlackList, pendingBlacklist) { - return errors.Errorf("blacklist changed (%v --> %v) during reconfiguration", prevProposalMetadata.BlackList, pendingBlacklist) + return fmt.Errorf("blacklist changed (%v --> %v) during reconfiguration", prevProposalMetadata.BlackList, pendingBlacklist) } v.Logger.Infof("Skipping verifying prev commits due to verification sequence advancing from %d to %d", prevPropRaw.VerificationSequence, currVerificationSeq) @@ -676,7 +676,7 @@ func (v *View) verifyBlacklist(prevCommitSignatures []*protos.Signature, currVer if v.MembershipNotifier != nil && v.MembershipNotifier.MembershipChange() { // If there has been a membership change, black list should remain the same if !equalIntLists(prevProposalMetadata.BlackList, pendingBlacklist) { - return errors.Errorf("blacklist changed (%v --> %v) during membership change", prevProposalMetadata.BlackList, pendingBlacklist) + return fmt.Errorf("blacklist changed (%v --> %v) during membership change", prevProposalMetadata.BlackList, pendingBlacklist) } v.Logger.Infof("Skipping verifying prev commits due to membership change") return nil @@ -685,7 +685,7 @@ func (v *View) verifyBlacklist(prevCommitSignatures []*protos.Signature, currVer _, f := computeQuorum(v.N) if v.blacklistingSupported(f, myLastCommitSignatures) && len(prevCommitSignatures) < len(myLastCommitSignatures) { - return errors.Errorf("only %d out of %d required previous commits is included in pre-prepare", + return fmt.Errorf("only %d out of %d required previous commits is included in pre-prepare", len(prevCommitSignatures), len(myLastCommitSignatures)) } @@ -709,7 +709,7 @@ func (v *View) verifyBlacklist(prevCommitSignatures []*protos.Signature, currVer expectedBlacklist := blacklist.computeUpdate() if !equalIntLists(pendingBlacklist, expectedBlacklist) { - return errors.Errorf("proposed blacklist %v differs from expected %v blacklist", pendingBlacklist, expectedBlacklist) + return fmt.Errorf("proposed blacklist %v differs from expected %v blacklist", pendingBlacklist, expectedBlacklist) } return nil diff --git a/internal/bft/viewchanger.go b/internal/bft/viewchanger.go index b1a49226..ca9ca33d 100644 --- a/internal/bft/viewchanger.go +++ b/internal/bft/viewchanger.go @@ -6,6 +6,7 @@ package bft import ( + "errors" "fmt" "sync" "sync/atomic" @@ -16,7 +17,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/pkg/metrics/disabled" "github.com/hyperledger-labs/SmartBFT/pkg/types" protos "github.com/hyperledger-labs/SmartBFT/smartbftprotos" - "github.com/pkg/errors" ) // ViewController controls the view @@ -680,7 +680,7 @@ func (v *ViewChanger) extractCurrentSequence() (uint64, *protos.Proposal) { // ValidateLastDecision validates the given decision, and returns its sequence when valid func ValidateLastDecision(vd *protos.ViewData, quorum int, n uint64, verifier api.Verifier) (lastSequence uint64, err error) { if vd.LastDecision == nil { - return 0, errors.Errorf("the last decision is not set") + return 0, errors.New("the last decision is not set") } if vd.LastDecision.Metadata == nil { // This is a genesis proposal, there are no signatures to validate, so we return at this point @@ -688,14 +688,14 @@ func ValidateLastDecision(vd *protos.ViewData, quorum int, n uint64, verifier ap } md := &protos.ViewMetadata{} if err = proto.Unmarshal(vd.LastDecision.Metadata, md); err != nil { - return 0, errors.Errorf("unable to unmarshal last decision metadata, err: %v", err) + return 0, fmt.Errorf("unable to unmarshal last decision metadata, err: %w", err) } if md.ViewId >= vd.NextView { - return 0, errors.Errorf("last decision view %d is greater or equal to requested next view %d", md.ViewId, vd.NextView) + return 0, fmt.Errorf("last decision view %d is greater or equal to requested next view %d", md.ViewId, vd.NextView) } numSigs := len(vd.LastDecisionSignatures) if numSigs < quorum { - return 0, errors.Errorf("there are only %d last decision signatures", numSigs) + return 0, fmt.Errorf("there are only %d last decision signatures", numSigs) } nodesMap := make(map[uint64]struct{}, n) validSig := 0 @@ -716,12 +716,12 @@ func ValidateLastDecision(vd *protos.ViewData, quorum int, n uint64, verifier ap VerificationSequence: int64(vd.LastDecision.VerificationSequence), } if _, err = verifier.VerifyConsenterSig(signature, proposal); err != nil { - return 0, errors.Errorf("last decision signature is invalid, error: %v", err) + return 0, fmt.Errorf("last decision signature is invalid, error: %w", err) } validSig++ } if validSig < quorum { - return 0, errors.Errorf("there are only %d valid last decision signatures", validSig) + return 0, fmt.Errorf("there are only %d valid last decision signatures", validSig) } return md.LatestSequence, nil } @@ -732,14 +732,14 @@ func ValidateInFlight(inFlightProposal *protos.Proposal, lastSequence uint64) er return nil } if inFlightProposal.Metadata == nil { - return errors.Errorf("in flight proposal metadata is nil") + return errors.New("in flight proposal metadata is nil") } inFlightMetadata := &protos.ViewMetadata{} if err := proto.Unmarshal(inFlightProposal.Metadata, inFlightMetadata); err != nil { - return errors.Errorf("unable to unmarshal the in flight proposal metadata, err: %v", err) + return fmt.Errorf("unable to unmarshal the in flight proposal metadata, err: %w", err) } if inFlightMetadata.LatestSequence != lastSequence+1 { - return errors.Errorf("the in flight proposal sequence is %d while the last decision sequence is %d", inFlightMetadata.LatestSequence, lastSequence) + return fmt.Errorf("the in flight proposal sequence is %d while the last decision sequence is %d", inFlightMetadata.LatestSequence, lastSequence) } return nil } @@ -786,9 +786,8 @@ func (v *ViewChanger) processViewDataMsg() { // returns view data messages included in votes func (v *ViewChanger) getViewDataMessages() []*protos.ViewData { - num := len(v.viewDataMsgs.votes) var messages []*protos.ViewData - for i := 0; i < num; i++ { + for range len(v.viewDataMsgs.votes) { vt := <-v.viewDataMsgs.votes vd := &protos.ViewData{} if err := proto.Unmarshal(vt.GetViewData().RawViewData, vd); err != nil { @@ -812,7 +811,7 @@ type proposalAndMetadata struct { } // CheckInFlight checks if there is an in-flight proposal that needs to be decided on (because a node might decided on it already) -func CheckInFlight(messages []*protos.ViewData, f int, quorum int, N uint64, verifier api.Verifier) (ok, noInFlight bool, inFlightProposal *protos.Proposal, err error) { +func CheckInFlight(messages []*protos.ViewData, f int, quorum int, n uint64, verifier api.Verifier) (ok, noInFlight bool, inFlightProposal *protos.Proposal, err error) { expectedSequence := maxLastDecisionSequence(messages) + 1 possibleProposals := make([]*possibleProposal, 0) proposalsAndMetadata := make([]*proposalAndMetadata, 0) @@ -825,12 +824,12 @@ func CheckInFlight(messages []*protos.ViewData, f int, quorum int, N uint64, ver } if vd.InFlightProposal.Metadata == nil { // should have been validated earlier - return false, false, nil, errors.Errorf("Node has a view data message where the in flight proposal metadata is nil") + return false, false, nil, errors.New("Node has a view data message where the in flight proposal metadata is nil") } inFlightMetadata := &protos.ViewMetadata{} if err = proto.Unmarshal(vd.InFlightProposal.Metadata, inFlightMetadata); err != nil { // should have been validated earlier - return false, false, nil, errors.Errorf("Node was unable to unmarshal the in flight proposal metadata, error: %v", err) + return false, false, nil, fmt.Errorf("Node was unable to unmarshal the in flight proposal metadata, error: %w", err) } proposalsAndMetadata = append(proposalsAndMetadata, &proposalAndMetadata{vd.InFlightProposal, inFlightMetadata}) diff --git a/internal/bft/viewchanger_test.go b/internal/bft/viewchanger_test.go index 2a252f47..01e10e4b 100644 --- a/internal/bft/viewchanger_test.go +++ b/internal/bft/viewchanger_test.go @@ -6,6 +6,7 @@ package bft_test import ( + "errors" "strings" "sync" "sync/atomic" @@ -19,7 +20,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/pkg/metrics/disabled" "github.com/hyperledger-labs/SmartBFT/pkg/types" protos "github.com/hyperledger-labs/SmartBFT/smartbftprotos" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "go.uber.org/zap" diff --git a/pkg/consensus/consensus.go b/pkg/consensus/consensus.go index 46c8ddec..20e77e77 100644 --- a/pkg/consensus/consensus.go +++ b/pkg/consensus/consensus.go @@ -6,6 +6,8 @@ package consensus import ( + "errors" + "fmt" "sort" "strings" "sync" @@ -18,7 +20,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/pkg/metrics/disabled" "github.com/hyperledger-labs/SmartBFT/pkg/types" protos "github.com/hyperledger-labs/SmartBFT/smartbftprotos" - "github.com/pkg/errors" ) // Consensus submits requests to be total ordered, @@ -106,7 +107,7 @@ func (c *Consensus) GetLeaderID() uint64 { func (c *Consensus) Start() error { if err := c.ValidateConfiguration(c.Comm.Nodes()); err != nil { - return errors.Wrapf(err, "configuration is invalid") + return fmt.Errorf("configuration is invalid: %w", err) } if c.Metrics == nil { @@ -309,7 +310,7 @@ func (c *Consensus) SubmitRequest(req []byte) error { c.consensusLock.RLock() defer c.consensusLock.RUnlock() if c.GetLeaderID() == 0 { - return errors.Errorf("no leader") + return errors.New("no leader") } c.Logger.Debugf("Submit Request: %s", c.RequestInspector.RequestID(req)) return c.controller.SubmitRequest(req) @@ -340,23 +341,23 @@ func (c *Consensus) proposalMaker() *algorithm.ProposalMaker { func (c *Consensus) ValidateConfiguration(nodes []uint64) error { if err := c.Config.Validate(); err != nil { - return errors.Wrap(err, "bad configuration") + return fmt.Errorf("bad configuration: %w", err) } nodeSet := make(map[uint64]bool) for _, val := range nodes { if val == 0 { - return errors.Errorf("nodes contains node id 0 which is not permitted, nodes: %v", nodes) + return fmt.Errorf("nodes contains node id 0 which is not permitted, nodes: %v", nodes) } nodeSet[val] = true } if !nodeSet[c.Config.SelfID] { - return errors.Errorf("nodes does not contain the SelfID: %d, nodes: %v", c.Config.SelfID, nodes) + return fmt.Errorf("nodes does not contain the SelfID: %d, nodes: %v", c.Config.SelfID, nodes) } if len(nodeSet) != len(nodes) { - return errors.Errorf("nodes contains duplicate IDs, nodes: %v", nodes) + return fmt.Errorf("nodes contains duplicate IDs, nodes: %v", nodes) } return nil diff --git a/pkg/types/config.go b/pkg/types/config.go index 1dc9bb14..86144daf 100644 --- a/pkg/types/config.go +++ b/pkg/types/config.go @@ -6,9 +6,8 @@ package types import ( + "errors" "time" - - "github.com/pkg/errors" ) // Configuration defines the parameters needed in order to create an instance of Consensus. @@ -115,73 +114,73 @@ var DefaultConfig = Configuration{ func (c Configuration) Validate() error { if c.SelfID == 0 { - return errors.Errorf("SelfID should be greater than zero") + return errors.New("SelfID should be greater than zero") } if c.RequestBatchMaxCount == 0 { - return errors.Errorf("RequestBatchMaxCount should be greater than zero") + return errors.New("RequestBatchMaxCount should be greater than zero") } if c.RequestBatchMaxBytes == 0 { - return errors.Errorf("RequestBatchMaxBytes should be greater than zero") + return errors.New("RequestBatchMaxBytes should be greater than zero") } if c.RequestBatchMaxInterval <= 0 { - return errors.Errorf("RequestBatchMaxInterval should be greater than zero") + return errors.New("RequestBatchMaxInterval should be greater than zero") } if c.IncomingMessageBufferSize == 0 { - return errors.Errorf("IncomingMessageBufferSize should be greater than zero") + return errors.New("IncomingMessageBufferSize should be greater than zero") } if c.RequestPoolSize == 0 { - return errors.Errorf("RequestPoolSize should be greater than zero") + return errors.New("RequestPoolSize should be greater than zero") } if c.RequestForwardTimeout <= 0 { - return errors.Errorf("RequestForwardTimeout should be greater than zero") + return errors.New("RequestForwardTimeout should be greater than zero") } if c.RequestComplainTimeout <= 0 { - return errors.Errorf("RequestComplainTimeout should be greater than zero") + return errors.New("RequestComplainTimeout should be greater than zero") } if c.RequestAutoRemoveTimeout <= 0 { - return errors.Errorf("RequestAutoRemoveTimeout should be greater than zero") + return errors.New("RequestAutoRemoveTimeout should be greater than zero") } if c.ViewChangeResendInterval <= 0 { - return errors.Errorf("ViewChangeResendInterval should be greater than zero") + return errors.New("ViewChangeResendInterval should be greater than zero") } if c.ViewChangeTimeout <= 0 { - return errors.Errorf("ViewChangeTimeout should be greater than zero") + return errors.New("ViewChangeTimeout should be greater than zero") } if c.LeaderHeartbeatTimeout <= 0 { - return errors.Errorf("LeaderHeartbeatTimeout should be greater than zero") + return errors.New("LeaderHeartbeatTimeout should be greater than zero") } if c.LeaderHeartbeatCount == 0 { - return errors.Errorf("LeaderHeartbeatCount should be greater than zero") + return errors.New("LeaderHeartbeatCount should be greater than zero") } if c.NumOfTicksBehindBeforeSyncing == 0 { - return errors.Errorf("NumOfTicksBehindBeforeSyncing should be greater than zero") + return errors.New("NumOfTicksBehindBeforeSyncing should be greater than zero") } if c.CollectTimeout <= 0 { - return errors.Errorf("CollectTimeout should be greater than zero") + return errors.New("CollectTimeout should be greater than zero") } if c.RequestBatchMaxCount > c.RequestBatchMaxBytes { - return errors.Errorf("RequestBatchMaxCount is bigger than RequestBatchMaxBytes") + return errors.New("RequestBatchMaxCount is bigger than RequestBatchMaxBytes") } if c.RequestForwardTimeout > c.RequestComplainTimeout { - return errors.Errorf("RequestForwardTimeout is bigger than RequestComplainTimeout") + return errors.New("RequestForwardTimeout is bigger than RequestComplainTimeout") } if c.RequestComplainTimeout > c.RequestAutoRemoveTimeout { - return errors.Errorf("RequestComplainTimeout is bigger than RequestAutoRemoveTimeout") + return errors.New("RequestComplainTimeout is bigger than RequestAutoRemoveTimeout") } if c.ViewChangeResendInterval > c.ViewChangeTimeout { - return errors.Errorf("ViewChangeResendInterval is bigger than ViewChangeTimeout") + return errors.New("ViewChangeResendInterval is bigger than ViewChangeTimeout") } if c.LeaderRotation && c.DecisionsPerLeader == 0 { - return errors.Errorf("DecisionsPerLeader should be greater than zero when leader rotation is active") + return errors.New("DecisionsPerLeader should be greater than zero when leader rotation is active") } if !c.LeaderRotation && c.DecisionsPerLeader != 0 { - return errors.Errorf("DecisionsPerLeader should be zero when leader rotation is off") + return errors.New("DecisionsPerLeader should be zero when leader rotation is off") } if c.RequestMaxBytes == 0 { - return errors.Errorf("RequestMaxBytes should be greater than zero") + return errors.New("RequestMaxBytes should be greater than zero") } if c.RequestPoolSubmitTimeout <= 0 { - return errors.Errorf("RequestPoolSubmitTimeout should be greater than zero") + return errors.New("RequestPoolSubmitTimeout should be greater than zero") } return nil diff --git a/pkg/wal/util.go b/pkg/wal/util.go index 040f3ea2..b7b66dfc 100644 --- a/pkg/wal/util.go +++ b/pkg/wal/util.go @@ -21,7 +21,7 @@ var padTable [][]byte func init() { padTable = make([][]byte, 8) - for i := 0; i < 8; i++ { + for i := range 8 { padTable[i] = make([]byte, i) } } diff --git a/pkg/wal/writeaheadlog.go b/pkg/wal/writeaheadlog.go index 4c4cdc50..d7d0b86e 100644 --- a/pkg/wal/writeaheadlog.go +++ b/pkg/wal/writeaheadlog.go @@ -7,6 +7,7 @@ package wal import ( "encoding/binary" + "errors" "fmt" "hash/crc32" "io" @@ -19,7 +20,6 @@ import ( "github.com/hyperledger-labs/SmartBFT/pkg/api" "github.com/hyperledger-labs/SmartBFT/pkg/metrics/disabled" protos "github.com/hyperledger-labs/SmartBFT/smartbftprotos" - "github.com/pkg/errors" ) const ( @@ -762,44 +762,34 @@ func InitializeAndReadAll( writeAheadLog, err = Create(logger, walDir, options) if err != nil { if !errors.Is(err, ErrWALAlreadyExists) { - err = errors.Wrap(err, "Cannot create Write-Ahead-Log") - - return nil, nil, err + return nil, nil, fmt.Errorf("Cannot create Write-Ahead-Log: %w", err) } logger.Infof("Write-Ahead-Log already exists at dir: %s; Trying to open", walDir) writeAheadLog, err = Open(logger, walDir, options) if err != nil { - err = errors.Wrap(err, "Cannot open Write-Ahead-Log") - - return nil, nil, err + return nil, nil, fmt.Errorf("Cannot open Write-Ahead-Log: %w", err) } initialState, err = writeAheadLog.ReadAll() if err != nil { if !errors.Is(err, io.ErrUnexpectedEOF) { - err = errors.Wrap(err, "Cannot read initial state from Write-Ahead-Log") - - return nil, nil, err + return nil, nil, fmt.Errorf("Cannot read initial state from Write-Ahead-Log: %w", err) } logger.Infof("Received io.ErrUnexpectedEOF, trying to repair Write-Ahead-Log at dir: %s", walDir) err = Repair(logger, walDir) if err != nil { - err = errors.Wrap(err, "Cannot repair Write-Ahead-Log") - - return nil, nil, err + return nil, nil, fmt.Errorf("Cannot repair Write-Ahead-Log: %w", err) } logger.Infof("Reading Write-Ahead-Log initial state after repair") initialState, err = writeAheadLog.ReadAll() if err != nil { - err = errors.Wrap(err, "Cannot initial state from Write-Ahead-Log, after repair") - - return nil, nil, err + return nil, nil, fmt.Errorf("Cannot initial state from Write-Ahead-Log, after repair: %w", err) } } } diff --git a/vendor/github.com/pkg/errors/.gitignore b/vendor/github.com/pkg/errors/.gitignore deleted file mode 100644 index daf913b1..00000000 --- a/vendor/github.com/pkg/errors/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/pkg/errors/.travis.yml b/vendor/github.com/pkg/errors/.travis.yml deleted file mode 100644 index 9159de03..00000000 --- a/vendor/github.com/pkg/errors/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go_import_path: github.com/pkg/errors -go: - - 1.11.x - - 1.12.x - - 1.13.x - - tip - -script: - - make check diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e7..00000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/Makefile b/vendor/github.com/pkg/errors/Makefile deleted file mode 100644 index ce9d7cde..00000000 --- a/vendor/github.com/pkg/errors/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -PKGS := github.com/pkg/errors -SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) -GO := go - -check: test vet gofmt misspell unconvert staticcheck ineffassign unparam - -test: - $(GO) test $(PKGS) - -vet: | test - $(GO) vet $(PKGS) - -staticcheck: - $(GO) get honnef.co/go/tools/cmd/staticcheck - staticcheck -checks all $(PKGS) - -misspell: - $(GO) get github.com/client9/misspell/cmd/misspell - misspell \ - -locale GB \ - -error \ - *.md *.go - -unconvert: - $(GO) get github.com/mdempsky/unconvert - unconvert -v $(PKGS) - -ineffassign: - $(GO) get github.com/gordonklaus/ineffassign - find $(SRCDIRS) -name '*.go' | xargs ineffassign - -pedantic: check errcheck - -unparam: - $(GO) get mvdan.cc/unparam - unparam ./... - -errcheck: - $(GO) get github.com/kisielk/errcheck - errcheck $(PKGS) - -gofmt: - @echo Checking code is gofmted - @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 54dfdcb1..00000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which 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. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## 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 can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Roadmap - -With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: - -- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) -- 1.0. Final release. - -## Contributing - -Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. - -Before sending a PR, please discuss your change by raising an issue. - -## License - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade..00000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 161aea25..00000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,288 +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" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - 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{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -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) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withStack) Unwrap() 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) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - 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{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - 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{}) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -// Unwrap provides compatibility for Go 1.13 error chains. -func (w *withMessage) Unwrap() 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 -} diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go deleted file mode 100644 index be0d10d0..00000000 --- a/vendor/github.com/pkg/errors/go113.go +++ /dev/null @@ -1,38 +0,0 @@ -// +build go1.13 - -package errors - -import ( - stderrors "errors" -) - -// Is reports whether any error in err's chain matches target. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error is considered to match a target if it is equal to that target or if -// it implements a method Is(error) bool such that Is(target) returns true. -func Is(err, target error) bool { return stderrors.Is(err, target) } - -// As finds the first error in err's chain that matches target, and if so, sets -// target to that error value and returns true. -// -// The chain consists of err itself followed by the sequence of errors obtained by -// repeatedly calling Unwrap. -// -// An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that -// As(target) returns true. In the latter case, the As method is responsible for -// setting target. -// -// As will panic if target is not a non-nil pointer to either a type that implements -// error, or to any interface type. As returns false if err is nil. -func As(err error, target interface{}) bool { return stderrors.As(err, target) } - -// Unwrap returns the result of calling the Unwrap method on err, if err's -// type contains an Unwrap method returning error. -// Otherwise, Unwrap returns nil. -func Unwrap(err error) error { - return stderrors.Unwrap(err) -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 779a8348..00000000 --- a/vendor/github.com/pkg/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 (\n\t) -// %+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/vendor/modules.txt b/vendor/modules.txt index 7d756cda..db38057f 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -4,9 +4,6 @@ github.com/davecgh/go-spew/spew # github.com/golang/protobuf v1.5.4 ## explicit; go 1.17 github.com/golang/protobuf/proto -# github.com/pkg/errors v0.9.1 -## explicit -github.com/pkg/errors # github.com/pmezard/go-difflib v1.0.0 ## explicit github.com/pmezard/go-difflib/difflib