From b0cf4b47571c93faa4eb67f2f17afbdf783f48ef Mon Sep 17 00:00:00 2001 From: Emmanuel Odeke Date: Sat, 28 Oct 2017 14:11:17 -0700 Subject: [PATCH] PubKeyFromBytes: return zero value PubKey on error Fixes https://github.com/tendermint/go-crypto/issues/48. This previously skewed up my fuzzing tests so ensure that on error we return the zero value PubKey. --- pub_key.go | 6 ++++-- pub_key_test.go | 7 +++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pub_key.go b/pub_key.go index 4d5c31b21..dfa012969 100644 --- a/pub_key.go +++ b/pub_key.go @@ -14,8 +14,10 @@ import ( ) func PubKeyFromBytes(pubKeyBytes []byte) (pubKey PubKey, err error) { - err = wire.ReadBinaryBytes(pubKeyBytes, &pubKey) - return + if err := wire.ReadBinaryBytes(pubKeyBytes, &pubKey); err != nil { + return PubKey{}, err + } + return pubKey, nil } //---------------------------------------- diff --git a/pub_key_test.go b/pub_key_test.go index 31642233c..097c5ea3b 100644 --- a/pub_key_test.go +++ b/pub_key_test.go @@ -6,6 +6,7 @@ import ( "github.com/btcsuite/btcutil/base58" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type keyData struct { @@ -39,3 +40,9 @@ func TestPubKeySecp256k1Address(t *testing.T) { assert.Equal(t, addr, addrB, "Expected addresses to match") } } + +func TestPubKeyInvalidDataProperReturnsEmpty(t *testing.T) { + pk, err := PubKeyFromBytes([]byte("foo")) + require.NotNil(t, err, "expecting a non-nil error") + require.True(t, pk.Empty(), "expecting an empty public key on error") +}