From 0c3b03617eb227ef272e024bd7ce116c9afd4e5a Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 19 Oct 2022 13:02:27 +0300 Subject: [PATCH] core: optimize HasBlock check for recent blocks When block is being spread through the network we can get a lot of invs with the same hash. Some more stale nodes may also announce previous or some earlier block. We can avoid full DB lookup for them and minimize inv handling time (timeouts in inv handler had happened in #2744). It doesn't affect tests, just makes node a little less likely to spend some considerable amount of time in the inv handler. --- pkg/core/blockchain.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 7e79f9b06d..08bce558b7 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -1714,6 +1714,16 @@ func (bc *Blockchain) HasTransaction(hash util.Uint256) bool { // HasBlock returns true if the blockchain contains the given // block hash. func (bc *Blockchain) HasBlock(hash util.Uint256) bool { + var height = bc.BlockHeight() + bc.headerHashesLock.RLock() + for i := int(height); i >= int(height)-4 && i >= 0; i-- { + if hash.Equals(bc.headerHashes[i]) { + bc.headerHashesLock.RUnlock() + return true + } + } + bc.headerHashesLock.RUnlock() + if header, err := bc.GetHeader(hash); err == nil { return header.Index <= bc.BlockHeight() }