descriptor: Represent multipath descriptors in a single Descriptor object

bitcoin/bitcoin: PR #36442

2 minor findings · 8 suggestions

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

Findings

Link

[minor] · getdescriptorinfo changes output without updating its RPC contract

getdescriptorinfo changes both multipath descriptor output and mixed hardened-marker rendering without updating its help, adding a release note, or providing a compatibility option.

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

Details and suggested fix

The descriptor field previously contained the first concrete expansion; it now retains all branches, although the help still promises only the first. Clients forwarding this field can consequently encounter multipath rejection in generatetodescriptor or importdescriptors with internal, or receive nested arrays from deriveaddresses. Separately, PUBLIC rendering now preserves each hardened marker rather than selecting one marker for the key expression, changing mixed-marker output strings and checksums.

Update the help to describe retained multipath notation and multipath_expansion, and document both output changes in a release note. Preserve the previous field behavior through a -deprecatedrpc option during migration, as the RPC compatibility guidelines prescribe for logical-meaning changes.


Link

[minor] · EvalDescriptorStringOrObject rebuilds descriptor branches at every index

Ranged RPC evaluation repeatedly clones even single-path descriptors and discards MuSig's cached aggregate provider instead of reusing it across indexes.

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

Details and suggested fix

GetMultipathExpansion() runs inside the range loop, whose default spans indexes 0 through 1000. It clones the descriptor even when there is only one branch. Each fresh MuSigPubkeyProvider starts without m_aggregate_provider, so aggregate-then-derive expressions rerun key aggregation at every index rather than caching it once as base did. Compute the expansion before the index loop and reuse that vector inside it. This preserves index-major output order, ExpandPrivate, and error handling. The wall-clock impact has not been measured.


Optional improvements

Link

[suggestion] · Multipath expansion makes quadratic copies of alternatives

Expanding an N-branch tuple copies its N alternatives into every branch before selection, although ordinary two-branch descriptors pay only a small constant cost.

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

Details and suggested fix

