Witness stacks in serialized form (optimization follow-ups) #36918

Open
sipa wants to merge 5 commits from 202610_witpack into master AGit
sipa commented 2026-11-19 18:27:33 +00:00 (Migrated from github.com)

This is a PR with follow-up optimizations to #36895.

Benchmarks for the various commits, in milliseconds, on recent Zen5 machine, gcc 15.3 -O2, median of 11 runs. All measure time from receipt to accept/reject (covering everything from deserialization to validation, if relevant):

block master 64061b6a4a 99841eb0f9 945c9e55fe 5401e67366
Before the proof-of-work check
❌ bad commitment, 4.0M × 0 B 275 21 21 21 21
❌ bad commitment, 2.0M × 1 B 134 15 15 15 15
❌ 399,700 txs without inputs or outputs 109 110 109 109 109
Valid blocks
✅ unknown version, 4.0M × 0 B 316 57 57 57 21
✅ unknown leaf version, 4.0M × 0 B 312 59 58 56 55
✅ unknown version, 2.66M × 0–1 B (random) 238 83 79 80 23
✅ unknown leaf version, 2.0M × 1 B 161 67 65 65 65
✅ 14,690 signed P2WPKH 118 117 117 117 118
Invalid blocks with valid proof of work
❌ P2WSH stack too large, 4.0M × 0 B 324 69 65 60 61
❌ P2WSH mismatch, 4.0M × 0 B 315 64 62 56 56
❌ P2WPKH item count, 4.0M × 0 B 314 59 56 56 21
❌ P2WSH stack too large, 2.0M × 1 B 191 97 95 93 93
❌ tapscript stack too large, 2.0M × 1 B 184 93 92 78 76
❌ P2TR bad control block, 2.0M × 1 B 160 66 65 65 66
❌ P2WSH mismatch, 2.0M × 1 B 165 69 67 66 65
This is a PR with follow-up optimizations to #36895. Benchmarks for the various commits, in milliseconds, on recent Zen5 machine, gcc 15.3 -O2, median of 11 runs. All measure time from receipt to accept/reject (covering everything from deserialization to validation, if relevant): | block | master | 64061b6a4a4 | 99841eb0f95 | 945c9e55fe1 | 5401e673666| |---|--:|--:|--:|--:|--:| | **Before the proof-of-work check** | | | | | | | ❌ bad commitment, 4.0M × 0 B | 275 | 21 | 21 | 21 | 21 | | ❌ bad commitment, 2.0M × 1 B | 134 | 15 | 15 | 15 | 15 | | ❌ 399,700 txs without inputs or outputs | 109 | 110 | 109 | 109 | 109 | | **Valid blocks** | | | | | | | ✅ unknown version, 4.0M × 0 B | 316 | 57 | 57 | 57 | 21 | | ✅ unknown leaf version, 4.0M × 0 B | 312 | 59 | 58 | 56 | 55 | | ✅ unknown version, 2.66M × 0–1 B (random) | 238 | 83 | 79 | 80 | 23 | | ✅ unknown leaf version, 2.0M × 1 B | 161 | 67 | 65 | 65 | 65 | | ✅ 14,690 signed P2WPKH | 118 | 117 | 117 | 117 | 118 | | **Invalid blocks with valid proof of work** | | | | | | | ❌ P2WSH stack too large, 4.0M × 0 B | 324 | 69 | 65 | 60 | 61 | | ❌ P2WSH mismatch, 4.0M × 0 B | 315 | 64 | 62 | 56 | 56 | | ❌ P2WPKH item count, 4.0M × 0 B | 314 | 59 | 56 | 56 | 21 | | ❌ P2WSH stack too large, 2.0M × 1 B | 191 | 97 | 95 | 93 | 93 | | ❌ tapscript stack too large, 2.0M × 1 B | 184 | 93 | 92 | 78 | 76 | | ❌ P2TR bad control block, 2.0M × 1 B | 160 | 66 | 65 | 65 | 66 | | ❌ P2WSH mismatch, 2.0M × 1 B | 165 | 69 | 67 | 66 | 65 |
DrahtBot commented 2026-11-19 18:27:43 +00:00 (Migrated from github.com)

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
Concept ACK optout21
Approach ACK ajtowns

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:

  • #36853 (test: Add test for CompactSize larger than MAX_SIZE value by maflcko)
  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36918 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36918.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36918#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Concept ACK | [optout21](https://github.com/bitcoin/bitcoin/pull/36918#pullrequestreview-6134531779) | | Approach ACK | [ajtowns](https://github.com/bitcoin/bitcoin/pull/36918#pullrequestreview-6082944401) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36853](https://github.com/bitcoin/bitcoin/pull/36853) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36853.svg"></sub> (test: Add test for CompactSize larger than MAX_SIZE value by maflcko) * [#36122](https://github.com/bitcoin/bitcoin/pull/36122) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36122.svg"></sub> (BIP460: CISA for Taproot key path spends by fjahr) 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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
