wallet, migration: Skip legacy wallet records rather than erasing them, and drop unused record erase functions

bitcoin/bitcoin: PR #36823

3 minor findings · 1 suggestion

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

Findings

Link

[minor] · Unchecked WriteTxMetadata is now the only write of retained transactions

Skipping TX records can leave retained transactions missing despite successful migration if WriteTxMetadata fails while SQLite still commits; no production occurrence of such a failure was identified.

Location: src/wallet/wallet.cpp:4248 (head).

Details and suggested fix

Adding DBKeys::TX to skip_types makes local_wallet_batch.WriteTxMetadata(*wtx) the only write recreating each retained transaction record, but its return value is ignored. Previously, the checked raw copy left the original record available if this rewrite failed. SQLiteBatch::WriteKey returns failure without recording a batch error, and RunWithinTxn checks only the callback result and commit. A failed replacement write can therefore leave the reloaded wallet without that transaction. A rescan cannot reconstruct its comments or original receive time, and recovery of that metadata requires the .legacy.bak file. Check the return value and return util::Error on failure so the existing migration rollback-and-restore path runs. Commit failures already enter recovery; this issue concerns failed writes whose SQLite transaction can still commit.


Link

[minor] · TX skips incorrectly trigger legacy descriptor conversion

A transaction-only BDB file now sets had_legacy_records and fails migration instead of preserving its transactions; no Core-produced wallet with this input was identified.

Location: src/wallet/wallet.cpp:3740 (head).

Details and suggested fix

MigrateToSQLite sets had_legacy_records for any skipped type, including DBKeys::TX, and the caller uses it to select DoMigration. For a corrupted or hand-built file containing transactions but no LEGACY_TYPES records, loading accepts the transactions without creating a LegacyDataSPKM. Descriptor derivation then encounters Assume(legacy_spkm) and returns “Legacy wallet data missing,” causing backup restoration in normal builds; builds configured with ABORT_ON_FAILED_ASSUME abort instead. Base checked only LEGACY_TYPES, skipped descriptor conversion, and retained the raw transaction records. Track actual legacy-record presence separately and retain buffered TX records when no legacy conversion will run. Narrowing the flag alone is insufficient because the flag-only branch does not recreate omitted transactions.


Link

[minor] · Malformed record keys now throw out of MigrateToSQLite

A corrupted or crafted BDB wallet containing an unmatched malformed key now fails migration with a stream exception, although known-prefix loading can accept it and base copied it unchanged.

Location: src/wallet/wallet.cpp:3738 (head).

Details and suggested fix

The full cursor returns raw record keys, but the new ss_key >> type assumes each contains a serialized string. A length prefix exceeding the available bytes throws std::ios_base::failure without conversion to the function's bilingual error result. Unlike the full scan, wallet loading selects known prefixes and need not encounter this stray record. Catch the parse failure and preserve the raw record as base did, or return false with a translated error. The exception occurs before deletion of the BDB file, so no data is lost. RPC converts it to RPC_MISC_ERROR; GUI exception handling was not established.


Optional improvements

Link

[suggestion] · MigrateToSQLite still documents a complete copy

The MigrateToSQLite contract promises to move all records, although success now commits a filtered database that still requires semantic migration.

Location: src/wallet/wallet.h:1056 (head).

Details and suggested fix

The comment still says “Move all records,” but skip_types selects records that are omitted before the original BDB file is deleted. Document this filtering and the caller's responsibility to persist the required replacements before presenting or reloading the migrated wallet. Also document that had_legacy_records becomes true for any skipped record, including TX, rather than only records in LEGACY_TYPES. These are important distinctions between successful storage conversion and completed wallet migration.


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

Reloading migrated wallets was introduced as a way to reconstruct incomplete or incorrect migration-time state, including for newly created watch-only and solvables wallets. It was not a substitute for preserving the data from which that state would be reconstructed.

The historical proposal explicitly identified lost CWalletTx metadata, such as time received, and fixed its copying alongside reload behavior. In the pinned migration, watch-only transactions are serialized into a new CWalletTx and written in full, while retained main-wallet transactions are rewritten. Skipping original database records therefore still requires complete replacement records, including metadata, before reload.

Source 1

Ralph's inferences

Copy-then-erase treated transaction migration as an exhaustive ownership partition, not merely a copy of transactions with owned outputs. Each existing transaction had to belong to the main wallet, the watch-only wallet, or both; an unassignable transaction caused migration to fail.

Both base and head test IsMine or IsFromMe, process transactions in insertion order so spend lookups work, and permit a transaction to remain in both wallets. The base erased only transactions belonging exclusively to the watch-only wallet. When original transaction records are skipped instead, the same completeness rule remains: all applicable destinations must receive their history, shared transactions must remain shared, and unexplained history must not silently disappear.

For wallets without spendable material, an empty main wallet was an intentional result, and emptiness was used as a completeness certificate before discarding that wallet.

The base avoids generating fresh spendable descriptors when there is no spendable material, requires the main wallet's address book and transaction map to be empty, and subsequently removes the descriptor-less local wallet before loading the results. Its comments explain that users migrating only watch-only scripts do not expect an unrelated empty spendable wallet. Skipping records must therefore preserve both transfer completeness and the evidence used to decide that discarding the main wallet is safe.

Database cleanliness and migration-time in-memory cleanliness are separate lifecycle obligations. A clean eventual reload cannot, by itself, establish an invariant that migration checks before that reload.

ApplyMigrationData performs ownership checks and the watch-only-only emptiness checks while the original wallet object still exists. It runs inside the outer database transaction; destruction and optional reloading happen later. The removed erasure path also supplied in-memory cleanup, whereas skipping database copies directly changes only persistence. The relevant preserved guarantee is that each pre-reload consumer sees the state its completeness decision requires, with transaction-commit timing distinguished from reload timing.

The original two-stage migration separated lossless storage conversion from semantic replacement. Moving record omission into storage conversion moves the point of disappearance earlier, but does not remove the obligation to finish the semantic migration or restore the backup on failure.

The base first reads every database record and checks cursor completion, copies the records into SQLite, and only then detects legacy records and applies descriptor conversion and transaction redistribution. It creates a backup before this work and restores it on later migration failure. With skipped records, conversion still depends on the already loaded wallet state, and migration activation and replacement completeness can no longer rely on finding those omitted records in the new database.