From d6fb1b0b3348106a51c3408cce9be8f1caeb12f8 Mon Sep 17 00:00:00 2001 From: rxbryan Date: Thu, 14 May 2026 03:31:07 +0100 Subject: [PATCH] script: support BIP-388 wallet policies rendering - Extend getdescriptorinfo to optionally return BIP-388 wallet policy template and keys for compatible multipath /* descriptors. - Move descriptor parsing logic out of getdescriptorinfo into a reusable ParseDescriptorInfo() interface returning structured DescriptorInfo. - Add unit tests validating policy generation against BIP-388 vectors. refs #32659 --- src/rpc/output_script.cpp | 42 ++-- src/script/descriptor.cpp | 440 ++++++++++++++++++++++++++++++++++ src/script/descriptor.h | 35 +++ src/test/descriptor_tests.cpp | 166 +++++++++++++ 4 files changed, 666 insertions(+), 17 deletions(-) diff --git a/src/rpc/output_script.cpp b/src/rpc/output_script.cpp index cb73fe544909..bb943907cfec 100644 --- a/src/rpc/output_script.cpp +++ b/src/rpc/output_script.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -185,6 +186,11 @@ static RPCMethod getdescriptorinfo() {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"}, {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"}, {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"}, + {RPCResult::Type::STR, "wallet_policy_template", /*optional=*/true, "BIP-388 wallet policy template with @N key placeholders. Only present if the provided descriptor is BIP-388 policy-compatible."}, + {RPCResult::Type::ARR, "wallet_policy_keys", /*optional=*/true, "BIP-388 key information vector, one \"[fingerprint/path]xpub\" per @N placeholder in order. Only present if the provided descriptor is BIP-388 policy-compatible.", + { + {RPCResult::Type::STR, "", ""}, + }}, } }, RPCExamples{ @@ -194,28 +200,30 @@ static RPCMethod getdescriptorinfo() }, [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue { - FlatSigningProvider provider; - std::string error; - auto descs = Parse(self.Arg("descriptor"), provider, error); - if (descs.empty()) { - throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); - } + auto info = ParseDescriptorInfo(self.Arg("descriptor")); + if (!info) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, util::ErrorString(info).original); UniValue result(UniValue::VOBJ); - result.pushKV("descriptor", descs.at(0)->ToString()); + result.pushKV("descriptor", info->descriptor); - if (descs.size() > 1) { - UniValue multipath_descs(UniValue::VARR); - for (const auto& d : descs) { - multipath_descs.push_back(d->ToString()); - } - result.pushKV("multipath_expansion", multipath_descs); + if (!info->expansion.empty()) { + UniValue arr(UniValue::VARR); + for (const auto& d : info->expansion) arr.push_back(d); + result.pushKV("multipath_expansion", arr); + } + + result.pushKV("checksum", info->checksum); + result.pushKV("isrange", info->is_range); + result.pushKV("issolvable", info->is_solvable); + result.pushKV("hasprivatekeys", info->has_private_keys); + + if (info->wallet_policy) { + result.pushKV("wallet_policy_template", info->wallet_policy->descriptor_template); + UniValue keys_arr(UniValue::VARR); + for (const auto& k : info->wallet_policy->keys) keys_arr.push_back(k); + result.pushKV("wallet_policy_keys", keys_arr); } - result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str())); - result.pushKV("isrange", descs.at(0)->IsRange()); - result.pushKV("issolvable", descs.at(0)->IsSolvable()); - result.pushKV("hasprivatekeys", provider.keys.size() > 0); return result; }, }; diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp index 67770ada78e0..c0ccf73a7c33 100644 --- a/src/script/descriptor.cpp +++ b/src/script/descriptor.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -158,6 +159,18 @@ std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorC typedef std::vector KeyPath; +struct MultipathContext { + struct KeyEntry { + size_t placeholder_idx; + std::unordered_set claimed_mn; + }; + + std::vector> per_key_mn; + mutable std::map> aggregate_claimed_mn; + mutable std::map key_map; + bool IsMultipath() const { return !per_key_mn.empty(); } +}; + /** Interface for public key objects in descriptors. */ struct PubkeyProvider { @@ -203,6 +216,21 @@ struct PubkeyProvider /** Get the descriptor string form. */ virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0; + /** Return the BIP-388 wallet policy placeholder for this key, or {} on failure. */ + virtual std::string ToTemplateString(size_t& placeholder_idx, size_t& traversal_idx, const MultipathContext& ctx = {}) const + { + const std::string ret{"@" + util::ToString(placeholder_idx)}; + ++placeholder_idx; + ++traversal_idx; + return ret; + } + + /** Append the last non-hardened derivation index for each @N. */ + virtual void GetDerivationIndex(std::vector& out) const {} + + /** Append the BIP32 origin and account-level xpub for each key. */ + virtual void GetKeyOrigins(std::vector>& out) const {} + /** Get the descriptor string form including private data (if available in arg). * If the private data is not available, the output string in the "out" parameter * will not contain any private key information, @@ -301,6 +329,29 @@ class OriginPubkeyProvider final : public PubkeyProvider { return std::make_unique(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe); } + + std::string ToTemplateString(size_t& placeholder_idx, size_t& traversal_idx, const MultipathContext& ctx) const override + { + return m_provider->ToTemplateString(placeholder_idx, traversal_idx, ctx); + } + + void GetDerivationIndex(std::vector& out) const override + { + m_provider->GetDerivationIndex(out); + } + + void GetKeyOrigins(std::vector>& out) const override + { + if (m_provider->IsBIP32()) { + std::optional root = m_provider->GetRootExtPubKey(); + if (root) { + out.emplace_back(m_origin, *root); + return; + } + } + // For musig, delegate so each participant emits its own origin. + m_provider->GetKeyOrigins(out); + } }; /** An object representing a parsed constant public key in a descriptor. */ @@ -591,6 +642,47 @@ class BIP32PubkeyProvider final : public PubkeyProvider { return std::make_unique(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe); } + void GetDerivationIndex(std::vector& out) const override + { + if (!m_path.empty() && m_derive == DeriveType::UNHARDENED_RANGED) { + out.push_back(m_path.back()); + } + } + std::string ToTemplateString(size_t& placeholder_idx, size_t& traversal_idx, const MultipathContext& ctx) const override + { + const size_t t_idx{traversal_idx++}; + + if (!ctx.IsMultipath() || t_idx >= ctx.per_key_mn.size() || !IsRange()) { + const std::string ret{"@" + util::ToString(placeholder_idx)}; + ++placeholder_idx; + return ret; + } + + // BIP 388 requires exactly one unhardened derivation step after the account xpub. + if (m_path.size() != 1 || m_derive != DeriveType::UNHARDENED_RANGED) { + return {}; + } + + const auto [M, N] = ctx.per_key_mn[t_idx]; + const std::string suffix{(M == 0 && N == 1) + ? "/**" + : "/<" + util::ToString(M) + ";" + util::ToString(N) + ">/*"}; + + const std::string xpub_str{EncodeExtPubKey(m_root_extkey)}; + auto it{ctx.key_map.find(xpub_str)}; + if (it != ctx.key_map.end()) { + auto& entry{it->second}; + if (entry.claimed_mn.contains(M) || entry.claimed_mn.contains(N)) return {}; + entry.claimed_mn.insert(M); + entry.claimed_mn.insert(N); + return "@" + util::ToString(entry.placeholder_idx) + suffix; + } + + ctx.key_map[xpub_str] = {placeholder_idx, {M, N}}; + const std::string placeholder{"@" + util::ToString(placeholder_idx)}; + ++placeholder_idx; + return placeholder + suffix; + } }; /** PubkeyProvider for a musig() expression */ @@ -794,6 +886,87 @@ class MuSigPubkeyProvider final : public PubkeyProvider { return 1 + m_participants.size(); } + std::string ToTemplateString(size_t& placeholder_idx, size_t& traversal_idx, const MultipathContext& ctx) const override + { + // BIP-388 disallows derivation before aggregation: + // VALID: tr(musig(@0,@1)/<0;1>/*,...) + // INVALID: tr(musig(@0/<0;1>/*,@1/<0;1>/*),...) + if (m_ranged_participants) return {}; + + const size_t first_t_idx{traversal_idx}; + // We also want to know if multiple musig expressions in a descriptor are duplicate, + // if so are they disjoint? + std::vector sorted_xpubs; + sorted_xpubs.reserve(m_participants.size()); + + std::string ret{"musig("}; + + for (size_t i{0}; i < m_participants.size(); ++i) { + const auto xpub{m_participants[i]->GetRootExtPubKey()}; + if (!xpub) return {}; + + const std::string xpub_str{EncodeExtPubKey(*xpub)}; + sorted_xpubs.push_back(xpub_str); + + auto it{ctx.key_map.find(xpub_str)}; + + if (it != ctx.key_map.end()) { + // We have seen this participant before so reuse existing placeholder. + // Musig participants are arguments to the aggregate, so BIP-388 disjointness does not apply to individual participants. + ret += "@" + util::ToString(it->second.placeholder_idx); + } else { + ctx.key_map[xpub_str] = {placeholder_idx, {}}; + ret += "@" + util::ToString(placeholder_idx); + ++placeholder_idx; + } + ++traversal_idx; + + if (i < m_participants.size() - 1) ret += ','; + } + ret += ')'; + + std::sort(sorted_xpubs.begin(), sorted_xpubs.end()); + const std::string aggregate_id{util::Join(sorted_xpubs, ",")}; + + // BIP 388 requires exactly one unhardened derivation step after the account xpub. + if (ctx.IsMultipath() && m_path.size() == 1 + && m_derive == DeriveType::UNHARDENED_RANGED + && first_t_idx + m_participants.size() <= ctx.per_key_mn.size()) { + const auto [M, N] = ctx.per_key_mn[first_t_idx]; + + // Check if the representation of the aggregate key, same set of participants, order independent exists. + // If so, we enforce disjointness. + auto& claimed = ctx.aggregate_claimed_mn[aggregate_id]; + if (claimed.contains(M) || claimed.contains(N)) return {}; + claimed.insert(M); + claimed.insert(N); + + const std::string suffix{(M == 0 && N == 1) + ? "/**" + : "/<" + util::ToString(M) + ";" + util::ToString(N) + ">/*"}; + ret += suffix; + } else { + ret += FormatHDKeypath(m_path, /*apostrophe=*/false); + if (IsRangedDerivation()) ret += "/*"; + } + + return ret; + } + void GetDerivationIndex(std::vector& out) const override + { + if (IsRangedDerivation() && !m_path.empty() + && m_derive == DeriveType::UNHARDENED_RANGED) { + for (size_t i{0}; i < m_participants.size(); ++i) { + out.push_back(m_path.back()); + } + } + } + void GetKeyOrigins(std::vector>& out) const override + { + for (const auto& p : m_participants) { + p->GetKeyOrigins(out); + } + } }; /** Base class for all Descriptor implementations. */ @@ -960,6 +1133,89 @@ class DescriptorImpl : public Descriptor return ret; } + std::optional BuildWalletPolicyKeys(WalletPolicy&& policy, size_t placeholder_idx, const MultipathContext& ctx) const + { + if (ctx.IsMultipath() && !ctx.key_map.empty()) { + std::vector keys(placeholder_idx); + std::vector> origins; + GetKeyOrigins(origins); + + // resolve duplicates via key_map + for (const auto& [origin, xpub] : origins) { + const std::string xpub_str{EncodeExtPubKey(xpub)}; + auto it{ctx.key_map.find(xpub_str)}; + if (it == ctx.key_map.end()) return std::nullopt; + const size_t N{it->second.placeholder_idx}; + if (keys[N].empty()) { + keys[N] = "[" + HexStr(origin.fingerprint) + FormatHDKeypath(origin.path) + "]" + xpub_str; + } + } + + for (const auto& k : keys) { + if (k.empty()) return std::nullopt; + } + policy.keys = std::move(keys); + return policy; + } + + std::vector> origins; + GetKeyOrigins(origins); + + if (origins.size() != placeholder_idx) return std::nullopt; + + policy.keys.reserve(origins.size()); + for (const auto& [origin, xpub] : origins) { + policy.keys.emplace_back("[" + HexStr(origin.fingerprint) + FormatHDKeypath(origin.path) + "]" + EncodeExtPubKey(xpub)); + } + return policy; + } + + // NOLINTNEXTLINE(misc-no-recursion) + virtual bool BuildWalletPolicyTemplate(std::string& out, size_t& placeholder_idx, size_t& traversal_idx, const MultipathContext& ctx = {}) const + { + std::string extra{ToStringExtra()}; + size_t pos{extra.empty() ? 0U : 1U}; + std::string ret{m_name + "(" + extra}; + + for (const auto& pubkey : m_pubkey_args) { + if (!pubkey->IsRange()) return false; + if (pos++) ret += ','; + const std::string key_str{pubkey->ToTemplateString(placeholder_idx, traversal_idx, ctx)}; + if (key_str.empty()) return false; + ret += key_str; + } + + for (const auto& sub : m_subdescriptor_args) { + if (pos++) ret += ','; + std::string sub_out; + if (!sub->BuildWalletPolicyTemplate(sub_out, placeholder_idx, traversal_idx, ctx)) return false; + ret += sub_out; + } + + out = std::move(ret) + ")"; + return true; + } + + virtual std::optional BuildWalletPolicy(const MultipathContext& ctx = {}) const + { + return std::nullopt; + } + + /** Build a complete WalletPolicy from the descriptor template and key origins. + * Returns std::nullopt on failure. + */ + // NOLINTNEXTLINE(misc-no-recursion) + std::optional DoBuildWalletPolicy(const MultipathContext& ctx) const + { + WalletPolicy policy; + size_t placeholder_idx{0}; + size_t traversal_idx{0}; + if (!BuildWalletPolicyTemplate(policy.descriptor_template, placeholder_idx, traversal_idx, ctx)) { + return std::nullopt; + } + return BuildWalletPolicyKeys(std::move(policy), placeholder_idx, ctx); + } + // NOLINTNEXTLINE(misc-no-recursion) bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const { @@ -1083,6 +1339,24 @@ class DescriptorImpl : public Descriptor } return count; } + + // NOLINTNEXTLINE(misc-no-recursion) + void GetDerivationIndex(std::vector& out) const + { + for (const auto& p : m_pubkey_args) p->GetDerivationIndex(out); + for (const auto& s : m_subdescriptor_args) s->GetDerivationIndex(out); + } + + // NOLINTNEXTLINE(misc-no-recursion) + void GetKeyOrigins(std::vector>& out) const + { + for (const auto& p : m_pubkey_args) { + p->GetKeyOrigins(out); + } + for (const auto& arg : m_subdescriptor_args) { + arg->GetKeyOrigins(out); + } + } }; /** A parsed addr(A) descriptor. */ @@ -1209,6 +1483,11 @@ class PKHDescriptor final : public DescriptorImpl { return std::make_unique(m_pubkey_args.at(0)->Clone()); } + + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + return DoBuildWalletPolicy(ctx); + } }; /** A parsed wpkh(P) descriptor. */ @@ -1242,6 +1521,11 @@ class WPKHDescriptor final : public DescriptorImpl { return std::make_unique(m_pubkey_args.at(0)->Clone()); } + + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + return DoBuildWalletPolicy(ctx); + } }; /** A parsed combo(P) descriptor. */ @@ -1315,6 +1599,11 @@ class MultisigDescriptor final : public DescriptorImpl std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), std::back_inserter(providers), [](const std::unique_ptr& p) { return p->Clone(); }); return std::make_unique(m_threshold, std::move(providers), m_sorted); } + + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + return DoBuildWalletPolicy(ctx); + } }; /** A parsed (sorted)multi_a(...) descriptor. Always uses x-only pubkeys. */ @@ -1361,6 +1650,11 @@ class MultiADescriptor final : public DescriptorImpl } return std::make_unique(m_threshold, std::move(providers), m_sorted); } + + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + return DoBuildWalletPolicy(ctx); + } }; /** A parsed sh(...) descriptor. */ @@ -1411,6 +1705,11 @@ class SHDescriptor final : public DescriptorImpl { return std::make_unique(m_subdescriptor_args.at(0)->Clone()); } + + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + return DoBuildWalletPolicy(ctx); + } }; /** A parsed wsh(...) descriptor. */ @@ -1452,6 +1751,11 @@ class WSHDescriptor final : public DescriptorImpl { return std::make_unique(m_subdescriptor_args.at(0)->Clone()); } + + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + return DoBuildWalletPolicy(ctx); + } }; /** A parsed tr(...) descriptor. */ @@ -1538,6 +1842,49 @@ class TRDescriptor final : public DescriptorImpl std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), std::back_inserter(subdescs), [](const std::unique_ptr& d) { return d->Clone(); }); return std::make_unique(m_pubkey_args.at(0)->Clone(), std::move(subdescs), m_depths); } + + // NOLINTNEXTLINE(misc-no-recursion) + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + // BIP-388 requires key expressions to include a derivation path + // suffix (/** or //*). Non-ranged keys have no such suffix. + if (!m_pubkey_args.at(0)->IsRange()) return std::nullopt; + + WalletPolicy policy; + size_t placeholder_idx{0}; + size_t traversal_idx{0}; + + const std::string internal_key{m_pubkey_args.at(0)->ToTemplateString(placeholder_idx, traversal_idx, ctx)}; + if (internal_key.empty()) return std::nullopt; + std::string ret{"tr(" + internal_key}; + + if (!m_subdescriptor_args.empty()) { + std::string scripts; + std::vector path; + for (size_t i{0}; i < m_depths.size(); ++i) { + if (i > 0) scripts += ','; + while (static_cast(path.size()) <= m_depths[i]) { + if (path.size()) scripts += '{'; + path.push_back(false); + } + std::string sub_out; + if (!m_subdescriptor_args[i]->BuildWalletPolicyTemplate(sub_out, placeholder_idx, traversal_idx, ctx)) { + return std::nullopt; + } + scripts += sub_out; + while (!path.empty() && path.back()) { + if (path.size() > 1) scripts += '}'; + path.pop_back(); + } + if (!path.empty()) path.back() = true; + } + ret += ',' + scripts; + } + ret += ')'; + policy.descriptor_template = std::move(ret); + + return BuildWalletPolicyKeys(std::move(policy), placeholder_idx, ctx); + } }; /* We instantiate Miniscript here with a simple integer as key type. @@ -1703,6 +2050,47 @@ class MiniscriptDescriptor final : public DescriptorImpl } return std::make_unique(std::move(providers), m_node.Clone()); } + + // NOLINTNEXTLINE(misc-no-recursion) + bool BuildWalletPolicyTemplate(std::string& out, size_t& placeholder_idx, size_t& traversal_idx, const MultipathContext& ctx = {}) const override + { + // Mirrors StringMaker's interface for m_node.ToString + struct TemplateStringifier { + const std::vector>& pubkeys; + size_t& placeholder_idx; + size_t& traversal_idx; + const MultipathContext& ctx; + mutable std::map cache; + + std::optional ToString(uint32_t key, [[maybe_unused]] bool& has_priv_key) const + { + if (key >= pubkeys.size()) return std::nullopt; + // toString is called twice when WRAP_C contains pk(k) and pkh(k). + // So we endup having more keys ctx.key_map than in the descriptor itself. + // since the double call always uses the seme key index, we cache the result and + // return it on repeat calls to avoid double-incrementing + // traversal_idx and triggering the claimed_mn disjointness check. + auto it{cache.find(key)}; + if (it != cache.end()) return it->second; + std::string ret{pubkeys[key]->ToTemplateString( + placeholder_idx, traversal_idx, ctx)}; + if (ret.empty()) return std::nullopt; + cache[key] = ret; + return ret; + } + }; + + bool has_priv_key{false}; + auto res = m_node.ToString(TemplateStringifier{m_pubkey_args, placeholder_idx, traversal_idx, ctx, {}}, has_priv_key); + if (!res) return false; + out = *res; + return true; + } + + std::optional BuildWalletPolicy(const MultipathContext& ctx) const override + { + return DoBuildWalletPolicy(ctx); + } }; /** A parsed rawtr(...) descriptor. */ @@ -2934,6 +3322,58 @@ std::string GetDescriptorChecksum(const std::string& descriptor) return ret; } +util::Result ParseDescriptorInfo(std::string_view descriptor) +{ + FlatSigningProvider provider; + std::string error; + auto descs = Parse(descriptor, provider, error); + if (descs.empty()) return util::Error{Untranslated(error)}; + + DescriptorInfo info; + info.descriptor = descs.at(0)->ToString(); + + if (descs.size() > 1) { + info.expansion.reserve(descs.size()); + for (const auto& d : descs) { + info.expansion.push_back(d->ToString()); + } + } + + info.checksum = GetDescriptorChecksum(std::string{descriptor}); + info.is_range = descs.at(0)->IsRange(); + info.is_solvable = descs.at(0)->IsSolvable(); + info.has_private_keys = !provider.keys.empty(); + + if (descs.size() == 2) { + const auto* desc_m{static_cast(descs[0].get())}; + const auto* desc_n{static_cast(descs[1].get())}; + Assert(desc_m && desc_n); + + std::vector m_idx, n_idx; + desc_m->GetDerivationIndex(m_idx); + desc_n->GetDerivationIndex(n_idx); + + if (m_idx.size() == n_idx.size() && !m_idx.empty()) { + MultipathContext ctx; + bool valid{true}; + + for (size_t i{0}; i < m_idx.size(); ++i) { + const uint32_t M{m_idx[i]}, N{n_idx[i]}; + if (M == N) { + valid = false; + break; + } + ctx.per_key_mn.emplace_back(M, N); + } + if (valid) { + info.wallet_policy = desc_m->BuildWalletPolicy(ctx); + } + } + } + + return info; +} + std::unique_ptr InferDescriptor(const CScript& script, const SigningProvider& provider) { return InferScript(script, ParseScriptContext::TOP, provider); diff --git a/src/script/descriptor.h b/src/script/descriptor.h index 0f1e799e8f16..694110cc573b 100644 --- a/src/script/descriptor.h +++ b/src/script/descriptor.h @@ -9,6 +9,7 @@ #include