WIP: wallet, migration: Contain all legacy wallet and migration related things in its own subdirectory, namespace, and classes

bitcoin/bitcoin: PR #36897

Provider refusals

write_verifier: Provider declined the request because of a cybersecurity restriction. Experiments remain incomplete; static verification can continue.

2 major findings · 4 minor findings · 4 suggestions

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

Findings

Link

[major] · migratewallet rejects transactions recognized by the split watch-only wallet

For private-key-enabled legacy wallets, a transaction belonging only to the split watch-only wallet now makes migratewallet fail and restore its backup.

Location: src/wallet/legacy/migration.cpp:308 (head).

Details and suggested fix

When an imported watch-only script has separate transaction history, removing the legacy script manager makes the main wallet's IsMine and IsFromMe checks false for those transactions. The watch-only branch recognizes and copies them, but execution then falls through to the unconditional !is_mine error. Skipping TX records during the SQLite copy does not remove them from the in-memory wtxOrdered loop. Base continued after copying such a transaction. Restore that conditional continue, skipping the main-wallet WriteTxMetadata, and return the ownership error only when neither wallet recognizes the transaction. The existing test_other_watchonly fixture exercises this partition.


Link

[major] · spkm_migration reaches a null-chain assertion during setup

The chainless LegacyWallet makes spkm_migration hit assert(m_chain) for every input before exercising migration, based on source inspection rather than a completed replay.

Location: src/wallet/test/fuzz/scriptpubkeyman.cpp:226 (head).

Details and suggested fix

LegacyWallet always constructs CWallet with chain=nullptr, but this target still calls SetLastBlockProcessed with its initialized chain tip. That setter calls WriteBestBlock, which calls chain() for a non-null block hash and asserts that m_chain exists. Base constructed the wallet with node.chain.get(), so this setup call worked. Use SetLastBlockProcessedInMem here to retain the in-memory tip without accessing a chain, while keeping LegacyWallet isolated.


Link

[minor] · Migration can still write unordered transactions that the new loader rejects

Unordered legacy transactions plus a legacy-only non-critical warning can produce an unloadable descriptor wallet; no production wallet with this combination was found.

Location: src/wallet/walletdb.cpp:712 (head).

Details and suggested fix

LoadWalletFromBDBRO skips ReorderTransactions for any result other than LOAD_OK, but LoadWalletForMigration accepts NONCRITICAL_ERROR. For example, an unexpected HD path in keymeta can leave transaction positions at -1. ApplyMigrationData then writes them, and serialization omits their n field. Base removed the legacy-only warning and repaired the positions on destination reload; the new descriptor loader instead returns CORRUPT, or aborts with ABORT_ON_FAILED_ASSUME. Without that abort, load_wallet=true fails and rolls back, while load_wallet=false reports success and leaves a wallet that later fails to load. Assign order positions before serializing every accepted migration result, using the now in-memory-only reorder operation.


Link

[minor] · New legacy headers fail the include-guard lint

By inspection, lint-include-guards.py rejects the mismatched closing #endif comments in bdbro.h and spkm.h.

Location: src/wallet/legacy/bdbro.h:112 (head).

Details and suggested fix

bdbro.h ends with BITCOIN_WALLET_BDBRO_H instead of BITCOIN_WALLET_LEGACY_BDBRO_H, and spkm.h ends with BITCOIN_WALL_LEGACY_SPKM_H instead of BITCOIN_WALLET_LEGACY_SPKM_H. The lint requires the final code line to match the path-derived guard exactly and exits with failure otherwise. Correct both closing comments to match their opening guards.


Link

[minor] · Migration ignores the configured -keypool size

LoadWalletForMigration leaves m_keypool_size at its default, so migration derives and persists larger descriptor ranges than requested when -keypool is smaller.

Location: src/wallet/legacy/load.cpp:643 (head).

Details and suggested fix

Base passed the argument context through LoadExisting, which called LoadWalletArgs. The new loader constructs LegacyWallet directly and never applies those arguments. During ApplyMigrationData, active descriptor creation passes this default size to GenerateNewSingleSig, which immediately tops up the descriptors. A later reload applies the configured size but cannot shrink the ranges already persisted; larger configured pools instead remain undersized until that reload tops them up. Apply LoadWalletArgs with the supplied argument context before migration creates the active descriptors.


Link

[minor] · Transaction records alone trigger the missing-legacy-data path

A transaction-only legacy file enters DoMigration and fails or aborts instead of following base's no-legacy path; no production wallet with this layout was found.

Location: src/wallet/legacy/migration.cpp:617 (head).

Details and suggested fix

MigrateToSQLite sets had_legacy_records for every skipped record, including TX. When a file contains transactions but no LEGACY_TYPES records, transaction loading creates no LegacyDataSPKM, yet this flag sends it into DoMigration. GetDescriptorsForLegacy then fails Assume(legacy_spkm), returning the missing-data error and rolling back, or aborting in abort-on-assume builds. Base tested only LEGACY_TYPES and completed the no-legacy conversion. Determine legacy-record presence independently of the skip set and preserve the original record-copy path for files with no legacy material.


