script: clarify implicit signature-cache input requirements #36395

Open
l0rinc wants to merge 9 commits from l0rinc/sigcache-input-invariants into master AGit
l0rinc commented 2026-09-30 22:39:18 +00:00 (Migrated from github.com)

Problem: Signature-cache hashing relies on input requirements that are implicit at its public entry methods.
Inspired by the Elements rangeproof-cache vulnerability behind the recent Liquid incident and the subsequent cache-key fix, this change clarifies an easy-to-misread hashing pattern: Write(data, size) hashes the data bytes without encoding the size.
Bitcoin Core's cache keys already include the signature hash, public key, and signature in separate ECDSA and Schnorr domains.
Bitcoin Core's signature-cache encoding is unambiguous for inputs accepted by its current script checker: a valid ECDSA public key's prefix determines its length, while a Schnorr public key is always 32 bytes, leaving the signature as the remaining suffix.

Fix: Use native HashWriter serialization in the typed ComputeEntry* methods so ECDSA public keys and signature vectors include their CompactSize lengths.
Schnorr retains its fixed-size public-key encoding and raw signature span.
Return the digest by value from the public ComputeEntry* methods so callers explicitly initialize the cache entry, where the previous chained Finalize(entry.begin()) obscured the output assignment.
Keep the prepared salt prefixes private and const, and copy them locally for each entry.
Retain the ECDSA salt padding and drop the Schnorr salt padding.
Add a nonce-taking constructor so tests can reproduce the encoding deterministically.
The process-local cache-entry bytes change, while script validity rules are unchanged.

**Problem:** Signature-cache hashing relies on input requirements that are implicit at its public entry methods. Inspired by the Elements rangeproof-cache vulnerability behind the recent [Liquid incident](https://blog.blockstream.com/liquid-network-security-incident-assessment) and the [subsequent cache-key fix](https://github.com/ElementsProject/elements/pull/1600), this change clarifies an easy-to-misread hashing pattern: `Write(data, size)` hashes the data bytes without encoding the size. Bitcoin Core's cache keys already include the signature hash, public key, and signature in separate ECDSA and Schnorr domains. Bitcoin Core's signature-cache encoding is unambiguous for inputs accepted by its current script checker: a valid ECDSA public key's prefix determines its length, while a Schnorr public key is always 32 bytes, leaving the signature as the remaining suffix. **Fix:** Use native `HashWriter` serialization in the typed `ComputeEntry*` methods so ECDSA public keys and signature vectors include their CompactSize lengths. Schnorr retains its fixed-size public-key encoding and raw signature span. Return the digest by value from the public `ComputeEntry*` methods so callers explicitly initialize the cache entry, where the previous chained `Finalize(entry.begin())` obscured the output assignment. Keep the prepared salt prefixes private and const, and copy them locally for each entry. Retain the ECDSA salt padding and drop the Schnorr salt padding. Add a nonce-taking constructor so tests can reproduce the encoding deterministically. The process-local cache-entry bytes change, while script validity rules are unchanged.
DrahtBot commented 2026-09-30 22:39:27 +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 instagibbs, 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:

  • #36188 (crypto: plug hardware optimized SHA256 into libsecp256k1's context by furszy)
  • #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.

<!--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/36395 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36395.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36395#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 | [instagibbs](https://github.com/bitcoin/bitcoin/pull/36395#issuecomment-5939526401), [fametrano](https://github.com/bitcoin/bitcoin/pull/36395#issuecomment-6397188720) | 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: * [#36188](https://github.com/bitcoin/bitcoin/pull/36188) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36188.svg"></sub> (crypto: plug hardware optimized SHA256 into libsecp256k1's context by furszy) * [#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-->
First-time contributor

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

🔵 Suggestion · ECDSA second pass does not check cache insertion

The new ECDSA caching passes would still pass if successful signatures were never inserted, so the second pass does not establish that the cache is populated.

Location: src/test/script_tests.cpp:163 (head).

🔵 Suggestion · Fuzz assertions miss different-tuple cache hits

The new script_sigcache assertions retain a pre-existing limitation: each input repeats one tuple against a fresh cache, so they cannot detect a cached success returned for a different sighash, key or signature.

Location: src/test/fuzz/script_sigcache.cpp:56 (head).

Review coverage was incomplete.


Reviewed: a772594831f7 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:806938d40e279b6d701b2e78128bb1a09b55193a0b697245a1dce6241d3081c1:3607c760b63c01fb7f1f349adfc3fd0614b148a7df02e42f2f0edc2d448925a1 --> <!-- ralph-base:dd96035e031edf56fcf66a09d443f257a346af1f --> <!-- ralph-head:a772594831f7ce95ef8e7ccb3652c92222f19720 --> <!-- ralph-case:44a404c60502d21daa14933283cd23d21ed4dc91fca84fa742140edbc15c4327 --> Earlier concerns neither republished nor resolved: 2 suggestions. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · ECDSA second pass does not check cache insertion** The new ECDSA caching passes would still pass if successful signatures were never inserted, so the second pass does not establish that the cache is populated. Location: [`src/test/script_tests.cpp:163`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a772594831f7ce95ef8e7ccb3652c92222f19720/src/test/script_tests.cpp#L163>) (head). **🔵 Suggestion · Fuzz assertions miss different-tuple cache hits** The new `script_sigcache` assertions retain a pre-existing limitation: each input repeats one tuple against a fresh cache, so they cannot detect a cached success returned for a different sighash, key or signature. Location: [`src/test/fuzz/script_sigcache.cpp:56`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/a772594831f7ce95ef8e7ccb3652c92222f19720/src/test/fuzz/script_sigcache.cpp#L56>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`a772594831f7`](<https://git.fish.foo/bitcoin/bitcoin/commit/a772594831f7ce95ef8e7ccb3652c92222f19720>) · [Review report](<https://review.fish.foo/report/36395-a772594831f7ce95ef8e7ccb3652c92222f19720-3221-7.html>) · [Previous reports](<https://review.fish.foo/traces/36395/>) [permalink](<https://review.fish.foo/report/36395-a772594831f7ce95ef8e7ccb3652c92222f19720-3221-7.html>)
DrahtBot commented 2026-09-30 23:41:02 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task lint: https://github.com/bitcoin/bitcoin/actions/runs/36786811940/job/110130078415
LLM reason (✨ experimental): CI failed due to lint-includes.py detecting a newly introduced Boost include (boost/test/tools/context.hpp) in src/test/key_tests.cpp.

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 `lint`: https://github.com/bitcoin/bitcoin/actions/runs/36786811940/job/110130078415</sub> <sub>LLM reason (✨ experimental): CI failed due to lint-includes.py detecting a newly introduced Boost include (`boost/test/tools/context.hpp`) in `src/test/key_tests.cpp`.</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>
instagibbs commented 2026-10-01 20:03:27 +00:00 (Migrated from github.com)

concept ACK on the tests, concept NACKy on the refactors due to blast radius. Will review the tests closer if split out

concept ACK on the tests, concept NACKy on the refactors due to blast radius. Will review the tests closer if split out
fametrano commented 2026-10-01 21:48:23 +00:00 (Migrated from github.com)

I ran the two script_tests.json rows this adds or changes, at c8d6a97afb, through btclib's script interpreter, and both give the expected result. I haven't reviewed the sigcache changes.

I ran the two script_tests.json rows this adds or changes, at c8d6a97afb366f82680601713942afb4955c2885, through btclib's script interpreter, and both give the expected result. I haven't reviewed the sigcache changes.
l0rinc commented 2026-10-02 03:38:52 +00:00 (Migrated from github.com)

concept NACKy on the refactors due to blast radius

The refactor is the meat of this change, the original error would still be possible even if we only add tests, and I want to make sure we learn from those mistakes and refactor to make such misunderstandings harder.
If we're afraid of touching a part of the code, it means it's not ours yet, and it's probably where the ugly bugs are buried.

> concept NACKy on the refactors due to blast radius The refactor is the meat of this change, the original error would still be possible even if we only add tests, and I want to make sure we learn from those mistakes and refactor to make such misunderstandings harder. If we're afraid of touching a part of the code, it means it's not ours yet, and it's probably where the ugly bugs are buried.
fametrano commented 2026-10-25 11:42:10 +00:00 (Migrated from github.com)

Concept ACK

The new tests catch five signature-cache bugs that the current unit tests miss. I made seven one-line breaking changes to sigcache.cpp and ran the unit tests on c8d6a97afb and on its base, d4b0e1e4b0.

On the base, the unit tests still pass with six of the seven changes. Only storing failed Schnorr checks is caught, by txvalidationcache_tests. On this PR, script_tests catches five of those six: dropping the public key or the sighash from the ECDSA or the Schnorr entry, and storing failed ECDSA checks. The cached passes in DoTest catch the ECDSA ones, and the new BIP341 vector checks catch the Schnorr ones.

The sixth change gives Schnorr entries the ECDSA salt, and no unit test catches it on either commit. The separate salts are all that keeps the two domains apart: with one salt, the ECDSA entry for a 33-byte key and a 63-byte signature equals the Schnorr entry for the key's first 32 bytes and a signature made of the key's last byte followed by those 63 bytes. A test that builds both entries with ComputeEntryECDSA and ComputeEntrySchnorr and checks that they differ passes on this PR and fails with that change. It could go in this PR; I can share it, and the seven changes.

Concept ACK The new tests catch five signature-cache bugs that the current unit tests miss. I made seven one-line breaking changes to `sigcache.cpp` and ran the unit tests on c8d6a97afb36 and on its base, d4b0e1e4b0. On the base, the unit tests still pass with six of the seven changes. Only storing failed Schnorr checks is caught, by `txvalidationcache_tests`. On this PR, `script_tests` catches five of those six: dropping the public key or the sighash from the ECDSA or the Schnorr entry, and storing failed ECDSA checks. The cached passes in `DoTest` catch the ECDSA ones, and the new BIP341 vector checks catch the Schnorr ones. The sixth change gives Schnorr entries the ECDSA salt, and no unit test catches it on either commit. The separate salts are all that keeps the two domains apart: with one salt, the ECDSA entry for a 33-byte key and a 63-byte signature equals the Schnorr entry for the key's first 32 bytes and a signature made of the key's last byte followed by those 63 bytes. A test that builds both entries with `ComputeEntryECDSA` and `ComputeEntrySchnorr` and checks that they differ passes on this PR and fails with that change. It could go in this PR; I can share it, and the seven changes.
DrahtBot commented 2026-11-02 11:53:26 +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-05 15:39:33 +00:00 (Migrated from github.com)

Rebased and replaced the hashing helper and cache-entry assertions with native serialization (with explicit size commitment), following the Liquid fix and @instagibbs's suggestion.
Made the salt prefixes const, removed the padding, and added tests that check the encoded bytes and make sure failed signature checks aren't cached.

Rebased and replaced the hashing helper and cache-entry assertions with native serialization (with explicit size commitment), following the [Liquid fix](https://github.com/ElementsProject/elements/pull/1600) and @instagibbs's suggestion. Made the salt prefixes const, removed the padding, and added tests that check the encoded bytes and make sure failed signature checks aren't cached.
Yudis-bit (Migrated from github.com) reviewed 2026-11-07 04:00:34 +00:00
Yudis-bit (Migrated from github.com) commented 2026-11-07 04:00:34 +00:00

The padding in master was there to fill a 64-byte chunk so the compression ran once at startup. With 33 bytes, the constructor leaves 33 bytes in the buffer and defers that transform into ComputeEntry.

For 65-byte uncompressed keys this also crosses the 192-byte mark, needing 4 transforms instead of 3.

Padding 31 zero bytes keeps the HashWriter changes and the precomputed chunk:

HashWriter{} << nonce << uint8_t{'E'} << std::array<uint8_t, 31>{}
The padding in master was there to fill a 64-byte chunk so the compression ran once at startup. With 33 bytes, the constructor leaves 33 bytes in the buffer and defers that transform into `ComputeEntry`. For 65-byte uncompressed keys this also crosses the 192-byte mark, needing 4 transforms instead of 3. Padding 31 zero bytes keeps the `HashWriter` changes and the precomputed chunk: ```cpp HashWriter{} << nonce << uint8_t{'E'} << std::array<uint8_t, 31>{} ```
l0rinc (Migrated from github.com) reviewed 2026-11-07 20:25:15 +00:00
l0rinc (Migrated from github.com) commented 2026-11-07 20:25:15 +00:00

Indeed, while Schnorr measured slightly faster without it (must be some alignment magic), there is an extra cost for uncompressed ECDSA keys: I restored the padding for ECDSA and added you as coauthor, thanks.

Indeed, while Schnorr measured slightly faster without it (must be some alignment magic), there is an extra cost for uncompressed ECDSA keys: I restored the padding for ECDSA and added you as coauthor, thanks.
DrahtBot commented 2026-11-26 17:41:07 +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!36395
No description provided.