1 major finding · 5 minor findings · 6 suggestions
Earlier concerns neither republished nor resolved: 2 minor findings. See the Run archive for their assessments.
Findings
[major] · spkm_migration aborts during setup on every input
The chainless LegacyWallet makes setup reach assert(m_chain) before migration logic; the supplied experiment reproduced this on four head inputs and reported passing base runs.
Location: src/wallet/test/fuzz/scriptpubkeyman.cpp:226 (head).
Details and suggested fix
LegacyWallet always passes nullptr as its chain, but the harness still calls SetLastBlockProcessed with the fixture's tip hash. That setter calls WriteBestBlock, which calls chain().findBlock whenever the stored hash is non-null. Consequently, every input aborts before exercising LegacyDataSPKM::MigrateToDescriptor. Remove the chain-tip initialization from this chainless harness. Replacing it directly with SetLastBlockProcessedInMem is not sufficient because that method is private.
[minor] · Accepted legacy-load errors can leave migrated transactions without ordering
A legacy wallet combining unordered transactions with a tolerated load error can produce records the descriptor loader now rejects; no real wallet with this combination was identified.
Location: src/wallet/walletdb.cpp:712 (head).
Details and suggested fix
LoadWalletFromBDBRO skips ReorderTransactions for every non-LOAD_OK result, although LoadWalletForMigration accepts NONCRITICAL_ERROR and NEED_RESCAN. For example, invalid HD-path key metadata can produce a tolerated error while leaving transactions at nOrderPos == -1. Migration removes the legacy metadata and rewrites the transactions without an "n" field. Base descriptor loading could then repair their ordering; the new check instead returns CORRUPT, or aborts in Assume-aborting builds. With load_wallet=true, ordinary builds roll migration back. With load_wallet=false, migration reports success but leaves a wallet that later fails to load, requiring backup restoration. Previously migrated but not yet loaded files can contain the same records; no other in-tree producer was identified. Run the now-in-memory reordering for every load status migration accepts, and retain descriptor-side repair for existing unordered files rather than asserting their absence.
[minor] · Migration ignores -keypool when generating active descriptors
The specialized loader leaves m_keypool_size at its default, so active descriptors generated during migration ignore nondefault -keypool values.
Location: src/wallet/legacy/load.cpp:643 (head).
Details and suggested fix
Previously, migration passed context.args through LoadExisting, which initialized m_keypool_size using LoadWalletArgs. LoadWalletForMigration now constructs the wallet directly without applying that setting. ApplyMigrationData subsequently creates active descriptors using the unchanged default and immediately tops them up. With -keypool=1, this derives and persists the default 1000 entries per descriptor, and later loading cannot shrink the ranges because top-up preserves the existing range end. Values above the default instead remain undersized until normal loading tops them up. Initialize m_keypool_size from the migration context with the existing minimum-one clamp before generating descriptors, and test a nondefault keypool range.
[minor] · Legacy header closing guards violate the include-guard lint
By inspection, the closing guard comments in legacy/bdbro.h and legacy/spkm.h would make lint-include-guards.py fail.
Location: src/wallet/legacy/bdbro.h:112 (head).
Details and suggested fix
lint-include-guards.py derives the guard identifier from the header path and requires the final code line to match it exactly. Change bdbro.h's closing comment from BITCOIN_WALLET_BDBRO_H to BITCOIN_WALLET_LEGACY_BDBRO_H, and spkm.h's from BITCOIN_WALL_LEGACY_SPKM_H to BITCOIN_WALLET_LEGACY_SPKM_H.
[minor] · Unused &batch capture causes a Clang warning-as-error failure
By inspection, Clang -Wall -Werror builds would reject the unused &batch capture with -Wunused-lambda-capture; no Clang failure was recorded.
Location: src/wallet/legacy/load.cpp:483 (head).
Details and suggested fix
The legacy LoadTxRecords lambda captures [&any_unordered, &batch], but its body never references batch. Unlike the descriptor loader, it deserializes with an empty witness-variant map rather than calling ReadWtxVariants. Remove &batch from the capture list.
[minor] · Concurrent migrations can delete each other's temporary database
Same-second concurrent migrations can choose the same unreserved temporary path and delete each other's files; no real occurrence of this race was identified.
Location: src/wallet/legacy/migration.cpp:168 (head).
Details and suggested fix
The unnamed wallet and a top-level plain-file wallet named default_wallet both compute walletdir/default_wallet_sqlite_<seconds>.tmp. Concurrent RPCs can both pass the absence check before one creates the database. If the other then receives FAILED_ALREADY_EXISTS, remove_tmp_and_fail still removes every entry in that directory. On systems permitting unlinking open files, this deletes the first migration's database and makes its eventual move fail. Base used distinct final database paths. These wallets already share a timestamped backup name, so the newly triggered rollback can also restore the other wallet's overwritten backup. Reserve the temporary directory exclusively, using a unique suffix and collision retry, and enable cleanup only after this invocation creates it.
Optional improvements
[suggestion] · The migration overload does not enforce its LegacyWallet requirement
MigrateLegacyToDescriptor accepts shared_ptr<CWallet> but requires an unchecked downcast to LegacyWallet; no current caller supplies the wrong type.
Location: src/wallet/legacy/migration.cpp:646 (head).
Details and suggested fix
The overload documents only that the wallet must be isolated, yet it performs static_pointer_cast<LegacyWallet> before calling legacy-only methods. An isolated ordinary CWallet therefore satisfies the documented contract but permits an invalid downcast. Both existing callers already hold a LegacyWallet: the name-based entry point receives one from LoadWalletForMigration, and the benchmark constructs one directly. Require std::shared_ptr<LegacyWallet> at entry, then upcast to std::shared_ptr<CWallet> for reload and cleanup bookkeeping. This enforces the new class boundary without changing current caller behavior.
[suggestion] · Skipping legacy keys extends the backup-only recovery window
Compared with base, skipping legacy keys extends the existing backup-only recovery window through descriptor generation, rather than ending it at the initial SQLite copy commit.
Location: src/wallet/legacy/migration.cpp:649 (head).
Details and suggested fix
MigrateToSQLite now excludes KEY, CRYPTED_KEY and the other legacy records before replacing the original database. The live path therefore contains no key material until MigrateToDescriptor commits, after deriving HD ranges and inferring imported descriptors. An interruption during that work leaves recovery dependent on .legacy.bak; normal loading rejects the intermediate legacy-flagged SQLite wallet, and migration refuses it because it is not BDB. The backup uses fs::copy_file without an explicit durability sync, so power-loss durability is not established. Base also had a backup-only interval during initial SQLite creation, but retained legacy keys once that copy committed. Keep copying the legacy key records and erase them within the apply transaction, as before, so the longer descriptor-generation phase does not extend that exposure.
[suggestion] · Pre-replacement move failures unnecessarily delete the original wallet
A directory wallet whose move fails before replacement is still rolled back by deleting its intact original and restoring the backup.
Location: src/wallet/legacy/migration.cpp:230 (head).
Details and suggested fix
A leftover wallet.dat-journal, directory-creation failure, or failed rename can make MoveDatabase return without replacing a directory wallet's BDB file. MigrateToSQLite nevertheless throws, leaving m_database pointing at that original. Rollback then collects its path, deletes it, and calls RestoreWallet. Recovery normally reproduces the original, but a restore failure leaves only the backup even though restoration was unnecessary. Have MoveDatabase report whether the destination was modified. Return without restoration for untouched directory-wallet failures, while retaining rollback after a plain-file Erase() or successful rename.
[suggestion] · Migration-failure tests do not verify file preservation or retryability
The new assertions would miss changes beyond the BDB header, modifications to the blocking file, and residual state that prevents retrying migration.
Location: test/functional/wallet_migration.py:249 (head).
Details and suggested fix
test_stale_journal and test_db_named_as_journal check the RPC error, journal existence, temporary-file cleanup and assert_is_bdb, which reads only 16 bytes. The journal failures currently delete and restore the original, so preserving its remaining pages is a meaningful invariant. Hash wallet.dat and the blocking journal before migration and compare them after failure. Then move the blocker aside, retry migration, and verify ownership of an address obtained before the failure. Apply the same preservation and retry checks to the permission test when read-only permissions can be enforced.
[suggestion] · The ReorderTransactions move also changes descriptor-load compatibility
The move commit combines relocation with rejection of unordered descriptor transactions, making a behavior change harder to validate independently.
Location: src/wallet/walletdb.cpp:712 at d1582ce6bff4 (commit) (commit).
Details and suggested fix
Commit d1582ce6bff404eb3a5a3d14d30e04223a41d0f6, titled as moving ReorderTransactions to LegacyWallet, also replaces unordered-transaction detection with Assume(nOrderPos >= 0) returning CORRUPT and removes descriptor-side repair. Split it with the behavior change first, documenting both the ordering invariant and compatibility impact while leaving CWallet::ReorderTransactions available to the legacy loader. Then move the method into LegacyWallet. This preserves the final tree and keeps both commits buildable; moving the method first would force removal of the descriptor call in that same commit.
[suggestion] · The journal-test commit message describes deletion instead of preservation
The message points reviewers at leftover-file removal, while the tested contract is refusing migration and preserving that file.
Location: test/functional/wallet_migration.py:217 at 789af4aebffa (commit) (commit).
Details and suggested fix
Commit 789af4aebffad1cbb9a7ab777444ca115f3c8895 says it covers “leftover file removal” introduced by 0b636b5c86822573987f6324ef99124a7809289a. That robustness commit instead makes MoveDatabase reject an unexpected sidecar, and the test commit explicitly asserts that the journal remains. Reword the message to say it covers refusing migration when another database file exists at the destination. This accurately identifies the file-preservation behavior the tests protect.
Earlier concerns
Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.
- [minor]: An ignored transaction insert can leave migrated history incomplete (earlier report)
- [minor]: Transaction records alone trigger the missing-legacy-data path (earlier report)
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
Migration recovery is intended to be automatic, not merely to report an RPC error and leave the user to repair disk state. The recovery discussion distinguishes failures while the original database is untouched from failures after it may have been removed or replaced. It also explicitly includes exceptions during creation or population of watch-only and solvables wallets in the rollback objective.
This explains the series’ distinction between returning an error before replacement and throwing into the outer restoration path afterward. It also explains why partially populated auxiliary wallets must remain represented in cleanup state: returning the exception text alone does not satisfy the intended disk-state recovery behavior. This is a historical design objective, not evidence that every failure path already met it at the comparison base.
Source 1 · Source 2 · Source 3 · Source 4
A wallet’s RPC name is also a filesystem path, potentially outside the wallet directory. Backup naming was therefore deliberately separated from that path: #32273 placed backups at the top level of walletdir using a single basename component. Restoration of a legacy backup is also distinct from loading it for normal use; #31451 avoided reloading legacy wallets when writable BDB support was unavailable.
MigrationFilePrefix preserves the name-versus-path distinction for backup and temporary filenames. The pinned restoration routine copies the backup into a directory’s wallet.dat without overwriting an existing database; migration invokes it without loading the restored legacy wallet. Consequently, recovery promises preservation of the legacy database, not necessarily preservation of a plain-file layout or restoration as a live wallet.
Rollback cleanup must not equate a wallet’s parent directory with disposable migration output. The unnamed-wallet recovery failure discussed in #34156 could delete the shared wallets directory. The corrective boundary was to remove specific database files associated with migration objects and only empty directories created for auxiliary wallets, rather than recursively removing wallet directories.
Both pinned base and head preserve the main wallet directory and track auxiliary directories separately. This history makes ownership of cleanup targets important for temporary databases, auxiliary wallets, and pre-existing destination files: successful restoration must not come at the expense of unrelated wallets or user data.
The recovery discussion specifically motivated building the temporary database beside the original, on the destination filesystem. A rename avoids leaving a partially copied wallet.dat, avoids copying a potentially large database, and retains data SQLite has already synchronized instead of relying on an unsynchronized copy followed by source deletion.
The head creates the temporary SQLite database under the original database’s parent directory. This is a durability and replacement-boundary decision, not simply a temporary-file placement preference. The historical comment explicitly covers both directory wallets and plain-file wallets located outside walletdir.
Database cleanup has a lifecycle and a file-set requirement: close the SQLite connection before deleting its files, and account for a journal left by a failed commit or rollback. The historical discussion notes that deletion with an open connection can fail on Windows, while other platforms may leave SQLite writing to an unlinked file.
This supplies historical context for resetting the temporary database before cleanup and for treating Files() as more than wallet.dat. At the pinned head, SQLite’s file inventory includes wallet.dat-journal, and MoveDatabase checks non-data-file destinations before moving the data file. The more specific hot-journal corruption explanation is stated in pinned code rather than established by the inspected historical comments.
Migration’s loading lifecycle was deliberately isolated from normal wallet ownership and notifications. In the original migration proposal, the author explained that unloading first and then loading without connecting signals resolved locking and hanging problems, including waiting for a shared pointer held by the GUI.
The comparison base reused CWallet::LoadExisting with an empty, chainless context, obtaining common database population and compatibility processing without registering an operational wallet. The head replaces that reuse with LoadWalletForMigration while retaining isolation; successful descriptor outputs are still discarded and normally loaded through the regular context afterward. The historical reason for isolation remains applicable even though the loading implementation is separated.
Rewriting transactions during migration was introduced specifically to persist changes made while loading, including adding nOrderPos, and to establish dependable transaction contents for later descriptor-wallet changes. The discussion explicitly answers why copying BDB records is insufficient: migration opens a BerkeleyRODatabase, so loader attempts to persist those upgrades do not write anything.
The base migration already rewrites retained main-wallet transactions and writes complete watch-only transactions. The specialized legacy loader retains unordered-transaction detection and reordering. These are the historical premises behind moving reordering to the legacy side and expecting migrated descriptor transactions to contain order information; the requirement is not justified merely by changing class or namespace ownership.
Source 1 · Source 2 · Source 3
Ralph's inferences
Directory-wallet replacement and plain-file conversion have different atomicity boundaries. A directory wallet permits replacement of its wallet.dat by rename; a plain wallet file must first cease occupying the pathname that becomes the new wallet directory. Thus the latter needs backup-based recovery across a file-to-directory transition, rather than an atomic file replacement.
The head explicitly delays the plain-file erase until the temporary database is populated, then routes subsequent failures through restoration. Its destination-sidecar check also reflects a separate assumption: an unrelated or interrupted SQLite journal must not be allowed to act on the replacement database. The code explains that SQLite could otherwise roll stale pages into it; refusing an unexpected file also avoids assuming that a journal-shaped filename is disposable.
Omitting normal loading work depends on treating the source as a transient, read-only legacy conversion object—not as an operational wallet or a descriptor wallet requiring current descriptor upgrades. The specialized loader still needs to reconstruct keys, HD metadata, addresses, decryption material, transactions, and ordering. Runtime configuration, keypool top-up, chain attachment, descriptor-cache upgrades, and version bookkeeping have different purposes and cannot all be dismissed merely because they once shared one function.
The base common lifecycle performed those additional duties, whereas the head legacy loader contains only legacy population and ordering. Conversion separately writes current opened/decrypted feature information, and the output normally undergoes regular loading. Historical feature-version work also documents upgrade–downgrade–upgrade compatibility, so omitted bookkeeping should be understood in that context. The inspected record supports this division of responsibilities but does not independently prove every omission harmless.
Filtering legacy and TX records before copying relies on semantic reconstruction already being available in memory. Legacy key/script records are replaced by descriptors; transactions must be serialized from their loaded, upgraded objects and assigned to the appropriate output wallets, rather than preserved indiscriminately as raw source records.
The base already erased legacy records, removed watch-only-only transactions from the main output, and rewrote retained transactions in insertion order so spend lookups worked. The head moves the exclusion earlier while retaining reconstruction and later reload of the resulting files. The same dependency underlies the nOrderPos invariant: legacy ordering repair must reach the serialized output, while newly created descriptor transactions are assumed to have order information from inception. The inspected history establishes the migration half of that assumption, not every possible descriptor-file provenance.
Unresolved disagreements
The recovery record contains a broader retention-policy tension. The minimal unnamed-wallet fix restricted deletion to identified files and empty created directories, while a participant argued that migration or wallet data should never be deleted even when believed uninteresting. The inspected discussion does not resolve that broader policy.
This distinguishes the concrete cleanup boundary present in pinned code from a stronger, unresolved preference to retain all migration artifacts. It is relevant to deletion of temporary and partially created wallets, but is not a finding about this series.