4 minor findings · 2 suggestions
Findings
[minor] · An ignored transaction insert can leave migrated history incomplete
Skipping DBKeys::TX makes an ignored WriteTxMetadata failure able to omit retained transaction history while migration reports success; production occurrence of the required committable SQLite failure is unconfirmed.
Location: src/wallet/legacy/migration.cpp:329 (head).
Details and suggested fix
MigrateToSQLite now omits transaction records, making local_wallet_batch.WriteTxMetadata(*wtx) the only insert for each transaction retained in the main wallet. Its return value is ignored. If that statement fails while the SQLite transaction remains committable, neither TxnCommit nor RunWithinTxn remembers the failure, so migration can succeed with the record absent. Base's checked initial copy preserved the original record if this later rewrite failed. Return util::Error when the insert fails so the enclosing transaction aborts and migration takes the existing backup-restoration path. Add a failure-injection test for a retained transaction. The unchecked watch-only WriteFullTx has a similar issue, but that destination already lacked a fallback in base.
[minor] · Migration can persist order positions that descriptor loading rejects
Migration can persist negative nOrderPos values that cause rollback or unloadable outputs with load_wallet=false; no current wallet producing these triggering inputs was identified.
Location: src/wallet/legacy/load.cpp:588 (head).
Details and suggested fix
LoadWalletForMigration accepts NONCRITICAL_ERROR and NEED_RESCAN, but this return skips ReorderTransactions for either result. An invalid key-metadata HD path can produce such a soft error without preventing descriptor conversion. Transactions can therefore retain -1; values below -1 also remain unnormalized because only -1 requests repair. Migration serializes these values, but normal descriptor loading now rejects every negative position. Base could repair -1 on the subsequent clean descriptor load after removing legacy metadata, and accepted values below -1. With default loading, head fails the reload and restores the backup; debug and fuzz builds can abort in Assume instead. With load_wallet=false, migration reports success without detecting the unloadable output. Normalize all negative positions before writing the outputs for every accepted load result, or explicitly reject the migration, and test these cases.
[minor] · Migration ignores -keypool when creating active descriptors
When migration creates active descriptors, a smaller-than-default -keypool setting is ignored, causing unnecessary derivation and persisted lookahead that later loads cannot shrink.
Location: src/wallet/legacy/load.cpp:643 (head).
Details and suggested fix
Base passed context.args into CWallet::LoadExisting, which initialized m_keypool_size from -keypool, clamped to at least one. LoadWalletForMigration instead constructs LegacyWallet directly and leaves m_keypool_size at DEFAULT_KEYPOOL_SIZE. When private keys are enabled and key material is migrated, active-descriptor generation uses that value for its initial top-up. For example, -keypool=1 now derives and stores the default range for every new active descriptor. A subsequent correctly configured load cannot undo the excess because TopUpWithDB only increases range ends. Pass the keypool setting into the migration loader and apply the existing clamping without restoring unrelated operational initialization.
[minor] · New legacy headers fail the include-guard lint
Source inspection shows that the closing #endif comments in bdbro.h and spkm.h would fail lint-include-guards.py; the lint was not executed.
Location: src/wallet/legacy/bdbro.h:112 (head).
Details and suggested fix
bdbro.h defines BITCOIN_WALLET_LEGACY_BDBRO_H but ends with #endif // BITCOIN_WALLET_BDBRO_H. Likewise, spkm.h defines BITCOIN_WALLET_LEGACY_SPKM_H but ends with #endif // BITCOIN_WALL_LEGACY_SPKM_H. The lint derives each guard from its file path and requires an exact match on the closing line, returning failure for either mismatch. Change both closing comments to match their defined guards.
Optional improvements
[suggestion] · The migration parameter hides its LegacyWallet requirement
Although both current callers supply LegacyWallet, the overload accepts std::shared_ptr<CWallet> and performs an unchecked downcast; a typed parameter would enforce the actual requirement.
Location: src/wallet/legacy/migration.h:53 (head).
Details and suggested fix
The declaration documents only isolation, but the implementation uses static_pointer_cast<LegacyWallet> before invoking migration-specific methods. The descriptor-flag check protects ordinary descriptor wallets, not an isolated base CWallet without that flag, which would reach an invalid downcast. Accept std::shared_ptr<LegacyWallet> instead and remove the unchecked cast. After the migration-specific operations, move ownership into a std::shared_ptr<CWallet> for the reset/reload loop, preserving its use_count() == 1 checks. Keep the isolation requirement as well.
[suggestion] · Descriptor-loading behavior changes are mixed into the ReorderTransactions move
Commit 59fd47320f9843c549bd0a4b5fd5c2233427aa80 combines method relocation with repair-to-rejection behavior, making the compatibility decision harder to review independently.
Location: src/wallet/walletdb.cpp:712 at 59fd47320f98 (commit) (commit).
Details and suggested fix
59fd47320f9843c549bd0a4b5fd5c2233427aa80 replaces unordered-position detection with Assume and CORRUPT, removes normal loading's repair call, and moves ReorderTransactions into LegacyWallet. Its direct parent, bb7c84a7ba9bae9b2db1ef9cf93bbd5aa103e014, still has both the normal-loader call through CWallet* and the legacy-loader call to the inherited method. Split the walletdb.cpp behavior change into a preceding commit, then make the remaining commit a pure move. This order keeps the inherited method available for legacy loading throughout; moving first would leave normal loading calling a member no longer on CWallet. It separates compatibility review from movement verification without changing the final tree.
Background
Ralph's summary of historical context for the behaviour affected by this change. The historical record reviewed here is incomplete.
Documented decisions
Legacy loading was deliberately reduced to the minimum necessary for migration, rather than preserved as a second operational wallet implementation.
In #26596, the author explicitly distinguished LegacyDataSPKM's indispensable migration data from operational legacy functionality that would be deleted. This supports separating conversion from CWallet::LoadExisting's normal-use initialization. The same discussion says migration must not proceed when keys cannot be decrypted: isolation does not eliminate key-integrity and decryption requirements.
Source 1 · Source 2 · Source 3
Migration and attachment to a usable, synchronized node wallet are separate operations; requiring the latter can unnecessarily prevent conversion.
#35266 describes the concrete case of a pruned node lacking blocks predating the wallet birthday and states that loading is unnecessary for migration. At the pinned base, migration already passed an empty, chainless context to LoadExisting, so chain attachment, notification registration, and rescanning were not prerequisites newly removed by the isolated loader. Normal loading of the resulting wallets remains a separate stage.
Migration is a semantic redistribution of wallet contents, not just a database-format conversion.
The original proposal specifies transferring watch-only transactions, labels, and descriptors to a separate wallet and removing them from the original. It also explicitly preserves HD chains, non-HD keys, and even the seed interpreted as a receivable private key. Consequently, the affected loader must reconstruct enough ownership, key-origin, HD-chain, transaction, and address-book information to preserve those distinctions before legacy records disappear.
The historical batching design sought both fewer disk operations and an all-or-failure migration outcome, rather than leaving a partially migrated wallet for the user to repair manually.
#28574 describes the earlier sequence of deleting legacy records, cloning and cleaning address-book entries, generating descriptors, and cloning and deleting transferred transactions. It consolidated writes into a descriptor-generation transaction and a migration-application transaction. This is the stated consistency objective behind the base's transactional erasure and commit-time cleanup; avoiding copies changes the staging mechanism, not that objective.
Transaction reordering exists to retain compatibility with very old wallets lacking order information; persisting repaired positions was discussed as making an old wallet behave like a new one.
In #4697, objections to removing ReorderTransactions explicitly emphasized compatibility with the oldest wallets. The discussion explains that without writing positions back, transactions return to nOrderPos=-1 on subsequent loads. This provides historical support for retaining normalization in legacy migration and persisting its result, but is not by itself proof that every descriptor wallet already satisfies the proposed stricter loading invariant.
Source 1 · Source 2 · Source 3 · Source 4 · Source 5
Ralph's inferences
The indispensable part of LoadExisting was its delegated reconstruction and validation of conversion inputs, not every initialization step performed by the wrapper.
The pinned base wrapper loads runtime arguments, populates the wallet, accepts specified load-result categories, warns about private keys in a private-key-disabled wallet, tops up the keypool, and conditionally attaches the chain. For migration, the conversion-critical responsibilities are database/path verification; interpreting flags before records; rejecting unsupported formats and critical corruption; validating keys and encrypted-key checksums; loading master keys, scripts, watch-only material and metadata; reconstructing active and inactive HD chains; and loading transactions, address-book data, locks, and ordering state. The head's isolated loader retains these record-oriented responsibilities. Fee policy, broadcasting configuration, wallet notifications, statistics, and operational legacy keypool top-up are not inherently needed to interpret existing records. Descriptor-cache upgrades likewise concern descriptor loading rather than pure legacy reconstruction. One qualification is that runtime arguments are not uniformly irrelevant: the base also initializes keypool size, which can affect newly generated descriptor lookahead. The inspected history does not justify treating every omitted setting or historical repair as behavior-neutral.
Copying records before deleting selected ones was a consequence of separating storage conversion from semantic conversion, rather than an independently documented requirement to write obsolete records temporarily.
At the pinned base, MigrateToSQLite first copies the complete database; ApplyMigrationData then replaces legacy key/script records with descriptors and redistributes transactions. That staging preserves unrelated records without reconstructing every record type. The separate skip-copy proposal explicitly premises omission on legacy records being replaced and transaction records already being rewritten. For that premise to hold, reconstruction must retain every required transaction body and metadata field, preserve unrelated records, and place transactions in every resulting wallet to which they belong. The inspected sources do not establish that the temporary copies themselves were required for recovery.
Source 1 · Source 2 · Source 3
Commit-time in-memory deletion protected agreement between durable transaction removal and the wallet's indexes and observers.
The pinned base's RemoveTxs stages database erasure and registers an on-commit callback that removes entries from wtxOrdered, mapTxSpends, m_txos, and mapWallet, emits deletion notifications, and invalidates cached state. Its historical change explicitly prepared removal for a broader database transaction. Deferring these effects avoids representing a transaction as deleted when the enclosing transaction aborts. An isolated object that will be discarded does not need the same external notifications, but checks and ownership decisions made before disposal still depend on a coherent distinction between retained and transferred records. Skipping a disk copy and cleaning up in-memory state address different responsibilities.
The recovery requirement is preservation of a recoverable original plus consistent completed outputs; it should not be confused with one globally atomic transaction across files and wallets.
Both pinned flows back up the legacy database before destructive replacement. The storage conversion reads records before deleting the original file, then creates SQLite storage; later migration uses database transactions and, on handled failure, removes created wallet files and restores the backup. Thus a skip-copy flow must preserve successful reconstruction, failure cleanup, and access to the original backup across the interval where the original path no longer contains the legacy database. Ordinary database rollback cannot recover a deleted source file or undo already committed changes in another wallet. The inspected code also distinguishes handled rollback from fatal filesystem/database failures, for which the backup remains the recovery resource; the historical consistency objective is not evidence of automatic crash recovery at every intermediate point.
The proposed descriptor-order invariant rests on the provenance of transaction records, not on descriptors or Bitcoin consensus intrinsically requiring order positions.
The intended argument has two branches: native wallet insertion assigns an order position—the pinned base search located wtx.nOrderPos = IncOrderPosNext(&batch)—and legacy migration computes missing positions before rewriting transaction records into descriptor wallets. Historical discussion establishes that missing positions belong to ancient-wallet compatibility and explains why repaired positions should persist. Together these premises explain why normal descriptor loading could regard a negative position as corruption rather than an upgrade request. However, the inspected evidence does not exhaust historical writers and recovery/import paths, so it does not establish the universal 'every supported descriptor wallet' claim. Nor does nonnegative ordering imply chronological, unique, or consensus-defined ordering.