Skip to content

test: Descriptor roundtrip and raw()/ addr() coverage - #36013

Open
pablomartin4btc wants to merge 2 commits into
bitcoin:masterfrom
pablomartin4btc:descriptor/roundtrip-raw-addr-tests
Open

pablomartin4btc wants to merge 2 commits into
bitcoin:masterfrom
pablomartin4btc:descriptor/roundtrip-raw-addr-tests

Conversation

@pablomartin4btc

Copy link
Copy Markdown
Member

Part 1 of 2, reviving #24361.

Ports the two test-only commits from the original PR above, re-applied against the current descriptor_tests.cpp — the original no longer applies cleanly, since DoCheck()'s signature has changed substantially since the original PR was created back in 2022.

norm_prv was dropped, and op_desc_id, spender_nlocktime, spender_nsequence, preimages, expected_prv/expected_pub, and desc_index were all added - so the original diff no longer applies...

diff -u <(git show 15220ec903:src/test/descriptor_tests.cpp | sed -n '/^void DoCheck/,/^{/p') \
        <(git show HEAD:src/test/descriptor_tests.cpp | sed -n '/^void DoCheck/,/^{/p')
@@ -1,3 +1,7 @@
-void DoCheck(const std::string& prv, const std::string& pub, const std::string& norm_prv, const std::string& norm_pub, int flags, const std::vector<std::vector<std::string>>& scripts, const std::optional<OutputType>& type, const std::set<std::vector<uint32_t>>& paths = ONLY_EMPTY,
-    bool replace_apostrophe_with_h_in_prv=false, bool replace_apostrophe_with_h_in_pub=false)
+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_desc_id = std::nullopt,
+             const std::set<std::vector<uint32_t>>& 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)
 {
 
  • Roundtrip testing that inferring a descriptor from a generated scriptPubKey reproduces the original descriptor's structure (keys stripped from both sides for comparison). Added extension for MuSig key expressions (#31244) and BIP389 multipath (#22838), both added since 2022, and skipping for multi-branch taproot trees, where sibling order isn't meaningful.
    (For more details check 1st commit body)
  • Check() coverage for valid raw() and addr() descriptors, previously exercised only for invalid inputs and only in the script-to-descriptor direction. Added a new NO_KEYS flag, since these descriptors have zero keys and several existing checks assumed at least one.
    (For more details check 2nd commit body)

No behavior change, test-only.


Part 2 (not yet opened): the ToString()/ToPrivateString() merge from #24361, independent of this PR — needs more design work before it's ready.

@DrahtBot DrahtBot added the Tests label Aug 18, 2026
@DrahtBot

DrahtBot commented Aug 18, 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
ACK fametrano
Concept ACK w0xlt, 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:

  • #36772 (test: Remove BOOST_FAIL and add info in descriptor_tests by rustaceanrob)
  • #36154 (wallet: fill PSBT_GLOBAL_XPUB by jeanpablojp)

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.

@w0xlt

w0xlt commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

Comment thread src/test/descriptor_tests.cpp Resolved
Comment thread src/test/descriptor_tests.cpp Resolved

@rustaceanrob rustaceanrob 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.

Left a comment regarding BOOST_TEST_INFO, which only prints the value the next failing check, not any check in scope

@pablomartin4btc

Copy link
Copy Markdown
Member Author

-Updates:

@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

Built at the head, ran the unit suite, and checked the six new addresses by decoding them outside of Core.

Comment thread src/test/descriptor_tests.cpp Resolved
Comment thread src/test/descriptor_tests.cpp Resolved
Comment thread src/test/descriptor_tests.cpp Resolved

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

ACK 2d230d8

Built test_bitcoin at the head and ran descriptor_tests, no errors. Recomputed the six new addr() vectors with btclib: the scriptPubKeys, the addresses back from them, the witness versions and programs, and the legacy/bech32/bech32m output types all match. One nit: the v1 vector cannot be a plain taproot address, since a P2TR script infers back as a solvable rawtr() and fails both the new structure compare and the existing solvability checks (tried addr(bc1padda8…) for 5120eb5b…); a short comment saying why it is a 40-byte program instead would spare the next reader the experiment.

Comment thread src/test/descriptor_tests.cpp Resolved
@DrahtBot
DrahtBot requested a review from jeanpablojp October 3, 2026 20:04
@pablomartin4btc
pablomartin4btc force-pushed the descriptor/roundtrip-raw-addr-tests branch from 2d230d8 to e2ac5a2 Compare October 8, 2026 01:47
pablomartin4btc and others added 2 commits October 7, 2026 18:56
Add DropKeys(), which strips a descriptor string down to structure
only (key material replaced with "<KEY>", sortedmulti()/sortedmulti_a()
normalized to multi()/multi_a(), checksum dropped), and use it to check
that inferring a descriptor back from a script it generated reproduces
the original descriptor's structure.

A few descriptor features need special handling for this comparison
to hold:

- MuSig key expressions (musig(...)) aren't recognized by the plain
  key-matching regex. Added a separate pass collapsing musig()
  expressions (and any trailing derivation path) to <KEY> before the
  plain-key regex runs, rather than teaching that regex to understand
  musig()'s internals recursively.
- Sibling branches within a taproot script tree have no meaningful
  order (it's a Merkle tree), so InferDescriptor() reconstructing a
  multi-leaf tree in a different but equally valid branch order isn't
  something a plain string comparison can account for. Skipped the
  check for any taproot descriptor with more than one script leaf,
  detected via the presence of '{' in the descriptor string (the
  grammar only emits '{'/'}' for grouping 2+ branches).
- sortedmulti_a() wasn't recognized by the normalization regex (found
  by jeanpablojp). Made the "_a" suffix optional and kept it in the
  replacement.

jeanpablojp also pointed out that comparing against the descriptor's
own re-serialization, rather than the original test string, avoids
needing this regex to understand BIP389 multipath syntax at all.
Switched the comparison accordingly and dropped the multipath
handling.

Co-authored-by: Pieter Wuille <[email protected]>
Add Check() coverage for valid raw() and addr() descriptors: a raw
script, legacy and P2SH addresses, two bech32 v0 addresses, and two
future-witness-version addresses (v1 and v2, both expected
non-standard/unsolvable) - verifying checksum handling, solvability,
script derivation, and structural roundtripping. Address/script pairs
verified against a live node's own validateaddress before use. The v1
vector uses a 40-byte witness program instead of a real 32-byte
taproot output key, since the latter infers back as a solvable
rawtr() (noted by fametrano).

These descriptors have no key expressions at all, which DoCheck()
didn't previously account for:

- keys_priv.keys is expected to be empty rather than non-empty, gated
  on a new NO_KEYS flag.
- GetMaxKeyExpr()/GetKeyCount() are expected to both report zero
  rather than the usual "highest index + 1 == count" relationship.
  Added the NO_KEYS-aware branch for it.
- HavePrivateKeys() returns false for a keyless descriptor, not
  vacuously true - it didn't exist when the original patch was
  written, so this wasn't previously exercised. Gated
  have_all_private_keys on NO_KEYS in addition to the existing
  MISSING_PRIVKEYS.
- raw()/addr() hardcode ToPrivateString() to always fail, so the
  existing "can serialize back to the private version" check needs
  skipping for these descriptors too. Extended its MISSING_PRIVKEYS
  gate to also cover NO_KEYS. Added an explicit check that it returns
  false, per jeanpablojp.

Co-authored-by: Pieter Wuille <[email protected]>
@DrahtBot

DrahtBot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/37714644244/job/113108232448
LLM reason (✨ experimental): CI failed because clang-tidy flagged /*op_desc_id=*/ comments in descriptor_tests.cpp as mismatched with the parameter name op_compat_desc_hash (warnings treated as errors).

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.

@pablomartin4btc
pablomartin4btc force-pushed the descriptor/roundtrip-raw-addr-tests branch from e2ac5a2 to cf9821a Compare October 8, 2026 03:50
@pablomartin4btc

Copy link
Copy Markdown
Member Author

-Updates:

  • Addressed @jeanpablojp's and @fametrano's feedback, thanks both!
  • Rebased — #35445 renamed DescriptorID/ op_desc_id to CompatDescriptorHash/ op_compat_desc_hash, leaving a few comments out of sync and failing tidy CI. Fixed.

@DrahtBot DrahtBot removed the CI failed label Oct 8, 2026

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

reACK cf9821a

descriptor_tests passes at the new head, and the raw()/addr() vectors are unchanged since 2d230d8, so my earlier check of them still holds. Thanks for the comment on the 40-byte v1 program.

const std::string KEY_RE_REPLACEMENT = "$1<KEY>$" + util::ToString(KEY_RE.mark_count());

/** Replace all key expressions in desc with "<KEY>", "sortedmulti" with "multi", and drop checksum. */
std::string DropKeys(std::string desc)

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.

Not sure if I am missing something, but it seems like this function can be simplified using regex_replace and std::regex:

diff --git a/src/test/descriptor_tests.cpp b/src/test/descriptor_tests.cpp
index 70c7d5e8b5..622157b2f6 100644
--- a/src/test/descriptor_tests.cpp
+++ b/src/test/descriptor_tests.cpp
@@ -14,7 +14,6 @@

 #include <optional>
 #include <regex>
-#include <sstream>
 #include <string>
 #include <vector>

@@ -188,46 +187,22 @@ const std::string STR_BIP32KEY = "(" + STR_XPUBPRV + "(/" + STR_KEYSTEP + ")*(/[
 /** ERE string matching a descriptor key expression. */
 const std::string STR_KEYEXPR = "(" + STR_MAYBE_ORIGIN + "(" + STR_PUBKEY + "|" + STR_PUBKEYHASH + "|" + STR_BIP32KEY + "))";

-/** Regular expression matching a descriptor key expression. */
-const std::regex KEY_RE("([(,])" + STR_KEYEXPR + "([),])", std::regex::extended);
-/** Regular expression matching "sortedmulti" or "sortedmulti_a", capturing the optional "_a". */
-const std::regex SORTEDMULTI_RE("(^|[(,])sortedmulti(_a)?[(]", std::regex::extended);
+/** Regular expression matching a descriptor key expression, with the trailing separator as lookahead. */
+const std::regex KEY_RE("([(,])" + STR_KEYEXPR + "(?=[),])");
 /** Regular expression collapsing a whole musig() key expression, including any trailing
  *  derivation path, to a single unit. musig()'s participants are plain keys with no
  *  parentheses of their own, and musig() cannot be nested or carry origin info (see
  *  ParsePubkey() in script/descriptor.cpp), so a match up to the first ')' is sufficient;
  *  KEY_RE above doesn't need to understand musig()'s internal structure as a result. */
-const std::regex MUSIG_RE("musig[(][^()]*[)][^(),]*", std::regex::extended);
-/** Replacement string for KEY_RE: keeps the separators captured in groups 1 and mark_count(),
- *  replacing the key expression itself with "<KEY>". The trailing group number is computed from
- *  KEY_RE's actual capture count rather than hardcoded, so it can't silently drift out of sync
- *  if STR_KEYEXPR's structure changes again in the future. */
-const std::string KEY_RE_REPLACEMENT = "$1<KEY>$" + util::ToString(KEY_RE.mark_count());
+const std::regex MUSIG_RE("musig[(][^()]*[)][^(),]*");

 /** Replace all key expressions in desc with "<KEY>", "sortedmulti" with "multi", and drop checksum. */
 std::string DropKeys(std::string desc)
 {
-    if (desc.size() >= 9 && *(desc.end() - 9) == '#') {
-        // Drop checksum
-        desc = desc.substr(0, desc.size() - 9);
-    }
-    {
-        // Collapse musig() expressions first; KEY_RE below only understands plain keys.
-        std::ostringstream ostr;
-        std::regex_replace(std::ostreambuf_iterator<char>(ostr), desc.begin(), desc.end(), MUSIG_RE, "<KEY>");
-        desc = ostr.str();
-    }
-    while (true) {
-        std::ostringstream ostr;
-        std::regex_replace(std::ostreambuf_iterator<char>(ostr), desc.begin(), desc.end(), KEY_RE, KEY_RE_REPLACEMENT);
-        auto newdesc = ostr.str();
-        ostr.str("");
-        std::regex_replace(std::ostreambuf_iterator<char>(ostr), newdesc.begin(), newdesc.end(), SORTEDMULTI_RE, "$1multi$2(");
-        auto newdesc2 = ostr.str();
-        std::swap(desc, newdesc2);
-        if (newdesc2 == desc) break;
-    }
-    return desc;
+    desc = desc.substr(0, desc.find('#'));
+    desc = std::regex_replace(desc, MUSIG_RE, "<KEY>");
+    desc = std::regex_replace(desc, KEY_RE, "$1<KEY>");
+    return std::regex_replace(desc, std::regex("sortedmulti"), "multi");
 }


// Check private keys are extracted from the private version but not the public one.
BOOST_CHECK(keys_priv.keys.size());
BOOST_CHECK_EQUAL(keys_priv.keys.empty(), !!(flags & NO_KEYS));

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.

nit: Could use (flags & NO_KEYS) != 0 for legibility. Had to look up the !! case

@DrahtBot

DrahtBot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

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

BOOST_TEST_INFO("Pub desc: " + pub);
// Check that the highest key expression index matches the number of keys in the descriptor.
// Descriptors with no keys at all (flags & NO_KEYS) have neither.
BOOST_TEST_INFO_SCOPE("Pub desc: " + pub);

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.

You can remove this line as of #36772, the descriptor is added as context at the top of DoCheck now

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.

6 participants