blocks: add resumable reobfuscation for existing block files

bitcoin/bitcoin: PR #33324

3 minor findings · 11 suggestions

Earlier concerns neither republished nor resolved: 1 major finding · 1 suggestion. See the Run archive for their assessments.

Findings

Link

[minor] · Key-file stat errors can select the wrong resume phase

A transient key-file file_size error during resume can activate mixed encodings; no filesystem exhibiting this trigger was identified, so production impact remains unconfirmed.

Location: src/node/blockstorage.cpp:225 (head).

Details and suggested fix

TryReadXorKeyFile returns nullopt when file_size fails, but ObfuscateBlocks interprets absence as migration progress. In a partly copied migration, a failed stat of xor.dat.reobfuscated can regenerate and overwrite the target key when no exact key was requested. Completed staged files whose originals were removed are not recopied and retain the previous target encoding. A failed stat of xor.dat instead skips remaining rewrites and proceeds to activation, potentially promoting a partial staged copy over its original. These paths can remove the pending marker while files disagree with the active key, causing later reads to fail without automatic resume repairing them. Treat only ENOENT as absence and propagate other errors before changing keys or data.


Link

[minor] · Resume can delete originals without durably committing the reused target key

After an interrupted or failed key sync, restart can delete originals without successfully syncing the reused target key; subsequent power-loss damage depends on filesystem writeback behavior.

Location: src/node/blockstorage.cpp:1346 (head).

Details and suggested fix

FileCommit performs fflush before the platform synchronization call. Failure or process interruption between those operations can leave all eight staged-key bytes readable without making them durable. On restart, TryReadXorKeyFile accepts that key and if (!new_key) skips WriteXorKeyFile, so only directory barriers precede resumed copying and original-file deletion. If power is lost before the key contents reach storage, rewritten files can depend on a key that is empty or stale after recovery. Open a reused staged key without truncation and require a successful FileCommit before allowing resumed deletion. Add fault-injection coverage for a failed key commit followed by retry.


Link

[minor] · Per-file symlinks become local copies and leave their targets unchanged

For undocumented per-file symlink layouts, migration duplicates data onto the blocksdir volume and leaves targets under their old key; prevalence and production impact are unknown.

Location: src/node/blockstorage.cpp:251 (head).

Details and suggested fix

entry.is_regular_file() follows symlinks, and MigrateBlockFile reads through them just as ordinary FlatFileSeq::Open reads do. However, it creates the staged regular file beside the link, and fs::remove(path) removes only the link. Activation therefore materializes the replacement in blocksdir while leaving the external target unchanged, possibly still zero-encoded. This can unexpectedly consume the blocksdir volume; if it fills, startup remains blocked by the pending migration until space is available. Detect per-file symlinks with symlink_status() during the initial scan and reject them with a path-specific error before staging a new migration.


Optional improvements

Link

[suggestion] · Windows migration phase ordering has no documented persistence guarantee

Migration uses DirectoryCommit as a phase barrier, but Windows makes it a successful no-op; the required rename-persistence ordering is undocumented and no corruption was demonstrated.

Location: src/util/fs_helpers.cpp:153 (head).

Details and suggested fix

The key filenames encode whether copying or activation remains unfinished. Data-file promotions must become durable before promoting xor.dat.reobfuscated, because that final rename removes the pending marker. Individual file commits use FlushFileBuffers on Windows, but the activation renames happen after those handles close, and the intervening CommitBlocksDir performs no Windows operation. If key promotion persisted before an earlier data promotion, the next startup would no longer know that activation was incomplete. Document the filesystem ordering guarantee that rules this out on supported Windows volumes, or explicitly narrow the recovery guarantee where it is unavailable.


Link

[suggestion] · Permanently unreadable source data has no documented migration recovery

An opt-in migration encountering permanently unreadable historical data retries the same failure on every startup, while the release notes cover only correctable filesystem problems.

Location: src/init.cpp:1409 (head).

Details and suggested fix

MigrateBlockFile requires reading every source to EOF, including historical sectors that normal startup need not read beyond its default six-block verification. Once the staged key exists, every startup resumes migration before chainstate loading. Selecting the old key fails the mismatch check, and -reindex cannot bypass migration. The all-or-nothing boundary can remain, but users need a supported recovery procedure when source bytes cannot be recovered. Document a discard-and-reindex or redownload procedure that handles both the damaged original and its partial staged replacement, while preserving the phase keys until migration finishes.


