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

bitcoin/bitcoin: PR #36897

4 minor findings · 1 suggestion

Earlier concerns neither republished nor resolved: 2 major findings · 7 minor findings · 7 suggestions. See the Run archive for their assessments.

Findings

Link

[minor] · Accepted noncritical loads can produce wallets rejected for missing nOrderPos

Migration can persist unordered transactions after an accepted noncritical load, producing a descriptor wallet the new loader rejects; no current wallet with the required combination was identified.

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

Details and suggested fix

LoadWalletFromBDBRO skips ReorderTransactions on NONCRITICAL_ERROR, although LoadWalletForMigration accepts that result. An invalid HD keypath can cause this warning without preventing descriptor construction. If the wallet also contains transactions with nOrderPos == -1, ApplyMigrationData writes them without ordering metadata. Base removed the offending legacy metadata and reconstructed order during descriptor reload; the new loader instead returns CORRUPT. With load_wallet=true, this causes rollback. With load_wallet=false, migration can report success but leave an unloadable wallet. Builds configured to abort on failed Assume terminate during reload instead. Run the now-memory-only reconstruction for every accepted load result before writing destination transactions, and test the combined conditions with both loading options.

This requires unordered legacy history that survived older clients' own non-OK-load guard, or an externally written file.


Link

[minor] · Migration ignores -keypool when creating active descriptors

Migration initializes new active descriptors with the default range of 1000 instead of honoring -keypool, adding persistent derivation and storage work when users request smaller pools.

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

Details and suggested fix

Base migration called LoadWalletArgs through CWallet::LoadExisting, which set m_keypool_size from the clamped -keypool argument. LoadWalletForMigration now constructs LegacyWallet without initializing that setting. When a spendable wallet receives new active descriptors, SetupDescriptorScriptPubKeyMans passes the default to GenerateNewSingleSig, which immediately tops up their ranges. A later normal load cannot shrink those ranges. With load_wallet=false, configured values above 1000 also never reach the migration output. Pass the clamped keypool size into the migration loader without restoring chain attachment, and test a non-default value against the resulting descriptor ranges.


Link

[minor] · TX records incorrectly trigger legacy-key migration

Files containing TX but no LEGACY_TYPES records now fail migration instead of taking the descriptor-flag-only path; no current Core-created wallet with this layout was identified.

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

Details and suggested fix

MigrateToSQLite sets had_legacy_records for every skipped type, but the caller's skip set includes TX as well as LEGACY_TYPES. A file containing transactions alone therefore enters DoMigration, where GetDescriptorsForLegacy finds no LegacyDataSPKM and reports “Legacy wallet data missing” after the database has been replaced. Ordinary builds restore the backup; builds that abort on failed Assume terminate instead. Base tested only for actual legacy records and took the descriptor-flag-only path. Keep legacy-record detection specific to LEGACY_TYPES, and preserve transaction copying when taking the no-legacy branch so that narrowing the flag does not silently discard the skipped transactions.


Link

[minor] · Replacement is published before a durable key copy is guaranteed

The replacement omits legacy keys before descriptor commit and relies on an unsynced backup, creating a conditional power-loss exposure; no filesystem-specific failure was observed.

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

Details and suggested fix

MigrateToSQLite now filters out legacy key records before committing and publishing the replacement database. The descriptor keys are committed later by MigrateToDescriptor. During that interval, recovery depends on the .legacy.bak file, which BerkeleyRODatabase::Backup creates with fs::copy_file without explicitly syncing its contents or directory entry. On a filesystem that persists the source replacement before the backup data, a power failure could leave neither file with recoverable keys. Base committed raw key records into the replacement before publishing it. Sync the backup file and its directory before removing or replacing the source. A plain process kill is not newly harmful here: the completed backup remains available, and base also required manual restoration after interruption at this stage.


Optional improvements

Link

[suggestion] · Migration overload does not enforce its required wallet subtype

The object-taking overload accepts std::shared_ptr<CWallet> despite requiring LegacyWallet, leaving an unchecked downcast; both current callers already provide the required subtype.

Location: src/wallet/legacy/migration.h:54 (head).

Details and suggested fix

The declaration documents only isolation, but the implementation uses static_pointer_cast<LegacyWallet> after the descriptor-wallet check and then invokes legacy-only methods. A plain non-descriptor CWallet can therefore compile as an argument despite violating the implementation's subtype requirement. Take std::shared_ptr<LegacyWallet> instead. The filename overload already holds that type, and the benchmark's unique_ptr<LegacyWallet> can convert to it. Keep a separately upcast shared_ptr<CWallet> for the later reload loop. This enforces the boundary without changing either current caller's behavior.


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

Disabling normal legacy-wallet loading was not intended to abandon legacy wallet.dat compatibility: migration remained the supported route to the new format.

The dedicated loader replaces the migration-only use of CWallet::LoadExisting, not the compatibility commitment itself. The original migration proposal explicitly covered both HD and non-HD keys, including the seed as a receivable private key. Separating the loader therefore must retain the legacy data needed for equivalent descriptor construction.

Source 1 · Source 2 · Source 3

