Review report

bitcoin/bitcoin: PR #36444

1 major finding · 6 minor findings · 11 suggestions

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

Findings

Link

[major] · Method extraction silently skips the import test's final sections

The normal functional-test entry point now skips the multipath and older() sections and six existing subtests, including the PR's new multipath_descriptor assertions.

Location: test/functional/wallet_importdescriptors.py:1085 (head).

Details and suggested fix

The class-level test_import_multipath definition ends run_test after the encrypted-wallet balance assertion. The six existing helper calls now belong to test_older, and neither extracted method is called by run_test. The framework runs run_test, rather than discovering every test_* method, so the script can finish successfully without these checks. Move the dispatch block back into run_test and call test_import_multipath() and test_older() there. Also remove the recursive test_older() call and correct the nonexistent test_multipath_import() call. Pass or regenerate the key material in the extracted helpers: extended_key and the older() section's xpub were locals of run_test and are now undefined.


Link

[minor] · Hardened-prefix normalization produces invalid multipath origins

For imports such as wpkh(xprv/<0h;1h>/*), public listdescriptors returns an unparsable multipath_descriptor whose xpub also differs between member rows.

Location: src/wallet/scriptpubkeyman.cpp:1650 (head).

Details and suggested fix

Import a checksummed wpkh(xprv/<0h;1h>/*) or wpkh(xprv/<0;1>/0h/*) with its private key. Import stores valid individual expansions, but GetMultipathString(false) reconstructs the alternatives and normalizes them using the current member's cache. Normalization copies the path through the last hardened step into the origin, producing a form such as wpkh([fp/<0h;1h>]xpubA/*). Core rejects multipath elements in origins, and each member supplies a different cached xpub for the same policy. This makes the field unusable for the stated policy-registration purpose for these imports. The individual desc fields remain valid, and the default wallet layout is unaffected because its alternatives follow a shared hardened prefix. Omit the public field when normalization would move a multipath element into the origin, and add an import-and-reparse test for these shapes.


Link

[minor] · Multipath accessors violate the manager-lock annotations

The new accessors omit required manager locks, which should trigger Clang thread-safety diagnostics in warnings-as-errors builds.

Location: src/wallet/scriptpubkeyman.cpp:1634 (head).

Details and suggested fix

GetMultipathString holds only this manager's cs_desc_man, but calls GetWalletDescriptor() on sibling managers without their mutexes. That method requires the called manager's lock. SetMultipathRelatives also writes m_wallet_descriptor, which is guarded by cs_desc_man, without acquiring it. Current callers hold cs_wallet, so no reachable runtime race was shown, but that lock does not satisfy the declared contracts. Acquire the lock in the setter. Gather sibling descriptor snapshots under their respective locks at the wallet or export layer, without retaining the current manager's lock while acquiring siblings. Simply nesting sibling locks here would introduce opposite acquisition orders as export walks the group.


Link

[minor] · Single-branch reimports erase that member's multipath relationship

Updating one branch persists singleton relatives, so its listdescriptors row loses multipath_descriptor while its sibling still reports the original policy.

Location: src/wallet/imports.cpp:232 (head).

Details and suggested fix

Import wpkh(xprv/<0;1>/*), then reimport wpkh(xprv/0/*) with a range covering the current range. AddWalletDescriptor updates the existing manager, and UpdateFrom leaves its relatives intact. The final import loop nevertheless replaces them with this request's mp_ids == [id0] and writes the descriptor. GetMultipathString requires more than one ID, so only the updated row loses the field. The same applies to a matching automatically generated branch. Reloading preserves the singleton; reimporting the full multipath descriptor restores the relationship. Change relatives only for multipath requests, preserving an existing group during single-path metadata updates, and test this across reload.


Link

[minor] · Watch-only export persists groups that its exported members cannot reconstruct

After watch-only export and restore, hardened-prefix multipath groups lose multipath_descriptor or abort listdescriptors in builds that abort on failed Assume checks.

Location: src/wallet/export.cpp:153 (head).

Details and suggested fix

For wpkh(xprv/<0;1>/0h/*), public export normalizes the members to forms like wpkh([fp/0/0h]xpubA/*) and wpkh([fp/1/0h]xpubB/*). ExportWatchOnlyWallet imports those individual strings and then attaches the remapped group IDs without checking reconstruction. The restored origins and root xpubs differ, so ReconstructMultipath fails and GetMultipathString reaches Assume(mp). Ordinary release builds omit the field; builds that abort on failed assumptions, including Debug and fuzz builds, abort. The watched scripts remain usable, and the default shared-hardened-prefix layout reconstructs correctly. Validate reconstruction of the exported members before attaching their relatives, and handle persisted reconstruction failure with a plain nullopt rather than Assume. Fixing normalization of the original multipath string alone does not repair this export path.


Link

[minor] · createwalletdescriptor leaves generated receive/change pairs unlinked

Unlike wallet initialization, createwalletdescriptor stores singleton relatives for both generated branches, so neither row reports multipath_descriptor.

Location: src/wallet/wallet.cpp:3456 (head).

Details and suggested fix

With internal omitted, createwalletdescriptor creates both directions but leaves mp_external_rel at its null default for each call. Each manager therefore stores only its own ID. This is reachable in a blank wallet after addhdkey when that key is supplied through hdkey, or when adding a missing output type. It leaves a gap in the promised multipath information for automatically generated descriptors. Carry the external manager's ID into internal-branch setup as initial wallet setup does, including when the external branch already exists and creation is skipped. Add a listdescriptors assertion to the RPC's tests.


Link

[minor] · getdescriptorinfo no longer returns the documented first branch

For multipath input, descriptor now contains the full expression rather than the documented first expansion, without a compatibility transition.

Location: src/rpc/output_script.cpp:212 (head).

Details and suggested fix

desc->ToString() retains the <a;b> expression, whereas base returned the first expanded descriptor. Clients following the documented single-path contract can consequently pass a multipath string to operations that reject it, such as generatetodescriptor or importdescriptors with internal. The updated functional expectation confirms the change but does not update that contract. Preserve the former value with desc->GetMultipathExpansion().at(0)->ToString(). If changing the RPC meaning is intentional instead, update the help and provide the documented deprecation and release-note transition, directing clients that need one branch to multipath_expansion[0].


Optional improvements

Link

[suggestion] · Descriptor evaluation re-clones the expansion at every range index

Ranged evaluation repeatedly copies descriptor trees and discards MuSig's aggregate-provider cache instead of reusing one expansion.

Location: src/rpc/util.cpp:1368 (head).

Details and suggested fix

For a ranged descriptor using the default 0 to 1000 range, this calls GetMultipathExpansion() 1001 times, including when the descriptor has only one path. Each call clones the tree. For aggregate-then-derive MuSig keys, the clones start without m_aggregate_provider, so aggregation repeats at each index rather than once per retained descriptor. Compute const auto expansions = desc->GetMultipathExpansion(); before the index loop and iterate over it, using a distinct inner variable name. This keeps the existing output order and shared signing-provider updates while avoiding the repeated work.


Link

[suggestion] · Expanded-string round trip checks the earlier reconstruction

The expanded-string section never asserts private serialization of exp_recon_pub because it reuses the earlier reconstruction and output.

Location: src/test/descriptor_tests.cpp:626 (head).

Details and suggested fix

exp_recon_pub is reconstructed from independently parsed expansion strings and checked in public form. The private call then targets recon_pub, and the equality assertion compares recon_pub_privs, which was already checked earlier. Call exp_recon_pub->ToPrivateString(prov, exp_recon_pub_privs) and compare exp_recon_pub_privs with prv so this section tests its own result. Also use mp_prv.at(0) rather than mp_pub.at(0) when constructing recon_prv in the private-input section.


Link

[suggestion] · Keypath round-trip comparison is tautological

The rewritten element-wise assertion compares res2 with itself rather than checking the reparsed child numbers against the original path.

Location: src/test/bip32_tests.cpp:475 (head).

Details and suggested fix

BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res2->at(i).ChildNumber()) always passes. Compare its second operand with res1->at(i).ChildNumber() to restore the direct numeric round-trip check. The following formatted-string equality still provides overlapping coverage.


Link

[suggestion] · Standalone-expansion lifetime check now exercises the parent

The test no longer uses a surviving expansion after destroying its multipath parent and sibling expansions.

Location: src/test/descriptor_tests.cpp:570 (head).

Details and suggested fix

The lambda now returns parsed, so the following ToString and Expand calls operate on the multipath parent itself. They do not exercise the ownership of expansions created by Clone() and ChooseMultipath(). Inside the lambda, obtain GetMultipathExpansion() and move out one element. Let the parent and other expansions leave scope before using that survivor, preserving the lifetime property described by the comment.


Link

[suggestion] · SPKM fuzz fixture stores unexpanded multipath parents

Multipath fuzz inputs create manager states that production imports do not produce and WalletDescriptor database loading rejects.

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

Details and suggested fix

A multipath parent can pass the direct Expand(0, ...) check because child-number access defaults to alternative zero. The factory then wraps the whole parent in WalletDescriptor and stores it in a manager. Real imports store each expansion separately, and FromStream rejects a multipath descriptor. These inputs therefore exercise artificial states, including multipath elements in derived origin data, rather than real per-branch managers. Select an element of GetMultipathExpansion() before both the expansion check and the WalletDescriptor construction.


Link

[suggestion] · listdescriptors assertions do not check each row's policy association

The test checks descriptor and multipath strings as separate multisets, so correctly computed policies attached to the wrong rows would pass.

Location: test/functional/wallet_listdescriptors.py:74 (head).

Details and suggested fix

Removing values from independent expected lists does not establish that a row's multipath_descriptor belongs to its desc. Swapping correctly computed pkh and tr policy strings during export or RPC assembly would preserve both multisets. Swapping stored relative groups is different and would probably fail public mode because normalization uses each row's own cached xpub. Build a mapping from each expected single-path descriptor to its expected multipath descriptor, and assert that association for both public and private listings.


Link

[suggestion] · Multipath relationship storage grows quadratically

Each of N members persists all N relative IDs, adding quadratic relationship storage without a branch-count cap.

Location: src/wallet/walletutil.h:98 (head).

Details and suggested fix

ImportDescriptor assigns the complete ordered mp_ids vector to every member, and serialization writes every copy. The ID payload is therefore 32 * N² bytes per group: 10,000 branches would require about 3.2 GB before other record data. That figure is arithmetic, not a measured import. These records are written under cs_wallet and read on reload. The usual two-branch cost is negligible, and large imports require an authenticated caller choosing the descriptor. Store the ordered group once and let members reference it through an opaque group ID. This preserves expansion order and SPKM identity while making relationship storage linear and providing one source of truth for group updates.


Link

[suggestion] · Expansion copies every alternative before selecting each branch

Cloning the complete multipath path for each branch makes alternative copying quadratic in the number of branches.

Location: src/script/descriptor.cpp:1330 (head).

Details and suggested fix

For each of k branches, GetMultipathExpansion clones the descriptor, including the BIP32PubkeyProvider::m_path element containing all k alternatives. Only afterward does ChooseMultipath replace that element with one alternative. Base constructed each branch from a fixed-length placeholder path. Select the branch during cloning so each independent output copies only its selected path. This avoids quadratic copying without changing expansion order. The extra cost comes from trusted RPC inputs, and it is negligible for the common <0;1> case.


Link

[suggestion] · Single-path origins now use heap-allocating multipath elements

Origin and PSBT paths acquire a vector allocation per element and admit multipath states that their wire serialization silently truncates.

Location: src/script/keyorigin.h:16 (head).

Details and suggested fix

Origins, PSBT derivation paths, and key metadata are single-path, but each KeyPathElement now owns a vector, typically a roughly 24-byte control block plus an allocation rather than a 4-byte index. DeserializeKeyOrigin constructs one for every four path bytes. Serialization writes only the first alternative without checking for others. An unexpanded parent's GetPubKey can copy alternatives into origin data, as in the SPKM fuzz fixture, although no current production caller serializing such an origin was found. Keep these paths in a non-multipath representation, such as a vector of SingleKeyPathElement, and reserve multipath elements for descriptor providers. The single-element serializer can retain the existing uint32 wire values.


Link

[suggestion] · GenerateWalletDescriptor leaves its Parse invariant unchecked

An internal Parse failure would now dereference null instead of throwing the former bounds-checked exception, although no current triggering input was found.

Location: src/wallet/walletutil.cpp:83 (head).

Details and suggested fix

desc goes directly into WalletDescriptor, whose constructor calls descriptor->IsRange(). The string is assembled from fixed grammar and a wallet xpub, so no current input producing a parse failure was found. Add Assert(desc) before constructing the wallet descriptor to preserve an explicit invariant failure rather than undefined behavior if this construction ever stops matching the parser.


Link

[suggestion] · ParseScript retains an unused result variable

The former result accumulator remains declared even though every parsing branch now returns directly.

Location: src/script/descriptor.cpp:2609 (head).

Details and suggested fix

ret is no longer assigned or returned anywhere in ParseScript. Delete the leftover std::unique_ptr<DescriptorImpl> ret declaration so the function reflects its new direct-return control flow.


Coverage details

Earlier concerns

Earlier reports raised these, with the titles and severities shown there. This review neither republished nor resolved them.