script: prevent partial reinitialization of sighash data #35662

Open
l0rinc wants to merge 5 commits from l0rinc/script-reset-precomputed-txdata into master AGit
l0rinc commented 2026-07-06 01:58:55 +00:00 (Migrated from github.com)

Problem: PrecomputedTransactionData could be default-constructed and filled later with Init().
That allowed an object to exist without transaction-specific data and left a public reuse path that was easy to get wrong.
The old Init() guard only checked m_spent_outputs_ready, which remained false after initialization without spent outputs even when the BIP143 prevout, sequence, and output hashes were already cached.
No current caller reuses an object across transactions, so validation and signing results are unchanged.
btck_script_pubkey_verify() in the experimental kernel C API also copied caller-supplied txdata on each verification call.

Fix: Remove default construction and Init() so each PrecomputedTransactionData object is built for one transaction.
Callers that already have the transaction and optional spent outputs construct it directly.
Validation stores txdata in std::optional and emplaces it only after a script-cache miss, keeping precomputation lazy.
ConnectBlock() also leaves txdata storage empty when assumevalid skips script checks, covering #35663.
The kernel verification path binds directly to caller-supplied txdata and constructs a local fallback only when needed.

**Problem:** `PrecomputedTransactionData` could be default-constructed and filled later with `Init()`. That allowed an object to exist without transaction-specific data and left a public reuse path that was easy to get wrong. The old `Init()` guard only checked [`m_spent_outputs_ready`](https://github.com/bitcoin/bitcoin/blob/2063f02bd5edebe1b5c9635db8850220811ebc90/src/script/interpreter.cpp#L1415), which remained false after initialization without spent outputs even when the BIP143 prevout, sequence, and output hashes were already cached. No current caller reuses an object across transactions, so validation and signing results are unchanged. `btck_script_pubkey_verify()` in the experimental kernel C API also copied caller-supplied txdata on each verification call. **Fix:** Remove default construction and `Init()` so each `PrecomputedTransactionData` object is built for one transaction. Callers that already have the transaction and optional spent outputs construct it directly. Validation stores txdata in `std::optional` and emplaces it only after a script-cache miss, keeping precomputation lazy. `ConnectBlock()` also leaves txdata storage empty when assumevalid skips script checks, covering #35663. The kernel verification path binds directly to caller-supplied txdata and constructs a local fallback only when needed.
DrahtBot commented 2026-07-06 01:59:02 +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 sedited
Stale ACK fametrano

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:

  • #36122 (BIP460: CISA for Taproot key path spends by fjahr)
  • #35713 (Remove boost as a unit test runner by rustaceanrob)
  • #32575 (consensus: Remove special treatment for single threaded script checking by fjahr)
  • #29491 ([EXPERIMENTAL] Schnorr batch verification for blocks 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.

LLM Linter (✨ experimental)

Possible places where named args for integral literals may be used (e.g. func(x, /*named_arg=*/0) in C++, and func(x, named_arg=0) in Python):

  • src/test/script_assets_tests.cpp: CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, signature_cache, txdata)
  • src/test/script_assets_tests.cpp: CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, signature_cache, txdata)

2026-11-26 19:34:58

<!--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/35662 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35662.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35662#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 | [sedited](https://github.com/bitcoin/bitcoin/pull/35662#pullrequestreview-5278446176) | | Stale ACK | [fametrano](https://github.com/bitcoin/bitcoin/pull/35662#issuecomment-6397135997) | 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: * [#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) * [#35713](https://github.com/bitcoin/bitcoin/pull/35713) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35713.svg"></sub> (Remove boost as a unit test runner by rustaceanrob) * [#32575](https://github.com/bitcoin/bitcoin/pull/32575) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/32575.svg"></sub> (consensus: Remove special treatment for single threaded script checking by fjahr) * [#29491](https://github.com/bitcoin/bitcoin/pull/29491) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/29491.svg"></sub> ([EXPERIMENTAL] Schnorr batch verification for blocks 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--> ### LLM Linter (✨ experimental) Possible places where named args for integral literals may be used (e.g. `func(x, /*named_arg=*/0)` in C++, and `func(x, named_arg=0)` in Python): - `src/test/script_assets_tests.cpp`: `CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, signature_cache, txdata)` - `src/test/script_assets_tests.cpp`: `CachingTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, true, signature_cache, txdata)` <sup>2026-11-26 19:34:58</sup>
sedited (Migrated from github.com) reviewed 2026-07-08 08:41:04 +00:00
sedited (Migrated from github.com) commented 2026-07-08 08:41:05 +00:00

