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

Open
l0rinc wants to merge 10 commits from l0rinc/blockfilter-restore-header-by-hash into master AGit
l0rinc commented 2026-12-02 11:48:19 +00:00 (Migrated from github.com)

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

**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 commented 2026-12-02 11:48:29 +00:00 (Migrated from github.com)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/37044 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/37044.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/37044#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [andrewtoth](https://github.com/bitcoin/bitcoin/pull/37044#pullrequestreview-6161264471) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--5faf32d7da4f0f540f40219e4f7537a3-->
First-time contributor

Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments.

🔵 Suggestion · Crash replay leaves duplicate filter payloads unreclaimed

Replaying persisted entries after an unclean restart can leave duplicate filter payloads unreclaimed, even without a reorg, because the saved append position now advances beyond the committed locator.

Location: src/index/blockfilterindex.cpp:265 (head).

🔵 Suggestion · Fatal tip-filter failures lack InitError() and rebuild guidance

Missing or corrupt committed-tip filters now stop startup without InitError() or rebuild advice, chiefly affecting daemon and GUI use because foreground bitcoind prints the log line.

Location: src/index/blockfilterindex.cpp:125 (head).

🔵 Suggestion · rpc_getblockfilter.py misses checksum-invalid startup records

A startup check reduced to file existence would still pass the new regression test, leaving readable tip-record corruption uncovered.

Location: test/functional/rpc_getblockfilter.py:90 (head).

🔵 Suggestion · Post-restart range checks never traverse the recovered hash entries

Only single-block calls follow restart, so the test never checks a range whose tip matches the height index but whose recovered ancestors require hash fallback.

Location: src/test/blockfilter_index_tests.cpp:257 (head).

Review coverage was incomplete.


Reviewed: fb1c51158ce5 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:e1a29e5e677c47d383756f0fcf8f3760725c91d1104dd3ccb2f333b6217eba26:47880f5569fd2047d249266f337c4f2a509adf7d96c3ccb1c7644c2c2a650bff --> <!-- ralph-base:2f3f6397bb92beccaccce16742f0574d1617fb3e --> <!-- ralph-head:fb1c51158ce5ebd2e38bc2446d9f976a7e04848d --> <!-- ralph-case:60c86be2da373b9c4044f8657510faba833cc2486d1d13e86e088abec9209c5e --> Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · Crash replay leaves duplicate filter payloads unreclaimed** Replaying persisted entries after an unclean restart can leave duplicate filter payloads unreclaimed, even without a reorg, because the saved append position now advances beyond the committed locator. Location: [`src/index/blockfilterindex.cpp:265`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fb1c51158ce5ebd2e38bc2446d9f976a7e04848d/src/index/blockfilterindex.cpp#L265>) (head). **🔵 Suggestion · Fatal tip-filter failures lack `InitError()` and rebuild guidance** Missing or corrupt committed-tip filters now stop startup without `InitError()` or rebuild advice, chiefly affecting daemon and GUI use because foreground `bitcoind` prints the log line. Location: [`src/index/blockfilterindex.cpp:125`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fb1c51158ce5ebd2e38bc2446d9f976a7e04848d/src/index/blockfilterindex.cpp#L125>) (head). **🔵 Suggestion · `rpc_getblockfilter.py` misses checksum-invalid startup records** A startup check reduced to file existence would still pass the new regression test, leaving readable tip-record corruption uncovered. Location: [`test/functional/rpc_getblockfilter.py:90`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fb1c51158ce5ebd2e38bc2446d9f976a7e04848d/test/functional/rpc_getblockfilter.py#L90>) (head). **🔵 Suggestion · Post-restart range checks never traverse the recovered hash entries** Only single-block calls follow restart, so the test never checks a range whose tip matches the height index but whose recovered ancestors require hash fallback. Location: [`src/test/blockfilter_index_tests.cpp:257`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fb1c51158ce5ebd2e38bc2446d9f976a7e04848d/src/test/blockfilter_index_tests.cpp#L257>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`fb1c51158ce5`](<https://git.fish.foo/bitcoin/bitcoin/commit/fb1c51158ce5ebd2e38bc2446d9f976a7e04848d>) · [Review report](<https://review.fish.foo/report/37044-fb1c51158ce5ebd2e38bc2446d9f976a7e04848d-3518-4.html>) · [Previous reports](<https://review.fish.foo/traces/37044/>) [permalink](<https://review.fish.foo/report/37044-fb1c51158ce5ebd2e38bc2446d9f976a7e04848d-3518-4.html>)
PiRK (Migrated from github.com) reviewed 2026-12-02 13:19:45 +00:00
PiRK (Migrated from github.com) commented 2026-12-02 13:19:45 +00:00

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

nit: could be a `const` function (not related to this diff)
PiRK commented 2026-12-02 13:21:40 +00:00 (Migrated from github.com)

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

CoinStatsIndex::RevertBlock has almost the same code. It likely has the same bug.
l0rinc commented 2026-12-02 19:25:57 +00:00 (Migrated from github.com)

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.

> 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 (Migrated from github.com) reviewed 2026-12-03 00:00:38 +00:00
andrewtoth (Migrated from github.com) left a comment

Concept ACK

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

Concept ACK This fixes index corruptions from unclean shutdowns while a reorg happens before restart.
andrewtoth (Migrated from github.com) commented 2026-12-03 00:00:01 +00:00

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;
 }
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: ```Python #!/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 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 commented 2026-12-04 12:05:54 +00:00 (Migrated from github.com)

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.

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.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!37044
No description provided.