Skip to content

wallet: store multipath descriptor - #36133

Closed
Sjors wants to merge 17 commits into
bitcoin:masterfrom
Sjors:2026/08/multipath-tag
Closed

Sjors wants to merge 17 commits into
bitcoin:masterfrom
Sjors:2026/08/multipath-tag

Conversation

@Sjors

@Sjors Sjors commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Status: this PR needs further conceptual review / discussion, before going too deep into code review.

HWI recently added a registerdescriptor command (bitcoin-core/HWI#842) which some hardware wallets require in order to (more safely) support multisig. This registration can then be used with displayaddress and signtx (using the --registration argument, see bitcoin-core/HWI#841 and bitcoin-core/HWI#841). Internally HWI converts the descriptor to a BIP388 policy. The only catch is that we need to provide a multipath descriptor, rather than separate receive and change descriptors. This PR makes that possible.

Our wallet already supported importing multipath descriptors, but upon import they are irreversibly turned into change and receive descriptors. We don't overhaul this fundamental descriptor wallet design. Rather (as per approach 5 from #36075) we store an additional record to hold on to the multipath descriptor strings and point to its matching receive and change descriptor.

Existing wallets are not impacted (and not "upgraded").

The main commits are:

  • refactor: introduce descriptor ParseState: the parser first collects keys, generates replacements (not yet normalized, just converting to public keys) and then applies those replacements (in reverse order).
  • descriptor: normalize keys in the multipath descriptor string: no record is generated if hardened derivation blocks normalization (those would be useless).
  • descriptor: let Parse return the multipath descriptor string
  • wallet: store multipath descriptor record on import

These commits make wallet handling consistent and expose the record through RPC:

  • wallet: store multipath descriptor record on wallet creation: covers default wallets and createwalletdescriptor.
  • wallet: expand multipath descriptors with 'h' hardened marker: we don't preserve the exact imported string anyway, so might as well make it consistent
  • wallet: copy multipath record in exportwatchonlywallet: remaps descriptor IDs to the destination wallet.
  • rpc: return multipath descriptor from getaddressinfo
  • rpc: return multipath descriptor from listdescriptors

The remaining commits provide parser plumbing, tests, and refactors that make the main changes easier to follow and keep the descriptor code maintainable:

  • miniscript: let FromString take a string_view
  • test: add MULTIPATH flag to descriptor test vectors: tags existing vectors
  • refactor: use util::Expected for descriptor parsers: replaces &error and introduces ParsePubkeyResult and other aliases that are expanded later (with less churn).
  • Four small helper extractions, kept as separate commits to make each change easier to review:
    • refactor: extract LastHardenedIndex helper
    • refactor: extract OriginKeyString helper
    • refactor: extract MergeNormalizedOrigin helper
    • refactor: extract HardenedPrefix helper
  • refactor: setup wallet descriptors per output type pair (dropping the loop over internal)

Based on:

@DrahtBot

DrahtBot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

Code Coverage & Benchmarks

For details see: https://corecheck.dev/bitcoin/bitcoin/pulls/36133.

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Concept ACK jeanpablojp

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #36013 (test: Descriptor roundtrip and raw()/ addr() coverage by pablomartin4btc)
  • #35998 (wallet: Handle or explicitly ignore WalletBatch write failures by achow101)
  • #35377 (wallet: Allow importing of descriptors without private keys when the wallet has the private keys by achow101)
  • #35041 (descriptor: speed-up Parse (xpub/xpriv) in ~30% by brunoerg)
  • #32861 (Have createwalletdescriptor auto-detect an unused(KEY) by Sjors)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@jeanpablojp jeanpablojp left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK

The matching approaches in #36075 work off descriptors a wallet already has, and storing a record instead means wallets created before this get none on their own.

Those get no record, and createwalletdescriptor on a pair that exists just answers Descriptor already exists. You can still rebuild one by hand, dumping the private descriptor, turning /0/* into /<0;1>/* and re-importing, which stores exactly what the new code would have. That needs the xprv though, since the public form is rejected on a wallet with private keys. Is that the intended path for existing wallets?

Comment thread src/wallet/walletdb.cpp
return DBErrors::CORRUPT;
}
}
pwallet->LoadMultipathDescriptor(std::move(multipath_desc));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two checks above reject a record whose id doesn't match its own string, and one that names a descriptor the wallet doesn't have. The string itself is never checked against those descriptors, so a record saying wpkh(record/<0;1>/*) next to an unrelated descriptor loads fine and both RPCs serve it. Is this deliberate?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC you're asking if we should Parse() the multipath string at load time and verify that it expands as expected. That's more heavy-lifting than we typically do at wallet load.

It could make sense to introduce a bitcoin-wallet command to perform a more thorough integrity check..

Comment thread src/wallet/wallet.cpp
AssertLockHeld(cs_wallet);
for (const auto& [id, multipath_desc] : m_multipath_descriptors) {
if (std::find(multipath_desc.desc_ids.begin(), multipath_desc.desc_ids.end(), desc_id) != multipath_desc.desc_ids.end()) {
return multipath_desc.descriptor;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<0;1> and <0;2> are different policies that share their /0/* expansion, so one descriptor can sit in two records and this hands back whichever the map reaches first. Would it be worth returning all of them, or refusing the ambiguity?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't seem realistic for someone to import a <0;1> and <0;2> descriptor, so I'm not too worried about supporting that. Is there a more realistic scenario?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough, I don't have a more realistic one. The idea was to avoid an arbitrary pick, but I take the point that it's over-protective for a case nobody hits.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is now prevented. But what you can do is import a multipath descriptor into a pre-existing wallet that lacked it; this then adds the record. Not a documented feature, but it's tested.

Comment thread src/wallet/wallet.cpp Outdated
// exists and if this call created at least one of its members
const bool pair_complete{GetScriptPubKeyMan(receive_id) && GetScriptPubKeyMan(change_id)};
if (!new_descs.empty() && pair_complete) {
AddMultipathDescriptor(batch, MultipathDescriptorRecord(std::move(*multipath_normalized), {receive_id, change_id}));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other two callers check this return, one warns and the other errors out. Dropped here, a failed write leaves the wallet created and reporting success with no record, and the transaction wrapping wallet setup never learns of it. Is this intended?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the missing handling and a [[nodiscard]].

Comment thread src/script/descriptor.cpp
multipath_str.replace(pos, kr.text.size(), kr.replacement);
next_pos = pos;
}
*multipath = AddChecksum(multipath_str);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The origin comes through as typed here when the key is an xpub, and normalized when it's the xprv, so desc and multipath can end up disagreeing on 84h versus 84' for the same key. Is this intended?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed multipath normalization to always uses h.

Additionally, 620bd8f now uses h when expanding multipath, so the expanded descriptors are consistent with the parent.

@Sjors

Sjors commented Sep 1, 2026 •

Copy link
Copy Markdown
Member Author

wallets created before this get none on their own.

Correct, I'll clarify in the description that this doesn't "upgrade" existing wallets. I think that's fine, because any multisig wallet using BIP388 registration is going to be new - since we don't support it yet.

since the public form is rejected on a wallet with private keys

See #35377.

@DrahtBot

DrahtBot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task macOS native, fuzz: https://github.com/bitcoin/bitcoin/actions/runs/33544094392/job/99977225999
LLM reason (✨ experimental): Fuzz test failure: descriptor_parse hit an assertion in script/descriptor.cpp (canonical_result && sp_canonical.empty()) and exited with code 1.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@achow101

achow101 commented Sep 2, 2026

Copy link
Copy Markdown
Member

Concept NACKish

My suggestion was not to store an extra record, but rather an extra field in WalletDescriptor which contains the ids of the other descriptors in the multipath. Reconstructing the multipath can be done by doing a pairwise traversal in Descriptor::ToString(), i.e. traverse all of the descriptors at the same time, entering the sub descriptors and PubkeyProviders located at the same indexes. The only difference should be a single derivation path element, so it should not be that hard to figure out where the multipath is. I'm pretty sure it would be less code too to do that. Currently on vacation, but I can look at implementing this method once I'm back.

Additionally, multipath descriptors do not inherently have a concept of receive and change descriptors. They are not limited to 2 descriptors once expanded. There should be no mention of "receive" or "change" when discussing multipath descriptors in the code.

@Sjors

Sjors commented Sep 2, 2026 •

Copy link
Copy Markdown
Member Author

IIUC you're objecting to two separate things:

  1. Storing the multipath record. You prefer to reconstruct it on the fly.
  2. The method of deriving the (normalized) multipath descriptor. You prefer to reconstruct it from individual descriptors, rather than have Parse yield it based on the original.

Given that we know the actual intended multipath descriptor at import (and wallet creation) time, it seems better to store it then. But doing so is indeed more involved, and storing the multipath becomes pointless if we do (1).

I'm pretty sure it would be less code too to do that.

The meat of the Parse change is not big, i.e. descriptor: let Parse return the multipath descriptor string and descriptor: normalize keys in the multipath descriptor string. Most of the churn in this PR comes from prep refactors.

The easiest implementation is just a regex. But having a mix of parser strategies in the already hard to understand Descriptor class, does not sound appealing.

My approach tries to stick to the existing recursive parser design.

Reconstructing the multipath can be done by doing a pairwise traversal [...] so it should not be that hard to figure out where the multipath is.

So we give a multipath descriptor to Parse, it gets split apart and then we reconstruct it? It feels wrong to throw away information this way, and essentially treat Parse as a black box. It's a sign we need to reconsider the entire Descriptor class.

I tried the approach in 2026/09/multipath-reconstruct, commit descriptor: reconstruct a multipath descriptor from its expansion 5694a99 (unpolished), with one additional prep refactor descriptor: let ToNormalizedString reject forms that are not publicly derivable fcd48f8. For that branch, I dropped the refactor commits it doesn't need, but I did keep the approach of storing a wallet record.


multipath descriptors do not inherently have a concept of receive and change descriptors.

Indeed, the Descriptor class should be agnostic, so I adjusted MultipathExtKeyNormalizationPrefix to handle more than two paths.

Also fixed the CI fuzzer failure.

@DrahtBot

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/34951927012/job/104324684735
LLM reason (✨ experimental): CI failed because the IWYU (include-what-you-use) lint check reported required header/include changes (failure generated from IWYU).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@achow101

Copy link
Copy Markdown
Member

Imo Parse should be able to take a multipath descriptor with private keys and produce a (normalized) public key descriptor, without the intermediate state of two individual descriptors. It has all the information it needs.

Parse should never return strings. it's job is to parse strings, not produce them. I think that having it produce a multipath string so that it can be stored is fundamentally the wrong way to go about this.

Even if parse could produce multipath descriptor strings, that doesn't help. We need to go from individual separated descriptor objects (not strings) to a multipath string. The wallet must not use multipath strings internally, it must not make any assumptions about the purposes of derivation paths.

Then I don't understand what you have in mind.

What I have in mind is that given multiple descriptor objects (not strings), you can walk them in simultaneously (a la ToStringHelper) to reconstruct a multipath descriptor.

This lets the next commit record key positions in the descriptor string
while its miniscript expression is parsed in place.
Use it to check whether parsing expands a descriptor into multiple descriptor.
The descriptors that a multipath descriptor expands to are new, derived
descriptors rather than user input, so give them canonical form.

When a multipath descriptor contains an apostrophe, replace them all
with 'h' and parse again.
Use util::Expected for ParsePubkeyInner, ParsePubkey, and ParseScript, so errors are returned directly instead of passed through an output argument.

The only behavior change is that a preexisting error string is cleared when nested descriptor parsing fails without producing an error message. Previously, the stale error was left intact.
Group the key expression index and signing provider shared by ParsePubkeyInner, ParsePubkey, and ParseScript in ParseState.

A later commit extends this state with key replacement collection.
Add an optional Parse() output for the unexpanded multipath descriptor. This is always a public descriptor, so ParseState optionally collects KeyReplacement entries tracking key locations in the input for private-to-public conversion.

The replacement sink is null unless the caller requests this output.
Split finding the last hardened derivation step out of
BIP32PubkeyProvider::ToNormalizedString. No behavior change. A later
commit reuses it when normalizing the keys of a multipath descriptor
string.
Split formatting the normalized public form of a derived key, i.e. its
origin followed by the extended public key at the last hardened step,
out of BIP32PubkeyProvider::ToNormalizedString. No behavior change. A
later commit reuses it when normalizing the keys of a multipath
descriptor string.
Split merging an outer key origin into an already normalized key
expression out of OriginPubkeyProvider::ToNormalizedString. No behavior
change. A later commit reuses it when normalizing the keys of a
multipath descriptor string.
Private extended keys followed by a fixed hardened prefix are now replaced by their key origin and the extended public key at the last hardened step, merging any explicit origin. This matches Descriptor::ToNormalizedString and produces BIP 388 wallet policy key expressions suitable for registering the multipath descriptor on a signing device.

A hardened multipath element or wildcard cannot be represented by a single publicly derivable multipath descriptor. Leave the Parse multipath output unset in those cases.

ParsePubkeyInner now returns an optional replacement alongside parsed providers so ParsePubkey can merge explicit key origin information before collecting it.
When importdescriptors expands a BIP 389 multipath descriptor into
separate receive and change descriptors, additionally store a record
containing the multipath descriptor string, as reported by the parser
in public form, along with the IDs of the wallet descriptors it
expanded to.

Reject overlap with a different multipath record before importing any of
the expanded descriptors.

Older wallet software ignores the new record.
Add an optional multipath field to getaddressinfo, containing the
multipath descriptor that this address' parent descriptor was expanded
from, in public form.
Add an optional multipath field to each listdescriptors entry that was
expanded from a multipath descriptor, containing the stored multipath
descriptor record. Every descriptor from the same multipath descriptor
returns the same value, always in public form.
The descriptor IDs in the record are translated to those of the
watchonly wallet.
Add SetupDescriptorScriptPubKeyManPair, used by default wallet creation
and createwalletdescriptor, which derives the receive and change
descriptors of an output type from a single multipath descriptor
string, built by a new GenerateMultipathDescriptorString.

This commit does not change behavior.
When SetupDescriptorScriptPubKeyManPair creates a descriptor pair, store
a record with the normalized multipath descriptor they derive from.

When createwalletdescriptor is used with the internal option, the record
is stored by whichever call completes the pair.
@Sjors
Sjors force-pushed the 2026/08/multipath-tag branch from f26ecc2 to 9323653 Compare September 25, 2026 11:37
@Sjors

Sjors commented Sep 25, 2026

Copy link
Copy Markdown
Member Author

Final rebase (after #36230 and #34861) so I can keep using it in Sjors#91 until there's an alternative.

(I'll close after CI is green)

What I have in mind is that given multiple descriptor objects (not strings), you can walk them in simultaneously (a la ToStringHelper) to reconstruct a multipath descriptor.

I'm going to leave that for someone else to implement.

Parse should never return strings.

That's a reasonable constraint on its own, but it leads to the (imo problematic) situation where you need to reconstruct something you already had.

Unless we implement a native multipath descriptor object, which IIUC you also don't want - and is probably even more complicated than what I did here.

@Sjors Sjors closed this Sep 28, 2026
Sjors added a commit to Sjors/bitcoin that referenced this pull request Sep 28, 2026
# Conflicts:
#	test/functional/wallet_createwalletdescriptor.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants