Skip to content

descriptor, rpc, wallet: do not echo key material in error messages - #36648

Open
fametrano wants to merge 1 commit into
bitcoin:masterfrom
fametrano:descriptor-errors-no-keys
Open

fametrano wants to merge 1 commit into
bitcoin:masterfrom
fametrano:descriptor-errors-no-keys

Conversation

@fametrano

@fametrano fametrano commented Oct 24, 2026 •

Copy link
Copy Markdown

Some descriptor error messages quote the string the caller sent, and a descriptor can hold a private key. The error then carries the key, or part of it, into places the request may not go: an application's log, an error reporter, a screenshot shared for help.

This PR stops the quoting. A failing key is named by its position, a failing entry of solving_data.descriptors by its index, and a function name is quoted only where the parser accepts it. The commit message lists each changed error.

before after
key '<key>' is not valid key is not valid
Multi: key '<key>' is not valid Multi: key 3: key is not valid
'wpkh(<key>)x' is not a valid descriptor function Unexpected text after the closing ')' of wpkh()
'<start of a key>(<rest>' is not a valid descriptor function Not a valid descriptor expression
Unable to parse descriptor '<descriptor>': Missing checksum Unable to parse descriptor at index 1: Missing checksum
Could not add descriptor '<descriptor>': ... the same, quoting the public form of the descriptor

@DrahtBot

DrahtBot commented Oct 24, 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
Stale ACK jpk68

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:

  • #36990 (test: replace hard-coded RPC error codes by l0rinc)
  • #36885 (wallet, rpc: Add analyzedescriptor for multisig setups by pablomartin4btc)
  • #36402 (refactor: wallet_importdescriptors to separate run_test() contents into specific functions by nebula-21)
  • #36257 (qa: assert_equal -> assert_true/assert_false by hodlinator)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #35918 (descriptor: Expose key expression parsing by pseudoramdom)

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.

@jpk68

jpk68 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

ACK ad18016

Comment thread src/script/descriptor.cpp Outdated
if (paren == std::string_view::npos || paren == 0 || paren > MAX_FUNCTION_NAME_CHARS) {
error = "Not a valid descriptor function";
} else {
error = strprintf("'%s(...' is not a valid descriptor function", expr_text.substr(0, paren));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For wpkh(KEY)x, the error is now 'wpkh(...' is not a valid descriptor function. wpkh is a valid function; the real problem is the trailing x. The old message echoed the full text, so the mistake was visible.

you can make it skip the key inside the function print the chars that is connected to ).

somethiing like that:

Invalid descriptor expression 'wpkh(...)x'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggested diff:

diff --git a/src/script/descriptor.cpp b/src/script/descriptor.cpp
index 3ae2da81d..29dbfa3a7 100644
--- a/src/script/descriptor.cpp
+++ b/src/script/descriptor.cpp
@@ -2828,15 +2828,29 @@ std::vector<std::unique_ptr<DescriptorImpl>> ParseScript(uint32_t& key_exp_index
         error = "A function is needed within P2WSH";
         return {};
     }
-    // Quote the function name only if it is 16 characters or fewer: every key is longer, and a bare key has no '('
+    // Show the expression as "name(...)rest", where the arguments are never quoted, the name
+    // only if it is 16 characters or fewer (every key is longer, and a bare key has no '('),
+    // and the text after the matching ')' only if it is no longer than MAX_QUOTED_TOKEN_CHARS.
     constexpr size_t MAX_FUNCTION_NAME_CHARS{16};
     const std::string_view expr_text{expr.begin(), expr.end()};
-    const size_t paren{expr_text.find('(')};
-    if (paren == std::string_view::npos || paren == 0 || paren > MAX_FUNCTION_NAME_CHARS) {
+    const size_t open{expr_text.find('(')};
+    if (open == std::string_view::npos || open == 0 || open > MAX_FUNCTION_NAME_CHARS) {
         error = "Not a valid descriptor function";
-    } else {
-        error = strprintf("'%s(...' is not a valid descriptor function", expr_text.substr(0, paren));
+        return {};
+    }
+    std::string shown{strprintf("%s(...", expr_text.substr(0, open))};
+    int depth{0};
+    for (size_t i{open}; i < expr_text.size(); ++i) {
+        if (expr_text[i] == '(') {
+            ++depth;
+        } else if (expr_text[i] == ')' && --depth == 0) {
+            const std::string_view rest{expr_text.substr(i + 1)};
+            shown += ')';
+            shown += rest.size() <= MAX_QUOTED_TOKEN_CHARS ? rest : std::string_view{"..."};
+            break;
+        }
     }
+    error = strprintf("Invalid descriptor expression '%s'", shown);
     return {};
 }