Link

[suggestion] · An existing shutdown request still commits a new migration

For a nonempty, differing-key migration, an existing shutdown request still creates the pending marker, forcing later startups to finish rewriting even after the option is removed.

Location: src/node/blockstorage.cpp:1348 (head).

Details and suggested fix

ObfuscateBlocks writes and commits xor.dat.reobfuscated before checking interrupt inside the copy loop. AppInitMain also checks ShutdownRequested only after calling migration. Cancelling during earlier initialization can therefore leave a pending migration without copying any data. Later startup resumes it automatically, and the pending and key-mismatch guards prevent ordinary startup with the old key. Check the interrupt before staging a new target when no migration is pending, while leaving recovery of already-pending migrations unchanged.


Link

[suggestion] · Unsupported directory sync produces only a generic migration error

If directory fsync returns EINVAL, migration fails without identifying the unsupported operation; no deployed filesystem exhibiting this trigger was identified.

Location: src/node/blockstorage.cpp:231 (head).

Details and suggested fix

DirectoryCommit returns false for EINVAL before logging, and CommitBlocksDir converts that result into Failed to commit blocks directory without a path or cause. On a fresh migration, the first barrier fails before staging the target key, but the operator cannot tell that directory synchronization is unsupported. Normal flushing ignores this return value, and the POSIX FileCommit branches tolerate unsupported synchronization, so ordinary operation does not explain the new refusal. Keep the refusal if required for recovery safety, but propagate a specific unsupported-directory-sync error naming blocksdir and document that requirement.


Link

[suggestion] · Copy failures lose the failing operation and OS error

Source-open, read, and direct staged-write failures can lose their operation and OS cause, making a pending migration harder to recover.

Location: src/node/blockstorage.cpp:247 (head).

Details and suggested fix

MigrateBlockFile does not check either open explicitly, discards std::ios_base::failure, and treats a read error as an unsuccessful EOF check. Its final exception names only the source file, so it does not distinguish an unreadable source, an uncreatable staged file, or ENOSPC during writing. FileCommit logs flush and synchronization errors, but those diagnostics do not cover these earlier failures. Check the opens and capture the failing operation, source or staged path, and OS error at the failure point before cleanup can overwrite it. Preserve the current close handling and resumable state.


Link

[suggestion] · Canonical matching arrives after the migration code that needs it

The final tree is correct, but the series introduces incomplete discovery and overbroad promotion before replacing both at the tip, requiring those migration paths to be validated twice.

Location: src/node/blockstorage.cpp:198 at ccbeaf2ee419 (commit) (commit).

Details and suggested fix

2faf8f16fe6fabf6841bbc5aea2fa52119110e47 extracts the old five-digit matcher. The migration in 91fa01a2edc5240198bc485e1dff5d2efd5a7789 then skips wider canonical files and promotes unrelated regular *.reobfuscated files. Those rules remain at c67c0acb98c769ea33c3775c79301e0732cb3185, the direct parent of ccbeaf2ee419bbefe7214c32e5ec87f637c68cbd, which introduces integer indices and suffix-aware canonical matching.

Keep the extraction separate, then place the standalone matcher and cleanup change immediately after it. Use that helper for promotion in the migration commit, move the wider-filename and unrelated-file assertions into the original test commit 37991210092c66f138e04308f91b6d3ac4b4c363, and remove the tip fix. Carry its cleanup rationale and required <string_view> include into the preparatory commit. This preserves the final behavior and lets discovery and promotion be validated once without known-incorrect intermediate migration states.


Link

[suggestion] · Multi-buffer migration lacks exact-byte assertions

Startup verifies indexed records, but the test never checks exact migrated bytes across multiple buffers or an unaligned tail.

Location: test/functional/feature_reobfuscation.py:54 (head).

Details and suggested fix

-checkblocks=0 verifies the initial 200-block chain, but its small coinbase-only records fit within the first 1 MiB. The remaining preallocated bytes are not compared, and every dummy payload is one byte. A regression that copies only the first REOBFUSCATION_BUFFER_SIZE buffer could therefore leave startup and the assert_not_equal checks passing. Make one deterministic dummy block or undo payload longer than two buffers with an unaligned tail. After migration and partial-copy resume, assert its exact length and bytes against the original XORed with the old/new key delta.


