wallet, rpc: Add analyzedescriptor for multisig setups

bitcoin/bitcoin: PR #36885

2 minor findings · 7 suggestions

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

Findings

Link

[minor] · Cached account-derived constants are misreported as watch_only

A constant key cached from an imported account xprv with a master origin is reported as watch_only, with can_sign=false for wpkh(P), when the wallet lacks that master, despite being signable.

Location: src/wallet/descriptor_analyzer.cpp:130 (head).

Details and suggested fix

Import wpkh([fpM/84h/1h/0h]xprvA/0/*) without the master key and let the descriptor derive P. HasPrivKey(P) misses because the stored private key is the account root. The recorded origin names fpM, but MatchHDKeys only has xpubA, whose fingerprint differs, so analyzing wpkh(P) remains WATCH_ONLY even after unlocking. The manager can nevertheless derive the private key through its cached index and ExpandPrivate. This affects constant-key analysis, not the extended cosigner slots covered by the known exact-matching limitation. Use the manager's cached derivation index to check its private-key capability instead of relying solely on the master-origin lookup, reporting UNKNOWN if that check requires unlocking. Add locked and unlocked regression cases with an account xprv carrying a master origin; the existing derived-constant fixture imports a master xprv and misses this case.


Link

[minor] · CheckRepeatedKeys repeats quadratic public derivations

A trusted analysis call on a crafted 999-slot sortedmulti_a leaf performs about 250,000 parent derivations per branch; multipath repeats the work, and wall-clock cost is unmeasured.

Location: src/script/descriptor_analyzer.cpp:213 (head).

Details and suggested fix

Use 500 copies of xpub A and 499 unrelated xpubs advertising A as their parent with unhardened child numbers. Each child's fingerprint lookup returns all 500 copies. Although those copies already share a group, the child never joins it, so IsDirectChild performs a derivation for every pair: 249,500 calls per branch. Existing duplicate issues do not short-circuit this work, and AnalyzeDescriptor(span) repeats it for every multipath expansion without an explicit branch-count limit. A coordinator can supply this descriptor for a trusted RPC or GUI client to analyze; the wallet-free work precedes cs_wallet. Cache repeated (parent xpub, nChild) derivations and bound candidate-parent work as well. Caching alone does not cover parents sharing a public point but carrying distinct chain codes.


Optional improvements

Link

[suggestion] · No wallet-level advisory identifies threshold-sized local ownership

For a 2-of-3 using two hardened sibling accounts from this wallet, recognized and can_sign are both true; per-key ownership exposes this, but no advisory explains that the wallet alone meets the threshold.

Location: src/wallet/descriptor_analyzer.cpp:170 (head).

Details and suggested fix

With an unlocked master deriving cosigner accounts at m/48h/1h/0h/2h and m/48h/1h/1h/2h, MatchHDKeys returns MINE for both slots. The structural checks cannot link hardened siblings, and CanSign() returns true upon finding either key. Add a non-blocking wallet-level advisory listing the owned cosigner IDs when the number of MINE entries in analysis.cosigners reaches the threshold. Count neither UNKNOWN entries nor MuSig participant occurrences. This would surface accidental signing concentration without requiring every setup client to reconstruct the check, while leaving the wallet-free analysis.recognized verdict unchanged.


Link

[suggestion] · Analysis help omits direct-child detection's metadata dependency

The help lists unhardened child xpubs as detectable without noting that edited parent fingerprints or child numbers evade that check, even though it already acknowledges other undetectable relationships.

Location: src/rpc/descriptor_util.cpp:30 (head).

Details and suggested fix

CheckRepeatedKeys selects candidate parents through child.fingerprint, and IsDirectChild derives only at child.nChild. Editing those fields leaves public derivation unchanged, so a real child with a different suffix, such as A/0/* beside its child's /1/*, can avoid all three grouping checks. Qualify HELP_DESCRIPTOR_ANALYSIS and the DescriptorAnalysis header to say that direct-child detection requires accurate parent-fingerprint and child-number metadata. Explain that these are best-effort duplicate checks, not a guarantee against deliberate disguise; the implementation comment already acknowledges that metadata can hide a child.


Link

[suggestion] · analyzedescriptor omits multipath and format-stability qualifications

Unlike getdescriptorinfo verbose, analyzedescriptor does not mark the shared formats experimental or explain that keys describes the first multipath expansion while analysis checks every branch.

Location: src/wallet/rpc/wallet.cpp:1095 (head).

Details and suggested fix

For a multisig key expression A/<0;1h>/*, an issue from the hardened second branch refers to the same key ID displayed with the first branch's /0/* derivation. Without the first-path explanation, that result appears contradictory. The shared keys and analysis formats also carry an EXPERIMENTAL warning in only one RPC. Add both qualifications to the analyzedescriptor help so callers can interpret branch-specific issues and understand the formats' stability consistently.


Link

[suggestion] · Locked-wallet tests never combine MINE and UNKNOWN

An early UNKNOWN return in CanSign() would pass the current tests even though a later MINE must make can_sign true.

Location: src/wallet/test/wallet_interfaces_tests.cpp:246 (head).

Details and suggested fix

The unit and functional locked-wallet cases test uncertain ownership separately from known ownership. They do not exercise CanSign() continuing past UNKNOWN to find MINE, which the current implementation correctly does. Reuse the locked master fixture with AccountKey(master)/0/* and the master xpub's /0/* in one descriptor, in both orders. Assert the corresponding UNKNOWN and MINE entries, CanSign()==true, and that the wallet remains locked.


Link

[suggestion] · Address tests miss failure after a successful multipath branch

The current address tests would still pass if a later derivation failure left a partial first_addresses list.

Location: src/wallet/test/wallet_interfaces_tests.cpp:223 (head).

Details and suggested fix

The interface contract requires an empty list if any branch cannot derive its first address. Existing assertions cover two successful branches and a failing single-path descriptor, so neither depends on first_addresses.clear(). Extend the public-only foreign-xpub case with wpkh(xpub/<0;1h>/*) and assert an empty list. Its first branch succeeds and its second needs an unavailable private key, directly exercising the all-or-nothing behavior.


Link

[suggestion] · WalletHDKeys duplicates descriptor traversal and cache copies under cs_wallet

Each analysis copies every manager's WalletDescriptor, including its cache, twice under cs_wallet; one inventory pass could build the same HD-key map without those copies.

Location: src/wallet/descriptor_analyzer.cpp:142 (head).

Details and suggested fix

GetHDPubKeys(All) copies each WalletDescriptor to collect ordinary root xpubs. WalletHDKeys then copies it again through GetWalletDescriptor().descriptor->GetKeyInventory() solely to add MuSig participants. The inventory already contains both sets of BIP32 roots. Build the map from an empty map in one pass over every BIP32Key, preserving each root's manager association, and obtain the inventory through a manager accessor under cs_desc_man without copying DescriptorCache. This leaves gethdkeys unchanged and removes redundant work; the practical latency benefit depends on cache sizes and has not been measured.


Link

[suggestion] · Analysis helpers are introduced and repackaged two commits later

Commit 32280f54 introduces analysis serialization and inline help in output_script.cpp, then c953a653 relocates and repackages them, creating an avoidable second review of the same code.

Location: src/rpc/output_script.cpp:365 at 32280f547736 (commit) (commit).

Details and suggested fix

32280f547736c59428471d1e22d8418da7a77264 adds the four analysis JSON helpers and inline result help to src/rpc/output_script.cpp. c953a6536f7b58fd8b2a63d1af7c073b30ae7ae6 then moves the helpers to src/rpc/descriptor_util.cpp and factors the help into HELP_DESCRIPTOR_ANALYSIS and DescriptorAnalysisResultFields(). The final behavior is unchanged, but the help changes layout as well as location, so this is less straightforward to validate as a pure move.

Keep the imported inspection commit 494c0cb85761cf43dca50d6851ec7ccb6fee6e67 intact, then extract only its key helpers and key-field help immediately afterward. Have 32280f547736c59428471d1e22d8418da7a77264 add the analysis helpers and help directly to the shared file. The preceding analyzer commit, c6c3fdfc5d3e6af2fb7c18afd2b658d35a7a47b1, already places the analyzer in bitcoin_common, so the staged extraction preserves dependencies and the final tree while letting reviewers validate the analysis RPC additions in their final location.


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

The setup work treats verification as a participant-side step before import, separate from descriptor assembly. The tracking design calls for reporting the participant's own slot, signing capability, threshold, output type, cosigner origins, and first address; the predecessor wizard identified the absence of this pre-import information as a backend gap.

This explains why the new analysis inspects a coordinator-supplied descriptor rather than trusting checks performed when it was constructed. Policy recognition, local ownership, and address agreement serve different parts of that verification.

Source 1 · Source 2

Repeated keys were explicitly identified as a way for fewer holders to satisfy an advertised threshold, even when a participant finds their own key and the expected threshold. The subsequent exchange favored warning during verification rather than rejecting an otherwise valid descriptor, and explicitly required showing the warning before confirmation. It also acknowledged that a participant cannot determine whether all other keys are controlled by one party.

This supports detecting obvious non-independent slots while preserving Core's ability to handle valid policies. It also bounds the security meaning of recognized: detecting repeated or related keys cannot certify independent people or organizations.

Source 1 · Source 2 · Source 3 · Source 4

BIP 341's construction guidance, quoted in an earlier implementation discussion, offers an aggregate 'everyone agrees' key path or an internal point with unknown discrete logarithm when no desired single-key condition exists. It also recommends randomizing the NUMS point to conceal that key-path spending is unavailable, with the randomizer disclosed to a verifier as evidence of its construction.

A multisig leaf is not the complete Taproot authorization policy: the internal key must also be accounted for. This history explains both recognizing an unspendable NUMS path and considering an aggregate of participants, while distinguishing authorization guarantees from privacy properties.

Source 1 · Source 2

The BIP 395 proposal describes a reproducible unspendable internal key built from the BIP 341 NUMS point as a synthetic BIP32 root, followed by unhardened derivation. Its stated purpose is to let wallets and signers reconstruct the key without retaining a separate random tweak; its chain code commits to the normalized policy.

This supplies prior design motivation for accepting visibly NUMS-derived extended-key expressions, rather than only the literal H constant. The pinned analyzer recognizes the NUMS-root relationship; this should not be conflated with implementing or validating the proposal's complete policy-commitment construction.

Source 1

Multipath descriptors were introduced to communicate receive and change derivations in one string without generic combinatorial expansion. The original proposal deliberately pairs corresponding path elements across keys and expands them into separate descriptors, rather than taking their Cartesian product.

The received string can describe multiple operational branches. Checking only its first expansion would not cover everything participants are about to import, which motivates analyzing every branch. This history does not itself specify the new analyzer's exact equivalence test.

Source 1

The derivehdkey work was motivated by multisig participants sharing account xpubs at hardened paths distinct from their default single-signature descriptors. Separately, the public-descriptor import proposal sought to avoid manually exposing private keys by locating wallet keys and verifying that an origin fingerprint and derivation actually produce the supplied xpub. It explicitly deferred matching through arbitrary intermediate origin prefixes.

These decisions explain why ownership checking commonly requires private derivation, why a fingerprint alone is insufficient, and why imported account-key coverage can be narrower than master-key coverage. They provide context for reporting uncertainty while locked rather than declaring the key absent.

Source 1 · Source 2

Earlier gethdkeys work explicitly accommodates partially private multisig descriptors: a wallet may contain an xpub without its corresponding private key. At the pinned base, gethdkeys determines private availability through the descriptor managers using that xpub, rather than treating every listed HD key as private.

This is the predecessor distinction behind mine versus watch_only. Merely seeing a key in the wallet is not equivalent to having signing material available in its descriptor context.

Source 1

Ralph's inferences

The threshold-sized MuSig rule generalizes the earlier 'everyone agrees' construction by comparing authorized coalitions: if the leaf already permits any k cosigners, a key path requiring at least k distinct members of that same set introduces no smaller authorized coalition. The inspected historical sources do not explicitly endorse this exact generalization.

This explains the pinned code's distinction between an aggregate of sufficient cosigners and an outsider or undersized aggregate. It concerns authorization, not equal addresses, signing protocols, or proof of independent ownership.

Source 1

The related-key checks are bounded evidence of shared control, not a proof of independence. Verifying a claimed direct unhardened child by derivation avoids trusting its metadata, but hardened relationships cannot be reconstructed publicly; the interface also expressly excludes general grandchild relationships and unknown unspendable keys from what it can detect.

The advertised setup guarantee must be read with these limits. A participant's successful ownership check and the absence of detected duplicates do not establish that all other slots are independently controlled or usable.

Source 1

Multipath setup equivalence and participant agreement on the concrete wallet are distinct checks. The pinned comparison uses shape, sorting, key-path classification, threshold, and ordered cosigner roots—not complete derivation equality—while the wallet RPC exposes an index-zero address for every path for participants to compare.

Equivalent analysis results need not mean identical receive and change derivations. Comparing every returned path's address supplies information that the structural verdict deliberately does not encode.

Source 1

Descriptor-local private-key matching follows the existing signing architecture: the pinned base expands private material using a descriptor manager's own keys. The new can_sign answer is narrower than complete spendability: its documented meaning is possession of private material for at least one key, with uncertainty represented separately when locked.

This explains why a private key stored alone elsewhere need not make an HD expression mine, and why can_sign must remain separate from recognized, threshold satisfaction, and immediate ability to finish a transaction. The locked-wallet state likewise expresses uncertainty about ownership, not a negative policy verdict.