Skip to content

script: prevent partial reinitialization of sighash data - #35662

Open
l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/script-reset-precomputed-txdata
Open

l0rinc wants to merge 5 commits into
bitcoin:masterfrom
l0rinc:l0rinc/script-reset-precomputed-txdata

Conversation

@l0rinc

@l0rinc l0rinc commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

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.

@DrahtBot

DrahtBot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

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

template <class T>
void PrecomputedTransactionData::Init(const T& txTo, std::vector<CTxOut>&& spent_outputs, bool force)
{
assert(!m_spent_outputs_ready);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
l0rinc marked this pull request as draft July 8, 2026 23:56
@l0rinc
l0rinc force-pushed the l0rinc/script-reset-precomputed-txdata branch from 1279d5d to 586620e Compare July 9, 2026 05:54
@l0rinc l0rinc changed the title script: reset precomputed txdata on reuse script: construct txdata at initialization sites Jul 9, 2026
@l0rinc l0rinc changed the title script: construct txdata at initialization sites script: remove deferred txdata initialization Jul 9, 2026
@l0rinc l0rinc changed the title script: remove deferred txdata initialization script: make txdata non-default-constructible Jul 9, 2026
@l0rinc
l0rinc force-pushed the l0rinc/script-reset-precomputed-txdata branch from 586620e to 92470f7 Compare July 9, 2026 19:21
@l0rinc
l0rinc marked this pull request as ready for review July 9, 2026 19:22
@DrahtBot DrahtBot removed the CI failed label Jul 9, 2026
@l0rinc
l0rinc force-pushed the l0rinc/script-reset-precomputed-txdata branch from 92470f7 to a5ac29b Compare August 5, 2026 22:27
@l0rinc l0rinc changed the title script: make txdata non-default-constructible script: prevent stale sighash caches across transactions Aug 5, 2026
@l0rinc

l0rinc commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

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 sedited left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ACK on the changes

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

Comment thread src/script/interpreter.h Outdated
private:
template <class T>
explicit PrecomputedTransactionData(const T& tx);
void Init(const T& tx, std::vector<CTxOut>&& spent_outputs, bool force);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

@l0rinc l0rinc changed the title script: prevent stale sighash caches across transactions script: prevent reinitializing sighash data for another transaction Sep 22, 2026
@l0rinc
l0rinc force-pushed the l0rinc/script-reset-precomputed-txdata branch from a5ac29b to e7e202b Compare September 22, 2026 23:25

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment thread src/script/interpreter.h Outdated
private:
template <class T>
explicit PrecomputedTransactionData(const T& tx);
void Init(const T& tx, std::vector<CTxOut>&& spent_outputs, bool force);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

@l0rinc
l0rinc force-pushed the l0rinc/script-reset-precomputed-txdata branch from e7e202b to 35a8964 Compare October 1, 2026 16:19
@l0rinc l0rinc changed the title script: prevent reinitializing sighash data for another transaction script: prevent partial reinitialization of sighash data Oct 4, 2026
@fametrano

Copy link
Copy Markdown

tACK 35a8964

On which staleness this prevents: on the base (7988380), 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
DrahtBot requested a review from sedited October 25, 2026 11:36
@l0rinc
l0rinc force-pushed the l0rinc/script-reset-precomputed-txdata branch from 35a8964 to 245711d Compare November 4, 2026 17:47
@l0rinc

l0rinc commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Simple rebase after #29843

In the experimental kernel C API, the conditional expression mixes the caller-supplied lvalue with a fallback prvalue. Its result is a prvalue that copies the supplied PrecomputedTransactionData on every verification call with supplied data.

Reproducer: https://godbolt.org/z/PzcKGW9da (GCC 15.2: one copy before, none after).

Keep optional storage only for the fallback and bind directly to emplace(). Both conditional arms are now lvalues, so a supplied object is reused while the fallback retains the same lifetime.
Extend the transaction-only constructor to accept spent outputs and a `force` flag, then use it where those inputs are already available.
This preserves each caller's precomputation behavior while removing default construction from the simple cases.
The PSBT caller discards partial spent outputs when any input UTXO is missing, preserving its existing all-or-none precomputation.
Cover forced and witness-detected constructor readiness before removing the initialization API.
SignTransaction() can provide spent outputs only when every input coin is available, so discard a partial collection when one is missing and construct txdata once with forced precomputation.
The kernel creation API likewise gathers spent outputs before constructing and releasing its handle.
The signature-cache fuzz checker does not read txdata, so its empty-transaction construction avoids unused hashing.
Script-cache hits return before validation gathers spent outputs or precomputes transaction data.
Store txdata in `std::optional` and emplace it only after a cache miss to preserve that behavior.
`ConnectBlock()` can skip script checks for blocks in the assumevalid period, so size its txdata storage only when checks can run.
Remove default construction and Init() so transaction-specific data is computed in the constructor.
Make the earlier compile-time constructor check reject default construction.
Existing callers already construct fresh data for each transaction, so validation and signing results are unchanged.
@l0rinc
l0rinc force-pushed the l0rinc/script-reset-precomputed-txdata branch from 245711d to 241f55d Compare November 26, 2026 19:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants