core: add tests for (*Blockchain).verifyHeader

This commit is contained in:
Evgenii Stratonikov 2020-08-13 13:57:30 +03:00
parent e8cf4d96ce
commit 7f2a931fb6
2 changed files with 37 additions and 3 deletions

View file

@ -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)
}

View file

@ -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()