6 minor findings · 7 suggestions
Findings
[minor] · The descriptor loader rejects order positions that migration still preserves
Accepted legacy loads can retain nOrderPos == -1, which the descriptor loader now rejects, causing rollback or an unloadable migration result; no production wallet with this combination was identified.
Location: src/wallet/walletdb.cpp:712 (head).
Details and suggested fix
LoadWalletFromBDBRO skips ReorderTransactions unless the result is LOAD_OK, but LoadWalletForMigration also accepts NONCRITICAL_ERROR and NEED_RESCAN. An unreadable ORDERPOSNEXT, for example, can leave unordered transactions unchanged. ApplyMigrationData serializes those transactions without an n field, so the new descriptor check rejects them. In ordinary builds, load_wallet=true rolls migration back, while load_wallet=false reports success and leaves a wallet that cannot subsequently load. Builds configured to abort on failed Assume abort instead. This also rejects older migrated descriptor wallets whose persistent noncritical errors suppressed the base loader's repair. Keep a tolerant in-memory repair in the descriptor loader rather than rejecting this previously accepted state.
[minor] · Pre-rename failures unnecessarily delete the untouched source wallet
For directory wallets, a refused sidecar or failed rename leaves the original intact, but migration deletes it during rollback and makes recovery depend on copying the backup back.
Location: src/wallet/legacy/migration.cpp:232 (head).
Details and suggested fix
MoveDatabase can return before replacement when it finds an unexpected destination file or cannot create the directory or perform the rename. MigrateToSQLite throws for all these errors, although m_database still points to the original BerkeleyRO file. Rollback consequently tracks and removes that original before calling RestoreWallet. The backup remains available, but a restore failure now leaves recovery to the user, and an expected refusal is reported as an unexpected exception. Have MoveDatabase report whether replacement occurred, and return false without restoration for untouched directory-wallet failures. Preserve rollback after plain-file Erase() or a successful replacement.
[minor] · spkm_migration asserts before reaching migration code
Source inspection shows that spkm_migration reaches assert(m_chain) during setup on every input; no fuzz run was performed.
Location: src/wallet/test/fuzz/scriptpubkeyman.cpp:226 (head).
Details and suggested fix
LegacyWallet always constructs its base wallet with chain=nullptr. The target still calls SetLastBlockProcessed with the initialized TestingSetup chain tip's non-null hash. That setter calls WriteBestBlock, which invokes chain().findBlock and hits the null-chain assertion before any input-dependent migration work. Use SetLastBlockProcessedInMem here so the fixture records its tip without attaching a chain or writing a locator.
[minor] · The new legacy headers mismatch the include-guard lint
Static inspection predicts that lint-include-guards.py rejects the closing comments in wallet/legacy/bdbro.h and wallet/legacy/spkm.h; the lint was not run.
Location: src/wallet/legacy/bdbro.h:112 (head).
Details and suggested fix
The lint requires the final code line to equal #endif // {header_id}, using the identifier derived from the header's path. These files end with BITCOIN_WALLET_BDBRO_H and BITCOIN_WALL_LEGACY_SPKM_H, respectively. Change the closing comments to BITCOIN_WALLET_LEGACY_BDBRO_H and BITCOIN_WALLET_LEGACY_SPKM_H. The preprocessor guards themselves still work.
[minor] · Transaction-only legacy wallets now enter the key-migration path
A legacy wallet with TX records but no key, script or watch material now fails migration at Assume(legacy_spkm); no current production path creating such a wallet was identified.
Location: src/wallet/legacy/migration.cpp:146 (head).
Details and suggested fix
MigrateToSQLite sets had_legacy_records for every skipped type, including TX. Loading transactions does not create a LegacyDataSPKM, so this input now enters DoMigration and fails with “Legacy wallet data missing” after the source has been replaced. Ordinary builds roll back; builds that abort on failed Assume abort instead. Base checked only LEGACY_TYPES, retained the copied transactions and set the descriptor flag. Track legacy material separately from skipped transactions, and preserve the transaction records in the flag-only branch. Merely excluding TX from the boolean would silently discard them.
[minor] · Migration ignores -keypool when creating active descriptors
Migration initially tops up new active descriptors to DEFAULT_KEYPOOL_SIZE rather than the configured -keypool, permanently over-expanding their ranges when a smaller value was requested.
Location: src/wallet/legacy/load.cpp:643 (head).
Details and suggested fix
LoadWalletForMigration constructs LegacyWallet directly without applying wallet arguments, leaving m_keypool_size at its default. When migration has spendable material and private keys are enabled, ApplyMigrationData creates active descriptors through GenerateNewSingleSig, which immediately tops them up using that value. Reloading with the requested smaller keypool cannot shrink the stored range. Pass the keypool setting into the isolated loader and apply the same max(configured_value, 1) clamping that base obtained through LoadWalletArgs.
Optional improvements
[suggestion] · Replacement drops legacy keys before descriptor keys commit
Between replacement and the descriptor-key commit, recovery depends on an unsynced .legacy.bak; the power-loss consequence is unverified and filesystem-dependent.
Location: src/wallet/legacy/migration.cpp:230 (head).
Details and suggested fix
MigrateToSQLite omits legacy private-key records and replaces the original before MigrateToDescriptor commits descriptor keys. During that interval, the backup is the only on-disk key copy, and BerkeleyRODatabase::Backup uses fs::copy_file without an explicit sync. A process crash requires manual backup restoration, as at base. Base already had an unsynced delete window, but its committed intermediate SQLite copy retained the legacy keys. At minimum, explicitly sync the backup and its containing directory before replacing the original so recovery does not depend on an uncommitted copy. This strengthens backup-based recovery without claiming that the whole migration is crash-atomic.
[suggestion] · The migration overload does not enforce its required wallet type
The object-taking MigrateLegacyToDescriptor overload requires LegacyWallet but accepts CWallet; current callers satisfy the requirement, so narrowing the parameter would enforce it without changing supported calls.
Location: src/wallet/legacy/migration.h:54 (head).
Details and suggested fix
The declaration documents isolation only, while the implementation performs static_pointer_cast<LegacyWallet> after checking just the descriptor flag. An isolated ordinary CWallet without that flag would pass the check but make the downcast invalid. Accept std::shared_ptr<LegacyWallet> explicitly: both LoadWalletForMigration and the benchmark already provide that type. Keep a separate CWallet-typed local for the post-migration reload loop if needed.
[suggestion] · The sole main-wallet TX writer ignores write failures
Skipping the bulk TX copy makes unchecked WriteTxMetadata failures capable of dropping history if the surrounding transaction still commits; this failure sequence has not been demonstrated.
Location: src/wallet/legacy/migration.cpp:386 (head).
Details and suggested fix
ApplyMigrationData now creates each retained main-wallet transaction record through WriteTxMetadata, but discards its boolean result. SQLiteBatch::WriteKey returns false for binding or execution errors without latching a transaction-wide failure, while RunWithinTxn proceeds to commit when its callback returns true. Return a util::Error when this write fails, and check the companion wallet's WriteFullTx result as well, so migration aborts and restores the backup rather than relying on a later commit failure to detect every statement error.
[suggestion] · The ReorderTransactions move also changes descriptor compatibility
The move commit combines mechanical relocation with rejecting previously repairable transaction records, making the compatibility decision harder to review separately.
Location: src/wallet/walletdb.cpp:712 at 72b24f8d5f52 (commit) (commit).
Details and suggested fix
72b24f8d5f52e2e07b7f5d8d71e9846ffa165dc1 moves ReorderTransactions into LegacyWallet, but also replaces descriptor-loader tracking with Assume plus CORRUPT and removes deferred repair. Its direct parent, 46b508d5ee3e86225ac1b81aef7c65142fe9b1fd, still has the repair call, and its legacy loader can call the inherited method. If retaining the stricter check, put the walletdb.cpp behavior change first in a separately explained commit, then make the relocation mechanical. Keep the later removal of ineffective source writes in 8844dd8e52badb1f36fad9cab46115f7135c44b6 separate. This preserves the final tree while exposing the compatibility rationale.
[suggestion] · The journal commit messages describe deletion instead of preservation
Two commit messages describe removing leftover journals, but their patches already reject the move and preserve those files.
Location: src/wallet/db.cpp:196 at aacc236254b2 (commit) (commit).
Details and suggested fix
At aacc236254b2bc3e936d78b587bd7527ab2c5cd4 itself, MoveDatabase returns an error for an unexpected destination sidecar before renaming anything; it does not delete that sidecar. At c8dd5265d6ffed79c5179b5ff6e57b8f382f5484 itself, both added tests expect failure and assert journal_path.exists(). Reword both messages to describe refusal and preservation rather than removal. Keeping the test-only commit separate is fine. If these commits belong to dependency PR #34909, make the wording correction there.
[suggestion] · Consecutive file renames duplicate include and guard churn
If restructuring the dependency series, moving directly from migrate.* to legacy/bdbro.* avoids reviewing an intermediate filename and its include changes twice.
Location: src/wallet/legacybdb.h:5 at aa94b02382d2 (commit) (commit).
Details and suggested fix
aa94b02382d2d02086cf68aba1a5899af2d94d35 introduces legacybdb.* and its new guard, then c755680879c2990d5e08e292160f1bee61b608cc immediately moves it to legacy/bdbro.* and changes the include sites again. Omit the intermediate rename and have c755680879c2990d5e08e292160f1bee61b608cc move migrate.* directly to the final path. The earlier extraction commits edced7df873e943d51d7c88f295c499f364d1c16 and 0adb4761c6bf9ef42fd137775a8e67b8a6328fc9 can remain separately reviewable. This preserves the final layout with one BDB rename rather than two. Retain the existing boundaries if they are needed to preserve dependency-PR traceability.
[suggestion] · The legacy transaction loader retains an unused batch capture
The unused &batch capture is expected to trigger Clang's -Wunused-lambda-capture under the project's -Wall; no build failure was observed.
Location: src/wallet/legacy/load.cpp:483 (head).
Details and suggested fix
The legacy lambda constructs CWalletTx with an empty witness-variant map and never references batch. The capture came from the descriptor loader, which still needs it for ReadWtxVariants. Remove &batch from the legacy capture list, leaving &any_unordered.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
Migration isolation was deliberate: unload the normal wallet, perform conversion without connecting its signals, and reload afterward. This avoided locking problems and GUI-held wallet references interfering with migration.
At the comparison base, migration obtained this isolation by passing an empty context to LoadExisting. LoadExisting nevertheless performed argument loading, database population, warnings, and keypool top-up; chain attachment was conditional. The isolated LegacyWallet preserves the no-chain/no-signals boundary while narrowing that loading path. The historical requirement is isolation during conversion, not use of the general-purpose loader itself.
Last-opened version/features and last-decrypted features were introduced to detect upgrade–downgrade–upgrade cycles. Automatic upgrades may need to run again after older software adds material, and upgrades needing private keys require separate tracking of decryption.
These records are upgrade bookkeeping, distinct from mandatory wallet flags that reject unsupported semantics. The base loader reads them and records successful opening only after automatic upgrades. The migration-only loader omits that general upgrade machinery, while ApplyMigrationData writes the destination's current version/features. The relevant compatibility boundary is therefore between interpreting the legacy source and declaring the converted descriptor database upgraded—not simply preserving every LoadExisting action.
Transaction reordering existed for compatibility with very old wallets lacking order positions. Historical discussion explicitly resisted dropping old-wallet compatibility and distinguished repeatable reconstruction from the preferable one-time repair that makes an old wallet behave like a new one.
The base database loader detects unordered transactions and invokes ReorderTransactions only after an otherwise clean load. Moving reconstruction into LegacyWallet places that compatibility work at the conversion boundary. The descriptor-only assumption of nonnegative order positions depends on migrated transaction records carrying the reconstructed information into the new database, rather than on the legacy source being rewritten successfully.
Source 1 · Source 2 · Source 3 · Source 4
Encrypted-key checksums distinguish an old record needing validation and upgrade from a corrupt record. Missing checksums trigger thorough checking and rewriting of encrypted keys; invalid present checksums stop loading. Valid checksums avoid unnecessary whole-wallet rewrites.
The extracted loader retains checksum validation, and LegacyDataSPKM retains the latch requiring thorough decryption checking when a checksum is absent. Removing source checksum rewrites separates two formerly coupled functions: validating old key material and persisting an optimization for later legacy loads. Since migration unlocks before conversion and replaces legacy key records with descriptor material, the validation guarantee remains relevant even when updating the read-only legacy source does not.
Migration was designed as a semantic conversion, not merely a database-format copy: watched material and its transactions/labels may move to another wallet, while the result should no longer depend on legacy wallet machinery.
Skipping legacy and TX records during the raw copy changes where preservation happens. The source loader's in-memory keys, transaction metadata, and ownership information become the inputs for constructing destination records and distributing history between wallets. The historical guarantee concerns preservation of the appropriate wallet contents, not byte-for-byte retention of legacy records in SQLite.
The stated consistency objective was success or failure, not a partially migrated wallet requiring manual restoration. Batching migration writes was justified by consistency as well as performance. Recovery also had to work without loading the restored legacy wallet when Berkeley DB writing support was unavailable.
This explains the backup-and-rollback boundary surrounding conversion and creation of companion wallets. It does not mean the comparison base already recovered automatically from every storage failure: its MigrateToSQLite deleted the original before creating and populating SQLite and asserted on several failures, explicitly relying on the backup. Temporary construction and exception-driven rollback address that same historical objective at additional failure stages.
Ralph's inferences
The existing loader's compatibility contract combined permissive old-format handling with fail-closed semantic checks; it was not a blanket rule to reject wallets whose recorded client version was newer.
Pinned code distinguishes unknown mandatory wallet flags from tolerated flags, and uses last-client information for upgrade bookkeeping and diagnostics. It also avoids automatic rewriting after any non-LOAD_OK result. The isolated loader's narrower scope therefore needs to be understood separately from both normal descriptor loading and automatic upgrade maintenance; accepting recoverable load statuses does not itself establish that every record was clean or reordered.
Temporary construction creates two different recovery phases: before replacement, abandon the temporary database while preserving the source; after possible replacement, recover through the backup.
The head constructs and commits the new database beside the source before moving it. Its false-return versus exception distinction explicitly encodes those phases. Locating temporary storage beside the actual source also supports the same-filesystem rename constraint even when the wallet is outside the configured wallet directory. The transaction that writes SQLite records and the filesystem replacement are separate operations, so database transaction atomicity alone does not cover the whole migration.
Plain-file compatibility prevents a uniform atomic-replacement guarantee: converting an existing file path into a wallet directory requires a destructive transition that ordinary wallet-directory replacement does not.
Both base and head retain plain-file-to-directory conversion. The head explicitly erases the original single file before creating the destination directory, whereas an existing directory permits replacing wallet.dat by rename. This is why backup-based rollback remains material even after temporary SQLite construction succeeds; the original cannot remain continuously available under its old pathname in the plain-file case.
A replacement SQLite database cannot be treated independently of destination sidecar files: a leftover journal may be replayed into the replacement, while deleting an unexpected file may destroy unrelated data.
The pinned head resolves this ambiguity by refusing unexpected destination sidecars and preserving them—not by deleting them, as some supplied intermediate commit descriptions suggest. Its recovery contract thus includes both preventing journal replay into the new database and limiting cleanup to migration-owned files. This constraint is additional to preserving the legacy backup.