I'm tending NACK here. Afaict this is just a hardening improvement, but I'm not sure if it really is one. We should never be hitting a code path where a re-initialization is possible, and this seems to relax that requirement. I think rather than messing with Init, we should seriously reconsider whether this data can be initialized at construction.

I'm tending NACK here. Afaict this is just a hardening improvement, but I'm not sure if it really is one. We should never be hitting a code path where a re-initialization is possible, and this seems to relax that requirement. I think rather than messing with `Init`, we should seriously reconsider whether this data can be initialized at construction.
l0rinc (Migrated from github.com) reviewed 2026-07-09 00:51:37 +00:00
l0rinc (Migrated from github.com) commented 2026-07-09 00:51:37 +00:00

I agree that resetting readiness flags inside Init() still leaves a reuse API around and makes the type responsible for defending against misuse after construction (I was hoping someone would object).

I’ll rework this so that PrecomputedTransactionData is always built for one transaction and has no public reinitialization path:

  • Call sites that already have the transaction and spent outputs can construct it directly.
  • Call sites that need to wait, such as validation before the script execution cache check, can store std::optional<PrecomputedTransactionData> and emplace() once all required data has been gathered.

This also seems like a natural place to fold in #35663: validation already needs optional txdata storage, so the assumevalid path can leave the per-block txdata vector empty when script checks are skipped, while still resizing it before any queued checks can take pointers into it.

I agree that resetting readiness flags inside `Init()` still leaves a reuse API around and makes the type responsible for defending against misuse after construction (I was hoping someone would object). I’ll rework this so that `PrecomputedTransactionData` is always built for one transaction and has no public reinitialization path: * Call sites that already have the transaction and spent outputs can construct it directly. * Call sites that need to wait, such as validation before the script execution cache check, can store `std::optional<PrecomputedTransactionData>` and `emplace()` once all required data has been gathered. This also seems like a natural place to fold in #35663: validation already needs optional txdata storage, so the assumevalid path can leave the per-block txdata vector empty when script checks are skipped, while still resizing it before any queued checks can take pointers into it.
l0rinc (Migrated from github.com) reviewed 2026-07-09 06:05:51 +00:00
l0rinc (Migrated from github.com) commented 2026-07-09 06:05:51 +00:00

Pushed: PrecomputedTransactionData is no longer default-constructible, public Init() is gone, and each object is built for one transaction.
ConnectBlock() also leaves txdata storage empty when script checks are skipped during assumevalid, so that path avoids the unused vector allocation.
This is indeed a lot nicer, thanks for the push. What do you think?

Pushed: `PrecomputedTransactionData` is no longer default-constructible, public `Init()` is gone, and each object is built for one transaction. `ConnectBlock()` also leaves txdata storage empty when script checks are skipped during assumevalid, so that path avoids the unused vector allocation. This is indeed a lot nicer, thanks for the push. What do you think?
l0rinc commented 2026-08-05 22:29:08 +00:00 (Migrated from github.com)

Rebased after recent merges, ready for review again. I understood @theuni has a similar attempt before, if it's published somewhere, please let me know and I'll add him as a coauthor.

Rebased after recent merges, ready for review again. I understood @theuni has a similar attempt before, if it's published somewhere, please let me know and I'll add him as a coauthor.
sedited (Migrated from github.com) approved these changes 2026-09-22 13:27:22 +00:00
sedited (Migrated from github.com) left a comment

ACK on the changes

I find the title a bit confusing. Which staleness are we exactly preventing with this change?

ACK on the changes I find the title a bit confusing. Which staleness are we exactly preventing with this change?
sedited (Migrated from github.com) commented 2026-09-22 13:05:57 +00:00

Why not remove it entirely? The diff from doing so is small.

Why not remove it entirely? The diff from doing so is small.
l0rinc (Migrated from github.com) reviewed 2026-09-22 23:59:00 +00:00
l0rinc (Migrated from github.com) left a comment

Updated the stack to remove the public Init() helper entirely and added a leading kernel API fix that avoids copying caller-supplied txdata on each verification call (had it in my backlog for a while, I could also push it separately if reviewers want).

@theuni, this touches the txdata lifetime area involved in the script-check issue you found , would you mind reviewing the approach and letting me know if it has your blessing?

Updated the stack to remove the public `Init()` helper entirely and added a leading kernel API fix that avoids copying caller-supplied txdata on each verification call (had it in my backlog for a while, I could also push it separately if reviewers want). @theuni, this touches the txdata lifetime area involved in the script-check issue you found , would you mind reviewing the approach and letting me know if it has your blessing?
l0rinc (Migrated from github.com) commented 2026-09-22 23:25:07 +00:00

Nice, I thought that should be a follow-up, but it was actually trivial. I removed Init() entirely and moved its body into the constructor - beautiful!