@fametrano fametrano Nov 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done: wpkh(KEY)x now gives Unexpected text after the closing ')' of wpkh(), which quotes the name only because it is a function the parser accepts, and never the text after the ), which can be the end of a key.

Comment thread src/script/descriptor.cpp
}
}
error = strprintf("Pubkey '%s' is invalid", str);
error = "Pubkey is invalid";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In a descriptor with many keys, the error doesn't say which one failed. For wsh(multi(2,KEY1,KEY2,KEY3)) with a typo in KEY3, the error is only:

Multi: key is not valid

With 15 keys, the user has to check each one by hand.

You can print the key's position. key_exp_index already counts the keys parsed before the failing one, so no key text is needed.

Something like that:

Multi: Key #3 is not valid

Note: the count includes each musig() aggregate key, so a key after a musig() gets a number one higher than a user would count. The test expectations for these messages still need updating.

@fametrano fametrano Nov 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done: the error gives the key's position in its list, counted from 1, as in Multi: key 3: key is not valid, and a key after a musig() is not counted one higher.

Comment thread src/script/descriptor.cpp
}
}
error = strprintf("Pubkey '%s' is invalid", str);
error = "Pubkey is invalid";

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

In a descriptor with many keys, the error doesn't say which one failed. For wsh(multi(2,KEY1,KEY2,KEY3)) with a typo in KEY3, the error is only:

Multi: key is not valid

With 15 keys, the user has to check each one by hand.

You can print the key's position. key_exp_index already counts the keys parsed before the failing one, so no key text is needed.

Something like that:

Multi: Key #3 is not valid

Note: the count includes each musig() aggregate key, so a key after a musig() gets a number one higher than a user would count. The test expectations for these messages still need updating.

@fametrano fametrano Nov 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done, as in the other copy of this comment: Multi: key 3: key is not valid, counted within the list.