GetMultipathExpansion() calls Clone() before ChooseMultipath(). BIP32PubkeyProvider::Clone() copies m_path, including the vector containing every tuple alternative. Thus wpkh(xpub/<0;1;...;N-1>/*) copies N alternatives N times before discarding the unwanted entries. Base expanded a fixed-length path containing a scalar placeholder, and the parser imposes no tuple-length cap. Pass the selected position through cloning so BIP32 and MuSig providers are constructed directly with concrete paths, retaining positional lockstep ordering and independent ownership. Elapsed time has not been measured.


Link

[suggestion] · Unexpanded descriptors expose implicit branch-0 derivation

Unexpanded multipath descriptors can produce branch-0 keys with multipath origins that serialize lossily; no current production caller deriving from such an object was identified.

Location: src/script/descriptor.h:207 (head).

Details and suggested fix

BIP32PubkeyProvider::GetPubKey() copies the full m_path into KeyOriginInfo, but derives through ChildNumber(), whose default selects alternative 0. Origin serialization then silently writes only that alternative. Similarly, CanSelfExpand() reports true for a path such as /<0;1h>/* because its hardening check examines only the first branch. The API documents no branch-selection precondition. Make Expand, ExpandFromCache, and ExpandPrivate explicitly reject unselected multipath objects, and document selection through GetMultipathExpansion() before derivation and hardening queries, including its singleton-clone behavior for single-path input.


Link

[suggestion] · CheckMultipath misses expansion lifetime and string checks

In CheckMultipath, the ownership check now operates on the parent, and multipath string results are discarded instead of checked.

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

Details and suggested fix

The lambda returns parsed, so neither the parent nor an expansion is destroyed before the subsequent operations. DoCheck selects individual expansions but keeps their parents alive, leaving the requirement that an expanded branch outlive its parent untested. Return one entry from GetMultipathExpansion() inside the lambda and let the parent and siblings be destroyed before exercising it. Also compare the parent's public and private string rendering against the supplied multipath inputs, including hardened tuple markers. The RPC tests cover two unhardened public cases, but do not replace those assertions across this helper's fixtures.


Link

[suggestion] · parse_hd_keypath compares the reparsed element with itself

The self-comparison no longer checks whether formatting and reparsing preserve the original child numbers and hardened bits.

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

Details and suggested fix

BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res2->at(i).ChildNumber()) always succeeds. The later string-equality assertion only checks that formatting has reached a fixed point, not that the original path survived the round trip. Compare the second operand with res1->at(i).ChildNumber() to restore that check.


Link

[suggestion] · The expansion contract is corrected only during the parser rewrite

The preparatory expansion commit introduces incomplete helper semantics that the parser rewrite later corrects, making the contract harder to review independently despite a correct final tree.

Location: src/script/descriptor.cpp:278 at f0f72245c116 (commit) (commit).

Details and suggested fix

f0f72245c116c180ee080fff828408ce038c5c86 introduces the expansion API with zero default lengths, missing origin forwarding, MuSig handling limited to its aggregate path, and ChooseMultipath() rebuilding elements from child numbers, losing their hardened spelling. 73c01b29ce2fecc25b4c52d657df12d794d5e629 corrects these while also rewriting descriptor parsing. Move the default-length, forwarding, marker-preservation, and corresponding traversal changes into the preparatory commit. Index() and the element constructors already exist there, and the new API has no callers yet. This preserves the API-before-parser organization while making the complete expansion contract reviewable in the smaller commit; it is not a defect at head.


Link

[suggestion] · DoCheck continues into null dereferences after parse failure

A parser regression makes this test helper dereference a null result after reporting a nonfatal assertion failure.

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

Details and suggested fix

Both Parse results are checked with BOOST_CHECK_MESSAGE, which allows execution to continue. The following calls to parse_privs->GetMultipathExpansion() and parse_pubs->GetMultipathExpansion() therefore have undefined behavior if either parse failed. Change both checks to BOOST_REQUIRE_MESSAGE so the test stops at the diagnostic identifying the failing descriptor.


Link

[suggestion] · HasHardenedDerivation copies each visited alternatives vector

The hardening predicate deep-copies path elements on existing derivation checks solely to inspect their hardened status.

Location: src/util/bip32.cpp:137 (head).

Details and suggested fix

[](KeyPathElement index) now copies a type owning std::vector<SingleKeyPathElement>, including for ordinary single-index elements. BIP32PubkeyProvider::IsHardened() reaches this predicate during uncached GetPubKey() and CanSelfExpand(). Take const KeyPathElement& index instead, avoiding the allocation and copy while preserving the current semantics.


Link

[suggestion] · Multipath solving_data expansion lacks later-branch coverage

The pre-existing coverage gap remains: functional tests would still pass if the migrated FundTransaction loop expanded only the first descriptor branch.

Location: src/wallet/rpc/spend.cpp:641 (head).

Details and suggested fix

The existing solving_data.descriptors cases use single-path descriptors, including the sh(wsh(pkh())) fixture in rpc_psbt.py. They do not require later iterations of GetMultipathExpansion() to populate m_external_provider. Add a checksummed, non-ranged multipath descriptor such as sh(wpkh(xpub/<0;1>)), fund its second branch, and explicitly select that external input. Assert that funding fails without solving data and succeeds with the multipath descriptor. This tests all-branch expansion while matching the caller's Expand(0, ...) 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

Multipath is an ordered, lockstep expansion, not a Cartesian product. BIP 389 requires equal tuple lengths across participating key expressions, selects the same tuple position throughout each resulting descriptor, prohibits duplicate tuple values, and permits only one multipath specifier per key expression.

The single-object representation must retain the association between branch positions across all keys, including the Taproot internal key and keys in every subtree. The base parser constructs complete Taproot descriptors position by position and repeats non-multipath components; the head's recursive GetMultipathExpansion moves that responsibility out of Parse without changing what each branch denotes.

Source 1

The motivating compatibility use case is bundling nearly identical receiving and change descriptors. For that interpretation, BIP 389 assigns receiving to the first expansion and change to the second; the roles follow position, not the numerical values written in the tuple.

Wallet import must continue to assign the second branch as internal when there are exactly two expansions. Preserving only the set of derived scripts, while reordering branches, would not preserve the wallet's address-generation roles. The pinned import code retains this positional assignment before processing each single-path descriptor.

Source 1

MuSig aggregate-key derivation exists to obtain fresh payment addresses without repeatedly deriving and aggregating every participant key, reducing storage and computation. BIP 328 constructs a deterministic synthetic xpub from the aggregate public key. Because there is no aggregate private key, only unhardened aggregate derivation is possible, and signers must reproduce each BIP32 tweak when producing partial signatures.

The new path-element representation must preserve numerical child indexes and the distinction between derivation of participant keys and derivation after aggregation. Hardened aggregate suffix steps and hardened aggregate wildcards remain cryptographically unavailable, even when participant private keys were supplied. BIP 328 also notes that an aggregate key used this way acquires xpub-like privacy concerns.

Source 1 · Source 2

MuSig descriptor semantics distinguish deriving participants before aggregation from deriving the resulting aggregate key. BIP 390 specifies participant derivation before KeySort and KeyAgg, and explains sorting as making participant order irrelevant and easing recovery when the original descriptor was not backed up. Its aggregate-derivation form additionally restricts participant key forms and simultaneous derivation features.

Representing participant multipath inside one provider must not alter which participant keys are aggregated for a selected branch or confuse participant derivation with aggregate tweaks. The pinned parser's exact acceptance rules need to be preserved separately from the broader wording of the retrieved BIP.

Source 1

Compatibility descriptor hashes preserve historical string formatting because wallet database records are linked through those identifiers. PR #27920 documented that changing apostrophe-based IDs could sever those links during wallet loading and rewriting. It explicitly extended compatibility formatting to hardened origin paths as well as derivation suffixes.

Storing the original hardened character in each element must not make existing wallet identifiers depend on whether an equivalent path was entered with h or an apostrophe. CompatDescriptorHash still hashes the compatibility string, rather than the ordinary public rendering. This is an internal wallet compatibility requirement, not a BIP 380 descriptor identifier.

Source 1 · Source 2 · Source 3

PSBT was designed for interoperable signing across clients, including offline and hardware signers. Its derivation metadata identifies a concrete key using a fingerprint and a sequence of 32-bit little-endian child indexes; it does not encode descriptor syntax or alternative branches. BIP 174 also places shared xpubs at the highest hardened derivation point so public descendants can be derived.

Changing KeyOriginInfo from integer vectors to richer path elements must preserve the existing binary index encoding and hardened high bit. Hardened-character spelling is textual metadata, not an additional wire field. The selected branch must already be concrete when origins are supplied to a PSBT signer; the richer descriptor object does not itself extend PSBT serialization.

Source 1

Ralph's inferences

The compatibility boundary is the ordered expansion, not Parse's former vector return type. A successful single-object Parse must retain all branches, and consumers that previously processed the vector must obtain equivalent ordered single-path descriptors. Existing checksum validation, rejection of incomplete parses, and private-key extraction remain independent obligations.

The base API returned expanded descriptors; the head validates the checksum and complete input consumption before returning one object, with GetMultipathExpansion providing the former branch-level representation. This separates representation changes from changes to the descriptor language or derived outputs.

Source 1

For MuSig, the exact pinned restrictions are more specific than a general prohibition on combining derivation features: aggregate derivation requires BIP32 participants and forbids ranged participants; participant multipath is positionally paired with equal lengths; simultaneous participant multipath and aggregate multipath is rejected. Hardened aggregate derivation is forbidden, but that is not a blanket prohibition on hardened participant derivation.

These are the existing parser guarantees that the single-object API must carry forward. They distinguish cryptographic impossibility from descriptor-language restrictions whose full historical motivation was not recovered.

Source 1

External-signer setup has its own receive/internal contract rather than treating every returned string as a general multipath import request. PSBT signing likewise expects concrete origins that the device can match to owned keys.

The pinned setup iterates separate receive and internal arrays, creates one manager per descriptor, and explicitly rejects multipath results. A single returned Descriptor object must therefore not be mistaken for a single-path descriptor merely because Parse no longer returns a vector. The inspected signer documentation also says PSBTs should include derivations and signers should fail when none match their keys.