Skip to content

Commit

Permalink
Recovers current header if it's not found in DB on startup
Browse files Browse the repository at this point in the history
  • Loading branch information
robschleusner committed Oct 13, 2023
1 parent de97793 commit 479ad41
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions core/headerchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,12 @@ func (hc *HeaderChain) loadLastState() error {
// properly and it doesn't crash the nodes
hc.currentHeader.Store(hc.genesisHeader)
}
} else {
// Recover the current header
log.Warn("Recovering Current Header")
recoverdHeader := hc.RecoverCurrentHeader()
rawdb.WriteHeadBlockHash(hc.headerDb, recoverdHeader.Hash())
hc.currentHeader.Store(recoverdHeader)
}

heads := make([]*types.Header, 0)
Expand Down Expand Up @@ -669,6 +675,30 @@ func (hc *HeaderChain) GetHeaderOrCandidate(hash common.Hash, number uint64) *ty
return header
}

// RecoverCurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache
func (hc *HeaderChain) RecoverCurrentHeader() *types.Header {
// Start logarithmic ascent to find the upper bound
high := uint64(1)
for hc.GetHeaderByNumber(high) != nil {
high *= 2
}
// Run binary search to find the max header
low := high / 2
for low <= high {
mid := (low + high) / 2
if hc.GetHeaderByNumber(mid) != nil {
low = mid + 1
} else {
high = mid - 1
}
}
header := hc.GetHeaderByNumber(high)
log.Info("Header Recovered: ", "hash", header.Hash().String())

return header
}

// GetHeaderOrCandidateByHash retrieves a block header from the database by hash, caching it if
// found.
func (hc *HeaderChain) GetHeaderOrCandidateByHash(hash common.Hash) *types.Header {
Expand Down

0 comments on commit 479ad41

Please sign in to comment.