Skip to content

index: prevent block filter loss and restart failures after reorgs - #37044

Open
l0rinc wants to merge 10 commits into
bitcoin:masterfrom
l0rinc:l0rinc/blockfilter-restore-header-by-hash
Open

l0rinc wants to merge 10 commits into
bitcoin:masterfrom
l0rinc:l0rinc/blockfilter-restore-header-by-hash

Conversation

@l0rinc

@l0rinc l0rinc commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem: A reorg can put a different block at the same height while an index still has the old block saved as its last committed tip.
The database preserves the old entries by block hash.
The block filter index looks up headers by height during startup and rewind, so it can fail to start or abort during a rewind.
CoinStats can also fail to start when a rewind tries to decode the parent's hash entry as a height entry.

The block filter index can save a new filter entry before it saves the next write position.
After an unclean shutdown, the index can resume writing at the old position and overwrite a filter still referenced by a stale branch.
getblockfilter reports index corruption for that block, and peers that request its compact filter get no response.

The block filter index can also start with a tip entry that points to a missing filter file. A later getblockfilter call then reports index corruption.

Fix: Use index_util::LookUpOne() when the block filter index starts or rewinds and when CoinStats rewinds.
If the height entry belongs to a different block, the helper reads the preserved hash entry in its stored format.
Save the next block filter position in the same database batch as the new height entry, so writes after a restart append past the filters the index still references.
Read the committed tip's filter at startup and verify its payload checksum before accepting the tip.

Fixes #34261

@DrahtBot