Optional improvements

Link

[suggestion] · Early record filtering makes interrupted descriptor generation depend on the backup

An interruption during descriptor generation now requires the .legacy.bak backup for key recovery; base's intermediate SQLite file retained legacy keys, although it was not normally loadable.

Location: src/wallet/legacy/migration.cpp:611 (head).

Details and suggested fix

MigrateToSQLite omits legacy records, unlinks the BDB source and commits the reduced SQLite file before generating descriptors. Until the descriptor-generation transaction commits, an abrupt process stop bypasses rollback and leaves the backup as the only on-disk source of those keys. Backup success is checked, but its implementation uses fs::copy_file without explicit synchronization, so durability after power loss is not established. Keep the previous copy-then-erase approach for legacy records, with their erasure inside the apply transaction, rather than extending backup-only recovery through descriptor generation.


Link

[suggestion] · The migration overload accepts CWallet but requires LegacyWallet

MigrateLegacyToDescriptor accepts objects that cannot safely pass its unchecked LegacyWallet downcast, although no current caller supplies such an object.

Location: src/wallet/legacy/migration.cpp:608 (head).

Details and suggested fix

The public overload takes std::shared_ptr<CWallet> and documents only isolation. Its descriptor-flag check does not exclude a plain non-descriptor CWallet, for which static_pointer_cast<LegacyWallet> has undefined behavior. Both current callers already provide LegacyWallet: the name-based overload receives it from LoadWalletForMigration, and the benchmark constructs it directly. Accept std::shared_ptr<LegacyWallet> at entry and perform the legacy work through that type, upcasting only for the later normal-wallet reload and result handling.


Link

[suggestion] · Main-wallet transaction creation ignores write failures

Because TX records are no longer bulk-copied, an ignored WriteTxMetadata failure followed by a successful commit would omit the transaction and its metadata from the migrated wallet.

Location: src/wallet/legacy/migration.cpp:313 (head).

Details and suggested fix

WriteTxMetadata writes the complete canonical transaction record, and it is now the only creation write for each retained main-wallet transaction. The previous bulk copy checked every write. SQLiteBatch::WriteKey can return false without aborting the transaction, while TxnCommit independently executes COMMIT; checking commit alone therefore does not establish that every transaction was stored. A copied best-block locator also need not request a rescan. Check the return value and return util::Error on failure so RunWithinTxn aborts and migration follows its backup-restoration path.


Link

[suggestion] · Temporary parser paths require reviewing the same rename twice

The series moves the BDB parser through legacybdb.{h,cpp} before its final path, requiring repeated guard, include and build-list updates.

Location: src/wallet/legacybdb.h:5 at 4d989645a25d (commit) (commit).

Details and suggested fix

4d989645a25d0a7b2e39196b2e6bbf23c53eb4d6 renames the parser from migrate.{h,cpp} to legacybdb.{h,cpp} to distinguish it from the extracted migration code. faf595b17992f3eb86b61dd8aa5c141cb66a19c6 then moves it to legacy/bdbro.{h,cpp}, changing the guards and include sites again. Rename the parser directly to its final path and extract migration code directly into legacy/migration.{h,cpp}, updating includes and CMake entries with each move. This removes a repeated validation pass while retaining move-only commits separate from behavior changes. If the preparatory commits are inherited from #34909, coordinate this there or during the dependency rebase rather than rewriting them independently here.


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

Ordered wallet loading exists because records have dependencies, not merely because they share a database. The historical redesign deliberately loaded keys and descriptors before transactions so ownership checks could work during transaction loading, while avoiding temporary scan state and associated slowdowns. Unknown records were explicitly not considered errors.

The base migration reuses the ordinary loader, which loads flags, key material, address-book data, decryption keys, and transactions in dependency order. The head extracts a migration-specific subset of that sequence. The relevant compatibility requirement is preserving the dependencies and interpretation of old records; the inspected history does not establish that migration must permanently share the normal loader implementation.

Source 1

Migration was intentionally isolated from normal wallet operation to avoid notification, locking, and ownership-lifetime interactions. The original migration discussion describes unloading the wallet and reloading it without signals after hangs caused by the GUI retaining a shared pointer.

The base already loads the source in a private context, and the extracted loader explicitly keeps the legacy wallet disconnected from signals and other users. Loader separation therefore intersects an existing operational isolation requirement, rather than just class organization.

Source 1

Watch-only splitting follows the descriptor-wallet restriction against mixing private-key material and watch-only scripts. A separate solvables wallet preserves script-solving information that the legacy wallet knew without having watched the corresponding outputs; the original discussion identifies PSBT enrichment with UTXOs, scripts, and public keys as its purpose.