Nice, I thought that should be a follow-up, but it was actually trivial. I removed `Init()` entirely and moved its body into the constructor - beautiful!
First-time contributor

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments.

🔵 Suggestion · Cache-hit tests do not cover lazy txdata construction

The migrated cache-hit test retains a pre-existing coverage gap: it would still pass if CheckInputScripts constructed txdata before checking the script cache.

Location: src/test/txvalidationcache_tests.cpp:119 (head).

Review coverage was incomplete.


Reviewed: 241f55dbecc8 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:dd96035e031edf56fcf66a09d443f257a346af1f --> <!-- ralph-head:241f55dbecc8c2ae824614a2410a0ea0255d6069 --> <!-- ralph-case:e0c30d786609b5ff837ff8d54b0aa527528fe65aab28bef9b12feee38901d420 --> Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · Cache-hit tests do not cover lazy `txdata` construction** The migrated cache-hit test retains a pre-existing coverage gap: it would still pass if `CheckInputScripts` constructed `txdata` before checking the script cache. Location: [`src/test/txvalidationcache_tests.cpp:119`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/241f55dbecc8c2ae824614a2410a0ea0255d6069/src/test/txvalidationcache_tests.cpp#L119>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`241f55dbecc8`](<https://git.fish.foo/bitcoin/bitcoin/commit/241f55dbecc8c2ae824614a2410a0ea0255d6069>) · [Review report](<https://review.fish.foo/report/35662-241f55dbecc8c2ae824614a2410a0ea0255d6069-3225-7.html>) · [Previous reports](<https://review.fish.foo/traces/35662/>) [permalink](<https://review.fish.foo/report/35662-241f55dbecc8c2ae824614a2410a0ea0255d6069-3225-7.html>)
fametrano commented 2026-10-25 11:36:40 +00:00 (Migrated from github.com)

tACK 35a8964f88

On which staleness this prevents: on the base (7988380da9), Init(A, {}) for a transaction with a witness, then Init(B, spent_outputs) for one without, passes the old assert(!m_spent_outputs_ready), since A was given no spent outputs. The object keeps A's BIP143 hashes, so B's BIP143 sighash comes out different from a fresh object's. I found no caller that initializes twice, so this is not reachable today; with this PR such code no longer compiles.

I compared 5961 BIP143 and BIP341 key path sighashes from a library I maintain with SignatureHash and SignatureHashSchnorr, on base and head, with txdata built with and without spent outputs and with and without force. All agree, and Taproot without spent outputs is refused on both. On head the unit tests pass (155 ctest entries, script_assets_tests skipped for lack of data), and so does test_kernel.

The kernel commit stops btck_script_pubkey_verify from copying the caller's txdata on every call. I measured base against head with a static Release libbitcoinkernel on an Apple M5, verifying a trivial script with precomputed txdata for a 10000-input transaction. One call takes about 100 µs on base and 0.17 µs on head, and the base cost grows with the input count. Verifying all 10000 inputs once drops from about 1 s to under 2 ms. I can share the harnesses in a gist.

tACK 35a8964f884391cf8aa2434c379561693b21f1f2 On which staleness this prevents: on the base (7988380da9), `Init(A, {})` for a transaction with a witness, then `Init(B, spent_outputs)` for one without, passes the old `assert(!m_spent_outputs_ready)`, since A was given no spent outputs. The object keeps A's BIP143 hashes, so B's BIP143 sighash comes out different from a fresh object's. I found no caller that initializes twice, so this is not reachable today; with this PR such code no longer compiles. I compared 5961 BIP143 and BIP341 key path sighashes from a library I maintain with `SignatureHash` and `SignatureHashSchnorr`, on base and head, with txdata built with and without spent outputs and with and without `force`. All agree, and Taproot without spent outputs is refused on both. On head the unit tests pass (155 ctest entries, `script_assets_tests` skipped for lack of data), and so does `test_kernel`. The kernel commit stops `btck_script_pubkey_verify` from copying the caller's txdata on every call. I measured base against head with a static Release libbitcoinkernel on an Apple M5, verifying a trivial script with precomputed txdata for a 10000-input transaction. One call takes about 100 µs on base and 0.17 µs on head, and the base cost grows with the input count. Verifying all 10000 inputs once drops from about 1 s to under 2 ms. I can share the harnesses in a gist.
DrahtBot commented 2026-10-30 01:30:13 +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).
l0rinc commented 2026-11-04 17:50:26 +00:00 (Migrated from github.com)
Simple rebase after https://github.com/bitcoin/bitcoin/pull/29843
DrahtBot commented 2026-11-26 17:43:32 +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).
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!35662
No description provided.