DrahtBot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK andrewtoth

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Comment thread src/index/blockfilterindex.cpp Outdated
@@ -239,18 +239,8 @@ uint64_t BlockFilterIndex::WriteFilterToDisk(FlatFilePos& pos, const BlockFilter

std::optional<uint256> BlockFilterIndex::ReadFilterHeader(int height, const uint256& expected_block_hash)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could be a const function (not related to this diff)

@PiRK

PiRK commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

CoinStatsIndex::RevertBlock has almost the same code. It likely has the same bug.

@l0rinc
l0rinc force-pushed the l0rinc/blockfilter-restore-header-by-hash branch from cce340d to 411ecaa Compare December 2, 2026 19:21
@l0rinc l0rinc changed the title index: prevent block filter index from failing to restart after a reorg index: prevent block filter and CoinStats indexes from failing to restart after a reorg Dec 2, 2026
@l0rinc

l0rinc commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

RevertBlock has almost the same code

I was thinking of upstreaming these separately, but you're right, they're basically the same bug, so I added the CoinStats equivalent here too.
I also checked the other indexes, and block filters and CoinStats seem to be the only ones using this height/hash key scheme.

@andrewtoth andrewtoth left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

This fixes index corruptions from unclean shutdowns while a reorg happens before restart.

Comment thread src/index/blockfilterindex.cpp Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a minor issue flagged by ralph as well, which is basically

  1. Starting on branch B, reorg to branch A.
  2. Reorg back to branch B, then crash.
  3. Before or during restart reorg back to branch A.
  4. Peer still on branch B requests a filter, the request is dropped.

The following test characterizes the behavior:

#!/usr/bin/env python3
from test_framework.messages import FILTER_TYPE_BASIC, msg_getcfilters
from test_framework.p2p import P2PInterface
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
from test_framework.wallet import getnewdestination


class BlockFilterReorgClobberTest(BitcoinTestFramework):
    def set_test_params(self):
        self.num_nodes = 1
        self.extra_args = [["-blockfilterindex", "-peerblockfilters"]]

    def run_test(self):
        node = self.nodes[0]

        b1 = node.getbestblockhash()
        node.invalidateblock(b1)
        a1 = self.generatetoaddress(node, 2, getnewdestination()[2])[0]
        node.reconsiderblock(b1)
        node.wait_for_index_sync()
        self.restart_node(0)

        node.invalidateblock(a1)
        node.wait_for_index_sync()
        node.kill_process()

        self.start_node(0)
        self.generate(node, 1)
        node.wait_for_index_sync()

        peer = node.add_p2p_connection(P2PInterface())
        peer.send_and_ping(msg_getcfilters(FILTER_TYPE_BASIC, 200, int(b1, 16)))
        # TODO: should be 1 after the patch
        assert_equal(peer.message_count["cfilter"], 0)


if __name__ == "__main__":
    BlockFilterReorgClobberTest(__file__).main()

This patch fixes it:

diff --git a/src/index/blockfilterindex.cpp b/src/index/blockfilterindex.cpp
--- a/src/index/blockfilterindex.cpp
+++ b/src/index/blockfilterindex.cpp
@@ -263,8 +263,10 @@ bool BlockFilterIndex::Write(const BlockFilter& filter, uint32_t block_height, c
     value.second.header = filter_header;
     value.second.pos = m_next_filter_pos;
 
-    m_db->Write(index_util::DBHeightKey(block_height), value);
-
     m_next_filter_pos.nPos += bytes_written;
+    CDBBatch batch(*m_db);
+    batch.Write(index_util::DBHeightKey(block_height), value);
+    batch.Write(DB_FILTER_POS, m_next_filter_pos);
+    m_db->WriteBatch(batch);
     return true;
 }

l0rinc and others added 8 commits December 3, 2026 20:57
Flush chainstate and the block filter locator at chain B's tip, then let chain A overwrite the same height entry before restoring chainstate to the flushed tip without rolling back the eager index writes.

`BlockFilterIndex::CustomInit()` reads the committed tip's filter header only from its height entry, so it rejects this state even though the matching entry remains available by hash.
Keep that failure as the expectation for the following fix.
A reorg can replace the height entry for the block filter index's committed locator.
After a crash, initialization can then miss the saved tip header even though its entry remains stored by hash.

Use `index_util::LookUpOne()` during initialization so the matching height entry remains the fast path and a displaced entry is read from its hash key.

The added checks need a running index, so they can only be added once `Init()` succeeds.
They mine one block and compare its filter header against one computed independently from chain B's tip, so a change that lets startup succeed while restoring the wrong header, such as the displaced height entry's, still fails.
Reorg node 0 to the other branch and kill it before the index commits, so the unclean restart brings back the old tip while its parent's height entry belongs to the other branch.
Then connect a longer branch that makes the block filter index rewind to that parent.

`CustomRemove()` reads the previous filter header only by height and asserts when the block hash differs, even though the matching entry remains available by hash.
Check the abort in a functional test because the failing `Assert()` would terminate a unit-test process.
After a reorg and unclean restart, a rewind can need a previous filter header whose height entry belongs to the other branch.

Use `index_util::LookUpOne()` to read the parent entry from either its matching height entry or its hash entry.
Return through the index error path instead of asserting if neither entry exists.

The functional test now expects the node to stay alive and return the replacement filter.
The C++ continuation is first added here because with the old height-only lookup, connecting the block after `InvalidateBlock()` would abort the unit-test process.
It mines after the rewind and checks the resulting header independently, which catches a change that merely avoids the abort while retaining the wrong parent header.
Reorg the CoinStats index onto a replacement branch that overwrites the committed tip's parent height entry, then invalidate the replacement tip so the index stays one block ahead of the active chain and the committed locator remains on the original branch.
Restart so initialization must rewind that locator.

`RevertBlock()` then reads the preserved hash entry into the height-entry pair type even though hash entries store only `DBVal`.
Expect the resulting fatal rewind error until the following fix.
CoinStats height entries store a block hash and `DBVal`, while preserved hash entries store only `DBVal`.
`RevertBlock()` reads both forms into the height-entry pair type, so restart fails when another branch occupies the expected parent's height.

Use `index_util::LookUpOne()` with the expected parent hash and height so the matching height entry remains the fast path and the hash entry is decoded as `DBVal`.
The existing muhash assertion also keeps a height-only workaround from passing with stats from the wrong branch.
Extend the preceding unclean-restart scenario by requesting a filter from the displaced branch after indexing the replacement blocks.

The persisted next position still points before the filter records written for that branch before the unclean restart, so the replacement blocks overwrite data referenced by its surviving height entries and `getblockfilter` reports index corruption.

Co-authored-by: Andrew Toth <[email protected]>
Block filter records and height entries are written eagerly, while the next flat-file position is persisted only on commit and block removal.
After an unclean restart, later indexing can therefore overwrite records still referenced by a stale branch's surviving height entries.

Write each height entry and the position immediately after its filter record in one database batch.
If the height entry is durable, later writes now append after the record it references.

The position write in `CustomRemove()` becomes redundant because removal does not advance the position.
Writing the position on removal alone also leaves records appended after the last removal unprotected.

Co-authored-by: Andrew Toth <[email protected]>
@l0rinc
l0rinc force-pushed the l0rinc/blockfilter-restore-header-by-hash branch from 411ecaa to 9dc8f83 Compare December 4, 2026 11:49
@l0rinc l0rinc changed the title index: prevent block filter and CoinStats indexes from failing to restart after a reorg index: prevent block filter loss and restart failures after reorgs Dec 4, 2026
@l0rinc

l0rinc commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased and added a functional test for the abort that can happen when the block filter index rewinds after an unclean restart. The unit test continues through the same rewind, mines another block, and verifies that its filter header builds on the correct parent. I also took @andrewtoth’s suggestion, extending the fix to save the next write position with every filter entry and simplifying the test that reproduces filter data being overwritten after restart.

Edit: The node now also reads the committed tip’s filter at startup and refuses to start if the record is missing or its payload checksum doesn’t match.

Stop the node cleanly and remove the flat file holding the committed tip's filter.
The node still starts with the index enabled, but `getblockfilter` reports index corruption for that tip.
The tip entry in the index database can point to a missing or unreadable flat-file record.
Read the filter at that position and verify its payload checksum before accepting the committed tip.

Update the deletion comment in `feature_init.py` because a missing tip filter now stops startup.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Block filter index corruption post reorg and unclean shutdown

4 participants