Skip to content

Commit

Permalink
Recovers header if hash is not found in DB on startup
Browse files Browse the repository at this point in the history
  • Loading branch information
robschleusner committed Oct 2, 2023
1 parent 983731f commit 60b70e9
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions core/headerchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,9 +454,9 @@ func (hc *HeaderChain) loadLastState() error {
if chead := hc.GetHeaderByHash(head); chead != nil {
hc.currentHeader.Store(chead)
} else {
// This is only done if during the stop, currenthead hash was not stored
// properly and it doesn't crash the nodes
hc.currentHeader.Store(hc.genesisHeader)
// Recover the current header
log.Info("Recovering Current Header")
hc.currentHeader.Store(hc.RecoverCurrentHeader())
}
}

Expand Down Expand Up @@ -640,6 +640,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 60b70e9

Please sign in to comment.