From c3e73c5b7d8abfd9418049112b4876a45b6ed990 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Tue, 3 Mar 2020 15:34:03 +0300 Subject: [PATCH] core: don't reverify stale headers in addHeader During networked synchronization we expect there to be a lot of duplicate headers received and it makes no sense for us reverifying them. --- pkg/core/blockchain.go | 15 ++++++++++++++- pkg/core/blockchain_test.go | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index b8a53c393..bb73152c7 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -333,17 +333,30 @@ func (bc *Blockchain) AddBlock(block *block.Block) error { } // AddHeaders processes the given headers and add them to the -// HeaderHashList. +// HeaderHashList. It expects headers to be sorted by index. func (bc *Blockchain) AddHeaders(headers ...*block.Header) error { return bc.addHeaders(bc.config.VerifyBlocks, headers...) } +// addHeaders is an internal implementation of AddHeaders (`verify` parameter +// tells it to verify or not verify given headers). func (bc *Blockchain) addHeaders(verify bool, headers ...*block.Header) (err error) { var ( start = time.Now() batch = bc.dao.store.Batch() ) + if len(headers) > 0 { + var i int + curHeight := bc.HeaderHeight() + for i = range headers { + if headers[i].Index > curHeight { + break + } + } + headers = headers[i:] + } + if len(headers) == 0 { return nil } else if verify { diff --git a/pkg/core/blockchain_test.go b/pkg/core/blockchain_test.go index 614218737..168dd0fc8 100644 --- a/pkg/core/blockchain_test.go +++ b/pkg/core/blockchain_test.go @@ -30,7 +30,7 @@ func TestAddHeaders(t *testing.T) { assert.Equal(t, h3.Hash(), bc.CurrentHeaderHash()) // Add them again, they should not be added. - require.Error(t, bc.AddHeaders(h3, h2, h1)) + require.NoError(t, bc.AddHeaders(h3, h2, h1)) assert.Equal(t, h3.Index, bc.HeaderHeight()) assert.Equal(t, uint32(0), bc.BlockHeight())