Link

[suggestion] · Migration coverage omits the missing-key bootstrap

Existing tests recreate a missing xor.dat only during ordinary startup, not while migration establishes its zero-source-key phase marker.

Location: src/node/blockstorage.cpp:1343 (head).

Details and suggested fix

When neither key exists, ObfuscateBlocks writes and commits a zero xor.dat before staging the target. That source marker distinguishes unfinished copying from activation on restart. The migration test retains it throughout copying and partial-copy resume, then removes it only for the activation scenario. Add a fixture with zero-encoded block and undo files and neither key present. Exercise migration and resume, asserting that interruption leaves both the zero source key and target marker and that the final decoded contents match. This protects the bootstrap used when migrating a pre-v28 directory directly.


Link

[suggestion] · Interrupt-and-resume behavior is only simulated on disk

The functional tests construct pending states by hand, so removing the actual SignalInterrupt early return would not fail them.

Location: test/functional/feature_reobfuscation.py:62 (head).

Details and suggested fix

The partial-copy cases validate recovery from staged files, but never request interruption while ObfuscateBlocks is running. Add a unit test with at least two small files and a fake kernel::Notifications whose progress callback sets SignalInterrupt after the first completed file. Assert that migration returns with both key markers present, the completed replacement staged, and unprocessed originals intact. Reset the signal, resume with requested_key=nullopt, and check decoded contents and removal of staging markers. This exercises the advertised shutdown-and-continue behavior without sleeps or large files.


Link

[suggestion] · Cleanup tests cannot distinguish prefix retention from deleting everything

The existing test already lacked contiguous-prefix coverage, and it does not check the canonical matcher's newly supported wider filenames.

Location: src/node/blockstorage.cpp:756 (head).

Details and suggested fix

feature_remove_pruned_files_on_startup.py removes blk00000.dat before reindex, so deleting every remaining block file would still satisfy its final filename assertion. The rewritten CleanupBlockRevFiles now uses integer indices and exact canonical names. Add a cleanup-level fixture containing blk00000.dat, blk00001.dat, blk00003.dat, blk100000.dat, matching undo files, and a noncanonical name. Before reindex writes new files, assert that the contiguous block-file prefix and noncanonical file remain, while post-gap block files and recognized undo files are removed.


Link

[suggestion] · Invalid -reobfuscate-blocks values escape pre-daemon checks

With -daemon and no -daemonwait, the parent reports success before malformed -reobfuscate-blocks values are rejected in the child.

Location: src/init.cpp:1403 (head).

Details and suggested fix

The child sends its success token before entering AppInitMain, but key syntax and the explicit nonzero-key conflict with -blocksxor=0 are checked only in step 7. A typo such as a 15-character hexadecimal key therefore reaches the late initialization error path instead of the parent's console and failure status. Move these argument-only checks into AppInitParameterInteraction alongside the existing pre-daemon parsing. Keep pending-state checks, including resumed zero-key handling and staged-key mismatches, after directory locking.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.

Background

Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.

Documented decisions

The predecessor conversion proposal already exposed the operational cost of mixed encodings. It required conversion to finish before bitcoind started. Participants proposed incremental or per-file decoding to permit interruption and node availability, while the author argued that RPC/P2P reads, reorganizations, and fetching previously pruned blocks introduced many encoding-selection edge cases.

These were concrete reasons for considering an all-or-nothing operational boundary, not a protocol requirement that conversion itself be uninterrupted. The current behavior makes the offline conversion resumable while withholding ordinary block access until completion.

Source 1 · Source 2 · Source 3 · Source 4 · Source 5

Unresolved disagreements

The inspected predecessor discussion does not settle the tradeoff between availability through incremental/background conversion and simplicity through an offline all-or-nothing encoding boundary.

Sjors and Wladimir van der Laan favored exploring incremental conversion; Larry Ruane described per-file detection and atomic replacement; Andrew Toth emphasized mixed-format servicing edge cases. These positions explain competing historical priorities, but do not establish a settled requirement for or against the current startup-only behavior.

Source 1 · Source 2 · Source 3 · Source 4