From 8723c91db96b85862f50357b0b8d8ffd90a4fcf3 Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Sat, 10 Mar 2018 21:44:05 -0800 Subject: [PATCH] types: Hash invoked for nil Data and Header should not panic Fixes https://github.com/tendermint/tendermint/issues/1298 Fixes https://github.com/tendermint/tendermint/issues/1299 Found while writing tests in https://github.com/tendermint/tendermint/pull/1300 --- types/block.go | 5 ++++- types/block_test.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/types/block.go b/types/block.go index 53fc6a81..970ca36f 100644 --- a/types/block.go +++ b/types/block.go @@ -179,7 +179,7 @@ type Header struct { // Hash returns the hash of the header. // Returns nil if ValidatorHash is missing. func (h *Header) Hash() cmn.HexBytes { - if len(h.ValidatorsHash) == 0 { + if h == nil || len(h.ValidatorsHash) == 0 { return nil } return merkle.SimpleHashFromMap(map[string]merkle.Hasher{ @@ -413,6 +413,9 @@ type Data struct { // Hash returns the hash of the data func (data *Data) Hash() cmn.HexBytes { + if data == nil { + return (Txs{}).Hash() + } if data.hash == nil { data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs } diff --git a/types/block_test.go b/types/block_test.go index 1fcfa469..e3e22743 100644 --- a/types/block_test.go +++ b/types/block_test.go @@ -3,7 +3,9 @@ package types import ( "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + crypto "github.com/tendermint/go-crypto" cmn "github.com/tendermint/tmlibs/common" ) @@ -73,3 +75,15 @@ func makeBlockID(hash string, partSetSize int, partSetHash string) BlockID { } } + +var nilBytes []byte + +func TestNilHeaderHashDoesntCrash(t *testing.T) { + assert.Equal(t, []byte((*Header)(nil).Hash()), nilBytes) + assert.Equal(t, []byte((new(Header)).Hash()), nilBytes) +} + +func TestNilDataHashDoesntCrash(t *testing.T) { + assert.Equal(t, []byte((*Data)(nil).Hash()), nilBytes) + assert.Equal(t, []byte(new(Data).Hash()), nilBytes) +}