First-time contributor

Earlier concerns neither republished nor resolved: 1 major finding · 2 suggestions. See the Run archive linked from the Review report for their assessments.

🔵 Suggestion · P2WSH hash mismatches still materialize the entire witness

The pre-existing P2WSH conversion still materializes every element before rejecting a script-hash mismatch, although the new constant-time back() makes that work avoidable.

Location: src/script/interpreter.cpp:1940 (head).

🔵 Suggestion · Witness rejection tests miss canonicality, count-limit and truncation checks

The new CScriptWitness::Unserialize() loop has only an oversized-element rejection unit test; its canonical-prefix, count-limit and short-payload checks lack deterministic witness coverage, despite differential fuzz coverage.

Location: src/script/script.h:724 (head).

🔵 Suggestion · Witness payload chunk boundaries lack deterministic coverage

CScriptWitness unit tests never successfully deserialize an element larger than MAX_VECTOR_ALLOCATE, leaving continuation offsets and stream consumption in the new chunk loop without deterministic checks.

Location: src/script/script.h:743 (head).

🔵 Suggestion · P2WPKH benchmark gives the public-key item 72 bytes

DeserializeBlockP2WPKH gives the compressed-public-key item 72 bytes instead of 33, so its synthetic block underrepresents transaction and witness counts at the same weight.

Location: src/bench/block_deserialize.cpp:117 (head).

Review coverage was incomplete.


Reviewed: 32a29373e0c8 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:58e9d98f3110c6e759f3148d974305b843fed33c --> <!-- ralph-head:32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c --> <!-- ralph-case:52ccd2eb1eb23e4e6398e7483bce487b57502df6c22e0347b20a11bc0025efd9 --> Earlier concerns neither republished nor resolved: 1 major finding · 2 suggestions. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · P2WSH hash mismatches still materialize the entire witness** The pre-existing P2WSH conversion still materializes every element before rejecting a script-hash mismatch, although the new constant-time `back()` makes that work avoidable. Location: [`src/script/interpreter.cpp:1940`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c/src/script/interpreter.cpp#L1940>) (head). **🔵 Suggestion · Witness rejection tests miss canonicality, count-limit and truncation checks** The new `CScriptWitness::Unserialize()` loop has only an oversized-element rejection unit test; its canonical-prefix, count-limit and short-payload checks lack deterministic witness coverage, despite differential fuzz coverage. Location: [`src/script/script.h:724`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c/src/script/script.h#L724>) (head). **🔵 Suggestion · Witness payload chunk boundaries lack deterministic coverage** `CScriptWitness` unit tests never successfully deserialize an element larger than `MAX_VECTOR_ALLOCATE`, leaving continuation offsets and stream consumption in the new chunk loop without deterministic checks. Location: [`src/script/script.h:743`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c/src/script/script.h#L743>) (head). **🔵 Suggestion · P2WPKH benchmark gives the public-key item 72 bytes** `DeserializeBlockP2WPKH` gives the compressed-public-key item 72 bytes instead of 33, so its synthetic block underrepresents transaction and witness counts at the same weight. Location: [`src/bench/block_deserialize.cpp:117`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c/src/bench/block_deserialize.cpp#L117>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`32a29373e0c8`](<https://git.fish.foo/bitcoin/bitcoin/commit/32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c>) · [Review report](<https://review.fish.foo/report/36918-32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c-3270-6.html>) · [Previous reports](<https://review.fish.foo/traces/36918/>) [permalink](<https://review.fish.foo/report/36918-32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c-3270-6.html>)
l0rinc (Migrated from github.com) reviewed 2026-11-19 19:33:38 +00:00
l0rinc (Migrated from github.com) commented 2026-11-19 19:33:38 +00:00

c462cc5 policy: iterate over witness stacks directly in IsWitnessStandard:

I'm not sure I understand the split: this was just added in the unmerged previous PR (one of my pending suggestions is exactly that we don't actually need a separate ToSpans), and now we remove it here again, so code we reviewed in the previous PR won't even end up being used... Is this meant to simplify cherry-picking to older versions?

