From 7f2a931fb6206cdfc47c5cceb857964ed6dff34c Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Thu, 13 Aug 2020 13:57:30 +0300 Subject: [PATCH] core: add tests for (*Blockchain).verifyHeader --- pkg/core/blockchain.go | 13 ++++++++++--- pkg/core/blockchain_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 386d24dab..14353cdff 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -1179,15 +1179,22 @@ func (bc *Blockchain) ApplyPolicyToTxSet(txes []*transaction.Transaction) []*tra return txes } +// Various errors that could be returns upon header verification. +var ( + ErrHdrHashMismatch = errors.New("previous header hash doesn't match") + ErrHdrIndexMismatch = errors.New("previous header index doesn't match") + ErrHdrInvalidTimestamp = errors.New("block is not newer than the previous one") +) + func (bc *Blockchain) verifyHeader(currHeader, prevHeader *block.Header) error { if prevHeader.Hash() != currHeader.PrevHash { - return errors.New("previous header hash doesn't match") + return ErrHdrHashMismatch } if prevHeader.Index+1 != currHeader.Index { - return errors.New("previous header index doesn't match") + return ErrHdrIndexMismatch } if prevHeader.Timestamp >= currHeader.Timestamp { - return errors.New("block is not newer than the previous one") + return ErrHdrInvalidTimestamp } return bc.verifyHeaderWitnesses(currHeader, prevHeader) } diff --git a/pkg/core/blockchain_test.go b/pkg/core/blockchain_test.go index 655831d8c..eaebeb630 100644 --- a/pkg/core/blockchain_test.go +++ b/pkg/core/blockchain_test.go @@ -26,6 +26,33 @@ import ( "github.com/stretchr/testify/require" ) +func TestVerifyHeader(t *testing.T) { + bc := newTestChain(t) + defer bc.Close() + prev := bc.topBlock.Load().(*block.Block).Header() + t.Run("Invalid", func(t *testing.T) { + t.Run("Hash", func(t *testing.T) { + h := prev.Hash() + h[0] = ^h[0] + hdr := newBlock(bc.config, 1, h).Header() + require.True(t, errors.Is(bc.verifyHeader(hdr, prev), ErrHdrHashMismatch)) + }) + t.Run("Index", func(t *testing.T) { + hdr := newBlock(bc.config, 3, prev.Hash()).Header() + require.True(t, errors.Is(bc.verifyHeader(hdr, prev), ErrHdrIndexMismatch)) + }) + t.Run("Timestamp", func(t *testing.T) { + hdr := newBlock(bc.config, 1, prev.Hash()).Header() + hdr.Timestamp = 0 + require.True(t, errors.Is(bc.verifyHeader(hdr, prev), ErrHdrInvalidTimestamp)) + }) + }) + t.Run("Valid", func(t *testing.T) { + hdr := newBlock(bc.config, 1, prev.Hash()).Header() + require.NoError(t, bc.verifyHeader(hdr, prev)) + }) +} + func TestAddHeaders(t *testing.T) { bc := newTestChain(t) defer bc.Close()