Skip to content

Commit

Permalink
make indexer handle null block hashes (#473)
Browse files Browse the repository at this point in the history
Before the future release 0.2.0 the block_hash is not stored in
database. In future releases we're using the block_hash to check for
reorgs.

There's a rare corner case where the indexer tries to retrieve a block
hash that happens to be null, in that case we should skip it and check
for reorgs later in the chain.

In the case when a reorg happens later in the chain, and the reorg
handler algorithm determines the reorg happened in a range we don't have
any data about, then the indexer should simply start indexing from 0, as
it's the safest option.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Bug Fixes**
- Enhanced reorganization detection by adding safeguards to handle
scenarios with missing block data.
	- Improved error handling to prevent issues during blockchain updates.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
fbac authored Feb 12, 2025
1 parent c5f81ec commit b789de6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion pkg/indexer/indexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,8 @@ func indexLogs(
zap.Uint64("blockNumber", reorgCheckAt),
)

if !bytes.Equal(storedBlockHash, onchainBlock.Hash().Bytes()) {
if storedBlockHash != nil &&
!bytes.Equal(storedBlockHash, onchainBlock.Hash().Bytes()) {
logger.Warn("blockchain reorg detected",
zap.Uint64("storedBlockNumber", storedBlockNumber),
zap.String("storedBlockHash", hex.EncodeToString(storedBlockHash)),
Expand Down
20 changes: 20 additions & 0 deletions pkg/indexer/reorgHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,26 @@ func (r *ReorgHandler) FindReorgPoint(detectedAt uint64) (uint64, []byte, error)
}

oldestBlock := storedBlocks[0]

if oldestBlock.BlockHash == nil {
startAtZero, err := r.client.BlockByNumber(
r.ctx,
big.NewInt(0),
)
if err != nil {
return 0, nil, fmt.Errorf("%w %d: %v", ErrGetBlock, oldestBlock.BlockNumber, err)
}

if err := r.queries.UpdateBlocksCanonicalityInRange(r.ctx, queries.UpdateBlocksCanonicalityInRangeParams{
StartBlockNumber: 0,
EndBlockNumber: detectedAt,
}); err != nil {
return 0, nil, fmt.Errorf("failed to update block range canonicality: %w", err)
}

return 0, startAtZero.Hash().Bytes(), nil
}

chainBlock, err := r.client.BlockByNumber(r.ctx, big.NewInt(int64(oldestBlock.BlockNumber)))
if err != nil {
return 0, nil, fmt.Errorf("%w %d: %v", ErrGetBlock, oldestBlock.BlockNumber, err)
Expand Down

0 comments on commit b789de6

Please sign in to comment.