blocks: add resumable reobfuscation for existing block files

bitcoin/bitcoin: PR #33324

3 minor findings · 9 suggestions

Findings

Link

[minor] · Resumed migration trusts readable keys without committing them

After an interrupted or failed key sync and a process-only restart, migration can delete old-key data without syncing the reused key, leaving recovery dependent on writeback before a later power loss.

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

Details and suggested fix

FileCommit() flushes stdio before synchronizing the file. A kill in that window, or a failed synchronization, can leave a readable eight-byte xor.dat.reobfuscated in the page cache. A restart without reboot accepts it through TryReadXorKeyFile() and skips WriteXorKeyFile(). The following CommitBlocksDir() calls synchronize the directory, not the reused key's contents, before originals and xor.dat are removed. A second power failure before writeback can therefore lose the key needed for rewritten files. A source xor.dat created during an earlier failed attempt has the same reuse gap; losing that marker can make recovery mistake an incomplete copy phase for activation. Commit both reused key files without truncating them before destructive operations, and stop if either commit fails. The new key is logged, so manual recovery may be possible.


Link

[minor] · blk/rev symlinks are replaced with files on the blocksdir volume

With per-file symlinks, whose support and production use are unconfirmed, migration relocates block data to the blocksdir volume and leaves old-key targets behind, potentially exhausting space and preventing startup until storage is corrected.

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

Details and suggested fix

entry.is_regular_file() follows symlinks, so a canonical block or undo filename pointing to another volume enters migration. MigrateBlockFile() reads through the link but creates its .reobfuscated replacement inside blocksdir. Removing the source pathname deletes only the link, and activation installs the staged regular file there. Unlike ordinary block-file access, this relocates the data without reclaiming the external target's space, so the destination needs capacity for all relocated files. Once a write fails, the staged key makes subsequent startups retry the migration. Detect these symlinks with symlink_status() and refuse with a clear error before staging the target key.


Link

[minor] · MigrateBlockFile() accepts EOF after a source read error

After a positive partial fread() error followed by EOF, migration accepts the copy and deletes the source without checking ferror(); actual corruption has not been established on glibc/Linux.

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

Details and suggested fix

AutoFile::detail_fread() returns the byte count without checking the source error indicator. The migration writes any positive partial result and reads again, then accepts the output based on feof() and its successful commit. A persistent error returning zero without EOF is rejected, but an earlier partial error followed by EOF is not. C does not guarantee the file position after a read error, while m_position assumes contiguous reads when selecting the XOR offset. Expose and check the source's ferror() state before accepting the copy, as ReadBinaryFile() already does, so an errored copy retains its original for retry.


Optional improvements

Link

[suggestion] · Permanent source damage leaves a pending migration without a documented recovery path

After opting into migration, a persistent read error outside the default startup-check window can block every restart; neither -reobfuscate-blocks=0 nor selecting the old key cancels the pending migration.

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

Details and suggested fix

An unreadable sector in historical block data can leave ordinary startup working because the default verification reads only the latest six blocks. Migration instead reads every selected file and aborts if a persistent read error prevents reaching EOF. Once xor.dat.reobfuscated exists, startup always resumes, an old-key request conflicts with the staged target, and BlockManager construction refuses to bypass the migration. The release notes explain repair-and-retry recovery, but that does not cover an unrecoverable source file. Document a supported recovery procedure for permanent source damage, rather than leaving filesystem repair and another retry as the only instructions.


Link

[suggestion] · Windows migration recovery relies on unstated metadata ordering

The migration uses xor.dat deletion as a phase barrier, but DirectoryCommit() does nothing on Windows; the required persistence ordering is unestablished, and the problematic crash state has not been observed.

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

Details and suggested fix

ObfuscateBlocks() removes xor.dat, commits the directory, and promotes staged data before activating the target key. Recovery treats a readable old key as evidence that originals still need conversion. If a crash preserves a promoted new-key file but loses the preceding key deletion, resume applies the delta to that file again. File contents are flushed earlier, but the Windows DirectoryCommit() implementation supplies no explicit barrier for these later metadata operations. Establish and document the filesystem ordering guarantee that excludes this state on supported Windows layouts; otherwise gate migration where that guarantee cannot be established.


Link

[suggestion] · Block-file copy errors discard the failing operation and cause

Failures from fopen(), fread(), fwrite(), or the checked output fclose() can reach startup as a path-only error, hiding the cause needed to resume migration.

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

Details and suggested fix

The empty ios_base::failure catch discards the exception, and the final error reports only Error reobfuscating block file <path>. Failed opens have no logging here, write_buffer() throws without the system error, and an output-close failure becomes the same message. This can hide causes such as permission errors or ENOSPC during a write; FileCommit() already logs its own synchronization failures. Capture the failing operation, affected path, and SysErrorString(errno) at the failure site, before cleanup can overwrite the error, and include them in the exception forwarded by initialization. Retain the existing behavior of keeping the source file when copying fails.


Link

[suggestion] · Unsupported directory synchronization is reported without its cause

On a non-Windows filesystem returning EINVAL for directory fsync(), a new migration fails without identifying the unsupported operation or directory; this filesystem-specific failure was not reproduced.

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

Details and suggested fix

