Skip to content

descriptor: Represent multipath descriptors in a single Descriptor object - #36442

Open
achow101 wants to merge 8 commits into
bitcoin:masterfrom
achow101:multipath-first-class
Open

achow101 wants to merge 8 commits into
bitcoin:masterfrom
achow101:multipath-first-class

Conversation

@achow101

@achow101 achow101 commented Oct 5, 2026

Copy link
Copy Markdown
Member

Currently, multipath descriptor strings treat the multipath specifiers as syntactic sugar. Once we finish parsing such a string, the multipath elements are lost as the result is the multiple distinct descriptors that the multipath is a shorthand for. This means that we are unable to return the multipath string for such descriptors.

This PR allows descriptors to actually be multipath where the multipath specifiers are represented inside of the paths of BIP32PubkeyProviders. This allows for the multipath string to be produced.

In order to achieve this, a lot of derivation path parsing is refactored. KeyPath is promoted to being its own class (which subclasses std::vector), while the individual derivation indexes become a KeyPathElement object so that the multipath elements can be represented. Furthermore, hardened derivation characters are now being stored within KeyPathElements so each element knows what the original hardened character was. This also cleans up a little bit of the descriptor implementation as we no longer have to carry around bool apostrophe in a bunch of places.

Lastly, Parse now returns a single Descriptor object, rather than a vector of them. If the descriptor is a multipath descriptor, the expansion can be retrieved using GetMultipathExpansion(). The wallet uses this and still must not store multipath descriptors.

@DrahtBot

DrahtBot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

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

External sites

Reviews

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

Type Reviewers
Concept ACK w0xlt, Sjors, pythcoiner, rkrux

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:

  • #36885 (wallet, rpc: Add analyzedescriptor for multisig setups by pablomartin4btc)
  • #36820 (refactor: remove more dead code by fanquake)
  • #36648 (descriptor, rpc, wallet: do not echo key material in error messages by fametrano)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #36070 (wallet: Add deriveHDKey interface by PraneethGunas)
  • #36005 (rpc, descriptor: warn when multipath expansion clones single-path key expressions by pythcoiner)
  • #35918 (descriptor: Expose key expression parsing by pseudoramdom)
  • #35377 (wallet: Allow importing of descriptors without private keys when the wallet has the private keys by achow101)
  • #34909 (wallet, refactor: modularise wallet by extracting out legacy wallet migration by rkrux)

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.

LLM Linter (✨ experimental)

Possible typos and grammar issues:

  • src/util/bip32.h: for a give multipath position → for a given multipath position [“give” is a typo]

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • src/qt/test/wallettests.cpp: WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1)
  • src/script/descriptor.cpp: std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, false)
  • src/script/descriptor.cpp: std::make_unique<ConstPubkeyProvider>(key_exp_index, pubkey, true)
  • src/script/descriptor.cpp: std::make_unique<ConstPubkeyProvider>(0, pubkey, false)
  • src/script/descriptor.cpp: std::make_unique<ConstPubkeyProvider>(0, pubkey, true)
  • src/test/psbt_tests.cpp: WalletDescriptor w_desc(std::move(desc), 0, 0, 10, 0)
  • src/wallet/rpc/spend.cpp: Parse(desc_str, desc_out, error, true)
  • src/wallet/scriptpubkeyman.cpp: Parse(desc_str, provider, error, false)
  • src/wallet/scriptpubkeyman.cpp: Parse(desc_str, provider, error, false)
  • src/wallet/test/util.cpp: Parse(desc_str, keys, error, false)
  • src/wallet/test/wallet_tests.cpp: WalletDescriptor w_desc{std::move(desc), 0, 0, 0, 0}
  • src/wallet/walletutil.cpp: Parse(desc_str, keys, error, false)
  • src/wallet/walletutil.cpp: WalletDescriptor w_desc(std::move(desc), creation_time, 0, 0, 0)

2026-11-24 21:29:50

@DrahtBot