Comment thread src/wallet/rpc/spend.cpp Outdated
Comment on lines +625 to +632
auto descs = Parse(desc_str, desc_out, error, true);
if (descs.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor '%s': %s", desc_str, error));
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor: %s", error));

@uqlidi uqlidi Oct 28, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

similar to the key index solving_data.descriptors is a list, now that the descriptor is no longer printed, the error doesn't say which one failed:

Unable to parse descriptor: Missing checksum

You can print its index in the list.

should be:

Unable to parse descriptor at index 1: Missing checksum

we could do something like that instead:

diff --git a/src/wallet/rpc/spend.cpp b/src/wallet/rpc/spend.cpp
index 383f752dc..0ab874793 100644
--- a/src/wallet/rpc/spend.cpp
+++ b/src/wallet/rpc/spend.cpp
@@ -622,14 +622,15 @@ CreatedTransactionResult FundTransaction(CWallet& wallet, const CMutableTransact
         }
 
         if (solving_data.exists("descriptors")) {
-            for (const UniValue& desc_univ : solving_data["descriptors"].get_array().getValues()) {
-                const std::string& desc_str  = desc_univ.get_str();
+            const auto& desc_values{solving_data["descriptors"].get_array().getValues()};
+            for (size_t desc_index{0}; desc_index < desc_values.size(); ++desc_index) {
+                const std::string& desc_str{desc_values[desc_index].get_str()};
                 FlatSigningProvider desc_out;
                 std::string error;
                 std::vector<CScript> scripts_temp;
                 auto descs = Parse(desc_str, desc_out, error, true);
                 if (descs.empty()) {
-                    throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor: %s", error));
+                    throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor at index %u: %s", desc_index, error));
                 }
                 for (auto& desc : descs) {
                     desc->Expand(0, desc_out, scripts_temp, desc_out);

@fametrano fametrano Nov 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done with your loop: Unable to parse descriptor at index 1: Missing checksum.

Comment thread src/util/bip32.cpp Outdated
const auto number{ToIntegral<uint32_t>(std::string_view{elem.begin(), elem.end()})};
if (!number) {
// A value longer than any uint32 may be a key written in the path: do not quote it
if (raw.size() > 11) return util::Unexpected{std::string{"Key path value is not a valid uint32"}};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@fametrano fametrano Nov 1, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

MAX_QUOTED_CHARS is gone: no error quotes text by length any more, so there is nothing left to share with bip32.cpp.

@fametrano

Copy link
Copy Markdown
Author

@uqlidi Thanks, I addressed all four points; the replies are inline.

@DrahtBot

DrahtBot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/41338732479/job/124943987697
LLM reason (✨ experimental): CI failed because IWYU/clang-format modified src/script/descriptor.cpp (adding <ranges>), so the lint check detected uncommitted formatting/include changes.

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.

@fametrano

Copy link
Copy Markdown
Author

I pushed a fix for the CI failure, and one of the two suggestions in the Ralph review.

The iwyu task wanted #include <ranges> in descriptor.cpp, and rpc_getdescriptoractivity.py still expected the old message for addrx(...). Both are fixed.

An expression with miniscript wrappers that fails to parse, such as z:pk(K) or vv:pk(K), now gives "Not a valid miniscript expression" instead of "Not a valid pk() expression". The wrappers may be what is wrong, and pk(K) itself can be valid.

The other suggestion adds the position of the failing tr() leaf and key path element, as in "tr(): leaf 2: pk(): key is not valid". It rewords errors master already has: 22 expectations change in descriptor_tests.cpp, 12 of them in master's own tests (+33 −27 in two files). I can add it here if a maintainer wants it.

Several error messages quote text from the descriptor the caller sent,
and that text can be a private key. Error text is often logged or
shared where the request is not. Even the first characters of a key
give away part of it.

Parsing (src/script/descriptor.cpp, src/util/bip32.cpp):
- "Key '%s' is invalid due to whitespace", "key '%s' is not valid" and
  "Pubkey '%s' is invalid" quoted the key. They quote nothing now.
- A key that fails inside multi(), sortedmulti(), multi_a(),
  sortedmulti_a(), musig() or a miniscript is named by its position, as
  in "Multi: key 3: key is not valid" and "Miniscript: key 2: key is not
  valid".
- "Multi threshold '%s' is not valid", "Key path value '%s' specifies
  multipath ..." and "Key path value '%s' is not a valid uint32" quote
  nothing now. A stray ',' or '/' inside a key can leave a short
  fragment of it as the threshold or a path value.
- "Provided checksum '%s' does not match computed checksum '%s'" no
  longer quotes the provided checksum, "Key origin start '[ character
  expected but not found, got '%c' instead" no longer quotes the
  character, and "Fingerprint '%s' is not hex" no longer quotes the
  fingerprint. A stray '#', ']' or '[' inside a key puts part of it
  there.
- "'%s' is not a valid descriptor function" no longer quotes the
  expression. A stray '(' inside a key leaves its first characters where
  a function name is expected, and a stray ')' leaves its last
  characters after the closing ')'. The message quotes the function name
  only where it is one of the descriptor and miniscript functions the
  parser accepts, as in "Not a valid pk() expression" and "Unexpected
  text after the closing ')' of wpkh()". Otherwise it reads "Not a valid
  descriptor expression", or "Unexpected text after the closing ')'".
  An expression with miniscript wrappers that fails to parse, as in
  z:pk(K), reads "Not a valid miniscript expression": the wrappers may
  be what is invalid.

Callers (src/rpc/util.cpp, src/wallet/imports.cpp,
src/wallet/rpc/spend.cpp):
- "Cannot derive script without private keys" and "Could not add
  descriptor" quote desc->ToString(), the public form, instead of the
  string sent.
- "Unable to parse descriptor" no longer quotes the string, and gives
  its index in solving_data.descriptors instead. No parsed descriptor
  exists there, and the parse error says what is wrong.

Tests are updated for the new messages. New tests check that no part of
a key is in the parse errors and the caller errors, including a key with
a typo in its last character or a stray ',', '/', '(', ')', '#', '[' or
']' inside it. They also check the exact text of the caller errors.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants