Skip to content

Improve utils/ error handling #1400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion utils/buffer/bounded_nonblocking_queue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func TestNewBoundedQueue(t *testing.T) {

// Case: maxSize < 1
_, err := NewBoundedQueue[bool](0, nil)
require.Error(err)
require.ErrorIs(err, errInvalidMaxSize)

// Case: maxSize == 1 and nil onEvict
b, err := NewBoundedQueue[bool](1, nil)
Expand Down
12 changes: 6 additions & 6 deletions utils/cb58/cb58.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@ package cb58
import (
"bytes"
"errors"
"fmt"
"math"

"github.com/mr-tron/base58/base58"

"github.com/ava-labs/avalanchego/utils/hashing"
)

const (
checksumLen = 4
)
const checksumLen = 4

var (
ErrBase58Decoding = errors.New("base58 decoding error")
ErrMissingChecksum = errors.New("input string is smaller than the checksum size")
errEncodingOverFlow = errors.New("encoding overflow")
errMissingChecksum = errors.New("input string is smaller than the checksum size")
errBadChecksum = errors.New("invalid input checksum")
)

Expand All @@ -41,10 +41,10 @@ func Encode(bytes []byte) (string, error) {
func Decode(str string) ([]byte, error) {
decodedBytes, err := base58.Decode(str)
if err != nil {
return nil, err
return nil, fmt.Errorf("%w: %s", ErrBase58Decoding, err)
}
if len(decodedBytes) < checksumLen {
return nil, errMissingChecksum
return nil, ErrMissingChecksum
}
// Verify the checksum
rawBytes := decodedBytes[:len(decodedBytes)-checksumLen]
Expand Down
14 changes: 8 additions & 6 deletions utils/compression/compressor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,21 +114,23 @@ func TestSizeLimiting(t *testing.T) {
continue
}
t.Run(compressionType.String(), func(t *testing.T) {
require := require.New(t)

compressor, err := compressorFunc(maxMessageSize)
require.NoError(t, err)
require.NoError(err)

data := make([]byte, maxMessageSize+1)
_, err = compressor.Compress(data) // should be too large
require.Error(t, err)
require.ErrorIs(err, ErrMsgTooLarge)

compressor2, err := compressorFunc(2 * maxMessageSize)
require.NoError(t, err)
require.NoError(err)

dataCompressed, err := compressor2.Compress(data)
require.NoError(t, err)
require.NoError(err)

_, err = compressor.Decompress(dataCompressed) // should be too large
require.Error(t, err)
require.ErrorIs(err, ErrDecompressedMsgTooLarge)
})
}
}
Expand Down Expand Up @@ -178,7 +180,7 @@ func fuzzHelper(f *testing.F, compressionType Type) {

if len(data) > maxMessageSize {
_, err := compressor.Compress(data)
require.Error(err)
require.ErrorIs(err, ErrMsgTooLarge)
}

compressed, err := compressor.Compress(data)
Expand Down
8 changes: 5 additions & 3 deletions utils/compression/type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,17 @@ import (
)

func TestTypeString(t *testing.T) {
require := require.New(t)

for _, compressionType := range []Type{TypeNone, TypeGzip, TypeZstd} {
s := compressionType.String()
parsedType, err := TypeFromString(s)
require.NoError(t, err)
require.Equal(t, compressionType, parsedType)
require.NoError(err)
require.Equal(compressionType, parsedType)
}

_, err := TypeFromString("unknown")
require.Error(t, err)
require.ErrorIs(err, errUnknownCompressionType)
}

func TestTypeMarshalJSON(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions utils/crypto/bls/public.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const PublicKeyLen = blst.BLST_P1_COMPRESS_BYTES

var (
ErrNoPublicKeys = errors.New("no public keys")
errFailedPublicKeyDecompress = errors.New("couldn't decompress public key")
ErrFailedPublicKeyDecompress = errors.New("couldn't decompress public key")
errInvalidPublicKey = errors.New("invalid public key")
errFailedPublicKeyAggregation = errors.New("couldn't aggregate public keys")
)
Expand All @@ -33,7 +33,7 @@ func PublicKeyToBytes(pk *PublicKey) []byte {
func PublicKeyFromBytes(pkBytes []byte) (*PublicKey, error) {
pk := new(PublicKey).Uncompress(pkBytes)
if pk == nil {
return nil, errFailedPublicKeyDecompress
return nil, ErrFailedPublicKeyDecompress
}
if !pk.KeyValidate() {
return nil, errInvalidPublicKey
Expand Down
2 changes: 1 addition & 1 deletion utils/crypto/bls/public_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func TestPublicKeyFromBytesWrongSize(t *testing.T) {

pkBytes := utils.RandomBytes(PublicKeyLen + 1)
_, err := PublicKeyFromBytes(pkBytes)
require.ErrorIs(err, errFailedPublicKeyDecompress)
require.ErrorIs(err, ErrFailedPublicKeyDecompress)
}

func TestPublicKeyBytes(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions utils/crypto/bls/signature.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
const SignatureLen = blst.BLST_P2_COMPRESS_BYTES

var (
errFailedSignatureDecompress = errors.New("couldn't decompress signature")
ErrFailedSignatureDecompress = errors.New("couldn't decompress signature")
errInvalidSignature = errors.New("invalid signature")
errNoSignatures = errors.New("no signatures")
errFailedSignatureAggregation = errors.New("couldn't aggregate signatures")
Expand All @@ -33,7 +33,7 @@ func SignatureToBytes(sig *Signature) []byte {
func SignatureFromBytes(sigBytes []byte) (*Signature, error) {
sig := new(Signature).Uncompress(sigBytes)
if sig == nil {
return nil, errFailedSignatureDecompress
return nil, ErrFailedSignatureDecompress
}
if !sig.SigValidate(false) {
return nil, errInvalidSignature
Expand Down
12 changes: 6 additions & 6 deletions utils/crypto/keychain/keychain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func TestNewLedgerKeychain(t *testing.T) {
// user request invalid number of addresses to derive
ledger := NewMockLedger(ctrl)
_, err := NewLedgerKeychain(ledger, 0)
require.Equal(err, ErrInvalidNumAddrsToDerive)
require.ErrorIs(err, ErrInvalidNumAddrsToDerive)

// ledger does not return expected number of derived addresses
ledger = NewMockLedger(ctrl)
Expand All @@ -38,7 +38,7 @@ func TestNewLedgerKeychain(t *testing.T) {
ledger = NewMockLedger(ctrl)
ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr}, errTest).Times(1)
_, err = NewLedgerKeychain(ledger, 1)
require.Equal(err, errTest)
require.ErrorIs(err, errTest)

// good path
ledger = NewMockLedger(ctrl)
Expand Down Expand Up @@ -160,7 +160,7 @@ func TestLedgerSigner_SignHash(t *testing.T) {
require.True(b)

_, err = s.SignHash(toSign)
require.Equal(err, errTest)
require.ErrorIs(err, errTest)

// good path 1 addr
ledger = NewMockLedger(ctrl)
Expand Down Expand Up @@ -218,7 +218,7 @@ func TestNewLedgerKeychainFromIndices(t *testing.T) {
// user request invalid number of indices
ledger := NewMockLedger(ctrl)
_, err := NewLedgerKeychainFromIndices(ledger, []uint32{})
require.Equal(err, ErrInvalidIndicesLength)
require.ErrorIs(err, ErrInvalidIndicesLength)

// ledger does not return expected number of derived addresses
ledger = NewMockLedger(ctrl)
Expand All @@ -230,7 +230,7 @@ func TestNewLedgerKeychainFromIndices(t *testing.T) {
ledger = NewMockLedger(ctrl)
ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr}, errTest).Times(1)
_, err = NewLedgerKeychainFromIndices(ledger, []uint32{0})
require.Equal(err, errTest)
require.ErrorIs(err, errTest)

// good path
ledger = NewMockLedger(ctrl)
Expand Down Expand Up @@ -382,7 +382,7 @@ func TestLedgerSignerFromIndices_SignHash(t *testing.T) {
require.True(b)

_, err = s.SignHash(toSign)
require.Equal(err, errTest)
require.ErrorIs(err, errTest)

// good path 1 addr
ledger = NewMockLedger(ctrl)
Expand Down
3 changes: 2 additions & 1 deletion utils/crypto/secp256k1/secp256k1.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const (
)

var (
ErrInvalidSig = errors.New("invalid signature")
errCompressed = errors.New("wasn't expecting a compressed key")
errMissingQuotes = errors.New("first and last characters should be quotes")
errMissingKeyPrefix = fmt.Errorf("private key missing %s prefix", PrivateKeyPrefix)
Expand Down Expand Up @@ -108,7 +109,7 @@ func (f *Factory) RecoverHashPublicKey(hash, sig []byte) (*PublicKey, error) {

rawPubkey, compressed, err := ecdsa.RecoverCompact(sig, hash)
if err != nil {
return nil, err
return nil, ErrInvalidSig
}

if compressed {
Expand Down
46 changes: 32 additions & 14 deletions utils/crypto/secp256k1/secp256k1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/cb58"
"github.com/ava-labs/avalanchego/utils/hashing"
)

Expand Down Expand Up @@ -100,7 +101,7 @@ func TestVerifyMutatedSignature(t *testing.T) {
copy(sig[32:], newSBytes[:])

_, err = f.RecoverPublicKey(msg, sig)
require.Error(err)
require.ErrorIs(err, errMutatedSig)
}

func TestPrivateKeySECP256K1RUnmarshalJSON(t *testing.T) {
Expand All @@ -123,30 +124,47 @@ func TestPrivateKeySECP256K1RUnmarshalJSONError(t *testing.T) {
tests := []struct {
label string
in []byte
err error
}{
{
"too short",
[]byte(`"`),
label: "too short",
in: []byte(`"`),
err: errMissingQuotes,
},
{
"missing start quote",
[]byte(`PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN"`),
label: "missing start quote",
in: []byte(`PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN"`),
err: errMissingQuotes,
},
{
"missing end quote",
[]byte(`"PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN`),
label: "missing end quote",
in: []byte(`"PrivateKey-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN`),
err: errMissingQuotes,
},
{
"incorrect prefix",
[]byte(`"PrivateKfy-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN"`),
label: "incorrect prefix",
in: []byte(`"PrivateKfy-ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN"`),
err: errMissingKeyPrefix,
},
{
`"PrivateKey-"`,
[]byte(`"PrivateKey-"`),
label: `"PrivateKey-"`,
in: []byte(`"PrivateKey-"`),
err: cb58.ErrBase58Decoding,
},
{
`"PrivateKey-1"`,
[]byte(`"PrivateKey-1"`),
label: `"PrivateKey-1"`,
in: []byte(`"PrivateKey-1"`),
err: cb58.ErrMissingChecksum,
},
{
label: `"PrivateKey-1"`,
in: []byte(`"PrivateKey-1"`),
err: cb58.ErrMissingChecksum,
},
{
label: `"PrivateKey-1"`,
in: []byte(`"PrivateKey-45PJLL"`),
err: errInvalidPrivateKeyLength,
},
}
for _, tt := range tests {
Expand All @@ -155,7 +173,7 @@ func TestPrivateKeySECP256K1RUnmarshalJSONError(t *testing.T) {

foo := PrivateKey{}
err := foo.UnmarshalJSON(tt.in)
require.Error(err)
require.ErrorIs(err, tt.err)
})
}
}
Expand Down
5 changes: 4 additions & 1 deletion utils/dynamicip/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package dynamicip

import (
"context"
"errors"
"fmt"
"net"
"strings"
Expand All @@ -23,6 +24,8 @@ const (
IFConfigMeName = "ifconfigme"
)

var errUnknownResolver = errors.New("unknown resolver")

// Resolver resolves our public IP
type Resolver interface {
// Resolve and return our public IP.
Expand All @@ -43,6 +46,6 @@ func NewResolver(resolverName string) (Resolver, error) {
case IFConfigMeName:
return &ifConfigResolver{url: ifConfigMeURL}, nil
default:
return nil, fmt.Errorf("got unknown resolver: %s", resolverName)
return nil, fmt.Errorf("%w: %s", errUnknownResolver, resolverName)
}
}
34 changes: 15 additions & 19 deletions utils/dynamicip/resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,44 +12,40 @@ import (

func TestNewResolver(t *testing.T) {
type test struct {
service string
validService bool
service string
err error
}
tests := []test{
{
service: OpenDNSName,
validService: true,
service: OpenDNSName,
err: nil,
},
{
service: IFConfigName,
validService: true,
service: IFConfigName,
err: nil,
},
{
service: IFConfigCoName,
validService: true,
service: IFConfigCoName,
err: nil,
},
{
service: IFConfigMeName,
validService: true,
service: IFConfigMeName,
err: nil,
},
{
service: strings.ToUpper(IFConfigMeName),
validService: true,
service: strings.ToUpper(IFConfigMeName),
err: nil,
},
{
service: "not a valid resolution service name",
validService: false,
service: "not a valid resolution service name",
err: errUnknownResolver,
},
}
for _, tt := range tests {
t.Run(tt.service, func(t *testing.T) {
require := require.New(t)
_, err := NewResolver(tt.service)
if tt.validService {
require.NoError(err)
} else {
require.Error(err)
}
require.ErrorIs(err, tt.err)
})
}
}
Loading