[NOD-641] Upgrade to github.com/pkg/errors v0.9.1 and use errors.As where needed (#614)

* [NOD-641] Upgrade to github.com/pkg/errors v0.9.1 and use errors.As where needed

* [NOD-641] Fix find and replace error

* [NOD-641] Use errors.As for error type checking

* [NOD-641] Fix errors.As for pointer types

* [NOD-641] Use errors.As where needed

* [NOD-641] Rename rErr->ruleErr

* [NOD-641] Rename derr->dbErr

* [NOD-641] e->flagsErr where necessary

* [NOD-641] change jerr to more appropriate name

* [NOD-641] Rename cerr->bdRuleErr

* [NOD-641] Rename serr->scriptErr

* [NOD-641] Use errors.Is instead of testutil.AreErrorsEqual in TestNewHashFromStr

* [NOD-641] Rename bdRuleErr->dagRuleErr

* [NOD-641] Rename mErr->msgErr

* [NOD-641] Rename dErr->deserializeErr
This commit is contained in:
Ori Newman 2020-02-03 12:38:33 +02:00 committed by GitHub
parent 41c8178ad3
commit eb953286ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
65 changed files with 314 additions and 192 deletions

View File

@ -8,6 +8,7 @@ import (
"fmt" "fmt"
"github.com/kaspanet/kaspad/database" "github.com/kaspanet/kaspad/database"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/pkg/errors"
) )
func (dag *BlockDAG) addNodeToIndexWithInvalidAncestor(block *util.Block) error { func (dag *BlockDAG) addNodeToIndexWithInvalidAncestor(block *util.Block) error {
@ -30,7 +31,8 @@ func (dag *BlockDAG) addNodeToIndexWithInvalidAncestor(block *util.Block) error
func (dag *BlockDAG) maybeAcceptBlock(block *util.Block, flags BehaviorFlags) error { func (dag *BlockDAG) maybeAcceptBlock(block *util.Block, flags BehaviorFlags) error {
parents, err := lookupParentNodes(block, dag) parents, err := lookupParentNodes(block, dag)
if err != nil { if err != nil {
if rErr, ok := err.(RuleError); ok && rErr.ErrorCode == ErrInvalidAncestorBlock { var ruleErr RuleError
if ok := errors.As(err, &ruleErr); ok && ruleErr.ErrorCode == ErrInvalidAncestorBlock {
err := dag.addNodeToIndexWithInvalidAncestor(block) err := dag.addNodeToIndexWithInvalidAncestor(block)
if err != nil { if err != nil {
return err return err

View File

@ -1,6 +1,7 @@
package blockdag package blockdag
import ( import (
"errors"
"path/filepath" "path/filepath"
"testing" "testing"
@ -33,8 +34,8 @@ func TestMaybeAcceptBlockErrors(t *testing.T) {
t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are missing: "+ t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are missing: "+
"Expected: %s, got: <nil>", ErrParentBlockUnknown) "Expected: %s, got: <nil>", ErrParentBlockUnknown)
} }
ruleErr, ok := err.(RuleError) var ruleErr RuleError
if !ok { if ok := errors.As(err, &ruleErr); !ok {
t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are missing: "+ t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are missing: "+
"Expected RuleError but got %s", err) "Expected RuleError but got %s", err)
} else if ruleErr.ErrorCode != ErrParentBlockUnknown { } else if ruleErr.ErrorCode != ErrParentBlockUnknown {
@ -71,8 +72,7 @@ func TestMaybeAcceptBlockErrors(t *testing.T) {
t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are invalid: "+ t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are invalid: "+
"Expected: %s, got: <nil>", ErrInvalidAncestorBlock) "Expected: %s, got: <nil>", ErrInvalidAncestorBlock)
} }
ruleErr, ok = err.(RuleError) if ok := errors.As(err, &ruleErr); !ok {
if !ok {
t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are invalid: "+ t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block if its parents are invalid: "+
"Expected RuleError but got %s", err) "Expected RuleError but got %s", err)
} else if ruleErr.ErrorCode != ErrInvalidAncestorBlock { } else if ruleErr.ErrorCode != ErrInvalidAncestorBlock {
@ -91,8 +91,7 @@ func TestMaybeAcceptBlockErrors(t *testing.T) {
t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block due to bad context: "+ t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block due to bad context: "+
"Expected: %s, got: <nil>", ErrUnexpectedDifficulty) "Expected: %s, got: <nil>", ErrUnexpectedDifficulty)
} }
ruleErr, ok = err.(RuleError) if ok := errors.As(err, &ruleErr); !ok {
if !ok {
t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block due to bad context: "+ t.Errorf("TestMaybeAcceptBlockErrors: rejecting the block due to bad context: "+
"Expected RuleError but got %s", err) "Expected RuleError but got %s", err)
} else if ruleErr.ErrorCode != ErrUnexpectedDifficulty { } else if ruleErr.ErrorCode != ErrUnexpectedDifficulty {

View File

@ -484,7 +484,7 @@ func (dag *BlockDAG) addBlock(node *blockNode,
// Connect the block to the DAG. // Connect the block to the DAG.
chainUpdates, err := dag.connectBlock(node, block, selectedParentAnticone, fastAdd) chainUpdates, err := dag.connectBlock(node, block, selectedParentAnticone, fastAdd)
if err != nil { if err != nil {
if _, ok := err.(RuleError); ok { if errors.As(err, &RuleError{}) {
dag.index.SetStatusFlags(node, statusValidateFailed) dag.index.SetStatusFlags(node, statusValidateFailed)
} else { } else {
return nil, err return nil, err
@ -574,8 +574,9 @@ func (dag *BlockDAG) connectBlock(node *blockNode,
newBlockUTXO, txsAcceptanceData, newBlockFeeData, err := node.verifyAndBuildUTXO(dag, block.Transactions(), fastAdd) newBlockUTXO, txsAcceptanceData, newBlockFeeData, err := node.verifyAndBuildUTXO(dag, block.Transactions(), fastAdd)
if err != nil { if err != nil {
newErrString := fmt.Sprintf("error verifying UTXO for %s: %s", node, err) newErrString := fmt.Sprintf("error verifying UTXO for %s: %s", node, err)
if err, ok := err.(RuleError); ok { var ruleErr RuleError
return nil, ruleError(err.ErrorCode, newErrString) if ok := errors.As(err, &ruleErr); ok {
return nil, ruleError(ruleErr.ErrorCode, newErrString)
} }
return nil, errors.New(newErrString) return nil, errors.New(newErrString)
} }
@ -1832,7 +1833,7 @@ func (dag *BlockDAG) processDelayedBlocks() error {
log.Errorf("Error while processing delayed block (block %s)", delayedBlock.block.Hash().String()) log.Errorf("Error while processing delayed block (block %s)", delayedBlock.block.Hash().String())
// Rule errors should not be propagated as they refer only to the delayed block, // Rule errors should not be propagated as they refer only to the delayed block,
// while this function runs in the context of another block // while this function runs in the context of another block
if _, ok := err.(RuleError); !ok { if !errors.As(err, &RuleError{}) {
return err return err
} }
} }

View File

@ -6,6 +6,7 @@ package blockdag
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -164,12 +165,13 @@ func TestIsKnownBlock(t *testing.T) {
if err == nil { if err == nil {
t.Fatalf("ProcessBlock for block 3D has no error when expected to have an error\n") t.Fatalf("ProcessBlock for block 3D has no error when expected to have an error\n")
} }
rErr, ok := err.(RuleError) var ruleErr RuleError
ok := errors.As(err, &ruleErr)
if !ok { if !ok {
t.Fatalf("ProcessBlock for block 3D expected a RuleError, but got %v\n", err) t.Fatalf("ProcessBlock for block 3D expected a RuleError, but got %v\n", err)
} }
if !ok || rErr.ErrorCode != ErrDuplicateTxInputs { if !ok || ruleErr.ErrorCode != ErrDuplicateTxInputs {
t.Fatalf("ProcessBlock for block 3D expected error code %s but got %s\n", ErrDuplicateTxInputs, rErr.ErrorCode) t.Fatalf("ProcessBlock for block 3D expected error code %s but got %s\n", ErrDuplicateTxInputs, ruleErr.ErrorCode)
} }
if isDelayed { if isDelayed {
t.Fatalf("ProcessBlock: block 3D " + t.Fatalf("ProcessBlock: block 3D " +
@ -994,7 +996,7 @@ func TestDAGIndexFailedStatus(t *testing.T) {
invalidBlock := util.NewBlock(invalidMsgBlock) invalidBlock := util.NewBlock(invalidMsgBlock)
isOrphan, isDelayed, err := dag.ProcessBlock(invalidBlock, BFNoPoWCheck) isOrphan, isDelayed, err := dag.ProcessBlock(invalidBlock, BFNoPoWCheck)
if _, ok := err.(RuleError); !ok { if !errors.As(err, &RuleError{}) {
t.Fatalf("ProcessBlock: expected a rule error but got %s instead", err) t.Fatalf("ProcessBlock: expected a rule error but got %s instead", err)
} }
if isDelayed { if isDelayed {
@ -1023,7 +1025,8 @@ func TestDAGIndexFailedStatus(t *testing.T) {
invalidBlockChild := util.NewBlock(invalidMsgBlockChild) invalidBlockChild := util.NewBlock(invalidMsgBlockChild)
isOrphan, isDelayed, err = dag.ProcessBlock(invalidBlockChild, BFNoPoWCheck) isOrphan, isDelayed, err = dag.ProcessBlock(invalidBlockChild, BFNoPoWCheck)
if rErr, ok := err.(RuleError); !ok || rErr.ErrorCode != ErrInvalidAncestorBlock { var ruleErr RuleError
if ok := errors.As(err, &ruleErr); !ok || ruleErr.ErrorCode != ErrInvalidAncestorBlock {
t.Fatalf("ProcessBlock: expected a rule error but got %s instead", err) t.Fatalf("ProcessBlock: expected a rule error but got %s instead", err)
} }
if isDelayed { if isDelayed {
@ -1051,7 +1054,7 @@ func TestDAGIndexFailedStatus(t *testing.T) {
invalidBlockGrandChild := util.NewBlock(invalidMsgBlockGrandChild) invalidBlockGrandChild := util.NewBlock(invalidMsgBlockGrandChild)
isOrphan, isDelayed, err = dag.ProcessBlock(invalidBlockGrandChild, BFNoPoWCheck) isOrphan, isDelayed, err = dag.ProcessBlock(invalidBlockGrandChild, BFNoPoWCheck)
if rErr, ok := err.(RuleError); !ok || rErr.ErrorCode != ErrInvalidAncestorBlock { if ok := errors.As(err, &ruleErr); !ok || ruleErr.ErrorCode != ErrInvalidAncestorBlock {
t.Fatalf("ProcessBlock: expected a rule error but got %s instead", err) t.Fatalf("ProcessBlock: expected a rule error but got %s instead", err)
} }
if isDelayed { if isDelayed {

View File

@ -83,8 +83,8 @@ func (e errNotInDAG) Error() string {
// isNotInDAGErr returns whether or not the passed error is an // isNotInDAGErr returns whether or not the passed error is an
// errNotInDAG error. // errNotInDAG error.
func isNotInDAGErr(err error) bool { func isNotInDAGErr(err error) bool {
_, ok := err.(errNotInDAG) var notInDAGErr errNotInDAG
return ok return errors.As(err, &notInDAGErr)
} }
// errDeserialize signifies that a problem was encountered when deserializing // errDeserialize signifies that a problem was encountered when deserializing
@ -99,8 +99,8 @@ func (e errDeserialize) Error() string {
// isDeserializeErr returns whether or not the passed error is an errDeserialize // isDeserializeErr returns whether or not the passed error is an errDeserialize
// error. // error.
func isDeserializeErr(err error) bool { func isDeserializeErr(err error) bool {
_, ok := err.(errDeserialize) var deserializeErr errDeserialize
return ok return errors.As(err, &deserializeErr)
} }
// dbPutVersion uses an existing database transaction to update the provided // dbPutVersion uses an existing database transaction to update the provided

View File

@ -248,12 +248,13 @@ func TestDAGStateDeserializeErrors(t *testing.T) {
test.name, err, test.errType) test.name, err, test.errType)
continue continue
} }
if derr, ok := err.(database.Error); ok { var dbErr database.Error
if ok := errors.As(err, &dbErr); ok {
tderr := test.errType.(database.Error) tderr := test.errType.(database.Error)
if derr.ErrorCode != tderr.ErrorCode { if dbErr.ErrorCode != tderr.ErrorCode {
t.Errorf("deserializeDAGState (%s): "+ t.Errorf("deserializeDAGState (%s): "+
"wrong error code got: %v, want: %v", "wrong error code got: %v, want: %v",
test.name, derr.ErrorCode, test.name, dbErr.ErrorCode,
tderr.ErrorCode) tderr.ErrorCode)
continue continue
} }

View File

@ -137,10 +137,10 @@ func TestFinality(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("TestFinality: buildNodeToDag expected an error but got <nil>") t.Errorf("TestFinality: buildNodeToDag expected an error but got <nil>")
} }
rErr, ok := err.(blockdag.RuleError) var ruleErr blockdag.RuleError
if ok { if errors.As(err, &ruleErr) {
if rErr.ErrorCode != blockdag.ErrFinality { if ruleErr.ErrorCode != blockdag.ErrFinality {
t.Errorf("TestFinality: buildNodeToDag expected an error with code %v but instead got %v", blockdag.ErrFinality, rErr.ErrorCode) t.Errorf("TestFinality: buildNodeToDag expected an error with code %v but instead got %v", blockdag.ErrFinality, ruleErr.ErrorCode)
} }
} else { } else {
t.Errorf("TestFinality: buildNodeToDag got unexpected error: %v", err) t.Errorf("TestFinality: buildNodeToDag got unexpected error: %v", err)
@ -152,13 +152,12 @@ func TestFinality(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("TestFinality: buildNodeToDag expected an error but got <nil>") t.Errorf("TestFinality: buildNodeToDag expected an error but got <nil>")
} }
rErr, ok = err.(blockdag.RuleError) if errors.As(err, &ruleErr) {
if ok { if ruleErr.ErrorCode != blockdag.ErrFinality {
if rErr.ErrorCode != blockdag.ErrFinality { t.Errorf("TestFinality: buildNodeToDag expected an error with code %v but instead got %v", blockdag.ErrFinality, ruleErr.ErrorCode)
t.Errorf("TestFinality: buildNodeToDag expected an error with code %v but instead got %v", blockdag.ErrFinality, rErr.ErrorCode)
} }
} else { } else {
t.Errorf("TestFinality: buildNodeToDag got unexpected error: %v", rErr) t.Errorf("TestFinality: buildNodeToDag got unexpected error: %v", ruleErr)
} }
} }
@ -269,13 +268,16 @@ func TestChainedTransactions(t *testing.T) {
isOrphan, isDelayed, err = dag.ProcessBlock(util.NewBlock(block2), blockdag.BFNoPoWCheck) isOrphan, isDelayed, err = dag.ProcessBlock(util.NewBlock(block2), blockdag.BFNoPoWCheck)
if err == nil { if err == nil {
t.Errorf("ProcessBlock expected an error") t.Errorf("ProcessBlock expected an error")
} else if rErr, ok := err.(blockdag.RuleError); ok { } else {
if rErr.ErrorCode != blockdag.ErrMissingTxOut { var ruleErr blockdag.RuleError
t.Errorf("ProcessBlock expected an %v error code but got %v", blockdag.ErrMissingTxOut, rErr.ErrorCode) if ok := errors.As(err, &ruleErr); ok {
if ruleErr.ErrorCode != blockdag.ErrMissingTxOut {
t.Errorf("ProcessBlock expected an %v error code but got %v", blockdag.ErrMissingTxOut, ruleErr.ErrorCode)
} }
} else { } else {
t.Errorf("ProcessBlock expected a blockdag.RuleError but got %v", err) t.Errorf("ProcessBlock expected a blockdag.RuleError but got %v", err)
} }
}
if isDelayed { if isDelayed {
t.Fatalf("ProcessBlock: block2 " + t.Fatalf("ProcessBlock: block2 " +
"is too far in the future") "is too far in the future")
@ -468,11 +470,11 @@ func TestGasLimit(t *testing.T) {
if err == nil { if err == nil {
t.Fatalf("ProcessBlock expected to have an error in block that exceeds gas limit") t.Fatalf("ProcessBlock expected to have an error in block that exceeds gas limit")
} }
rErr, ok := err.(blockdag.RuleError) var ruleErr blockdag.RuleError
if !ok { if !errors.As(err, &ruleErr) {
t.Fatalf("ProcessBlock expected a RuleError, but got %v", err) t.Fatalf("ProcessBlock expected a RuleError, but got %v", err)
} else if rErr.ErrorCode != blockdag.ErrInvalidGas { } else if ruleErr.ErrorCode != blockdag.ErrInvalidGas {
t.Fatalf("ProcessBlock expected error code %s but got %s", blockdag.ErrInvalidGas, rErr.ErrorCode) t.Fatalf("ProcessBlock expected error code %s but got %s", blockdag.ErrInvalidGas, ruleErr.ErrorCode)
} }
if isDelayed { if isDelayed {
t.Fatalf("ProcessBlock: overLimitBlock " + t.Fatalf("ProcessBlock: overLimitBlock " +
@ -503,11 +505,10 @@ func TestGasLimit(t *testing.T) {
if err == nil { if err == nil {
t.Fatalf("ProcessBlock expected to have an error") t.Fatalf("ProcessBlock expected to have an error")
} }
rErr, ok = err.(blockdag.RuleError) if !errors.As(err, &ruleErr) {
if !ok {
t.Fatalf("ProcessBlock expected a RuleError, but got %v", err) t.Fatalf("ProcessBlock expected a RuleError, but got %v", err)
} else if rErr.ErrorCode != blockdag.ErrInvalidGas { } else if ruleErr.ErrorCode != blockdag.ErrInvalidGas {
t.Fatalf("ProcessBlock expected error code %s but got %s", blockdag.ErrInvalidGas, rErr.ErrorCode) t.Fatalf("ProcessBlock expected error code %s but got %s", blockdag.ErrInvalidGas, ruleErr.ErrorCode)
} }
if isOrphan { if isOrphan {
t.Fatalf("ProcessBlock: overLimitBlock got unexpectedly orphan") t.Fatalf("ProcessBlock: overLimitBlock got unexpectedly orphan")

View File

@ -85,8 +85,8 @@ func (e errDeserialize) Error() string {
// isDeserializeErr returns whether or not the passed error is an errDeserialize // isDeserializeErr returns whether or not the passed error is an errDeserialize
// error. // error.
func isDeserializeErr(err error) bool { func isDeserializeErr(err error) bool {
_, ok := err.(errDeserialize) var deserializeErr errDeserialize
return ok return errors.As(err, &deserializeErr)
} }
// internalBucket is an abstraction over a database bucket. It is used to make // internalBucket is an abstraction over a database bucket. It is used to make

View File

@ -7,6 +7,7 @@ package blockdag
import ( import (
"fmt" "fmt"
"github.com/kaspanet/kaspad/dagconfig" "github.com/kaspanet/kaspad/dagconfig"
"github.com/pkg/errors"
"time" "time"
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
@ -95,7 +96,8 @@ func (dag *BlockDAG) processOrphans(hash *daghash.Hash, flags BehaviorFlags) err
// still missing. // still missing.
_, err := lookupParentNodes(orphan.block, dag) _, err := lookupParentNodes(orphan.block, dag)
if err != nil { if err != nil {
if ruleErr, ok := err.(RuleError); ok && ruleErr.ErrorCode == ErrParentBlockUnknown { var ruleErr RuleError
if ok := errors.As(err, &ruleErr); ok && ruleErr.ErrorCode == ErrParentBlockUnknown {
continue continue
} }
return err return err
@ -111,7 +113,7 @@ func (dag *BlockDAG) processOrphans(hash *daghash.Hash, flags BehaviorFlags) err
if err != nil { if err != nil {
// Since we don't want to reject the original block because of // Since we don't want to reject the original block because of
// a bad unorphaned child, only return an error if it's not a RuleError. // a bad unorphaned child, only return an error if it's not a RuleError.
if _, ok := err.(RuleError); !ok { if !errors.As(err, &RuleError{}) {
return err return err
} }
log.Warnf("Verification failed for orphan block %s: %s", orphanHash, err) log.Warnf("Verification failed for orphan block %s: %s", orphanHash, err)

View File

@ -5,6 +5,7 @@
package blockdag package blockdag
import ( import (
"github.com/pkg/errors"
"math" "math"
"path/filepath" "path/filepath"
"testing" "testing"
@ -186,8 +187,8 @@ func TestCheckBlockSanity(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("CheckBlockSanity: transactions disorder is not detected") t.Errorf("CheckBlockSanity: transactions disorder is not detected")
} }
ruleErr, ok := err.(RuleError) var ruleErr RuleError
if !ok { if !errors.As(err, &ruleErr) {
t.Errorf("CheckBlockSanity: wrong error returned, expect RuleError, got %T", err) t.Errorf("CheckBlockSanity: wrong error returned, expect RuleError, got %T", err)
} else if ruleErr.ErrorCode != ErrTransactionsNotSorted { } else if ruleErr.ErrorCode != ErrTransactionsNotSorted {
t.Errorf("CheckBlockSanity: wrong error returned, expect ErrTransactionsNotSorted, got %v, err %s", ruleErr.ErrorCode, err) t.Errorf("CheckBlockSanity: wrong error returned, expect ErrTransactionsNotSorted, got %v, err %s", ruleErr.ErrorCode, err)
@ -479,8 +480,10 @@ func TestCheckBlockSanity(t *testing.T) {
if err == nil { if err == nil {
t.Errorf("CheckBlockSanity: error is nil when it shouldn't be") t.Errorf("CheckBlockSanity: error is nil when it shouldn't be")
} }
rError := err.(RuleError) var rError RuleError
if rError.ErrorCode != ErrWrongParentsOrder { if !errors.As(err, &rError) {
t.Fatalf("CheckBlockSanity: expected a RuleError, but got %s", err)
} else if rError.ErrorCode != ErrWrongParentsOrder {
t.Errorf("CheckBlockSanity: Expected error was ErrWrongParentsOrder but got %v", err) t.Errorf("CheckBlockSanity: Expected error was ErrWrongParentsOrder but got %v", err)
} }
if delay != 0 { if delay != 0 {

View File

@ -5,6 +5,7 @@
package main package main
import ( import (
"github.com/pkg/errors"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -37,7 +38,8 @@ func loadBlockDB() (database.DB, error) {
if err != nil { if err != nil {
// Return the error if it's not because the database doesn't // Return the error if it's not because the database doesn't
// exist. // exist.
if dbErr, ok := err.(database.Error); !ok || dbErr.ErrorCode != var dbErr database.Error
if ok := errors.As(err, &dbErr); !ok || dbErr.ErrorCode !=
database.ErrDbDoesNotExist { database.ErrDbDoesNotExist {
return nil, err return nil, err

View File

@ -84,7 +84,8 @@ func loadConfig() (*ConfigFlags, []string, error) {
parser := flags.NewParser(&activeConfig, flags.Default) parser := flags.NewParser(&activeConfig, flags.Default)
remainingArgs, err := parser.Parse() remainingArgs, err := parser.Parse()
if err != nil { if err != nil {
if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); !ok || flagsErr.Type != flags.ErrHelp {
parser.WriteHelp(os.Stderr) parser.WriteHelp(os.Stderr)
} }
return nil, nil, err return nil, nil, err

View File

@ -68,7 +68,8 @@ func waitForSubnetworkToBecomeAccepted(client *rpcclient.Client, subnetworkID *s
for { for {
_, err := client.GetSubnetwork(subnetworkID.String()) _, err := client.GetSubnetwork(subnetworkID.String())
if err != nil { if err != nil {
if rpcError, ok := err.(*rpcmodel.RPCError); ok && rpcError.Code == rpcmodel.ErrRPCSubnetworkNotFound { var rpcError *rpcmodel.RPCError
if ok := errors.As(err, &rpcError); ok && rpcError.Code == rpcmodel.ErrRPCSubnetworkNotFound {
log.Infof("Subnetwork not found") log.Infof("Subnetwork not found")
retries++ retries++

View File

@ -41,7 +41,8 @@ func collectTransactions(client *rpcclient.Client, addrPubKeyHash *util.AddressP
results, err := client.SearchRawTransactionsVerbose(addrPubKeyHash, skip, resultsCount, true, false, nil) results, err := client.SearchRawTransactionsVerbose(addrPubKeyHash, skip, resultsCount, true, false, nil)
if err != nil { if err != nil {
// Break when there are no further txs // Break when there are no further txs
if rpcError, ok := err.(*rpcmodel.RPCError); ok && rpcError.Code == rpcmodel.ErrRPCNoTxInfo { var rpcError *rpcmodel.RPCError
if ok := errors.As(err, &rpcError); ok && rpcError.Code == rpcmodel.ErrRPCNoTxInfo {
break break
} }

View File

@ -6,6 +6,7 @@ package main
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -32,7 +33,8 @@ func main() {
parser := flags.NewParser(&cfg, flags.Default) parser := flags.NewParser(&cfg, flags.Default)
_, err := parser.Parse() _, err := parser.Parse()
if err != nil { if err != nil {
if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); !ok || flagsErr.Type != flags.ErrHelp {
parser.WriteHelp(os.Stderr) parser.WriteHelp(os.Stderr)
} }
return return

View File

@ -172,7 +172,8 @@ func loadConfig() (*ConfigFlags, []string, error) {
preParser := flags.NewParser(preCfg, flags.HelpFlag) preParser := flags.NewParser(preCfg, flags.HelpFlag)
_, err := preParser.Parse() _, err := preParser.Parse()
if err != nil { if err != nil {
if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp { var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); ok && flagsErr.Type == flags.ErrHelp {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, "") fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "The special parameter `-` "+ fmt.Fprintln(os.Stderr, "The special parameter `-` "+
@ -216,7 +217,7 @@ func loadConfig() (*ConfigFlags, []string, error) {
parser := flags.NewParser(activeConfig, flags.Default) parser := flags.NewParser(activeConfig, flags.Default)
err = flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile) err = flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile)
if err != nil { if err != nil {
if _, ok := err.(*os.PathError); !ok { if pErr := &(os.PathError{}); !errors.As(err, pErr) {
fmt.Fprintf(os.Stderr, "Error parsing config file: %s\n", fmt.Fprintf(os.Stderr, "Error parsing config file: %s\n",
err) err)
fmt.Fprintln(os.Stderr, usageMessage) fmt.Fprintln(os.Stderr, usageMessage)
@ -227,7 +228,8 @@ func loadConfig() (*ConfigFlags, []string, error) {
// Parse command line options again to ensure they take precedence. // Parse command line options again to ensure they take precedence.
remainingArgs, err := parser.Parse() remainingArgs, err := parser.Parse()
if err != nil { if err != nil {
if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); !ok || flagsErr.Type != flags.ErrHelp {
fmt.Fprintln(os.Stderr, usageMessage) fmt.Fprintln(os.Stderr, usageMessage)
} }
return nil, nil, err return nil, nil, err

View File

@ -5,6 +5,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/pkg/errors"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
@ -110,9 +111,10 @@ func main() {
// rpcmodel.Error as it reallistcally will always be since the // rpcmodel.Error as it reallistcally will always be since the
// NewCommand function is only supposed to return errors of that // NewCommand function is only supposed to return errors of that
// type. // type.
if jerr, ok := err.(rpcmodel.Error); ok { var rpcModelErr rpcmodel.Error
if ok := errors.As(err, &rpcModelErr); ok {
fmt.Fprintf(os.Stderr, "%s error: %s (command code: %s)\n", fmt.Fprintf(os.Stderr, "%s error: %s (command code: %s)\n",
method, err, jerr.ErrorCode) method, err, rpcModelErr.ErrorCode)
commandUsage(method) commandUsage(method)
os.Exit(1) os.Exit(1)
} }

View File

@ -267,7 +267,8 @@ func loadConfig() (*Config, []string, error) {
preParser := newConfigParser(&preCfg, &serviceOpts, flags.HelpFlag) preParser := newConfigParser(&preCfg, &serviceOpts, flags.HelpFlag)
_, err := preParser.Parse() _, err := preParser.Parse()
if err != nil { if err != nil {
if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp { var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); ok && flagsErr.Type == flags.ErrHelp {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
return nil, nil, err return nil, nil, err
} }
@ -313,7 +314,7 @@ func loadConfig() (*Config, []string, error) {
err := flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile) err := flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile)
if err != nil { if err != nil {
if _, ok := err.(*os.PathError); !ok { if pErr := &(os.PathError{}); !errors.As(err, pErr) {
fmt.Fprintf(os.Stderr, "Error parsing config "+ fmt.Fprintf(os.Stderr, "Error parsing config "+
"file: %s\n", err) "file: %s\n", err)
fmt.Fprintln(os.Stderr, usageMessage) fmt.Fprintln(os.Stderr, usageMessage)
@ -331,7 +332,8 @@ func loadConfig() (*Config, []string, error) {
// Parse command line options again to ensure they take precedence. // Parse command line options again to ensure they take precedence.
remainingArgs, err := parser.Parse() remainingArgs, err := parser.Parse()
if err != nil { if err != nil {
if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp { var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); !ok || flagsErr.Type != flags.ErrHelp {
fmt.Fprintln(os.Stderr, usageMessage) fmt.Fprintln(os.Stderr, usageMessage)
} }
return nil, nil, err return nil, nil, err
@ -344,7 +346,8 @@ func loadConfig() (*Config, []string, error) {
// Show a nicer error message if it's because a symlink is // Show a nicer error message if it's because a symlink is
// linked to a directory that does not exist (probably because // linked to a directory that does not exist (probably because
// it's not mounted). // it's not mounted).
if e, ok := err.(*os.PathError); ok && os.IsExist(err) { var e *os.PathError
if ok := errors.As(err, &e); ok && os.IsExist(err) {
if link, lerr := os.Readlink(e.Path); lerr == nil { if link, lerr := os.Readlink(e.Path); lerr == nil {
str := "is symlink %s -> %s mounted?" str := "is symlink %s -> %s mounted?"
err = errors.Errorf(str, e.Path, link) err = errors.Errorf(str, e.Path, link)

View File

@ -370,7 +370,8 @@ func (cmd *importCmd) Execute(args []string) error {
resultsChan := importer.Import() resultsChan := importer.Import()
results := <-resultsChan results := <-resultsChan
if results.err != nil { if results.err != nil {
dbErr, ok := results.err.(database.Error) var dbErr database.Error
ok := errors.As(err, dbErr)
if !ok || ok && dbErr.ErrorCode != database.ErrDbNotOpen { if !ok || ok && dbErr.ErrorCode != database.ErrDbNotOpen {
shutdownChannel <- results.err shutdownChannel <- results.err
return return

View File

@ -6,6 +6,7 @@ package main
import ( import (
"github.com/kaspanet/kaspad/util/panics" "github.com/kaspanet/kaspad/util/panics"
"github.com/pkg/errors"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -39,7 +40,8 @@ func loadBlockDB() (database.DB, error) {
if err != nil { if err != nil {
// Return the error if it's not because the database doesn't // Return the error if it's not because the database doesn't
// exist. // exist.
if dbErr, ok := err.(database.Error); !ok || dbErr.ErrorCode != var dbErr database.Error
if ok := errors.As(err, &dbErr); !ok || dbErr.ErrorCode !=
database.ErrDbDoesNotExist { database.ErrDbDoesNotExist {
return nil, err return nil, err
@ -96,7 +98,8 @@ func realMain() error {
// Parse command line and invoke the Execute function for the specified // Parse command line and invoke the Execute function for the specified
// command. // command.
if _, err := parser.Parse(); err != nil { if _, err := parser.Parse(); err != nil {
if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp { var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); ok && flagsErr.Type == flags.ErrHelp {
parser.WriteHelp(os.Stderr) parser.WriteHelp(os.Stderr)
} else { } else {
log.Error(err) log.Error(err)

View File

@ -4,7 +4,10 @@
package database package database
import "fmt" import (
"fmt"
"github.com/pkg/errors"
)
// ErrorCode identifies a kind of error. // ErrorCode identifies a kind of error.
type ErrorCode int type ErrorCode int
@ -199,8 +202,9 @@ func makeError(c ErrorCode, desc string, err error) Error {
// IsErrorCode returns whether or not the provided error is a script error with // IsErrorCode returns whether or not the provided error is a script error with
// the provided error code. // the provided error code.
func IsErrorCode(err error, c ErrorCode) bool { func IsErrorCode(err error, c ErrorCode) bool {
if err, ok := err.(Error); ok { var errError Error
return err.ErrorCode == c if ok := errors.As(err, &errError); ok {
return errError.ErrorCode == c
} }
return false return false

View File

@ -11,6 +11,7 @@ import (
"container/list" "container/list"
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"github.com/pkg/errors"
"hash/crc32" "hash/crc32"
"io" "io"
"os" "os"
@ -379,7 +380,8 @@ func (s *blockStore) writeData(data []byte, fieldName string) error {
n, err := wc.curFile.file.WriteAt(data, int64(wc.curOffset)) n, err := wc.curFile.file.WriteAt(data, int64(wc.curOffset))
wc.curOffset += uint32(n) wc.curOffset += uint32(n)
if err != nil { if err != nil {
if pathErr, isOk := err.(*os.PathError); isOk && pathErr.Err == syscall.ENOSPC { var pathErr *os.PathError
if ok := errors.As(err, &pathErr); ok && pathErr.Err == syscall.ENOSPC {
log.Errorf("No space left on the hard disk, exiting...") log.Errorf("No space left on the hard disk, exiting...")
os.Exit(1) os.Exit(1)
} }

2
go.mod
View File

@ -15,7 +15,7 @@ require (
github.com/jessevdk/go-flags v1.4.0 github.com/jessevdk/go-flags v1.4.0
github.com/jrick/logrotate v1.0.0 github.com/jrick/logrotate v1.0.0
github.com/kr/pretty v0.1.0 // indirect github.com/kr/pretty v0.1.0 // indirect
github.com/pkg/errors v0.8.1 github.com/pkg/errors v0.9.1
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 // indirect golang.org/x/net v0.0.0-20190620200207-3b0461eec859 // indirect
golang.org/x/sys v0.0.0-20190426135247-a129542de9ae // indirect golang.org/x/sys v0.0.0-20190426135247-a129542de9ae // indirect

2
go.sum
View File

@ -33,6 +33,8 @@ github.com/onsi/gomega v1.4.1 h1:PZSj/UFNaVp3KxrzHOcS7oyuWA7LoOY/77yCTEFu21U=
github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=

View File

@ -6,6 +6,7 @@ package main
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
"net" "net"
"net/http" "net/http"
_ "net/http/pprof" _ "net/http/pprof"
@ -293,7 +294,8 @@ func loadBlockDB() (database.DB, error) {
if err != nil { if err != nil {
// Return the error if it's not because the database doesn't // Return the error if it's not because the database doesn't
// exist. // exist.
if dbErr, ok := err.(database.Error); !ok || dbErr.ErrorCode != var dbErr database.Error
if ok := errors.As(err, &dbErr); !ok || dbErr.ErrorCode !=
database.ErrDbDoesNotExist { database.ErrDbDoesNotExist {
return nil, err return nil, err

View File

@ -7,6 +7,7 @@ package mempool
import ( import (
"github.com/kaspanet/kaspad/blockdag" "github.com/kaspanet/kaspad/blockdag"
"github.com/kaspanet/kaspad/wire" "github.com/kaspanet/kaspad/wire"
"github.com/pkg/errors"
) )
// RuleError identifies a rule violation. It is used to indicate that // RuleError identifies a rule violation. It is used to indicate that
@ -63,15 +64,16 @@ func dagRuleError(dagErr blockdag.RuleError) RuleError {
// was successfully extracted. // was successfully extracted.
func extractRejectCode(err error) (wire.RejectCode, bool) { func extractRejectCode(err error) (wire.RejectCode, bool) {
// Pull the underlying error out of a RuleError. // Pull the underlying error out of a RuleError.
if rerr, ok := err.(RuleError); ok { var ruleErr RuleError
err = rerr.Err if ok := errors.As(err, &ruleErr); ok {
err = ruleErr.Err
} }
switch err := err.(type) { var dagRuleErr blockdag.RuleError
case blockdag.RuleError: if errors.As(err, &dagRuleErr) {
// Convert the DAG error to a reject code. // Convert the DAG error to a reject code.
var code wire.RejectCode var code wire.RejectCode
switch err.ErrorCode { switch dagRuleErr.ErrorCode {
// Rejected due to duplicate. // Rejected due to duplicate.
case blockdag.ErrDuplicateBlock: case blockdag.ErrDuplicateBlock:
code = wire.RejectDuplicate code = wire.RejectDuplicate
@ -92,11 +94,14 @@ func extractRejectCode(err error) (wire.RejectCode, bool) {
} }
return code, true return code, true
}
case TxRuleError: var trErr TxRuleError
return err.RejectCode, true if errors.As(err, &trErr) {
return trErr.RejectCode, true
}
case nil: if err == nil {
return wire.RejectInvalid, false return wire.RejectInvalid, false
} }

View File

@ -811,8 +811,9 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([]
// transactions are allowed into blocks. // transactions are allowed into blocks.
err := blockdag.CheckTransactionSanity(tx, subnetworkID) err := blockdag.CheckTransactionSanity(tx, subnetworkID)
if err != nil { if err != nil {
if cerr, ok := err.(blockdag.RuleError); ok { var ruleErr blockdag.RuleError
return nil, nil, dagRuleError(cerr) if ok := errors.As(err, &ruleErr); ok {
return nil, nil, dagRuleError(ruleErr)
} }
return nil, nil, err return nil, nil, err
} }
@ -918,8 +919,9 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([]
// with respect to its defined relative lock times. // with respect to its defined relative lock times.
sequenceLock, err := mp.cfg.CalcSequenceLockNoLock(tx, mp.mpUTXOSet) sequenceLock, err := mp.cfg.CalcSequenceLockNoLock(tx, mp.mpUTXOSet)
if err != nil { if err != nil {
if cerr, ok := err.(blockdag.RuleError); ok { var dagRuleErr blockdag.RuleError
return nil, nil, dagRuleError(cerr) if ok := errors.As(err, &dagRuleErr); ok {
return nil, nil, dagRuleError(dagRuleErr)
} }
return nil, nil, err return nil, nil, err
} }
@ -933,7 +935,8 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([]
// transaction mass. // transaction mass.
err = blockdag.ValidateTxMass(tx, mp.mpUTXOSet) err = blockdag.ValidateTxMass(tx, mp.mpUTXOSet)
if err != nil { if err != nil {
if ruleError, ok := err.(blockdag.RuleError); ok { var ruleError blockdag.RuleError
if ok := errors.As(err, &ruleError); ok {
return nil, nil, dagRuleError(ruleError) return nil, nil, dagRuleError(ruleError)
} }
return nil, nil, err return nil, nil, err
@ -946,8 +949,9 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([]
txFee, err := blockdag.CheckTransactionInputsAndCalulateFee(tx, nextBlockBlueScore, txFee, err := blockdag.CheckTransactionInputsAndCalulateFee(tx, nextBlockBlueScore,
mp.mpUTXOSet, mp.cfg.DAGParams, false) mp.mpUTXOSet, mp.cfg.DAGParams, false)
if err != nil { if err != nil {
if cerr, ok := err.(blockdag.RuleError); ok { var dagRuleErr blockdag.RuleError
return nil, nil, dagRuleError(cerr) if ok := errors.As(err, &dagRuleErr); ok {
return nil, nil, dagRuleError(dagRuleErr)
} }
return nil, nil, err return nil, nil, err
} }
@ -1006,8 +1010,9 @@ func (mp *TxPool) maybeAcceptTransaction(tx *util.Tx, rejectDupOrphans bool) ([]
err = blockdag.ValidateTransactionScripts(tx, mp.mpUTXOSet, err = blockdag.ValidateTransactionScripts(tx, mp.mpUTXOSet,
txscript.StandardVerifyFlags, mp.cfg.SigCache) txscript.StandardVerifyFlags, mp.cfg.SigCache)
if err != nil { if err != nil {
if cerr, ok := err.(blockdag.RuleError); ok { var dagRuleErr blockdag.RuleError
return nil, nil, dagRuleError(cerr) if ok := errors.As(err, &dagRuleErr); ok {
return nil, nil, dagRuleError(dagRuleErr)
} }
return nil, nil, err return nil, nil, err
} }

View File

@ -6,6 +6,7 @@ package mempool
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"testing" "testing"
"time" "time"
@ -313,24 +314,24 @@ func TestCheckTransactionStandard(t *testing.T) {
} }
// Ensure error type is a TxRuleError inside of a RuleError. // Ensure error type is a TxRuleError inside of a RuleError.
rerr, ok := err.(RuleError) var ruleErr RuleError
if !ok { if !errors.As(err, &ruleErr) {
t.Errorf("checkTransactionStandard (%s): unexpected "+ t.Errorf("checkTransactionStandard (%s): unexpected "+
"error type - got %T", test.name, err) "error type - got %T", test.name, err)
continue continue
} }
txrerr, ok := rerr.Err.(TxRuleError) txRuleErr, ok := ruleErr.Err.(TxRuleError)
if !ok { if !ok {
t.Errorf("checkTransactionStandard (%s): unexpected "+ t.Errorf("checkTransactionStandard (%s): unexpected "+
"error type - got %T", test.name, rerr.Err) "error type - got %T", test.name, ruleErr.Err)
continue continue
} }
// Ensure the reject code is the expected one. // Ensure the reject code is the expected one.
if txrerr.RejectCode != test.code { if txRuleErr.RejectCode != test.code {
t.Errorf("checkTransactionStandard (%s): unexpected "+ t.Errorf("checkTransactionStandard (%s): unexpected "+
"error code - got %v, want %v", test.name, "error code - got %v, want %v", test.name,
txrerr.RejectCode, test.code) txRuleErr.RejectCode, test.code)
continue continue
} }
} }

View File

@ -392,7 +392,7 @@ func (sm *SyncManager) handleTxMsg(tmsg *txMsg) {
// simply rejected as opposed to something actually going wrong, // simply rejected as opposed to something actually going wrong,
// so log it as such. Otherwise, something really did go wrong, // so log it as such. Otherwise, something really did go wrong,
// so log it as an actual error. // so log it as an actual error.
if _, ok := err.(mempool.RuleError); ok { if errors.As(err, &mempool.RuleError{}) {
log.Debugf("Rejected transaction %s from %s: %s", log.Debugf("Rejected transaction %s from %s: %s",
txID, peer, err) txID, peer, err)
} else { } else {
@ -491,14 +491,15 @@ func (sm *SyncManager) handleBlockMsg(bmsg *blockMsg) {
// rejected as opposed to something actually going wrong, so log // rejected as opposed to something actually going wrong, so log
// it as such. Otherwise, something really did go wrong, so log // it as such. Otherwise, something really did go wrong, so log
// it as an actual error. // it as an actual error.
if _, ok := err.(blockdag.RuleError); ok { if errors.As(err, &blockdag.RuleError{}) {
log.Infof("Rejected block %s from %s: %s", blockHash, log.Infof("Rejected block %s from %s: %s", blockHash,
peer, err) peer, err)
} else { } else {
log.Errorf("Failed to process block %s: %s", log.Errorf("Failed to process block %s: %s",
blockHash, err) blockHash, err)
} }
if dbErr, ok := err.(database.Error); ok && dbErr.ErrorCode == var dbErr database.Error
if ok := errors.As(err, &dbErr); ok && dbErr.ErrorCode ==
database.ErrCorruption { database.ErrCorruption {
panic(dbErr) panic(dbErr)
} }

View File

@ -1113,7 +1113,7 @@ func (p *Peer) isAllowedReadError(err error) bool {
} }
// Don't allow the error if it's not specifically a malformed message error. // Don't allow the error if it's not specifically a malformed message error.
if _, ok := err.(*wire.MessageError); !ok { if msgErr := &(wire.MessageError{}); !errors.As(err, &msgErr) {
return false return false
} }
@ -1147,7 +1147,8 @@ func (p *Peer) shouldHandleReadError(err error) bool {
if err == io.EOF { if err == io.EOF {
return false return false
} }
if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() { var opErr *net.OpError
if ok := errors.As(err, &opErr); ok && !opErr.Temporary() {
return false return false
} }

View File

@ -121,8 +121,9 @@ detect if a command is unimplemented by the remote RPC server:
netTotals, err := client.GetNetTotals() netTotals, err := client.GetNetTotals()
if err != nil { if err != nil {
if jerr, ok := err.(*rpcmodel.RPCError); ok { var jErr *rpcmodel.RPCError
switch jerr.Code { if errors.As(err, jErr) {
switch jErr.Code {
case rpcmodel.ErrRPCUnimplemented: case rpcmodel.ErrRPCUnimplemented:
// Handle not implemented error // Handle not implemented error

View File

@ -395,7 +395,8 @@ func (c *Client) shouldLogReadError(err error) bool {
if err == io.EOF { if err == io.EOF {
return false return false
} }
if opErr, ok := err.(*net.OpError); ok && !opErr.Temporary() { var opErr *net.OpError
if ok := errors.As(err, &opErr); ok && !opErr.Temporary() {
return false return false
} }

View File

@ -5,6 +5,7 @@
package rpcmodel_test package rpcmodel_test
import ( import (
"github.com/pkg/errors"
"reflect" "reflect"
"testing" "testing"
@ -48,12 +49,17 @@ func TestCommandMethod(t *testing.T) {
continue continue
} }
if err != nil { if err != nil {
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
if gotErrorCode != test.err.(rpcmodel.Error).ErrorCode { errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
var testRPCModelErr rpcmodel.Error
errors.As(err, &testRPCModelErr)
testErrorCode := testRPCModelErr.ErrorCode
if gotErrorCode != testErrorCode {
t.Errorf("Test #%d (%s) mismatched error code "+ t.Errorf("Test #%d (%s) mismatched error code "+
"- got %v (%v), want %v", i, test.name, "- got %v (%v), want %v", i, test.name,
gotErrorCode, err, gotErrorCode, err,
test.err.(rpcmodel.Error).ErrorCode) testErrorCode)
continue continue
} }
@ -101,12 +107,17 @@ func TestMethodUsageFlags(t *testing.T) {
continue continue
} }
if err != nil { if err != nil {
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
if gotErrorCode != test.err.(rpcmodel.Error).ErrorCode { errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
var testRPCModelErr rpcmodel.Error
errors.As(err, &testRPCModelErr)
testErrorCode := testRPCModelErr.ErrorCode
if gotErrorCode != testErrorCode {
t.Errorf("Test #%d (%s) mismatched error code "+ t.Errorf("Test #%d (%s) mismatched error code "+
"- got %v (%v), want %v", i, test.name, "- got %v (%v), want %v", i, test.name,
gotErrorCode, err, gotErrorCode, err,
test.err.(rpcmodel.Error).ErrorCode) testErrorCode)
continue continue
} }
@ -159,12 +170,17 @@ func TestMethodUsageText(t *testing.T) {
continue continue
} }
if err != nil { if err != nil {
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
if gotErrorCode != test.err.(rpcmodel.Error).ErrorCode { errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
var testRPCModelErr rpcmodel.Error
errors.As(err, &testRPCModelErr)
testErrorCode := testRPCModelErr.ErrorCode
if gotErrorCode != testErrorCode {
t.Errorf("Test #%d (%s) mismatched error code "+ t.Errorf("Test #%d (%s) mismatched error code "+
"- got %v (%v), want %v", i, test.name, "- got %v (%v), want %v", i, test.name,
gotErrorCode, err, gotErrorCode, err,
test.err.(rpcmodel.Error).ErrorCode) testErrorCode)
continue continue
} }

View File

@ -7,6 +7,7 @@ package rpcmodel
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/pkg/errors"
"reflect" "reflect"
"strconv" "strconv"
"strings" "strings"
@ -136,10 +137,11 @@ func UnmarshalCommand(r *Request) (interface{}, error) {
// The most common error is the wrong type, so // The most common error is the wrong type, so
// explicitly detect that error and make it nicer. // explicitly detect that error and make it nicer.
fieldName := strings.ToLower(rt.Field(i).Name) fieldName := strings.ToLower(rt.Field(i).Name)
if jerr, ok := err.(*json.UnmarshalTypeError); ok { var jsonErr *json.UnmarshalTypeError
if ok := errors.As(err, &jsonErr); ok {
str := fmt.Sprintf("parameter #%d '%s' must "+ str := fmt.Sprintf("parameter #%d '%s' must "+
"be type %s (got %s)", i+1, fieldName, "be type %s (got %s)", i+1, fieldName,
jerr.Type, jerr.Value) jsonErr.Type, jsonErr.Value)
return nil, makeError(ErrInvalidType, str) return nil, makeError(ErrInvalidType, str)
} }

View File

@ -6,6 +6,7 @@ package rpcmodel_test
import ( import (
"encoding/json" "encoding/json"
"github.com/pkg/errors"
"math" "math"
"reflect" "reflect"
"testing" "testing"
@ -337,7 +338,9 @@ func TestAssignFieldErrors(t *testing.T) {
"want %T", i, test.name, err, test.err) "want %T", i, test.name, err, test.err)
continue continue
} }
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
if gotErrorCode != test.err.ErrorCode { if gotErrorCode != test.err.ErrorCode {
t.Errorf("Test #%d (%s) mismatched error code - got "+ t.Errorf("Test #%d (%s) mismatched error code - got "+
"%v (%v), want %v", i, test.name, gotErrorCode, "%v (%v), want %v", i, test.name, gotErrorCode,
@ -391,7 +394,9 @@ func TestNewCommandErrors(t *testing.T) {
"want %T", i, test.name, err, test.err) "want %T", i, test.name, err, test.err)
continue continue
} }
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
if gotErrorCode != test.err.ErrorCode { if gotErrorCode != test.err.ErrorCode {
t.Errorf("Test #%d (%s) mismatched error code - got "+ t.Errorf("Test #%d (%s) mismatched error code - got "+
"%v (%v), want %v", i, test.name, gotErrorCode, "%v (%v), want %v", i, test.name, gotErrorCode,
@ -439,7 +444,9 @@ func TestMarshalCommandErrors(t *testing.T) {
"want %T", i, test.name, err, test.err) "want %T", i, test.name, err, test.err)
continue continue
} }
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
if gotErrorCode != test.err.ErrorCode { if gotErrorCode != test.err.ErrorCode {
t.Errorf("Test #%d (%s) mismatched error code - got "+ t.Errorf("Test #%d (%s) mismatched error code - got "+
"%v (%v), want %v", i, test.name, gotErrorCode, "%v (%v), want %v", i, test.name, gotErrorCode,
@ -508,7 +515,9 @@ func TestUnmarshalCommandErrors(t *testing.T) {
"want %T", i, test.name, err, test.err) "want %T", i, test.name, err, test.err)
continue continue
} }
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
if gotErrorCode != test.err.ErrorCode { if gotErrorCode != test.err.ErrorCode {
t.Errorf("Test #%d (%s) mismatched error code - got "+ t.Errorf("Test #%d (%s) mismatched error code - got "+
"%v (%v), want %v", i, test.name, gotErrorCode, "%v (%v), want %v", i, test.name, gotErrorCode,

View File

@ -5,6 +5,7 @@
package rpcmodel_test package rpcmodel_test
import ( import (
"github.com/pkg/errors"
"reflect" "reflect"
"testing" "testing"
@ -703,7 +704,9 @@ func TestGenerateHelpErrors(t *testing.T) {
"want %T", i, test.name, err, test.err) "want %T", i, test.name, err, test.err)
continue continue
} }
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
if gotErrorCode != test.err.ErrorCode { if gotErrorCode != test.err.ErrorCode {
t.Errorf("Test #%d (%s) mismatched error code - got "+ t.Errorf("Test #%d (%s) mismatched error code - got "+
"%v (%v), want %v", i, test.name, gotErrorCode, "%v (%v), want %v", i, test.name, gotErrorCode,

View File

@ -6,6 +6,7 @@ package rpcmodel_test
import ( import (
"encoding/json" "encoding/json"
"github.com/pkg/errors"
"reflect" "reflect"
"testing" "testing"
@ -114,7 +115,8 @@ func TestMiscErrors(t *testing.T) {
// supported. // supported.
wantErr := rpcmodel.Error{ErrorCode: rpcmodel.ErrInvalidType} wantErr := rpcmodel.Error{ErrorCode: rpcmodel.ErrInvalidType}
_, err = rpcmodel.MarshalResponse(make(chan int), nil, nil) _, err = rpcmodel.MarshalResponse(make(chan int), nil, nil)
if jerr, ok := err.(rpcmodel.Error); !ok || jerr.ErrorCode != wantErr.ErrorCode { var rpcModelErr rpcmodel.Error
if ok := errors.As(err, &rpcModelErr); !ok || rpcModelErr.ErrorCode != wantErr.ErrorCode {
t.Errorf("MarshalResult: did not receive expected error - got "+ t.Errorf("MarshalResult: did not receive expected error - got "+
"%v (%[1]T), want %v (%[2]T)", err, wantErr) "%v (%[1]T), want %v (%[2]T)", err, wantErr)
return return
@ -123,7 +125,7 @@ func TestMiscErrors(t *testing.T) {
// Force an error in MarshalResponse by giving it a result type that // Force an error in MarshalResponse by giving it a result type that
// can't be marshalled. // can't be marshalled.
_, err = rpcmodel.MarshalResponse(1, make(chan int), nil) _, err = rpcmodel.MarshalResponse(1, make(chan int), nil)
if _, ok := err.(*json.UnsupportedTypeError); !ok { if jErr := &(json.UnsupportedTypeError{}); !errors.As(err, &jErr) {
wantErr := &json.UnsupportedTypeError{} wantErr := &json.UnsupportedTypeError{}
t.Errorf("MarshalResult: did not receive expected error - got "+ t.Errorf("MarshalResult: did not receive expected error - got "+
"%v (%[1]T), want %T", err, wantErr) "%v (%[1]T), want %T", err, wantErr)

View File

@ -5,6 +5,7 @@
package rpcmodel_test package rpcmodel_test
import ( import (
"github.com/pkg/errors"
"reflect" "reflect"
"sort" "sort"
"testing" "testing"
@ -214,7 +215,9 @@ func TestRegisterCmdErrors(t *testing.T) {
"want %T", i, test.name, err, test.err) "want %T", i, test.name, err, test.err)
continue continue
} }
gotErrorCode := err.(rpcmodel.Error).ErrorCode var gotRPCModelErr rpcmodel.Error
errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
if gotErrorCode != test.err.ErrorCode { if gotErrorCode != test.err.ErrorCode {
t.Errorf("Test #%d (%s) mismatched error code - got "+ t.Errorf("Test #%d (%s) mismatched error code - got "+
"%v, want %v", i, test.name, gotErrorCode, "%v, want %v", i, test.name, gotErrorCode,

View File

@ -7,6 +7,7 @@ package rpcmodel_test
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"reflect" "reflect"
"testing" "testing"
@ -1122,12 +1123,15 @@ func TestRPCServerCommandErrors(t *testing.T) {
continue continue
} }
if terr, ok := test.err.(rpcmodel.Error); ok { var testErr rpcmodel.Error
gotErrorCode := err.(rpcmodel.Error).ErrorCode if errors.As(err, &testErr) {
if gotErrorCode != terr.ErrorCode { var gotRPCModelErr rpcmodel.Error
errors.As(err, &gotRPCModelErr)
gotErrorCode := gotRPCModelErr.ErrorCode
if gotErrorCode != testErr.ErrorCode {
t.Errorf("Test #%d (%s) mismatched error code "+ t.Errorf("Test #%d (%s) mismatched error code "+
"- got %v (%v), want %v", i, test.name, "- got %v (%v), want %v", i, test.name,
gotErrorCode, terr, terr.ErrorCode) gotErrorCode, testErr, testErr.ErrorCode)
continue continue
} }
} }

View File

@ -343,7 +343,7 @@ func handleGetBlockTemplateProposal(s *Server, request *rpcmodel.TemplateRequest
} }
if err := s.cfg.DAG.CheckConnectBlockTemplate(block); err != nil { if err := s.cfg.DAG.CheckConnectBlockTemplate(block); err != nil {
if _, ok := err.(blockdag.RuleError); !ok { if !errors.As(err, &blockdag.RuleError{}) {
errStr := fmt.Sprintf("Failed to process block proposal: %s", err) errStr := fmt.Sprintf("Failed to process block proposal: %s", err)
log.Error(errStr) log.Error(errStr)
return nil, &rpcmodel.RPCError{ return nil, &rpcmodel.RPCError{
@ -365,8 +365,8 @@ func handleGetBlockTemplateProposal(s *Server, request *rpcmodel.TemplateRequest
func dagErrToGBTErrString(err error) string { func dagErrToGBTErrString(err error) string {
// When the passed error is not a RuleError, just return a generic // When the passed error is not a RuleError, just return a generic
// rejected string with the error text. // rejected string with the error text.
ruleErr, ok := err.(blockdag.RuleError) var ruleErr blockdag.RuleError
if !ok { if !errors.As(err, &ruleErr) {
return "rejected: " + err.Error() return "rejected: " + err.Error()
} }

View File

@ -9,6 +9,7 @@ import (
"github.com/kaspanet/kaspad/util" "github.com/kaspanet/kaspad/util"
"github.com/kaspanet/kaspad/util/daghash" "github.com/kaspanet/kaspad/util/daghash"
"github.com/kaspanet/kaspad/wire" "github.com/kaspanet/kaspad/wire"
"github.com/pkg/errors"
) )
// handleSendRawTransaction implements the sendRawTransaction command. // handleSendRawTransaction implements the sendRawTransaction command.
@ -42,7 +43,7 @@ func handleSendRawTransaction(s *Server, cmd interface{}, closeChan <-chan struc
// so log it as an actual error. In both cases, a JSON-RPC // so log it as an actual error. In both cases, a JSON-RPC
// error is returned to the client with the deserialization // error is returned to the client with the deserialization
// error code // error code
if _, ok := err.(mempool.RuleError); ok { if errors.As(err, &mempool.RuleError{}) {
log.Debugf("Rejected transaction %s: %s", tx.ID(), log.Debugf("Rejected transaction %s: %s", tx.ID(),
err) err)
} else { } else {

View File

@ -393,8 +393,9 @@ func parseCmd(request *rpcmodel.Request) *parsedRPCCmd {
if err != nil { if err != nil {
// When the error is because the method is not registered, // When the error is because the method is not registered,
// produce a method not found RPC error. // produce a method not found RPC error.
if jerr, ok := err.(rpcmodel.Error); ok && var rpcModelErr rpcmodel.Error
jerr.ErrorCode == rpcmodel.ErrUnregisteredMethod { if ok := errors.As(err, &rpcModelErr); ok &&
rpcModelErr.ErrorCode == rpcmodel.ErrUnregisteredMethod {
parsedCmd.err = rpcmodel.ErrRPCMethodNotFound parsedCmd.err = rpcmodel.ErrRPCMethodNotFound
return &parsedCmd return &parsedCmd
@ -610,7 +611,7 @@ func (s *Server) Start() {
// using the default size for read/write buffers. // using the default size for read/write buffers.
ws, err := websocket.Upgrade(w, r, nil, 0, 0) ws, err := websocket.Upgrade(w, r, nil, 0, 0)
if err != nil { if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok { if !errors.As(err, &websocket.HandshakeError{}) {
log.Errorf("Unexpected websocket error: %s", log.Errorf("Unexpected websocket error: %s",
err) err)
} }

View File

@ -6,6 +6,7 @@ package txscript
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
) )
// ErrorCode identifies a kind of script error. // ErrorCode identifies a kind of script error.
@ -308,8 +309,9 @@ func scriptError(c ErrorCode, desc string) Error {
// IsErrorCode returns whether or not the provided error is a script error with // IsErrorCode returns whether or not the provided error is a script error with
// the provided error code. // the provided error code.
func IsErrorCode(err error, c ErrorCode) bool { func IsErrorCode(err error, c ErrorCode) bool {
if err, ok := err.(Error); ok { var errError Error
return err.ErrorCode == c if ok := errors.As(err, &errError); ok {
return errError.ErrorCode == c
} }
return false return false

View File

@ -334,9 +334,10 @@ func testScripts(t *testing.T, tests [][]interface{}, useSigCache bool) {
} }
} }
if !success { if !success {
if serr, ok := err.(Error); ok { var scriptErr Error
if ok := errors.As(err, &scriptErr); ok {
t.Errorf("%s: want error codes %v, got %v", name, t.Errorf("%s: want error codes %v, got %v", name,
allowedErrorCodes, serr.ErrorCode) allowedErrorCodes, scriptErr.ErrorCode)
continue continue
} }
t.Errorf("%s: want error codes %v, got err: %v (%T)", t.Errorf("%s: want error codes %v, got err: %v (%T)",

View File

@ -6,6 +6,7 @@ package txscript
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"testing" "testing"
) )
@ -300,7 +301,8 @@ func TestExceedMaxScriptSize(t *testing.T) {
// Ensure adding data that would exceed the maximum size of the script // Ensure adding data that would exceed the maximum size of the script
// does not add the data. // does not add the data.
script, err := builder.AddData([]byte{0x00}).Script() script, err := builder.AddData([]byte{0x00}).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { var errScriptNotCanonical ErrScriptNotCanonical
if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatalf("ScriptBuilder.AddData allowed exceeding max script "+ t.Fatalf("ScriptBuilder.AddData allowed exceeding max script "+
"size: %v", len(script)) "size: %v", len(script))
} }
@ -313,7 +315,7 @@ func TestExceedMaxScriptSize(t *testing.T) {
// script does not add the data. // script does not add the data.
builder.Reset().AddFullData(make([]byte, MaxScriptSize-3)) builder.Reset().AddFullData(make([]byte, MaxScriptSize-3))
script, err = builder.AddOp(Op0).Script() script, err = builder.AddOp(Op0).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatalf("ScriptBuilder.AddOp unexpected modified script - "+ t.Fatalf("ScriptBuilder.AddOp unexpected modified script - "+
"got len %d, want len %d", len(script), len(origScript)) "got len %d, want len %d", len(script), len(origScript))
} }
@ -326,7 +328,7 @@ func TestExceedMaxScriptSize(t *testing.T) {
// script does not add the data. // script does not add the data.
builder.Reset().AddFullData(make([]byte, MaxScriptSize-3)) builder.Reset().AddFullData(make([]byte, MaxScriptSize-3))
script, err = builder.AddInt64(0).Script() script, err = builder.AddInt64(0).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatalf("ScriptBuilder.AddInt64 unexpected modified script - "+ t.Fatalf("ScriptBuilder.AddInt64 unexpected modified script - "+
"got len %d, want len %d", len(script), len(origScript)) "got len %d, want len %d", len(script), len(origScript))
} }
@ -351,7 +353,8 @@ func TestErroredScript(t *testing.T) {
t.Fatalf("ScriptBuilder.AddFullData unexpected error: %v", err) t.Fatalf("ScriptBuilder.AddFullData unexpected error: %v", err)
} }
script, err := builder.AddData([]byte{0x00, 0x00, 0x00, 0x00, 0x00}).Script() script, err := builder.AddData([]byte{0x00, 0x00, 0x00, 0x00, 0x00}).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { var errScriptNotCanonical ErrScriptNotCanonical
if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatalf("ScriptBuilder.AddData allowed exceeding max script "+ t.Fatalf("ScriptBuilder.AddData allowed exceeding max script "+
"size: %v", len(script)) "size: %v", len(script))
} }
@ -363,7 +366,7 @@ func TestErroredScript(t *testing.T) {
// Ensure adding data, even using the non-canonical path, to a script // Ensure adding data, even using the non-canonical path, to a script
// that has errored doesn't succeed. // that has errored doesn't succeed.
script, err = builder.AddFullData([]byte{0x00}).Script() script, err = builder.AddFullData([]byte{0x00}).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatal("ScriptBuilder.AddFullData succeeded on errored script") t.Fatal("ScriptBuilder.AddFullData succeeded on errored script")
} }
if !bytes.Equal(script, origScript) { if !bytes.Equal(script, origScript) {
@ -374,7 +377,7 @@ func TestErroredScript(t *testing.T) {
// Ensure adding data to a script that has errored doesn't succeed. // Ensure adding data to a script that has errored doesn't succeed.
script, err = builder.AddData([]byte{0x00}).Script() script, err = builder.AddData([]byte{0x00}).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatal("ScriptBuilder.AddData succeeded on errored script") t.Fatal("ScriptBuilder.AddData succeeded on errored script")
} }
if !bytes.Equal(script, origScript) { if !bytes.Equal(script, origScript) {
@ -385,7 +388,7 @@ func TestErroredScript(t *testing.T) {
// Ensure adding an opcode to a script that has errored doesn't succeed. // Ensure adding an opcode to a script that has errored doesn't succeed.
script, err = builder.AddOp(Op0).Script() script, err = builder.AddOp(Op0).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatal("ScriptBuilder.AddOp succeeded on errored script") t.Fatal("ScriptBuilder.AddOp succeeded on errored script")
} }
if !bytes.Equal(script, origScript) { if !bytes.Equal(script, origScript) {
@ -396,7 +399,7 @@ func TestErroredScript(t *testing.T) {
// Ensure adding an integer to a script that has errored doesn't // Ensure adding an integer to a script that has errored doesn't
// succeed. // succeed.
script, err = builder.AddInt64(0).Script() script, err = builder.AddInt64(0).Script()
if _, ok := err.(ErrScriptNotCanonical); !ok || err == nil { if !errors.As(err, &errScriptNotCanonical) || err == nil {
t.Fatal("ScriptBuilder.AddInt64 succeeded on errored script") t.Fatal("ScriptBuilder.AddInt64 succeeded on errored script")
} }
if !bytes.Equal(script, origScript) { if !bytes.Equal(script, origScript) {

View File

@ -6,6 +6,7 @@ package util_test
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"math" "math"
"reflect" "reflect"
@ -260,24 +261,25 @@ func TestBlockErrors(t *testing.T) {
// Ensure TxHash returns expected error on invalid indices. // Ensure TxHash returns expected error on invalid indices.
_, err = b.TxHash(-1) _, err = b.TxHash(-1)
if _, ok := err.(util.OutOfRangeError); !ok { var outOfRangeErr util.OutOfRangeError
if !errors.As(err, &outOfRangeErr) {
t.Errorf("TxHash: wrong error - got: %v <%T>, "+ t.Errorf("TxHash: wrong error - got: %v <%T>, "+
"want: <%T>", err, err, util.OutOfRangeError("")) "want: <%T>", err, err, util.OutOfRangeError(""))
} }
_, err = b.TxHash(len(Block100000.Transactions) + 1) _, err = b.TxHash(len(Block100000.Transactions) + 1)
if _, ok := err.(util.OutOfRangeError); !ok { if !errors.As(err, &outOfRangeErr) {
t.Errorf("TxHash: wrong error - got: %v <%T>, "+ t.Errorf("TxHash: wrong error - got: %v <%T>, "+
"want: <%T>", err, err, util.OutOfRangeError("")) "want: <%T>", err, err, util.OutOfRangeError(""))
} }
// Ensure Tx returns expected error on invalid indices. // Ensure Tx returns expected error on invalid indices.
_, err = b.Tx(-1) _, err = b.Tx(-1)
if _, ok := err.(util.OutOfRangeError); !ok { if !errors.As(err, &outOfRangeErr) {
t.Errorf("Tx: wrong error - got: %v <%T>, "+ t.Errorf("Tx: wrong error - got: %v <%T>, "+
"want: <%T>", err, err, util.OutOfRangeError("")) "want: <%T>", err, err, util.OutOfRangeError(""))
} }
_, err = b.Tx(len(Block100000.Transactions) + 1) _, err = b.Tx(len(Block100000.Transactions) + 1)
if _, ok := err.(util.OutOfRangeError); !ok { if !errors.As(err, &outOfRangeErr) {
t.Errorf("Tx: wrong error - got: %v <%T>, "+ t.Errorf("Tx: wrong error - got: %v <%T>, "+
"want: <%T>", err, err, util.OutOfRangeError("")) "want: <%T>", err, err, util.OutOfRangeError(""))
} }

View File

@ -7,7 +7,7 @@ package daghash
import ( import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"github.com/kaspanet/kaspad/testutil" "errors"
"math/big" "math/big"
"reflect" "reflect"
"testing" "testing"
@ -215,7 +215,7 @@ func TestNewHashFromStr(t *testing.T) {
t.Logf("Running %d tests", len(tests)) t.Logf("Running %d tests", len(tests))
for i, test := range tests { for i, test := range tests {
result, err := NewHashFromStr(test.in) result, err := NewHashFromStr(test.in)
if !testutil.AreErrorsEqual(err, test.err) { if !errors.Is(err, test.err) {
t.Errorf(unexpectedErrStr, i, err, test.err) t.Errorf(unexpectedErrStr, i, err, test.err)
continue continue
} else if err != nil { } else if err != nil {

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"strings" "strings"
@ -397,7 +398,7 @@ func TestVarIntNonCanonical(t *testing.T) {
// Decode from wire format. // Decode from wire format.
rbuf := bytes.NewReader(test.in) rbuf := bytes.NewReader(test.in)
val, err := ReadVarInt(rbuf) val, err := ReadVarInt(rbuf)
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
t.Errorf("ReadVarInt #%d (%s) unexpected error %v", i, t.Errorf("ReadVarInt #%d (%s) unexpected error %v", i,
test.name, err) test.name, err)
continue continue

View File

@ -7,6 +7,7 @@ package wire
import ( import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"github.com/pkg/errors"
"io" "io"
"net" "net"
"reflect" "reflect"
@ -360,7 +361,7 @@ func TestReadMessageWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+ t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+
"want: %v <%T>", i, err, err, "want: %v <%T>", i, err, err,
@ -438,7 +439,7 @@ func TestWriteMessageWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.err { if err != test.err {
t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+ t.Errorf("ReadMessage #%d wrong error got: %v <%T>, "+
"want: %v <%T>", i, err, err, "want: %v <%T>", i, err, err,

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"net" "net"
"reflect" "reflect"
@ -281,7 +282,7 @@ func TestAddrWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -301,7 +302,7 @@ func TestAddrWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -2,6 +2,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -232,7 +233,7 @@ func TestBlockLocatorWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -252,7 +253,7 @@ func TestBlockLocatorWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"math/rand" "math/rand"
"reflect" "reflect"
@ -146,7 +147,7 @@ func TestFeeFilterWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -166,7 +167,7 @@ func TestFeeFilterWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -126,7 +127,7 @@ func TestFilterAddWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -146,7 +147,7 @@ func TestFilterAddWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -172,7 +173,7 @@ func TestFilterLoadWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -192,7 +193,7 @@ func TestFilterLoadWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -207,7 +208,7 @@ func TestGetBlockInvsWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -227,7 +228,7 @@ func TestGetBlockInvsWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -2,6 +2,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -190,7 +191,7 @@ func TestGetBlockLocatorWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -210,7 +211,7 @@ func TestGetBlockLocatorWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -238,7 +239,7 @@ func TestGetDataWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -258,7 +259,7 @@ func TestGetDataWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -195,7 +196,7 @@ func TestGetHeadersWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -215,7 +216,7 @@ func TestGetHeadersWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -296,7 +297,7 @@ func TestHeadersWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -316,7 +317,7 @@ func TestHeadersWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -238,7 +239,7 @@ func TestInvWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -258,7 +259,7 @@ func TestInvWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -7,6 +7,7 @@ package wire
import ( import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -237,7 +238,7 @@ func TestMerkleBlockWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -257,7 +258,7 @@ func TestMerkleBlockWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -228,7 +229,7 @@ func TestNotFoundWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -248,7 +249,7 @@ func TestNotFoundWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -169,7 +170,7 @@ func TestPongWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -189,7 +190,7 @@ func TestPongWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"reflect" "reflect"
"testing" "testing"
@ -265,7 +266,7 @@ func TestRejectWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -285,7 +286,7 @@ func TestRejectWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)

View File

@ -6,6 +6,7 @@ package wire
import ( import (
"bytes" "bytes"
"github.com/pkg/errors"
"io" "io"
"net" "net"
"reflect" "reflect"
@ -81,7 +82,7 @@ func TestVersion(t *testing.T) {
// accounting for ":", "/" // accounting for ":", "/"
err = msg.AddUserAgent(strings.Repeat("t", err = msg.AddUserAgent(strings.Repeat("t",
MaxUserAgentLen-len(customUserAgent)-2+1), "") MaxUserAgentLen-len(customUserAgent)-2+1), "")
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
t.Errorf("AddUserAgent: expected error not received "+ t.Errorf("AddUserAgent: expected error not received "+
"- got %v, want %T", err, MessageError{}) "- got %v, want %T", err, MessageError{})
@ -274,7 +275,7 @@ func TestVersionWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.writeErr { if err != test.writeErr {
t.Errorf("KaspaEncode #%d wrong error got: %v, "+ t.Errorf("KaspaEncode #%d wrong error got: %v, "+
"want: %v", i, err, test.writeErr) "want: %v", i, err, test.writeErr)
@ -294,7 +295,7 @@ func TestVersionWireErrors(t *testing.T) {
// For errors which are not of type MessageError, check them for // For errors which are not of type MessageError, check them for
// equality. // equality.
if _, ok := err.(*MessageError); !ok { if msgErr := &(MessageError{}); !errors.As(err, &msgErr) {
if err != test.readErr { if err != test.readErr {
t.Errorf("KaspaDecode #%d wrong error got: %v, "+ t.Errorf("KaspaDecode #%d wrong error got: %v, "+
"want: %v", i, err, test.readErr) "want: %v", i, err, test.readErr)