Migration must partition more than keys: transaction history and receiving labels follow watched ownership, whereas solvable-but-unwatched material has different historical semantics. The base copies watch-only transactions and transfers receiving address-book entries, while retaining transactions that also belong to the main wallet. Skipping raw records before reconstruction does not remove these semantic distinctions.

Source 1 · Source 2 · Source 3

Transaction-order metadata was introduced to give wallet transactions and accounting entries a fixed order rather than sorting their presentation solely by time. The original change accommodated records without an order position and deliberately encoded new accounting metadata so older versions and third-party software could continue reading and storing it.

An absent order position is therefore a historical-format compatibility case, not necessarily corruption. The base shared loader detects unordered transactions and invokes repair. The head confines that repair to legacy loading, making the transition from old records to persisted, ordered descriptor-wallet records the important compatibility boundary.

Source 1

Encrypted-key checksums were introduced to detect corruption at load time and avoid decrypting every key on each session's first unlock. For old records, checksums were to be written only after successful decryption, so corruption would not simply be given a matching checksum. Appending the checksum preserved old-reader compatibility. A later correction explicitly distinguished a missing checksum, which triggers a thorough check and rewrite, from an invalid checksum, which stops loading as corruption.

The removed checksum writes belong to a persistent legacy-format upgrade and performance mechanism. Their integrity purpose is distinct from the write itself: the head retains thorough decryption checking when needed and the partial-decryption corruption error, even though migration no longer rewrites legacy encrypted-key records.

Source 1 · Source 2 · Source 3

The independent BDB parser was designed to keep legacy-wallet dumping and migration available without retaining the Berkeley DB dependency. Its advertised interface is read-only access to the original file.

The base already uses this backend for migration. Historical automatic-upgrade code can consequently run against a database that accepts write calls without persisting them. Separating migration loading and removing legacy writes should be understood in that already-read-only setting, rather than as removing ordinary writable legacy-wallet operation.

Source 1

The original migration documentation treats conversion as best-effort across the unusually broad set of legacy script configurations and explicitly provides an original-wallet backup as the recovery route for unexpected failure or omitted scripts. It separately requires fresh backups of the resulting descriptor wallets because their address-generation configuration changes.

The pinned migration makes its legacy backup before unlocking and before deleting/replacing the BDB file. When raw legacy and transaction records are omitted from the initial SQLite copy, that original-file backup remains a different protection from successful reconstruction of the resulting wallets. It is not a substitute for backing up those resulting wallets.

Source 1

Ralph's inferences

The base copy-then-delete transaction strategy implements ownership partitioning without assuming that every transaction belongs to exactly one resulting wallet. It first preserves the original records, copies relevant transactions to the watch-only wallet, and removes only watch-only transactions that do not also belong to the main wallet. Processing in insertion order also supports recognizing spends through previously loaded transactions.

Skipping TX records during the initial transfer changes where preservation occurs: the intermediate SQLite copy no longer carries those records automatically. The same historical distinctions—main-only, watch-only-only, and shared transactions, including their wallet metadata—remain relevant when interpreting reconstruction. This is an explanation of the existing strategy, not an assessment of the replacement.

Read-only loading separates validating or repairing the in-memory legacy interpretation from durably upgrading a wallet. The backend explicitly permits automatic-upgrade write calls to succeed without writing, on the premise that upgrades can occur again after migration. The loader also avoids rewriting or upgrading after a load error so as not to worsen corruption.

Unordered-transaction repair and encrypted-key checksum handling have different persistence needs. Repaired order positions describe transaction state that the new wallets use; legacy checksum rewrites upgrade records that migration replaces. Removing source writes does not by itself remove the need to validate old encrypted keys or carry forward the repaired transaction interpretation.

Original-file recoverability, database-transaction atomicity, and completeness of reconstructed wallets are separate protections. The inspected transfer code deletes the source only after reading its records and relies on an earlier backup for critical failures. Individual SQLite transactions do not themselves establish one atomic commit spanning storage replacement and all split wallets.

The historical backup promise should not be read as proof that every intermediate SQLite state is independently usable or that automatic rollback covers every filesystem failure. Early record skipping makes the distinction between backup recovery and completed reconstruction especially important, without changing the historical reason for retaining the original backup.

Source 1

Unresolved disagreements

The original migration discussion contains competing views on solvable-only multisig compatibility. One position questioned creating a descriptor solvables wallet because it begins watching transactions and does not alone preserve the legacy signing workflow; another emphasized preserving PSBT-solving information and eliminating all legacy-wallet dependencies. The inspected sample does not resolve every workflow concern.

Watch-only and solvables splitting is not simply a lossless file-format substitution: preserving script knowledge, watched history, and signing workflows are distinct goals. This historical disagreement bounds what can be inferred from the existence of split wallets and a recovery backup.

Source 1 · Source 2 · Source 3