Repository navigation
Conversation
|
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. External sites
ReviewsSee the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste ConflictsReviewers, 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. |
| /** | ||
| * @brief Pass each item of a witness stack to the callback, in index order. | ||
| * This reads the stack once, unlike repeated btck_witness_stack_get_item_at | ||
| * calls. |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I switched to this shape in 9d0f1d0. I feel much better about this approach.
|
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. |
957ca29 to
9d0f1d0
Compare
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 f122aee from pr36895-oo-optim1. Both with an input with n one-byte witness items through the C API.
|
| const auto& stack{btck_WitnessStack::get(witness_stack)}; | ||
| assert(items_len == stack.size()); | ||
| for (const auto item : stack) { | ||
| *items++ = item.data(); |
There was a problem hiding this comment.
Passing back pointers to structure internals as void* seems odd? It also potentially introduces lifetime issues, in case the caller keeps items around longer than the corresponding WitnessStack?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 in shared_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 the CScriptWitness and the vector<span> generated from ToSpans, and then continue to provide the current interface with out the O(n)/O(n^2) annoyance.
There was a problem hiding this comment.
Thanks. Owned handles came up when the API was added. Structs holding a shared_ptr were suggested (#30595 (comment)), and the API went with raw pointers, where a const pointer is a borrowed view (#30595 (comment)), which the header also spells out.
For example, btck_StringView (#36584) follows that rule as do the get_items pointers.
btck_WitnessStack is just a pointer to the CScriptWitness inside the input. Keeping the spans next to it would mean btck_transaction_input_get_witness_stack allocating an object on every call that every binding then has to destroy.
There was a problem hiding this comment.
I could imagine it maybe being better for the kernel's witness wrapper to have both the
CScriptWitnessand thevector<span>generated fromToSpans, and then continue to provide the current interface with out the O(n)/O(n^2) annoyance.
I agree with @ajtowns, I independently also arrived at this conclusion.
Keeping the spans next to it would mean
btck_transaction_input_get_witness_stackallocating an object on every call that every binding then has to destroy.
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.
There was a problem hiding this comment.
Got it. I misunderstood the convention and thought getters had to return borrowed views. I think what I can do is drop get_items and have btck_transaction_input_get_witness_stack return an owned object that holds the CScriptWitness and its spans.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
9d0f1d0 to
0b83346
Compare
|
Pushed 0b83346. |
0b83346 to
af9942c
Compare
af9942c to
4a30676
Compare
|
Concept ACK |
|
|
||
| struct WitnessStack { | ||
| const CScriptWitness witness; | ||
| const std::vector<std::span<const unsigned char>> items; |
There was a problem hiding this comment.
Having items point into witness makes 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 4a30676
diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp
index 1f6ba57769..d80c37e3db 100644
--- a/src/kernel/bitcoinkernel.cpp
+++ b/src/kernel/bitcoinkernel.cpp
@@ -605,13 +605,36 @@ void KernelLogger::Log(const util::log::Entry& entry) const
}
}
-struct WitnessStack {
- const CScriptWitness witness;
- const std::vector<std::span<const unsigned char>> items;
+class WitnessStack
+{
+ //! Relative to the first item. CScriptWitness serializations fit in 32 bits.
+ struct ItemPosition {
+ uint32_t offset;
+ uint32_t size;
+ };
+
+ CScriptWitness m_witness;
+ std::vector<ItemPosition> m_positions;
- explicit WitnessStack(const CScriptWitness& w) : witness{w}, items(witness.begin(), witness.end()) {}
- // Copied spans would point into other.witness.
- WitnessStack(const WitnessStack& other) : WitnessStack{other.witness} {}
+public:
+ explicit WitnessStack(const CScriptWitness& witness) : m_witness{witness}
+ {
+ if (m_witness.empty()) return;
+ m_positions.reserve(m_witness.size());
+ const auto* first{m_witness.front().data()};
+ for (const auto item : m_witness) {
+ m_positions.push_back({.offset = static_cast<uint32_t>(item.data() - first),
+ .size = static_cast<uint32_t>(item.size())});
+ }
+ }
+
+ size_t Count() const { return m_positions.size(); }
+
+ std::span<const unsigned char> GetItem(size_t index) const
+ {
+ const auto& position{m_positions[index]};
+ return {m_witness.front().data() + position.offset, position.size};
+ }
};
} // namespace
@@ -873,14 +896,15 @@ void btck_transaction_input_destroy(btck_TransactionInput* input)
size_t btck_witness_stack_count_items(const btck_WitnessStack* witness_stack)
{
- return btck_WitnessStack::get(witness_stack).items.size();
+ return btck_WitnessStack::get(witness_stack).Count();
}
int btck_witness_stack_get_item_at(const btck_WitnessStack* witness_stack, size_t index, btck_WriteBytes writer, void* user_data)
{
- const auto& items{btck_WitnessStack::get(witness_stack).items};
- assert(index < items.size());
- return writer(items[index].data(), items[index].size(), user_data);
+ const auto& stack{btck_WitnessStack::get(witness_stack)};
+ assert(index < stack.Count());
+ const auto item{stack.GetItem(index)};
+ return writer(item.data(), item.size(), user_data);
}
btck_WitnessStack* btck_witness_stack_copy(const btck_WitnessStack* witness_stack)
There was a problem hiding this comment.
Thanks! Would it be worth holding the witness in a shared_ptr<const CScriptWitness> and storing the first item's address once? GetItem would no longer read the size header and decode two CompactSizes through front() 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
diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp
index d80c37e3db..8da3ea8d80 100644
--- a/src/kernel/bitcoinkernel.cpp
+++ b/src/kernel/bitcoinkernel.cpp
@@ -613,17 +613,19 @@ class WitnessStack
uint32_t size;
};
- CScriptWitness m_witness;
+ //! Shared by copies keeping m_first valid for all of them.
+ std::shared_ptr<const CScriptWitness> m_witness;
+ const unsigned char* m_first{nullptr};
std::vector<ItemPosition> m_positions;
public:
- explicit WitnessStack(const CScriptWitness& witness) : m_witness{witness}
+ explicit WitnessStack(const CScriptWitness& witness) : m_witness{std::make_shared<const CScriptWitness>(witness)}
{
- if (m_witness.empty()) return;
- m_positions.reserve(m_witness.size());
- const auto* first{m_witness.front().data()};
- for (const auto item : m_witness) {
- m_positions.push_back({.offset = static_cast<uint32_t>(item.data() - first),
+ if (m_witness->empty()) return;
+ m_positions.reserve(m_witness->size());
+ m_first = m_witness->front().data();
+ for (const auto item : *m_witness) {
+ m_positions.push_back({.offset = static_cast<uint32_t>(item.data() - m_first),
.size = static_cast<uint32_t>(item.size())});
}
}
@@ -633,7 +635,7 @@ public:
std::span<const unsigned char> GetItem(size_t index) const
{
const auto& position{m_positions[index]};
- return {m_witness.front().data() + position.offset, position.size};
+ return {m_first + position.offset, position.size};
}
};Was also wondering if you would you rather copy the item bytes into one buffer with a 4-byte end offset per item? GetItem would also skip front() 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.
There was a problem hiding this comment.
I personally wouldn't go for the shared_ptr<const CScriptWitness> witness. It makes copies faster, but the shared_ptr overhead 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)?
Was also wondering if you would you rather copy the item bytes into one buffer with a 4-byte end offset per item?
I think this makes sense, yeah! I ran some quick benches and it seems to perform better than my earlier suggestion with ItemPosition that required reading front() on every access, and has a lower memory footprint. So I think your suggestion would then look something like the below?
git diff on 4a30676
diff --git a/src/kernel/bitcoinkernel.cpp b/src/kernel/bitcoinkernel.cpp
index 1f6ba57769..07f5eb1308 100644
--- a/src/kernel/bitcoinkernel.cpp
+++ b/src/kernel/bitcoinkernel.cpp
@@ -605,13 +605,31 @@ void KernelLogger::Log(const util::log::Entry& entry) const
}
}
-struct WitnessStack {
- const CScriptWitness witness;
- const std::vector<std::span<const unsigned char>> items;
+class WitnessStack
+{
+ std::vector<unsigned char> m_bytes;
+ //! Where each item ends in m_bytes. CScriptWitness serializations fit in 32 bits.
+ std::vector<uint32_t> m_ends;
- explicit WitnessStack(const CScriptWitness& w) : witness{w}, items(witness.begin(), witness.end()) {}
- // Copied spans would point into other.witness.
- WitnessStack(const WitnessStack& other) : WitnessStack{other.witness} {}
+public:
+ explicit WitnessStack(const CScriptWitness& witness)
+ {
+ // The serialization size is an upper bound for the item bytes.
+ m_bytes.reserve(::GetSerializeSize(witness));
+ m_ends.reserve(witness.size());
+ for (const auto item : witness) {
+ m_bytes.insert(m_bytes.end(), item.begin(), item.end());
+ m_ends.push_back(static_cast<uint32_t>(m_bytes.size()));
+ }
+ }
+
+ size_t Count() const { return m_ends.size(); }
+
+ std::span<const unsigned char> GetItem(size_t index) const
+ {
+ const uint32_t start{index == 0 ? 0 : m_ends[index - 1]};
+ return std::span{m_bytes}.subspan(start, m_ends[index] - start);
+ }
};
} // namespace
@@ -873,14 +891,15 @@ void btck_transaction_input_destroy(btck_TransactionInput* input)
size_t btck_witness_stack_count_items(const btck_WitnessStack* witness_stack)
{
- return btck_WitnessStack::get(witness_stack).items.size();
+ return btck_WitnessStack::get(witness_stack).Count();
}
int btck_witness_stack_get_item_at(const btck_WitnessStack* witness_stack, size_t index, btck_WriteBytes writer, void* user_data)
{
- const auto& items{btck_WitnessStack::get(witness_stack).items};
- assert(index < items.size());
- return writer(items[index].data(), items[index].size(), user_data);
+ const auto& stack{btck_WitnessStack::get(witness_stack)};
+ assert(index < stack.Count());
+ const auto item{stack.GetItem(index)};
+ return writer(item.data(), item.size(), user_data);
}
btck_WitnessStack* btck_witness_stack_copy(const btck_WitnessStack* witness_stack)
There was a problem hiding this comment.
Sorry for jumping in.
I'm wondering about one thing with copying the items into a new buffer: btck_WitnessStack would no longer hold a CScriptWitness. I'm not sure whether we'll ever want to expose Core functionality on the witness stack, but if we do, would dropping the CScriptWitness make that harder? For example, a btck_witness_stack_to_bytes could just reuse CScriptWitness::Serialize, which writes the stored wire-format serialization as-is, instead of re-encoding the format ourselves.
Edit: please also see #36911 (comment) related to having a to_bytes function.
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 the ItemPosition version suggested in #36909 (comment) against the same code with the first item's address cached (only to see the cost without front(), 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):
per block scan only
deserialize only 3.51 ms
deserialize + scan, ItemPosition (front()) 4.35 ms 0.84 ms
deserialize + scan, ItemPosition (cached) 4.19 ms 0.69 ms
There was a problem hiding this comment.
would dropping the
CScriptWitnessmake that harder?
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 CScriptWitness are VerifyScript and CountWitnessSigOps. Both also need the scriptSig and the spent scriptPubKey, so a kernel function for either would take the transaction or input, as btck_script_pubkey_verify does, and those already hold the CScriptWitness. Also the handle's contents are private so if it ever needs a CScriptWitness again then only bitcoinkernel.cpp would need to change.
There was a problem hiding this comment.
So I think your suggestion would then look something like the below?
Yes, thanks for drafting the diff! I thought it through, and felt good about it. I pushed edf5784 with you as co-author.
|
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? |
Copy the items into one buffer and keep each item's end offset instead of walking them on each call. btck_transaction_input_get_witness_stack returns an owned copy. Drop WitnessStackView. Co-authored-by: stickies-v <[email protected]>
4a30676 to
edf5784
Compare
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. |

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.