mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
kernel: make btck_witness_stack_get_item_at O(1) #36909
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!36909
Loading…
Reference in a new issue
No description provided.
Delete branch "kernel-witness-stack-iterate-items"
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?
Since #36895,
btck_witness_stack_get_item_atwalks the items before the one it returns, so reading a whole witness stack through it is O(n^2).btck_WitnessStackcopies the items into one buffer and keeps where each one ends, which makesbtck_witness_stack_get_item_atO(1) without changing its signature.btck_transaction_input_get_witness_stackis O(n) instead of O(1), because it copies every item when it creates the witness stack.Breaking changes:
btck_transaction_input_get_witness_stackreturns an ownedbtck_WitnessStack*, which must be destroyed withbtck_witness_stack_destroy.WitnessStackViewis removed, andGetWitnessStack()returns aWitnessStack.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.
Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments.
🟠 Minor · The ownership change leaves old C callers silently compatible
Unchanged C callers can leak the new owned result of
btck_transaction_input_get_witness_stack; no affected in-tree caller was found, and external consumers were not inspected.Location:
src/kernel/bitcoinkernel.h:1825(head).🔵 Suggestion · Obtaining a witness stack now allocates even for counting
The owning getter adds allocations for count-only and empty-witness queries; a borrowed getter plus single-pass accessor could avoid that cost for scans, at the expense of constant-time random indexing.
Location:
src/kernel/bitcoinkernel.cpp:878(head).Reviewed:
edf5784346d3· Review report · Previous reportspermalink
This processes the witness stack from the bottom to the top, treating it more like a queue than a stack. Doesn't really feel the right API to me?
Hmmm, I think that's a fair point. I suppose I was too focused on how because of it being serialized it can only be read one item at a time from the bottom up. On second thought / glance a call that writes every item's pointer and size into two arrays passed to it, so the items can be read from either end might be the better shape for the API.
Instead of adding a new callback type to the API, we could expose the witness stack's serialization, e.g. btck_witness_stack_to_bytes, which would also read the whole witness in a single call, and let the bindings or caller decide how to decode it?
update: opened #36911 as an alternative.
I switched to this shape in
9d0f1d05bd. I feel much better about this approach.Thanks! The latest push drops the callback. The function now writes every item's pointer and size into two arrays passed to it. I'll take a look your PR as well!
Just for reference here I ran #36909 on top of @optout21 's commit f122aeeb88 from pr36895-oo-optim1. Both with an input with n one-byte witness items through the C API.
get_item_atloop (before / after)get_items(before / after)Passing back pointers to structure internals as
void*seems odd? It also potentially introduces lifetime issues, in case the caller keepsitemsaround longer than the correspondingWitnessStack?Thanks, I just want to make sure I understand you correctly. Which part is the bigger concern for you? The
void*type itself, or handing out pointers into the witness stack's storage at all?It looks like for the C++ wrapper I should have returned copies rather than spans. I'll fix that. Though, in your view would it still be a problem for the plain C code to get the raw pointers?
Everything else seems to also use
void*so that seems consistent at least. I think any raw pointers should be hidden in an opaque Handle type, and owned (or wrapped inshared_ptr)? I'm not really deeply familiar with the kernel api though. I could imagine it maybe being better for the kernel's witness wrapper to have both theCScriptWitnessand thevector<span>generated fromToSpans, and then continue to provide the current interface with out the O(n)/O(n^2) annoyance.Thanks. Owned handles came up when the API was added. Structs holding a
shared_ptrwere suggested (https://github.com/bitcoin/bitcoin/pull/30595#discussion_r2237140589), and the API went with raw pointers, where a const pointer is a borrowed view (https://github.com/bitcoin/bitcoin/pull/30595#issuecomment-3252313496), which the header also spells out.For example,
btck_StringView(#36584) follows that rule as do theget_itemspointers.btck_WitnessStackis just a pointer to theCScriptWitnessinside the input. Keeping the spans next to it would meanbtck_transaction_input_get_witness_stackallocating an object on every call that every binding then has to destroy.Pushed
0b833469c1.WitnessStackApi::GetItems()now returns copies of the items🐙 This pull request conflicts with the target branch and needs rebase.
I agree with @ajtowns, I independently also arrived at this conclusion.
I think that's fine. It's a small constant number of allocations, and only when the user actually needs the witness stack. Having to destroy the object also seems trivial. It's better to avoid leaking the implementation into the interface, and it seems to me like here we can easily do this.
Got it. I misunderstood the convention and thought getters had to return borrowed views. I think what I can do is drop
get_itemsand havebtck_transaction_input_get_witness_stackreturn an owned object that holds theCScriptWitnessand its spans.Sounds good. Meta comment: I think it would have made more sense to open this PR after/when the witness stack changes get merged. At this point, it's all speculation, and not the best use of time imo.
Got it. I appreciate the feedback and would be happy to follow that approach. I would normally prepare patches for anticipated changes, even if they aren’t necessarily guaranteed. I'm just curious then in this repo, what is the appropriate use of a draft PR?
Pushed
4a30676get_itemsis now gone.btck_WitnessStackkeeps a span for each item, which makesbtck_witness_stack_get_item_atO(1), andbtck_transaction_input_get_witness_stackreturns an owned copy.Now that #36895 is merged, ready for review.
Concept ACK
Approach ACK
Having
itemspoint intowitnessmakes copy and move operations tricky: it requires a hand-written copy constructor (C.20), and leaves the other special members implicit (C.21). An alternative would be to store offsets. It's a bit more code, but I think it's more idiomatic, and it also halves the memory footprint per item on 64-bit platforms (16 to 8 bytes).git diff on
4a3067668eThanks! Would it be worth holding the witness in a
shared_ptr<const CScriptWitness>and storing the first item's address once?GetItemwould no longer read the size header and decode two CompactSizes throughfront()on every read. Copies would share the witness instead of duplicating it, which saves an allocation when the witness stack has items.git diff on
Was also wondering if you would you rather copy the item bytes into one buffer with a 4-byte end offset per item?
GetItemwould also skipfront()without a stored pointer, and the offsets would take 4 bytes per item instead of 8. The downside is that creating a witness stack copies the items one at a time instead of in one block.I personally wouldn't go for the
shared_ptr<const CScriptWitness>witness. It makes copies faster, but theshared_ptroverhead is a waste when we don't copy, and I suspect that will be the large majority of usage. I think almost all usage is going to be a single sequential read (e.g. the entire witness stack, or the last element)?I think this makes sense, yeah! I ran some quick benches and it seems to perform better than my earlier suggestion with
ItemPositionthat required readingfront()on every access, and has a lower memory footprint. So I think your suggestion would then look something like the below?git diff on
4a3067668eSorry for jumping in.
I'm wondering about one thing with copying the items into a new buffer:
btck_WitnessStackwould no longer hold aCScriptWitness. I'm not sure whether we'll ever want to expose Core functionality on the witness stack, but if we do, would dropping theCScriptWitnessmake that harder? For example, abtck_witness_stack_to_bytescould just reuseCScriptWitness::Serialize, which writes the stored wire-format serialization as-is, instead of re-encoding the format ourselves.Edit: please also see https://github.com/bitcoin/bitcoin/pull/36911#issuecomment-7282278042 related to having a
to_bytesfunction.On
shared_ptr: I agree. In the kernel API we currently use it for larger objects like blocks and transactions, not for small ones like this. It adds an allocation every time a witness stack is created, and only saves one when a non-empty stack is copied, which should be rare.On
front(): I wanted a sense of how much calling it on every lookup costs, so I compared theItemPositionversion suggested in https://github.com/bitcoin/bitcoin/pull/36909#discussion_r4722455120 against the same code with the first item's address cached (only to see the cost withoutfront(), not as a proposal). Avoiding front() cuts the time to scan all witness items by about 18%, but only about 4% once block deserialization is included, so in the grand scheme of things it may not matter much. Mainnet block 840000 (3050 txs, 3765 inputs, 6826 witness items):I was curious about the practical performance trade-off of this optimization, so I ran a benchmark on Linux ARM64. I used OpenAI Codex to prepare and run the benchmarks and analyze the experimental results, and ChatGPT to assist with drafting.
With a synthetic witness stack containing 100 elements of 32 bytes each, the complete C API operation, including retrieval, traversal, and destruction, was approximately 14.7x faster.
However, for smaller witness stacks, such as P2TR key path and P2WPKH, the additional cost of creating the object outweighed the traversal improvement when the stack was retrieved and traversed only once.
One question remains open for me: how common are these different usage patterns in real-world libbitcoinkernel applications?
I don't think so? At least not in a way that touches the API. It looks like apart from the class and a wallet setter, the functions in Core's headers that take a
CScriptWitnessareVerifyScriptandCountWitnessSigOps. Both also need the scriptSig and the spent scriptPubKey, so a kernel function for either would take the transaction or input, asbtck_script_pubkey_verifydoes, and those already hold theCScriptWitness. Also the handle's contents are private so if it ever needs aCScriptWitnessagain then onlybitcoinkernel.cppwould need to change.Yes, thanks for drafting the diff! I thought it through, and felt good about it. I pushed
edf5784346with you as co-author.Thanks for measuring. That's the trade-off I was considering earlier. I believe small stacks are more common. Even still an application reading blocks from the network can't choose which witnesses it gets so I think it's better to keep the worst case linear than to try to optimize for the common case.