DirectoryCommit() deliberately returns false without logging when directory synchronization returns EINVAL. CommitBlocksDir() then throws only Failed to commit blocks directory, leaving both the initialization error and log without the reason or path. For a fresh migration, the first barrier precedes target-key staging, so removing the option still permits normal startup. Preserve an explicit unsupported-sync result and report it with the blocks path in the migration error. Also document that migration refuses unsupported directory synchronization, unlike the existing FileCommit() behavior that tolerates EINVAL.


Link

[suggestion] · Legacy migration without xor.dat is missing from coverage

The tests do not exercise migration from an unobfuscated directory lacking both key files, or assert a fresh migration to a chosen nonzero hexadecimal key.

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

Details and suggested fix

The cached-chain fixture already has xor.dat before its first migration. Its later deletion always follows creation of a valid staged key, which selects activation-only recovery. Consequently, the branch that creates and commits a zero source key for a legacy directory is not exercised. After completing zero-key removal and stopping the node, delete xor.dat with no migration pending and run with a different explicit nonzero hexadecimal target. Assert the exact bytes stored in xor.dat; the existing -checkblocks=0 startup then also verifies indexed block and undo records under that key.


Link

[suggestion] · Resume fixtures do not exercise the migration interrupt

The hand-built interrupted states would still pass if ObfuscateBlocks() ignored shutdown between files.

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

Details and suggested fix

run_startup() waits for full RPC initialization before stopping the node, so the existing cases test recovery from prepared on-disk states rather than the interrupt transition. Add a unit test with several small files and a kernel::Notifications::progress() override that triggers SignalInterrupt once, on the first positive progress callback. Assert that migration returns with remaining originals unchanged and the staged key present, then reset the interrupt, resume, and check decoded contents.


Link

[suggestion] · Pruned-reindex tests miss preservation of the usable prefix

The existing pruned-reindex assertions permit deleting every old block file and do not exercise cleanup of six-digit filenames.

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

Details and suggested fix

feature_remove_pruned_files_on_startup.py removes file zero before -reindex and expects only newly created blk00000.dat and rev00000.dat afterward. Those assertions cannot distinguish correct prefix preservation from deleting everything. Add a direct CleanupBlockRevFiles() fixture containing blk00000.dat, blk00001.dat, blk00003.dat, blk100000.dat, and undo files including rev100000.dat. Assert that only the first two block files survive. This checks the contiguous-prefix invariant and the wider-name matching introduced by the shared integer-indexed collector.


Link

[suggestion] · The zero-key resume fixture skips data conversion

The -blocksxor=0 resume fixture uses equal source and target keys, so it never tests conversion of remaining nonzero-encoded files.

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

Details and suggested fix

The preceding explicit zero-key migration completes and asserts a zero active key before this case stages another zero key. Obfuscation::Delta() is therefore zero, and MigrateBlockFile() is never called. Keep the direct conversion check, but start the resume case with a nonzero active key, stage a zero target, and restart with only -blocksxor=0. Assert that the active key becomes zero, staged migration files disappear, and startup succeeds with the existing -checkblocks=0 setting.


Link

[suggestion] · Filename contracts change late in the commit series

The final tree is correct, but the last commit replaces earlier promotion logic and broadens pruned-reindex matching, requiring reviewers to revisit both after reviewing migration.

Location: src/node/blockstorage.cpp:1381 at 9b85da609e61 (commit) (commit).

Details and suggested fix

2faf8f16fe6fabf6841bbc5aea2fa52119110e47 extracts discovery with five-digit matching and string indices. The migration commit, 91fa01a2edc5240198bc485e1dff5d2efd5a7789, then promotes unrelated regular files such as notes.reobfuscated because it checks only the suffix. 9b85da609e6133b5d74759ba0b0dc3b6af20849f corrects promotion and also changes pruned-reindex cleanup to canonical integer matching with wider filenames.

Keep extraction as a refactor and place the canonical integer-matching and cleanup behavior change immediately after it. Fold suffix-aware promotion into the migration commit, and put the blk100001.dat and notes.reobfuscated test edits into b1f98f690cdfc1f0239d00fbda6257c0376f3a7c. Move <string_view> with the matcher. This leaves the final tree unchanged while separating cleanup behavior from migration and presenting the final promotion contract when migration is introduced.


Coverage details

Background

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

Documented decisions

Block-file XOR protects availability against accidental interpretation of peer-supplied bytes, not against an adversary with filesystem access. The original proposal specifically cited antivirus quarantine, deletion, or corruption preventing reorgs and responses to block requests.

Reobfuscating legacy files extends that same availability protection to existing block and undo data. It does not introduce confidentiality or integrity protection, and key rotation should not be interpreted as a cryptographic security boundary.

Source 1

Unresolved disagreements

The earlier conversion-tool discussion exposed a usability-versus-complexity tradeoff without establishing a general resolution: some participants favored interruptible conversion with mixed-format or background access, while the author favored all-or-nothing operation because RPC/P2P reads, reorgs, and newly stored pruned blocks create switching edge cases.

Automatic resume before chainstate loading takes a different availability posture from allowing normal node operation during conversion. The historical debate explains why resumability and mixed-key runtime access are separate design decisions; it is not a recommendation to change the pinned startup-only approach.

Source 1 · Source 2 · Source 3 · Source 4