DrahtBot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task ASan + LSan + UBSan + integer: https://github.com/bitcoin/bitcoin/actions/runs/37381217840/job/112003412636
LLM reason (✨ experimental): The build failed because walletload_tests.cpp assigns Parse()’s std::unique_ptr<Descriptor> result to a vector of unique pointers.

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.

@w0xlt

w0xlt commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 20, 2026
…ne object

# Conflicts:
#	src/script/descriptor.cpp
#	src/wallet/imports.cpp
#	src/wallet/test/walletload_tests.cpp
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 20, 2026
Apply the four reconstruction commits on top of the latest bitcoin#36442, keeping its newer predecessor implementation and the private-key substitution integration.
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 20, 2026
Apply the wallet relationship commits onto the latest bitcoin#36442 and bitcoin#36443 implementations. Integrate known-key substitution and repair extracted functional-test setup.
@Sjors Sjors mentioned this pull request Oct 20, 2026
7 tasks
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 20, 2026
Apply the wallet relationship commits onto the latest bitcoin#36442 and bitcoin#36443 implementations. Integrate known-key substitution and repair extracted functional-test setup.

Integration fixes carried by this merge:
- Fix Clang -Wthread-safety errors by locking each descriptor manager when
  reading its multipath descriptor or updating its relationships.
- Snapshot local keys, cache and relative IDs before acquiring relatives'
  locks, and retain shared descriptor ownership during reconstruction.
- Reconstruct exported multipath descriptors before taking the caller's
  descriptor lock, avoiding receive/change lock-order inversions.
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 20, 2026
…ne object

# Conflicts:
#	src/script/descriptor.cpp
#	src/wallet/imports.cpp
#	src/wallet/test/walletload_tests.cpp

Integration fixes carried by this merge:
- Preserve the hardened marker when deserializing single key-path elements,
  with serialize_hd_keypath coverage for hardened and unhardened children.
- Add direct KeyPath and standard-library includes, remove includes made
  unused by the single-descriptor Parse refactor, and normalize include
  ordering to pass IWYU 23.
- Guard failed Parse() results in both descriptor fuzz targets before
  multipath expansion; malformed corpus inputs otherwise dereference null.
- Include <array> for descriptor comparisons to satisfy IWYU 23 at this
  integration point.
- Construct the optional hardened marker at return after a plain-char
  suffix check, avoiding GCC 12 -Wmaybe-uninitialized in the previous
  releases CI job.
- Guard an empty key-path span before trimming a trailing slash; m/
  otherwise underflows size_t in the sanitizer bip32_tests job.
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 20, 2026
Apply the four reconstruction commits on top of the latest bitcoin#36442, keeping its newer predecessor implementation and the private-key substitution integration.

Include <variant> for the comparison operators used by multipath
reconstruction, satisfying IWYU 23 without relying on transitive includes.
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 20, 2026
Apply the wallet relationship commits onto the latest bitcoin#36442 and bitcoin#36443 implementations. Integrate known-key substitution and repair extracted functional-test setup.

Integration fixes carried by this merge:
- Fix Clang -Wthread-safety errors by locking each descriptor manager when
  reading its multipath descriptor or updating its relationships.
- Snapshot local keys, cache and relative IDs before acquiring relatives'
  locks, and retain shared descriptor ownership during reconstruction.
- Reconstruct exported multipath descriptors before taking the caller's
  descriptor lock, avoiding receive/change lock-order inversions.
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 21, 2026
…ne object

# Conflicts:
#	src/script/descriptor.cpp
#	src/wallet/imports.cpp
#	src/wallet/test/walletload_tests.cpp

Integration fixes carried by this merge:
- Preserve the hardened marker when deserializing single key-path elements,
  with serialize_hd_keypath coverage for hardened and unhardened children.
- Add direct KeyPath and standard-library includes, remove includes made
  unused by the single-descriptor Parse refactor, and normalize include
  ordering to pass IWYU 23.
- Guard failed Parse() results in both descriptor fuzz targets before
  multipath expansion; malformed corpus inputs otherwise dereference null.
- Include <array> for descriptor comparisons to satisfy IWYU 23 at this
  integration point.