Migration deliberately operates on an isolated wallet and reloads the result afterward; attaching signals during conversion has no benefit. Migration also has valid uses that do not require loading the result into the current node.

The base LoadExisting call used a context without a chain, avoiding AttachChain and its notification registration and rescan. The dedicated loader must preserve that isolation. The later load_wallet option was motivated by pruned nodes that cannot rescan the wallet's history, so conversion must remain distinct from chain attachment and ordinary wallet use.

Source 1 · Source 2

Conversion is a semantic redistribution, not merely a database-format change: descriptor wallets cannot mix watch-only and private-key material in the legacy manner, so related transactions and labels may move to separate wallets.

This explains why the previous flow copied records and subsequently removed legacy records and watch-only-only transactions. The skip-copy flow must preserve the final ownership partition, including transactions relevant to both resulting wallets and associated address-book metadata. The original proposal also required a new backup after migration because the resulting wallet structure and active descriptors change.

Source 1 · Source 2

The predecessor skip-copy proposal justified omitting legacy and transaction records because migration replaces the former with descriptor records and already rewrites the latter.

The historical justification is replacement completeness, not that these records are disposable. At the pinned head, filtering happens while collecting records, before database replacement, and transaction persistence occurs during ApplyMigrationData. Skipped information must therefore survive in the loaded migration state until its destination representation is written.

Source 1

Migration's failure-handling changes were motivated by automatic recovery without manual intervention: build the SQLite replacement before touching the original, catch conversion failures, and restrict cleanup to migration-owned files and directories.

The base conversion explicitly distinguishes failures that leave the source untouched from failures after replacement that must enter backup restoration. The cleanup history includes an unnamed wallet whose parent was the shared wallets directory, making directory-wide deletion unsafe. Filtering records earlier does not change these replacement and cleanup guarantees.

Source 1 · Source 2

Restoring a failed migration must not leave a read-only BDB wallet loaded as though it were usable normally.

The SQLite-only-build failure discussion explicitly identified this risk when RestoreWallet attempted to reload the legacy backup. With normal legacy loading disabled, the pinned rollback restores the backup with load_after_restore=false and verifies that no wallet was loaded. A migration-specific loader must not weaken that boundary.

Source 1 · Source 2 · Source 3

Persistent transaction order predates descriptor wallets: the 2012 change introduced a fixed wallet order, assigned positions on insertion, represented missing positions as -1, and tested reconstruction of mixed ordered and unordered history.

Reordering is an upgrade for old wallet history, not a descriptor-specific ordering policy or blockchain ordering rule. The pinned base reconstructs missing positions using receipt time while offsetting existing positions, then persists changed transaction metadata and the next-position counter.

Source 1

Ralph's inferences

CWallet::LoadExisting supplied established decoding, validation, and load-result handling; its ordinary runtime setup was not itself necessary for migration.

The base path populated the wallet, accepted LOAD_OK, NONCRITICAL_ERROR, and NEED_RESCAN, and attached to the chain only when one was supplied. Compatibility obligations visible in the dedicated loader include checksum-less historical keys with key-pair validation, optional encrypted-key checksums, HD path strings and key-origin metadata, inactive HD chains, address-book data, persistent locks, and transaction metadata. Safety also includes validating an obsolete default key, rejecting unsupported wkey records, and avoiding upgrade work after a non-OK load result. Removing source-write attempts does not remove these decoding and corruption checks.

The descriptor-wallet ordering invariant rests on supported provenance, not merely the descriptor flag: native wallets are created under an insertion path that assigns and writes order positions, while migrated wallets normalize legacy history and persist its replacement records.

Native descriptor wallets were introduced as newly created wallets, after persistent ordering already existed. The pinned AddToWallet assigns nOrderPos through IncOrderPosNext and writes the transaction; migration's base loader invokes reconstruction for unordered history. These paths explain why ordinary descriptor loading can expect ordering metadata. They do not establish that an arbitrary edited, corrupted, or third-party-produced database has valid ordering.

Source 1 · Source 2 · Source 3

Deferred reconstruction must persist both every changed transaction position and the reconstructed next-position counter in the destination databases; successful read-only loading is not evidence that either was saved.

The read-only backend deliberately returns success for upgrade writes without modifying the source. The previous reconstruction wrote changed nOrderPos values and ORDERPOSNEXT together. Once reconstruction becomes memory-only, destination persistence must carry both pieces forward, including the watch-only wallet's applicable transactions and counter. Copying the original raw counter cannot substitute for persisting a reconstructed value, and the obligation applies even when the user elects not to load the migrated wallets immediately.

Source 1

Copy-then-delete is not itself the demonstrated safety requirement; the requirements are complete replacement of intentionally omitted records, preservation of other records, and an intact recovery boundary.

The base conversion copied opaque records wholesale, while the predecessor proposal identifies specific types whose replacement makes copying unnecessary. A skip-copy conversion consequently must retain unfiltered records, finish reading and constructing the temporary database before destructive replacement, and route any later conversion or requested-load failure through bounded cleanup and backup restoration. This states the historical contract, not an assessment of whether the current series satisfies it.

Source 1 · Source 2 · Source 3