mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:17:38 +00:00
descriptor: speed-up Parse (xpub/xpriv) in ~30% #35041
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!35041
Loading…
Reference in a new issue
No description provided.
Delete branch "2026-04-descriptor"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This PR speeds up descriptor parsing, for basically descriptors that use xpub/xpriv, through some targeted improvements (I've been working on fuzz targets for wallet stuff for a while. I've noticed that some of them are slow so I started to work on understanding why and improve what can be improved. The finding came from it):
Avoid redundant base58 decoding when parsing extended keys (this is the major improvement)
ParsePubkeyInner unconditionally called both DecodeExtKey() and DecodeExtPubKey(), each running a full DecodeBase58Check (two SHA256 passes over ~111 bytes). A new DecodeExtKeyOrPubKey() function performs a single base58 decode and then checks the prefix, halving the cryptographic work per key. The interfaces of DecodeSecret, DecodeExtKey, and DecodeExtPubKey are also updated to accept string_view instead of const std::string&, eliminating unnecessary string copies in the descriptor parser and allowing DecodeBase58/DecodeBase58Check to use pointer-range iteration instead of strlen.
Replace O(n) charset lookup with precomputed table
DescriptorChecksum previously called std::string::find() for every character in the descriptor string, doing up to 96 comparisons per character. This replaces it with a 256-entry precomputed lookup table for O(1) lookups. The benefit scales with descriptor length.
Parse()with the following descriptor:This PR:
Master:
I didn't put the benchmark itself here but if reviewers think worth, I can do it.
Joint work with claude 😅
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.
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:
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 places where named args for integral literals may be used (e.g.
func(x, /*named_arg=*/0)in C++, andfunc(x, named_arg=0)in Python):src/key_io.cpp:DecodeBase58Check(str, data, 78)2026-10-19 15:15:11
There have been a few base58 optimization attempts before (https://github.com/bitcoin/bitcoin/pull/29473 and independently before https://github.com/bitcoin/bitcoin/pull/21176) - would it help if we revived them?
I'll take a look on those PRs and try, thank you. I think their focus is to improve/rewrites the algorithm itself, here is more about the way it's been used.
Concept ACK
Shouldn't really matter, but I thinks this could be constexpr too.
Done.
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/27288256306/job/80601410847LLM reason (✨ experimental): CI failed because IWYU detected missing/incorrect includes in
src/script/descriptor.cpp(autofix ran and then the IWYU check failed).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.
🐙 This pull request conflicts with the target branch and needs rebase.
ACK 0339b33e41f13f87111c2e03e1ddc42bc6a596c4
Why this change is acceptable when prior optimization attempts in this area were rejected (https://github.com/bitcoin/bitcoin/pull/35041#issuecomment-4217337173):
DecodeBase58Check()into one.O(1)lookup table.In my subjective view they have a lower impact on code readability than the rejected PRs. Also, the author of this PR motivates it through the concrete second-order effect of speeding up fuzz targets.
(I'm still open to reviewing further optimizations in this area, without guarantees of priority).
Benchmark code
Benchmark results - 36.7% less time
(Run under
doas pyperf system tune).nit: Could document & enforce the
endpointer not changing as well:Started experimenting with returning
std::optional<std::variant<CExtKey, CExtPubKey>>and validatingIsValid()inside of the function but seems cleaner to leave that out of this PR. :)nit-level suggestions:
staticforconstexprvariables as they are only evaluated once anyway (still needed forINPUT_CHARSETto simplify capture in lambda).INPUT_CHARSET_POStoint8_tto better match range of possible values and decrease size.tableas at least GCC will trigger an assert at compile time when indexing out of bounds instd::array.uint8_tover longerunsigned char.Could also pass a string view in here to clean up the callers and then derive
pszandendonly in the first line of this function?Yes, I like the string view approach, but I think we would have to rename the internal helpers to avoid recursion.
Not sure about dropping
staticbecause it guarantees the value is computed at compile time; I cannot see why not using it, especially for debug builds.The other points are valid, I'm going to address them since I intend to address https://github.com/bitcoin/bitcoin/pull/35041#discussion_r3909496481.
Done.
Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/35041#discussion_r3906003696 (string view) and changed INPUT_CHARSET_POS element type from int to int8_t as well as the index casts from unsigned char to uint8_t. Thanks @hodlinator and @maflcko for reviewing it.
re-ACK
ddcacd25e7Initial ACK: https://github.com/bitcoin/bitcoin/pull/35041#pullrequestreview-5016944887
nit: If you touch again, maybe you could use "Internal" as the disambiguating suffix rather than "Raw"?
nit: Could further constrain
endhere:(It both cannot mutate the data it points to and it is not allowed to be modified to point at other memory).
Thanks for applying most of my feedback!
It is
constexprwhich guarantees the value to be computed at compile time, sostaticis redundant forINPUT_CHARSET_POSandCHECKSUM_CHARSET.Base:
d0d1e49c8c1e5582056e8a843229507871f8d1b8Head:
61cb3d966a855a551307889daea9c45c2c1db203Findings
Minor
Avoid pointer arithmetic on an empty string view (src/base58.cpp:45, head)
A default-constructed empty
std::string_viewmay have a nulldata()pointer. Formingendfrom it, and later subtractingend - psz, is undefined behavior. The previous string-based decoder handled an emptystd::stringthrough its non-nullc_str(). Handle an empty view before forming the range or normalize it to a non-null empty buffer. No checked-in caller passing a default-constructed view was identified, so production impact is unconfirmed.Suggestions
Add a benchmark for extended-key descriptor parsing (src/script/descriptor.cpp:2052, head)
Please add a
Parsebenchmark using an extended-key descriptor. The existing descriptor benchmark callsParsebeforebench.runand times onlyExpand, so it cannot reproduce the reported parsing improvement or track future parser-throughput regressions. A separate benchmark would measure this path without changing parser behavior.Review coverage was incomplete. adversarial_glm: Output failed validation: invalid review output
Full review report
Could take this opportunity and make this operation 32bit overflow-safe by clamping to max size (not that it really matters, such large inputs are unlikely to reach here)?
Yes, going to address it.
Done.
Done.
Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/35041/changes/59daebcf05db41d83f9d1974b5c79be3eaf62770#r3911747081 and https://github.com/bitcoin/bitcoin/pull/35041/changes/59daebcf05db41d83f9d1974b5c79be3eaf62770#r4311175392
re-ACK
61cb3d966anit: This
std::max(..., 0)is only useful whenvchdoesn't have1-prefix padding andmax_ret_lenis negative.Could instead add a precondition for the argument (or make it unsigned):
tACK
61cb3d966aI checked that this speed-up changes no answer: the new size cap in
DecodeBase58Rawsits on every base58 decode,DecodeExtKeyOrPubKeyon every extended key in a descriptor, and no test calls the new decoder directly. I built this head and its merge base and ran both over 33,465 seeded cases from the BIP32 library I maintain: the BIP32 vectors, 1,000 random key pairs and their mutations (padding, NUL, wrong versions and lengths, depth 0 with a parent, off-curve keys, scalars out of range), plus raw base58 and 6,323 descriptors.The output of
DecodeBase58andDecodeBase58Checkat seven limits,DecodeExtKey,DecodeExtPubKey,GetDescriptorChecksumandParse, error strings included, is byte-identical on both builds. On all 11,083 key stringsDecodeExtKeyOrPubKeymatches the two separate decoders. My library agrees with Core on every key string, except 800 testnet and ypub-style keys it accepts by design and Core rejects on mainnet. The checksums agree on 6,321 descriptors; for#andpkh(#),GetDescriptorChecksumreturns nothing.Ralph's verifier dropped, by reading the code, the candidate that the cap can hit
assert(carry == 0); this run exercises it. As controls, removing the cap's+ 1aborts on that assert, and dropping the private prefix check or changing the checksum table's fill value shows up as differences. The unit suites for base58, BIP32, key_io, descriptors and miniscript pass. The comparison is a sample, on mainnet parameters and without sanitizers, and has no valid WIF key, default-constructedstring_viewor negative limit among its inputs. I did not measure the speed-up. Harness, generator and output: https://gist.github.com/fametrano/90d85e64cc4336a69769ccf978bef12b/7b02fad518ad93b46fe72ae6c739bd3ae087686eACK
61cb3d966a