- Construct the optional hardened marker at return after a plain-char
  suffix check, avoiding GCC 12 -Wmaybe-uninitialized in the previous
  releases CI job.
- Guard an empty key-path span before trimming a trailing slash; m/
  otherwise underflows size_t in the sanitizer bip32_tests job.
- Reserve the known extended-key serialization length in bip32_tests to
  avoid a GCC 14 -Warray-bounds false positive in the Windows cross build;
  the round-trip and exact serialized-size checks remain unchanged.
Sjors added a commit to Sjors/bitcoin that referenced this pull request Oct 21, 2026
Apply the four reconstruction commits on top of the latest bitcoin#36442, keeping its newer predecessor implementation and the private-key substitution integration.

Include <variant> for the comparison operators used by multipath
reconstruction, satisfying IWYU 23 without relying on transitive includes.

@Sjors Sjors left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code review up to b220521 util: Store hardened character in KeyPathElement

  • 7fac137 util: Change all key path operations to operate with std::vector: in the tests not "all" are changed. That seems better for readability, but worth pointing out in the commit message.

Comment thread src/test/bip32_tests.cpp
BOOST_CHECK(res2.has_value());
BOOST_REQUIRE_EQUAL(res2->size(), res1->size());
for (size_t i{0}; i < res2->size(); ++i) {
BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res2->at(i).ChildNumber());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In 7fac137 util: Change all key path operations to operate with std::vector

diff --git a/src/test/bip32_tests.cpp b/src/test/bip32_tests.cpp
index 3bfc2a6535..7958456e3e 100644
--- a/src/test/bip32_tests.cpp
+++ b/src/test/bip32_tests.cpp
@@ -473,5 +473,5 @@ BOOST_AUTO_TEST_CASE(parse_hd_keypath)
             BOOST_REQUIRE_EQUAL(res2->size(), res1->size());
             for (size_t i{0}; i < res2->size(); ++i) {
-                BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res2->at(i).ChildNumber());
+                BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res1->at(i).ChildNumber());
             }
             const std::string keypath_str3{FormatHDKeypath(*res2, /*hardened_char=*/'\'')};

It still passes after this fix.

Comment thread src/script/sign.cpp
CExtPubKey extpub = CreateMuSig2SyntheticXpub(agg_pub);
for (const uint32_t i : agg_info.path) {
if (i >> 31) return false; // Hardened derivation is not possible from a public key
for (const auto& i : agg_info.path) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In 7fac137 util: Change all key path operations to operate with std::vector nit: KeyPathElement& is more clear.

void DoCheck(std::string prv, std::string pub, const std::string& norm_pub, int flags,
const std::vector<std::vector<std::string>>& scripts, const std::optional<OutputType>& type, std::optional<uint256> op_compat_desc_hash = std::nullopt,
const std::set<std::vector<uint32_t>>& paths = ONLY_EMPTY, bool replace_apostrophe_with_h_in_prv=false,
const std::set<std::vector<uint32_t>>& paths_in = ONLY_EMPTY, bool replace_apostrophe_with_h_in_prv=false,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In 7fac137 util: Change all key path operations to operate with std::vector: if you make ONLY_EMPTY a const std::set<KeyPath>, the compiler makes life easier (thanks Claude...):

diff --git a/src/test/descriptor_tests.cpp b/src/test/descriptor_tests.cpp
index db090e2eb0..2866cdccc3 100644
--- a/src/test/descriptor_tests.cpp
+++ b/src/test/descriptor_tests.cpp
@@ -122,5 +122,5 @@ static size_t CountUniqueXpubs(const std::string& desc)
 }

-const std::set<std::vector<uint32_t>> ONLY_EMPTY{{}};
+const std::set<KeyPath> ONLY_EMPTY{{}};

 std::set<CPubKey> GetKeyData(const FlatSigningProvider& provider, int flags) {
@@ -172,17 +172,9 @@ std::set<std::pair<CPubKey, KeyOriginInfo>> GetKeyOriginData(const FlatSigningPr
 void DoCheck(std::string prv, std::string pub, const std::string& norm_pub, int flags,
              const std::vector<std::vector<std::string>>& scripts, const std::optional<OutputType>& type, std::optional<uint256> op_compat_desc_hash = std::nullopt,
-             const std::set<std::vector<uint32_t>>& paths_in = ONLY_EMPTY, bool replace_apostrophe_with_h_in_prv=false,
+             const std::set<KeyPath>& paths = ONLY_EMPTY, bool replace_apostrophe_with_h_in_prv=false,
              bool replace_apostrophe_with_h_in_pub=false, uint32_t spender_nlocktime=0, uint32_t spender_nsequence=CTxIn::SEQUENCE_FINAL,
              std::map<std::vector<uint8_t>, std::vector<uint8_t>> preimages={},
              std::optional<std::string> expected_prv = std::nullopt, std::optional<std::string> expected_pub = std::nullopt, int desc_index = 0)
 {
-    std::set<KeyPath> paths;
-    for (const std::vector<uint32_t>& path : paths_in) {
-        KeyPath keypath;
-        for (uint32_t elem : path) {
-            keypath.emplace_back(elem);
-        }
-        paths.emplace(std::move(keypath));
-    }
     std::set<KeyPath> left_paths = paths;

@@ -516,5 +508,5 @@ void DoCheck(std::string prv, std::string pub, const std::string& norm_pub, int
 void Check(const std::string& prv, const std::string& pub, const std::string& norm_pub, int flags,
            const std::vector<std::vector<std::string>>& scripts, const std::optional<OutputType>& type, std::optional<uint256> op_compat_desc_hash = std::nullopt,
-           const std::set<std::vector<uint32_t>>& paths = ONLY_EMPTY, uint32_t spender_nlocktime=0,
+           const std::set<KeyPath>& paths = ONLY_EMPTY, uint32_t spender_nlocktime=0,
            uint32_t spender_nsequence=CTxIn::SEQUENCE_FINAL, std::map<std::vector<uint8_t>, std::vector<uint8_t>> preimages={},
            std::optional<std::string> expected_prv = std::nullopt, std::optional<std::string> expected_pub = std::nullopt, int desc_index = 0)
@@ -543,5 +535,5 @@ void CheckMultipath(const std::string& prv,
         const std::vector<std::vector<std::vector<std::string>>>& scripts,
         const std::optional<OutputType>& type,
-        const std::vector<std::set<std::vector<uint32_t>>>& paths)
+        const std::vector<std::set<KeyPath>>& paths)
 {
     assert(expanded_prvs.size() == expanded_pubs.size());

Comment thread src/util/bip32.h Outdated

public:
KeyPathElement() = default;
KeyPathElement(uint32_t index, bool hardened) : m_index(index), m_hardened(hardened) {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In 7fac137 util: Change all key path operations to operate with std::vector: let's Assume or Assert that index < BIP32_HARDENED_FLAG.

Comment thread src/util/bip32.h
/** Derivation index, without the hardened flag */
uint32_t m_index;
bool m_hardened;
std::optional<char> m_hardened;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In b220521 util: Store hardened character in KeyPathElement: worth elaborating in the commit message why you're doing this. E.g.:

It's important for descriptor ID stability that we track whether hardened derivation used an h or apostrophe. Unify this tracking in KeyPathElement.

Note that this breaks downgrading a mixed usage miniscript:

diff --git a/test/functional/wallet_backwards_compatibility.py b/test/functional/wallet_backwards_compatibility.py
index 0d94d9107a..1e6ecc418c 100755
--- a/test/functional/wallet_backwards_compatibility.py
+++ b/test/functional/wallet_backwards_compatibility.py
@@ -340,4 +340,14 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
             assert_equal(res[0]["success"], True)

+        # A key expression that mixes both hardened markers. Older releases recompute
+        # the descriptor ID when loading, and print such an expression with a single
+        # marker.
+        node_master.createwallet(wallet_name="miniscript_mixed")
+        wallet = node_master.get_wallet_rpc("miniscript_mixed")
+        miniscript_mixed = miniscript_desc.replace("[beefdead/4h/5h]", "[beefdead/4'/5h]")
+        assert miniscript_mixed != miniscript_desc
+        res = wallet.importdescriptors([{"desc": descsum_create(miniscript_mixed), "timestamp":"now"}])
+        assert_equal(res[0]["success"], True)
+
         # Unload wallets and copy to older nodes:
         node_master_wallets_dir = node_master.wallets_path
@@ -346,4 +356,5 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
         node_master.unloadwallet("w3")
         node_master.unloadwallet("miniscript")
+        node_master.unloadwallet("miniscript_mixed")

         for node in previous_nodes:
@@ -359,9 +370,10 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
         for node in descriptors_nodes:
             self.log.info(f"- {node.version}")
-            for wallet_name in ["w1", "w2", "w3", "miniscript"]:
+            for wallet_name in ["w1", "w2", "w3", "miniscript", "miniscript_mixed"]:
+                is_miniscript = wallet_name in ("miniscript", "miniscript_mixed")
                 if self.major_version_less_than(node, 22) and wallet_name == "w1":
                     # Descriptor wallets created after 0.21 have taproot descriptors which 0.21 does not support, tested below
                     continue
-                if self.major_version_less_than(node, 24) and wallet_name == "miniscript":
+                if self.major_version_less_than(node, 24) and is_miniscript:
                     # Miniscript was introduced in 24.0
                     continue
@@ -372,5 +384,5 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
                     # result in wallets that cannot be loaded into 31.0 and 31.1.
                     # These wallets will emit a "Wallet corrupted" error.
-                    if wallet_name == "miniscript" and n.version in (310000, 310100):
+                    if is_miniscript and n.version in (310000, 310100):
                         assert_raises_rpc_error(-4, "Wallet corrupted", n.loadwallet, wallet_name)
                         continue
@@ -400,5 +412,5 @@ class BackwardsCompatibilityTest(BitcoinTestFramework):
                         assert_equal(info['private_keys_enabled'], True)
                         assert_equal(info['keypoolsize'], 0)
-                    elif wallet_name == "miniscript":
+                    elif is_miniscript:
                         descs = wallet.listdescriptors()["descriptors"]
                         assert any(desc["desc"].startswith("wsh(or_b(pk") for desc in descs), "Miniscript descriptor missing"

We could refuse to import those, but BIP380 permits it.

Or restore the previous behavior:

diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp
index 1cc3cf7c2d..6e98a22189 100644
--- a/src/script/descriptor.cpp
+++ b/src/script/descriptor.cpp
@@ -1887,4 +1887,5 @@ enum class ParseScriptContext {
  * @param[in] split BIP32 path string, using either ' or h for hardened derivation
  * @param[out] out Vector of parsed key paths
+ * @param[out] hardened only updated if hardened derivation is found
  * @param[out] error parsing error message
  * @param[in] allow_multipath Allows the parsed path to use the multipath specifier
@@ -1892,5 +1893,5 @@ enum class ParseScriptContext {
  * @returns false if parsing failed
  **/
-[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, std::string& error, bool allow_multipath, bool& has_hardened)
+[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, char& hardened, std::string& error, bool allow_multipath, bool& has_hardened)
 {
     auto parse_elem = [&](std::span<const char> elem) -> std::optional<KeyPathElement> {
@@ -1902,4 +1903,5 @@ enum class ParseScriptContext {
         if (parsed->IsHardened()) {
             has_hardened = true;
+            hardened = elem.back();
         }
         return *parsed;
@@ -1970,8 +1972,8 @@ enum class ParseScriptContext {
 }

-[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, std::string& error, bool allow_multipath)
+[[nodiscard]] bool ParseKeyPath(const std::vector<std::span<const char>>& split, std::vector<KeyPath>& out, char& hardened, std::string& error, bool allow_multipath)
 {
     bool dummy;
-    return ParseKeyPath(split, out, error, allow_multipath, /*has_hardened=*/dummy);
+    return ParseKeyPath(split, out, hardened, error, allow_multipath, /*has_hardened=*/dummy);
 }

@@ -1995,5 +1997,5 @@ static DeriveType ParseDeriveType(std::vector<std::span<const char>>& split, cha

 /** Parse a public key that excludes origin information. */
-std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t& key_exp_index, const std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, std::string& error)
+std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t& key_exp_index, const std::span<const char>& sp, ParseScriptContext ctx, FlatSigningProvider& out, char& hardened, std::string& error)
 {
     std::vector<std::unique_ptr<PubkeyProvider>> ret;
@@ -2059,7 +2061,6 @@ std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t& key_exp_
     }
     std::vector<KeyPath> paths;
-    char hardened{'h'};
     DeriveType type = ParseDeriveType(split, hardened);
-    if (!ParseKeyPath(split, paths, error, /*allow_multipath=*/true)) return {};
+    if (!ParseKeyPath(split, paths, hardened, error, /*allow_multipath=*/true)) return {};
     if (extkey.key.IsValid()) {
         extpubkey = extkey.Neuter();
@@ -2067,4 +2068,5 @@ std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkeyInner(uint32_t& key_exp_
     }
     for (auto& path : paths) {
+        path.SetHardenedChar(hardened);
         ret.emplace_back(std::make_unique<BIP32PubkeyProvider>(key_exp_index, extpubkey, std::move(path), type, hardened));
     }
@@ -2153,5 +2155,5 @@ std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkey(uint32_t& key_exp_index
             }
             bool has_hardened = false;
-            if (!ParseKeyPath(deriv_split, derivation_multipaths, error, /*allow_multipath=*/true, has_hardened)) {
+            if (!ParseKeyPath(deriv_split, derivation_multipaths, dummy, error, /*allow_multipath=*/true, has_hardened)) {
                 error = "musig(): " + error;
                 return {};
@@ -2227,7 +2229,9 @@ std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkey(uint32_t& key_exp_index
         return {};
     }
-    // This is set if either the origin or path suffix contains a hardened derivation.
+    // A key expression is always written with a single hardened marker: that of the last
+    // hardened step parsed. Descriptor IDs of wallets with Miniscript descriptors depend on this.
+    char hardened{'h'};
     if (origin_split.size() == 1) {
-        return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, error);
+        return ParsePubkeyInner(key_exp_index, origin_split[0], ctx, out, hardened, error);
     }
     if (origin_split[0].empty() || origin_split[0][0] != '[') {
@@ -2252,8 +2256,9 @@ std::vector<std::unique_ptr<PubkeyProvider>> ParsePubkey(uint32_t& key_exp_index
     std::copy_n(fpr_bytes.begin(), info.fingerprint.size(), info.fingerprint.begin());
     std::vector<KeyPath> path;
-    if (!ParseKeyPath(slash_split, path, error, /*allow_multipath=*/false)) return {};
+    if (!ParseKeyPath(slash_split, path, hardened, error, /*allow_multipath=*/false)) return {};
     info.path = path.at(0);
-    auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, error);
+    auto providers = ParsePubkeyInner(key_exp_index, origin_split[1], ctx, out, hardened, error);
     if (providers.empty()) return {};
+    info.path.SetHardenedChar(hardened);
     ret.reserve(providers.size());
     for (auto& prov : providers) {

Comment thread src/util/bip32.h Outdated
KeyPathElement() = default;
KeyPathElement(uint32_t index, bool hardened) : m_index(index), m_hardened(hardened) {}
KeyPathElement(uint32_t num) : m_index(num & ~BIP32_HARDENED_FLAG), m_hardened(num & BIP32_HARDENED_FLAG) {}
KeyPathElement(uint32_t index, std::optional<char> hardened) : m_index(index), m_hardened(hardened) {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In b220521 util: Store hardened character in KeyPathElement:

Assume(index < BIP32_HARDENED_FLAG);
Assume(!hardened || *hardened == 'h' || *hardened == '\'');

Comment thread src/util/bip32.cpp
}

std::string KeyPathElement::ToString(const std::optional<char>& hardened_char) const
{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In b220521 util: Store hardened character in KeyPathElement:

Assume(!hardened_char || *hardened_char == 'h' || *hardened_char == '\'');

(all three assumes that I suggested for this commit pass the tests)

Comment thread src/util/bip32.cpp

bool is_hardened = false;
const char last = elem.back();
char last = elem.back();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In b220521 util: Store hardened character in KeyPathElement nit: char can stay const

Comment thread src/script/descriptor.cpp
return false;
}
out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*hardened_char*/std::nullopt);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In b220521 util: Store hardened character in KeyPathElement nit: lost = in the comment.

Comment thread src/util/bip32.h
/** Write HD keypaths as strings */
std::string WriteHDKeypath(const KeyPath& keypath, bool apostrophe = false);
std::string FormatHDKeypath(const KeyPath& path, bool apostrophe = false);
std::string WriteHDKeypath(const KeyPath& keypath, const std::optional<char>& hardened_char = 'h');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In b220521 util: Store hardened character in KeyPathElement: light preference for dropping these defaults. In e.g. scriptpubkeyman.cpp‎ you're setting h anyway.

@pythcoiner pythcoiner 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

i've reviewed 2f727b3552 to 13d56f38eb and added few remarks inline

Comment thread src/util/bip32.h
const std::vector<SingleKeyPathElement>& Indexes() const { return m_indexes; }
size_t MultipathLen() const { return m_indexes.size(); }
bool IsMultipath() const { return m_indexes.size() > 1; }
const SingleKeyPathElement& Index(size_t multipath_pos) const { return m_indexes.at(multipath_pos); }

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.

2 remarks here:

  • shouldn't multipath_pos default to 0 in order to mirror ChildNumber() and IsHardened()?
  • it seems weird that Index return a SinglePathElement because its < & == operate on the child number rather the underlying m_index

Comment thread src/util/bip32.h
public:
SingleKeyPathElement() = default;
SingleKeyPathElement(uint32_t index, std::optional<char> hardened) : m_index(index), m_hardened(hardened) {}
SingleKeyPathElement(uint32_t num) : m_index(num & ~BIP32_HARDENED_FLAG), m_hardened(bool(num & BIP32_HARDENED_FLAG) ? std::optional{'h'} : std::nullopt) {}

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.

I think it worth have constant for the default hardened marker:

(see 159c260)

Comment thread src/util/bip32.h
uint32_t ChildNumber() const { return m_index | (m_hardened.has_value() ? BIP32_HARDENED_FLAG : BIP32_UNHARDENED_FLAG); }

bool IsHardened() const { return m_hardened.has_value(); }
void SetHardenedChar(char hardened)

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.

SetHardenedChar can read like if it set the hardened property, while it only overwrite the hardened char. Since all callers uses the hardcoded default char maybe the method can be renamed to smth like NormalizedHardenedMarker, it would also prevent a future caller to pass an arbitrary char?

Comment thread src/util/bip32.cpp

bool is_hardened = false;
const char last = elem.back();
char last = elem.back();

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.

const seems have inadvertly dropped

Comment thread src/script/descriptor.cpp
Comment on lines +498 to +499
BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive) {}
BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive, char hardened) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive), m_hardened(hardened) {}

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.

it seems a single constructor works?

Suggested change
BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive) {}
BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive, char hardened) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive), m_hardened(hardened) {}
BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive, char hardened = 'h') : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive), m_hardened(hardened) {}

Comment thread src/util/bip32.h

class KeyPathElement {
private:
std::vector<SingleKeyPathElement> m_indexes;

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.

I'd rename the field as the "index" semantic seems not fit there, SingleKeyPathElement carry not only the index but also the hardened marker

Suggested change
std::vector<SingleKeyPathElement> m_indexes;
std::vector<SingleKeyPathElement> m_child_numbers;

Comment thread src/test/bip32_tests.cpp
BOOST_CHECK(res2.has_value());
BOOST_REQUIRE_EQUAL(res2->size(), res1->size());
for (size_t i{0}; i < res2->size(); ++i) {
BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res2->at(i).ChildNumber());

@pythcoiner pythcoiner Nov 10, 2026 •

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.

this test currently cant fail

Suggested change
BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res2->at(i).ChildNumber());
BOOST_CHECK_EQUAL(res2->at(i).ChildNumber(), res1->at(i).ChildNumber());

Comment thread src/util/bip32.h
Comment on lines +93 to +94
bool operator<(const KeyPathElement& other) const { return m_indexes < other.m_indexes; }
bool operator==(const KeyPathElement& other) const { return m_indexes == other.m_indexes; }

@pythcoiner pythcoiner Nov 10, 2026 •

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.

maybe here it should be documented that operators apply on the child number but not on the marker char

Comment thread src/util/bip32.h

/** Parse an HD keypaths like "m/7/0'/2000". */
[[nodiscard]] bool ParseHDKeypath(const std::string& keypath_str, std::vector<uint32_t>& keypath);
std::optional<KeyPath> ParseHDKeypath(const std::string& keypath_str, bool allow_multipath = false);

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.

shouldnt we return an Expected here?

@fametrano fametrano left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The migratewallet fix holds on 0f2dc37, but the PR adds no test for it.

achow101 fixed SingleKeyPathElement::Unserialize after my inline note on 74915ef. When I migrate a v29.4 legacy watch-only wallet that holds wpkh([d34db33f/84h/0h/0h/0/5]<pubkey>), 0f2dc37 keeps the origin path 84h/0h/0h/0/5, as v31.1 does; 74915ef gave 84h/0h/0h/0h/5h. On 74915ef bip32_tests and descriptor_tests still pass. The test below reads a KeyOriginInfo back from its serialization: it fails on 74915ef (2147483648 != 0) and passes on 0f2dc37.

--- a/src/test/bip32_tests.cpp
+++ b/src/test/bip32_tests.cpp
@@ -7,6 +7,7 @@
 #include <clientversion.h>
 #include <key.h>
 #include <key_io.h>
+#include <script/keyorigin.h>
 #include <streams.h>
 #include <test/util/common.h>
 #include <test/util/setup_common.h>
@@ -480,4 +481,21 @@ BOOST_AUTO_TEST_CASE(parse_hd_keypath)
     }
 }
 
+BOOST_AUTO_TEST_CASE(key_origin_serialization_roundtrip)
+{
+    // A key origin as the wallet stores it: unhardened steps stay unhardened when read back.
+    const auto path{ParseHDKeypath("m/84h/0h/0h/0/5")};
+    BOOST_REQUIRE(path);
+    KeyOriginInfo info{};
+    info.path = *path;
+    DataStream ss{};
+    ss << info;
+    KeyOriginInfo read;
+    ss >> read;
+    BOOST_REQUIRE_EQUAL(read.path.size(), path->size());
+    for (size_t i{0}; i < read.path.size(); ++i) {
+        BOOST_CHECK_EQUAL(read.path[i].ChildNumber(), path->at(i).ChildNumber());
+    }
+}
+
 BOOST_AUTO_TEST_SUITE_END()

The script that builds the wallet, the commands and their output are in https://gist.github.com/fametrano/fc7fd1b054657138a96a73befa81da66/5dabccf7307d47f9f2063df62fb7ce93e54ca0ab.

We will want to have member functions on KeyPath later, so make it a
class now.
Moves all of the multipath parsing into ParseHDKeypath, and let
KeyPathElement be a multipath element.
Internally, descriptor parsing will produce multipath descriptor objects
rather than std::vector<DescriptorImpl>. This single multipath
descriptor becomes std::vector<Descriptor> within Parse. Future commits
will return the single multipath descriptor object for all descriptor parsing.
Instead of a std::vector<std::unique_ptr<Descriptor>>, Parse can return
a single std::unique_ptr<Descriptor> that contains the multipath
information if the descriptor was multipath. Callers that
require the multipath expansion use GetMultipathExpansion() to get the
expanded descriptors.
@DrahtBot

Copy link
Copy Markdown
Contributor

🐙 This pull request conflicts with the target branch and needs rebase.

@rkrux

rkrux commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Concept ACK for the overall refactor and plus one on returning a single object from the Parse method, I never liked reading a vector being returned from it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants