From ad7ac99e70d2987440a48719b6c04a27e6b63973 Mon Sep 17 00:00:00 2001 From: Gary Rong Date: Tue, 12 Mar 2024 10:07:20 +0800 Subject: [PATCH] core: stop rewinding if chain is gapped or genesis is reached --- core/blockchain.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/core/blockchain.go b/core/blockchain.go index 55da62132e..bc2b51988b 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -662,7 +662,7 @@ func (bc *BlockChain) rewindHashHead(root common.Hash) (*types.Header, uint64) { if !bc.HasState(head.Root) { // If search limit is reached, return the genesis block as // the new chain head. - if head.Number.Uint64() < limit { + if head.Number.Uint64() <= limit { log.Info("Rewinding limit reached, resetting to genesis", "number", head.Number, "hash", head.Hash(), "limit", limit) return bc.genesisBlock.Header(), rootNumber } @@ -744,7 +744,20 @@ func (bc *BlockChain) rewindPathHead(root common.Hash) (*types.Header, uint64) { log.Info("Pivot block reached, resetting to genesis", "number", head.Number, "hash", head.Hash()) return bc.genesisBlock.Header(), rootNumber } - head = bc.GetHeader(head.ParentHash, head.Number.Uint64()-1) // Keep rewinding + // If the chain is gapped in the middle, return the genesis + // block as the new chain head + parent := bc.GetHeader(head.ParentHash, head.Number.Uint64()-1) // Keep rewinding + if parent == nil { + log.Error("Missing block in the middle, resetting to genesis", "number", head.Number.Uint64()-1, "hash", head.ParentHash) + return bc.genesisBlock.Header(), rootNumber + } + head = parent + + // If the genesis block is reached, stop searching. + if head.Number.Uint64() == 0 { + log.Info("Genesis block reached", "number", head.Number, "hash", head.Hash()) + return head, rootNumber + } } // Recover if the target state if it's not available yet. if !bc.HasState(head.Root) {