> [c462cc5](https://github.com/bitcoin/bitcoin/pull/36918/changes/c462cc5430d2827101dd67e8668e07a3691c9274) _policy: iterate over witness stacks directly in IsWitnessStandard_: I'm not sure I understand the split: this was just added in the unmerged previous PR (one of my pending suggestions is exactly that we don't actually need a separate `ToSpans`), and now we remove it here again, so code we reviewed in the previous PR won't even end up being used... Is this meant to simplify cherry-picking to older versions?
sipa (Migrated from github.com) reviewed 2026-11-19 20:40:09 +00:00
sipa (Migrated from github.com) commented 2026-11-19 20:40:09 +00:00

Is this meant to simplify cherry-picking to older versions?

Yes. #36895 is just the minimal part to get the memory usage savings in, which hopefully doesn't need that much discussion. This PR (and the side track #36906) likely need some debate about which changes exactly are worth it.

> Is this meant to simplify cherry-picking to older versions? Yes. #36895 is just the minimal part to get the memory usage savings in, which hopefully doesn't need that much discussion. This PR (and the side track #36906) likely need some debate about which changes exactly are worth it.
DrahtBot commented 2026-11-19 21:01:56 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/44588028340/job/135786171179
LLM reason (✨ experimental): CI failed because IWYU added a missing <span> include to src/bench/block_deserialize.cpp, leaving an uncommitted diff that the check rejects.

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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/44588028340/job/135786171179</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU added a missing `<span>` include to `src/bench/block_deserialize.cpp`, leaving an uncommitted diff that the check rejects.</sub> <details><summary>Hints</summary> 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. </details>
DrahtBot commented 2026-11-25 00:53:10 +00:00 (Migrated from github.com)

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

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
sipa commented 2026-11-27 01:59:34 +00:00 (Migrated from github.com)

Ready for review.

Ready for review.
ajtowns (Migrated from github.com) reviewed 2026-11-27 03:56:53 +00:00
ajtowns (Migrated from github.com) left a comment

Approach ACK 5401e67366

Approach ACK 5401e673666daf1108483debcd8f9782b1de4957
ajtowns (Migrated from github.com) commented 2026-11-27 03:27:36 +00:00

What do you think of making this auto stack = witness.ToVectors() and changing it to const auto pop{[&](std::vector<valtype>& stack) { and pop(stack) so that the stack variables are scoped to where they're used?

What do you think of making this `auto stack = witness.ToVectors()` and changing it to `const auto pop{[&](std::vector<valtype>& stack) {` and `pop(stack)` so that the `stack` variables are scoped to where they're used?
ajtowns (Migrated from github.com) commented 2026-11-27 03:56:25 +00:00

The back() commit feels hardest to justify. Arguably:

  • just having back() be O(1) isn't enough -- if annexes become standard, we want to access both the last and second last elements quickly for standardness checks; and conceivably we could want to access the third last element as well if a script size check was re-introduced or similar.
  • back() not being O(1) is a potential footgun for the future, but so is operator[] not being O(1)

Perhaps a ToLastSpans(n) that returns a vector of the last (up to) n stack elements would eventually be more useful?

The back() commit feels hardest to justify. Arguably: * just having back() be O(1) isn't enough -- if annexes become standard, we want to access both the last and second last elements quickly for standardness checks; and conceivably we could want to access the third last element as well if a script size check was re-introduced or similar. * back() not being O(1) is a potential footgun for the future, but so is operator[] not being O(1) Perhaps a `ToLastSpans(n)` that returns a vector of the last (up to) n stack elements would eventually be more useful?
ajtowns (Migrated from github.com) commented 2026-11-27 03:11:29 +00:00

Worth an Assume(m_data); ? Would previously have been caught via operator[] doing Assume(last_offset < size()) with last_offset having wrapped around to max I think.

Worth an `Assume(m_data);` ? Would previously have been caught via `operator[]` doing `Assume(last_offset < size())` with `last_offset` having wrapped around to max I think.
ajtowns (Migrated from github.com) commented 2026-11-27 03:06:43 +00:00

What do you think of renaming this to DecodeCompactSizeUnchecked (like txmempool removeUnchecked)? The difference between "Read" and "Decode" is not very obvious ("ReadCompactSize" is also described in its comments as "Decode a CompactSize-encoded variable-length integer.").

What do you think of renaming this to `DecodeCompactSizeUnchecked` (like txmempool `removeUnchecked`)? The difference between "Read" and "Decode" is not very obvious ("ReadCompactSize" is also described in its comments as "Decode a CompactSize-encoded variable-length integer.").
sipa (Migrated from github.com) reviewed 2026-11-27 16:48:08 +00:00
sipa (Migrated from github.com) commented 2026-11-27 16:49:08 +00:00

Done.

Done.
sipa (Migrated from github.com) commented 2026-11-27 16:50:40 +00:00

If annexes were to become standard, it would be possible to instead store the offset to the penultimate element, and making back() do one forward iteration step.

At that point, there probably should just be a "get iterator to element at position X" or so?

If annexes were to become standard, it would be possible to instead store the offset to the penultimate element, and making `back()` do one forward iteration step. At that point, there probably should just be a "get iterator to element at position X" or so?
sipa (Migrated from github.com) commented 2026-11-27 16:48:48 +00:00

Done.

Done.
sipa (Migrated from github.com) commented 2026-11-27 16:48:08 +00:00

Done.

Done.
ajtowns (Migrated from github.com) reviewed 2026-11-28 03:40:44 +00:00
ajtowns (Migrated from github.com) commented 2026-11-28 03:40:44 +00:00

Ah, keeping a pointer to 2nd or 3rd last element works, yeah. Maybe stack.back(0) and stack.back(1) or something would be better than stack[stack.size()-1] in that case (with an error if you try stack.back(2) and that can't be efficient. Sounds solvable either way though.

Ah, keeping a pointer to 2nd or 3rd last element works, yeah. Maybe `stack.back(0)` and `stack.back(1)` or something would be better than `stack[stack.size()-1]` in that case (with an error if you try `stack.back(2)` and that can't be efficient. Sounds solvable either way though.
optout21 (Migrated from github.com) reviewed 2026-12-01 16:41:54 +00:00
optout21 (Migrated from github.com) left a comment

Concept ACK (32a29373e0)

Worthwhile optimizations, a followup of #36895.
Code review and tests are OK.
Left some minor remarks, and some general ones here:

1, The last-element optimization's commit message states: "but does not change the minimum allocation size of a single-element stack". I believe this is true on 64-bit systems, so it should be qualified "(on 64-bit systems)".

2, I have some doubts about the last-element optimization: it produces a speed-up, but the effect of the extra memory used is not trivial.
Using the mempool accounting rule (memusage::MallocUsage, 64-bit, rounds as ((alloc + 31) >> 4) << 4), P2WPKH, the most common input type, uses 144 instead of 128 bytes total, a 12.5% extra. With real glibc rounding ((n + 8 + 15) & ~15, minimum 32), it's still 128.

Some options that may be considered:

  • Always store the last element index (current state of 6134604)
  • Never last element index
  • Store the extra last-index only for witness stacks with elements above a threshold (e.g. >= 4), as iterating over only a few elements is not that slow. But the element count may be not always readily available, so it could use the total data size (stored in the first 4 bytes), e.g. skip the last element index if data size < 128. With small data it is likely that the number of elements is small (this is an approximation), for large data the relative extra memory (the 4 extra bytes) is small. Overall this would reduce the extra memory usage. Drawbacks: the code becomes even more complex (header is 4 or 8 bytes), the optimal threshold limit is hard to estimate.
  • Use compact encoding to store the data size and the element index, may use less extra memory.
Concept ACK (32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c) Worthwhile optimizations, a followup of #36895. Code review and tests are OK. Left some minor remarks, and some general ones here: 1, The last-element optimization's commit message states: "but does not change the minimum allocation size of a single-element stack". I believe this is true on 64-bit systems, so it should be qualified "(on 64-bit systems)". 2, I have some doubts about the last-element optimization: it produces a speed-up, but the effect of the extra memory used is not trivial. Using the mempool accounting rule (`memusage::MallocUsage`, 64-bit, rounds as `((alloc + 31) >> 4) << 4`), P2WPKH, the most common input type, uses 144 instead of 128 bytes total, a 12.5% extra. With real glibc rounding (`(n + 8 + 15) & ~15`, minimum 32), it's still 128. Some options that may be considered: - Always store the last element index (current state of 6134604) - Never last element index - Store the extra last-index only for witness stacks with elements above a threshold (e.g. >= 4), as iterating over only a few elements is not that slow. But the element count may be not always readily available, so it could use the total data size (stored in the first 4 bytes), e.g. skip the last element index if data size < 128. With small data it is likely that the number of elements is small (this is an approximation), for large data the relative extra memory (the 4 extra bytes) is small. Overall this would reduce the extra memory usage. Drawbacks: the code becomes even more complex (header is 4 *or* 8 bytes), the optimal threshold limit is hard to estimate. - Use compact encoding to store the data size and the element index, may use less extra memory.
optout21 (Migrated from github.com) commented 2026-12-01 16:25:10 +00:00

32a2937 script: only convert the witness to vectors when it is used:

Nit: This check could come before the ToString(), if (witness.empty()).

> [32a2937](https://github.com/bitcoin/bitcoin/pull/36918/changes/32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c) _script: only convert the witness to vectors when it is used_: Nit: This check could come before the `ToString()`, `if (witness.empty())`.
Lines 1950-1952
optout21 (Migrated from github.com) commented 2026-12-01 16:18:34 +00:00

32a2937 script: only convert the witness to vectors when it is used:

Small optimization for error case: This check (for P2WSH with a wrong script hash) could be moved before witness.ToVectors(), using back().

> [32a2937](https://github.com/bitcoin/bitcoin/pull/36918/changes/32a29373e0c8f0a7c9bfe8ab92e60d02b93ceb6c) _script: only convert the witness to vectors when it is used_: Small optimization for error case: This check (for P2WSH with a wrong script hash) could be moved before `witness.ToVectors()`, using `back()`.
optout21 (Migrated from github.com) commented 2026-12-01 15:36:15 +00:00

2d5b121 script: deserialize witness stacks directly into their serialization:

Nit: Alternative for the for loop:
data.insert(data.end(), src.begin(), src.end())
Simpler, depending on taste, and about as fast, depending on compiler optimizations.

> [2d5b121](https://github.com/bitcoin/bitcoin/pull/36918/changes/2d5b121db269df5a24d7b79e49405c77811f7520) _script: deserialize witness stacks directly into their serialization_: Nit: Alternative for the `for` loop: `data.insert(data.end(), src.begin(), src.end())` Simpler, depending on taste, and about as fast, depending on compiler optimizations.
optout21 (Migrated from github.com) commented 2026-12-01 15:50:02 +00:00

a9e2ed1 script: decode the CompactSizes in witness stacks inline:

Nit: I suggest an Assume on the size before memcpy:
Assume(dst.size() <= data.size());
The old SpanReader threw before reading, this assume would restore the check in debug and fuzz builds and at no cost in release builds.
With hardened std::span (_GLIBCXX_ASSERTIONS or libc++ hardening), an overrun is caught only after it has already happened.

> [a9e2ed1](https://github.com/bitcoin/bitcoin/pull/36918/changes/a9e2ed1878cd29a9c4814592cfecc432bb282d28) _script: decode the CompactSizes in witness stacks inline_: Nit: I suggest an `Assume` on the size before `memcpy`: `Assume(dst.size() <= data.size());` The old SpanReader threw before reading, this assume would restore the check in debug and fuzz builds and at no cost in release builds. With hardened `std::span` (`_GLIBCXX_ASSERTIONS` or libc++ hardening), an overrun is caught only after it has already happened.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36918
No description provided.