crypto: plug hardware optimized SHA256 into libsecp256k1's context #36188

Open
furszy wants to merge 9 commits from 2026_secp_pluggable_sha into master AGit
furszy commented 2026-09-07 20:28:23 +00:00 (Migrated from github.com)

Since https://github.com/bitcoin-core/secp256k1/pull//1777 , libsecp256k1 allows an externally provided SHA256 compression function. This PR plug ours in, so it runs on our SHA-NI/ARMv8/SSE4 hardware optimized implementation instead of the libsecp bare internal one.

The biggest gains are at the signing side, not at the verification side.

Benchmarks at the bench introduction commit (43c9bdbf8ada1b581b5ab1f0a102517c243a60da) and at the tip:

On ARM64, arm_shani implementation

benchmark before after change
ECDSASign 79.2 µs 69.3 µs -13%
SchnorrSign 39.9 µs 37.1 µs -7%
ECDSAVerify 27.4 µs 27.3 µs -0%
SchnorrVerify 28.1 µs 27.8 µs -1%
EllSwiftCreate 29.8 µs 28.8 µs -3%
BIP324_ECDH 30.4 µs 30.1 µs -1%
Since https://github.com/bitcoin-core/secp256k1/pull//1777 , libsecp256k1 allows an externally provided SHA256 compression function. This PR plug ours in, so it runs on our SHA-NI/ARMv8/SSE4 hardware optimized implementation instead of the libsecp bare internal one. The biggest gains are at the signing side, not at the verification side. Benchmarks at the bench introduction commit (43c9bdbf8ada1b581b5ab1f0a102517c243a60da) and at the tip: On ARM64, `arm_shani` implementation | benchmark | before | after | change | |---|---|---|---| | `ECDSASign` | 79.2 µs | 69.3 µs | -13% | | `SchnorrSign` | 39.9 µs | 37.1 µs | -7% | | `ECDSAVerify` | 27.4 µs | 27.3 µs | -0% | | `SchnorrVerify` | 28.1 µs | 27.8 µs | -1% | | `EllSwiftCreate` | 29.8 µs | 28.8 µs | -3% | | `BIP324_ECDH` | 30.4 µs | 30.1 µs | -1% |
DrahtBot commented 2026-09-07 20:28:31 +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
ACK theStack
Concept ACK sedited, ismaelsadeeq, hebasto, fjahr
Stale ACK fametrano, w0xlt

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:

  • #36985 ([RFC] ipc: add Events interface for chain and mempool notifications by ViniciusCestarii)
  • #36395 (script: clarify implicit signature-cache input requirements by l0rinc)
  • #35733 (sign: Remove FillableSigningProvider by achow101)
  • #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/key.cpp: secp256k1_schnorrsig_verify(GetSecp256k1PublicContext(), sig.data(), hash.begin(), 32, &pubkey_verify)
  • src/pubkey.cpp: secp256k1_schnorrsig_verify(GetSecp256k1PublicContext(), sigbytes.data(), msg.begin(), 32, &pubkey)

2026-11-02 15:39:36

<!--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/36188 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36188.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36188#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 | | ---- | --------- | | ACK | [theStack](https://github.com/bitcoin/bitcoin/pull/36188#pullrequestreview-5787649096) | | Concept ACK | [sedited](https://github.com/bitcoin/bitcoin/pull/36188#issuecomment-5581070938), [ismaelsadeeq](https://github.com/bitcoin/bitcoin/pull/36188#issuecomment-5582747055), [hebasto](https://github.com/bitcoin/bitcoin/pull/36188#pullrequestreview-5168598520), [fjahr](https://github.com/bitcoin/bitcoin/pull/36188#pullrequestreview-5973351371) | | Stale ACK | [fametrano](https://github.com/bitcoin/bitcoin/pull/36188#issuecomment-6394594852), [w0xlt](https://github.com/bitcoin/bitcoin/pull/36188#pullrequestreview-5687655063) | 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: * [#36985](https://github.com/bitcoin/bitcoin/pull/36985) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36985.svg"></sub> ([RFC] ipc: add Events interface for chain and mempool notifications by ViniciusCestarii) * [#36395](https://github.com/bitcoin/bitcoin/pull/36395) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36395.svg"></sub> (script: clarify implicit signature-cache input requirements by l0rinc) * [#35733](https://github.com/bitcoin/bitcoin/pull/35733) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35733.svg"></sub> (sign: Remove FillableSigningProvider by achow101) * [#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/key.cpp`: `secp256k1_schnorrsig_verify(GetSecp256k1PublicContext(), sig.data(), hash.begin(), 32, &pubkey_verify)` - `src/pubkey.cpp`: `secp256k1_schnorrsig_verify(GetSecp256k1PublicContext(), sigbytes.data(), msg.begin(), 32, &pubkey)` <sup>2026-11-02 15:39:36</sup>
DrahtBot commented 2026-09-07 21:39:41 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/34159538723/job/101858273499
LLM reason (✨ experimental): CI failed because the IWYU lint check detected missing/incorrect headers (generated “Failure generated from IWYU” for src/bench/ecc_sign_verify.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 `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/34159538723/job/101858273499</sub> <sub>LLM reason (✨ experimental): CI failed because the IWYU lint check detected missing/incorrect headers (generated “Failure generated from IWYU” for `src/bench/ecc_sign_verify.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>
w0xlt commented 2026-09-08 07:00:28 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
fjahr commented 2026-09-08 07:23:32 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
sedited commented 2026-09-08 07:30:06 +00:00 (Migrated from github.com)

Finally! Concept ACK

Finally! Concept ACK
ismaelsadeeq commented 2026-09-08 09:32:32 +00:00 (Migrated from github.com)

Awesome Concept ACK

Awesome Concept ACK
theStack commented 2026-09-08 16:55:02 +00:00 (Migrated from github.com)

Splendid Concept ACK

Splendid Concept ACK
fanquake commented 2026-09-09 10:51:52 +00:00 (Migrated from github.com)

cc @real-or-random

cc @real-or-random
hebasto (Migrated from github.com) reviewed 2026-09-10 14:48:12 +00:00
hebasto (Migrated from github.com) left a comment

Concept ACK.

Concept ACK.
DrahtBot commented 2026-09-24 01:04:48 +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).
theStack (Migrated from github.com) reviewed 2026-09-30 14:38:02 +00:00
theStack (Migrated from github.com) left a comment

LGTM, just left two organizational comments. The MuSig and BIP352 modules could also take use of the plugged in compression function, either here or in a follow-up PR.

LGTM, just left two organizational comments. The MuSig and BIP352 modules could also take use of the plugged in compression function, either here or in a follow-up PR.
theStack (Migrated from github.com) commented 2026-09-30 14:34:35 +00:00

An alternative to this split-up would be to keep having only one "full" (i.e. non-static) context and use it for both signing and verifying (and any other API calls that either involve a generator point multiplication or hashing). It's true that some functions don't take use of the blinding data generated with _context_randomize, but it also doesn't slow things down or hurt in another way.
The only challenge might be to find a good name for that context, since it's not only used for signing anymore (FullContext, DynamicContext, ...?).

An alternative to this split-up would be to keep having only one "full" (i.e. non-static) context and use it for both signing and verifying (and any other API calls that either involve a generator point multiplication or hashing). It's true that some functions don't take use of the blinding data generated with `_context_randomize`, but it also doesn't slow things down or hurt in another way. The only challenge might be to find a good name for that context, since it's not only used for signing anymore (`FullContext`, `DynamicContext`, ...?).
theStack (Migrated from github.com) commented 2026-09-24 13:06:48 +00:00

minimal-diff nit: from all the secp function calls in this file, this (_schnorrsig_verify) is the only one that involves hashing and thus benefits from the SHA256 override, i.e. it would be fine if the others kept using the static context

minimal-diff nit: from all the secp function calls in this file, this (`_schnorrsig_verify`) is the only one that involves hashing and thus benefits from the SHA256 override, i.e. it would be fine if the others kept using the static context
First-time contributor

🔵 Suggestion · Public context loses the static context's signing misuse check

A future generator-based signing call using this context would run with fixed blinding instead of aborting; no current caller passing the public context to such an operation was found.

Location: src/pubkey.cpp:40 (head).

🔵 Suggestion · Context test does not observe the production SHA256 installation

The test installs its counting callback independently, so removing either production SHA256Transform installation would leave these assertions passing despite losing the optimization.

Location: src/test/key_tests.cpp:425 (head).

🔵 Suggestion · DER-lax fuzz target retains unnecessary RNG setup

Removing the per-input ECC_Context removed this fuzz target's only global-PRNG consumer, leaving its seed call and associated includes unnecessary.

Location: src/test/fuzz/secp256k1_ecdsa_signature_parse_der_lax.cpp:29 (base).

🔵 Suggestion · SHA256Transform declaration omits the compression contract

The header describes dispatch but not the raw compression interface libsecp relies on, leaving state, block units and input-alignment requirements undocumented.

Location: src/crypto/sha256.h:53 (head).

🔵 Suggestion · Benchmark includes span.h without using its helpers

The new benchmark has no direct use of span.h; its key and public-key headers already provide the dependencies needed by their APIs.

Location: src/bench/ecc_sign_verify.cpp:9 (head).

🔵 Suggestion · Signing-context routing lacks regression coverage

Narrowed. key_tests.cpp:428-432 now checks that CKey::Sign routes through the sign context, but nothing checks KeyPair::SignSchnorr (key.cpp:425). A misrouted Schnorr signing call would still produce valid signatures and pass.

Location: src/test/key_tests.cpp:428 (head).

Review coverage was incomplete.


Reviewed: 67ac80993df9 · Full review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:4d44b6ffa09c54db24f8f0ab27ae388beae06a733efcae741ca64db76bb1c938:7efd3c3ba41667382004cfa7a7db56605da7d8f9b7ab69bc483f27117390ba48 --> <!-- ralph-base:0e38ad26af922abdc0fc36c9379e17efd2a72b80 --> <!-- ralph-head:67ac80993df931040587bcebb623503216476767 --> <!-- ralph-case:75cca5c71ab2ab650f054467cb6b41f231f27f7a2a768a53e200a422f599e8c3 --> **🔵 Suggestion · Public context loses the static context's signing misuse check** A future generator-based signing call using this context would run with fixed blinding instead of aborting; no current caller passing the public context to such an operation was found. Location: [`src/pubkey.cpp:40`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67ac80993df931040587bcebb623503216476767/src/pubkey.cpp#L40>) (head). **🔵 Suggestion · Context test does not observe the production SHA256 installation** The test installs its counting callback independently, so removing either production SHA256Transform installation would leave these assertions passing despite losing the optimization. Location: [`src/test/key_tests.cpp:425`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67ac80993df931040587bcebb623503216476767/src/test/key_tests.cpp#L425>) (head). **🔵 Suggestion · DER-lax fuzz target retains unnecessary RNG setup** Removing the per-input ECC_Context removed this fuzz target's only global-PRNG consumer, leaving its seed call and associated includes unnecessary. Location: [`src/test/fuzz/secp256k1_ecdsa_signature_parse_der_lax.cpp:29`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/504aab70a08471fdb5f461e3b77aecaee5eab370/src/test/fuzz/secp256k1_ecdsa_signature_parse_der_lax.cpp#L29>) (base). **🔵 Suggestion · SHA256Transform declaration omits the compression contract** The header describes dispatch but not the raw compression interface libsecp relies on, leaving state, block units and input-alignment requirements undocumented. Location: [`src/crypto/sha256.h:53`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67ac80993df931040587bcebb623503216476767/src/crypto/sha256.h#L53>) (head). **🔵 Suggestion · Benchmark includes span.h without using its helpers** The new benchmark has no direct use of span.h; its key and public-key headers already provide the dependencies needed by their APIs. Location: [`src/bench/ecc_sign_verify.cpp:9`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67ac80993df931040587bcebb623503216476767/src/bench/ecc_sign_verify.cpp#L9>) (head). **🔵 Suggestion · Signing-context routing lacks regression coverage** Narrowed. key_tests.cpp:428-432 now checks that CKey::Sign routes through the sign context, but nothing checks KeyPair::SignSchnorr (key.cpp:425). A misrouted Schnorr signing call would still produce valid signatures and pass. Location: [`src/test/key_tests.cpp:428`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/67ac80993df931040587bcebb623503216476767/src/test/key_tests.cpp#L428>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`67ac80993df9`](<https://git.fish.foo/bitcoin/bitcoin/commit/67ac80993df931040587bcebb623503216476767>) · [Full review report](<https://review.fish.foo/traces/36188-67ac80993df931040587bcebb623503216476767-2202-12.html>) · [Previous reports](<https://review.fish.foo/traces/36188/>) [permalink](<https://review.fish.foo/traces/36188-67ac80993df931040587bcebb623503216476767-2202-12.html>)
furszy (Migrated from github.com) reviewed 2026-09-30 15:46:22 +00:00
furszy (Migrated from github.com) commented 2026-09-30 15:46:22 +00:00

An alternative to this split-up would be to keep having only one "full" (i.e. non-static) context and use it for both signing and verifying (and any other API calls that either involve a generator point multiplication or hashing). It's true that some functions don't take use of the blinding data generated with _context_randomize, but it also doesn't slow things down or hurt in another way.

What if we ever want to re-seed the context rng? (secp256k1_context_randomize docs suggests doing it). By having two contexts, we avoid adding a mutex on the verification side and keep that context immutable and thread safe after construction.

> An alternative to this split-up would be to keep having only one "full" (i.e. non-static) context and use it for both signing and verifying (and any other API calls that either involve a generator point multiplication or hashing). It's true that some functions don't take use of the blinding data generated with _context_randomize, but it also doesn't slow things down or hurt in another way. What if we ever want to re-seed the context rng? (`secp256k1_context_randomize` docs suggests doing it). By having two contexts, we avoid adding a mutex on the verification side and keep that context immutable and thread safe after construction.
theStack (Migrated from github.com) reviewed 2026-09-30 16:27:03 +00:00
theStack (Migrated from github.com) commented 2026-09-30 16:27:03 +00:00

An alternative to this split-up would be to keep having only one "full" (i.e. non-static) context and use it for both signing and verifying (and any other API calls that either involve a generator point multiplication or hashing). It's true that some functions don't take use of the blinding data generated with _context_randomize, but it also doesn't slow things down or hurt in another way.

What if we ever want to re-seed the context rng? (secp256k1_context_randomize docs suggests doing it). By having two contexts, we avoid adding a mutex on the verification side and keep that context immutable and thread safe after construction.

Fair point, I didn't consider that there could be potential use-cases where the context needs any further modification after its initial setup in ECC_Start. Not sure how realistic plans of implementing re-seeding in Core currently are (and what the actual gain in security would really be by doing that), but I agree it's worth to take into account. No strong objection on the split-up, but wanted to bring the simpler option for discussion.

> > An alternative to this split-up would be to keep having only one "full" (i.e. non-static) context and use it for both signing and verifying (and any other API calls that either involve a generator point multiplication or hashing). It's true that some functions don't take use of the blinding data generated with _context_randomize, but it also doesn't slow things down or hurt in another way. > > What if we ever want to re-seed the context rng? (`secp256k1_context_randomize` docs suggests doing it). By having two contexts, we avoid adding a mutex on the verification side and keep that context immutable and thread safe after construction. Fair point, I didn't consider that there could be potential use-cases where the context needs any further modification after its initial setup in `ECC_Start`. Not sure how realistic plans of implementing re-seeding in Core currently are (and what the actual gain in security would really be by doing that), but I agree it's worth to take into account. No strong objection on the split-up, but wanted to bring the simpler option for discussion.
real-or-random (Migrated from github.com) reviewed 2026-10-01 13:52:19 +00:00
real-or-random (Migrated from github.com) commented 2026-10-01 13:52:19 +00:00

Not sure how realistic plans of implementing re-seeding in Core currently are (and what the actual gain in security would really be by doing that),

I suspect there's a real gain when it comes to certain types of side-channel attack (e.g., power analysis). There were many discussions in the past, and I wrote a libsecp256k1 issue a while ago. The problem is just that nobody is working on it. ;)

The simplest thing we could do is to re-randomize the context after every operation that makes an ecmult_gen (pubkey generation and signing). This would be a ~100% hit in performance for these operations because rerandomizing also needs an ecmult_gen. 100% sounds huge but I'm not sure if anyone would really care here for these operations.

If people do care, the next simplest thing is to it only after (every n operations). For example, if we set n=10, then the performance hit is only 10%.

Anyway, this discussion belongs to a separate issue. But I agree that it's worth taking into account.

> Not sure how realistic plans of implementing re-seeding in Core currently are (and what the actual gain in security would really be by doing that), I suspect there's a real gain when it comes to certain types of side-channel attack (e.g., power analysis). There were many discussions in the past, and I wrote [a libsecp256k1 issue](https://github.com/bitcoin-core/secp256k1/issues/1141) a while ago. The problem is just that nobody is working on it. ;) The simplest thing we could do is to re-randomize the context after every operation that makes an ecmult_gen (pubkey generation and signing). This would be a ~100% hit in performance for these operations because rerandomizing also needs an ecmult_gen. 100% sounds huge but I'm not sure if anyone would really care here for these operations. If people do care, the next simplest thing is to it only after (every n operations). For example, if we set n=10, then the performance hit is only 10%. Anyway, this discussion belongs to a separate issue. But I agree that it's worth taking into account.
furszy (Migrated from github.com) reviewed 2026-10-01 17:47:25 +00:00
furszy (Migrated from github.com) commented 2026-10-01 17:47:25 +00:00

Nice issue write-up.

I think we shouldn't over-think this now. Most of the work in this PR is about structuring the code properly so that we don't continue expanding the technical debt (the transform callback plug could have been done in 2 commits max otherwise, but they would be built on top of a dirty base). Once this lands, any future decision should be simple to do and isolated.

Nice issue write-up. I think we shouldn't over-think this now. Most of the work in this PR is about structuring the code properly so that we don't continue expanding the technical debt (the transform callback plug could have been done in 2 commits max otherwise, but they would be built on top of a dirty base). Once this lands, any future decision should be simple to do and isolated.
furszy commented 2026-10-15 04:47:18 +00:00 (Migrated from github.com)

conflicts solved, ready for review

conflicts solved, ready for review
DrahtBot commented 2026-10-15 05:47:17 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/38682946486/job/116251332091
LLM reason (✨ experimental): CI failed the IWYU lint check: it added/fixed includes in eight files, leaving a diff that caused the check to exit with an error.

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/38682946486/job/116251332091</sub> <sub>LLM reason (✨ experimental): CI failed the IWYU lint check: it added/fixed includes in eight files, leaving a diff that caused the check to exit with an error.</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>
fametrano commented 2026-10-25 06:54:11 +00:00 (Migrated from github.com)

tACK ecf779fa06

On an Apple M5 (arm_shani), a differential harness compared a context using libsecp256k1's own compression with one using SHA256Transform, with both Core's arm_shani and portable transforms. It ran 20,000 random rounds of tagged hashes, BIP340 signing of 0- to 300-byte messages, ECDSA, ElligatorSwift XDH, MuSig2 and silent payments labels, plus the BIP340 vectors. All results matched, and a sample also matched the pure-Python code of a library I maintain. Unit tests and ctest pass.

Medians of three interleaved bench_bitcoin runs against 7caaaca9d2, the commit before the plug: ECDSASign -11%, SchnorrSign -3.7%, EllSwiftCreate -3.7%, BIP324_ECDH -1.9%, SchnorrVerify -1.2%. The ConnectBlock benches stay within noise. With Core's portable transform forced, hashing and signing run at libsecp256k1's own speed, so a CPU that falls back to it loses nothing per operation.

Non-blocking: ECCContextCreate goes from 13.5 µs to 176 µs. Almost all of it is the libsecp256k1 self-test of the plugged function, run once for each of the two contexts: 88 µs each here, about 0.5 ms each with the portable transform. Creating the verify context with secp256k1_context_clone before randomizing the sign context keeps the plugged function and skips the second test. From reading the code, not measuring, this matters mainly for the secp256k1_ecdsa_signature_parse_der_lax fuzz target, which builds a context for every input that parses. Happy to share the scripts as a gist.

tACK ecf779fa06cef78ca668715cba21b30a1fda8a06 On an Apple M5 (arm_shani), a differential harness compared a context using libsecp256k1's own compression with one using `SHA256Transform`, with both Core's arm_shani and portable transforms. It ran 20,000 random rounds of tagged hashes, BIP340 signing of 0- to 300-byte messages, ECDSA, ElligatorSwift XDH, MuSig2 and silent payments labels, plus the BIP340 vectors. All results matched, and a sample also matched the pure-Python code of a library I maintain. Unit tests and ctest pass. Medians of three interleaved bench_bitcoin runs against 7caaaca9d2, the commit before the plug: ECDSASign -11%, SchnorrSign -3.7%, EllSwiftCreate -3.7%, BIP324_ECDH -1.9%, SchnorrVerify -1.2%. The ConnectBlock benches stay within noise. With Core's portable transform forced, hashing and signing run at libsecp256k1's own speed, so a CPU that falls back to it loses nothing per operation. Non-blocking: ECCContextCreate goes from 13.5 µs to 176 µs. Almost all of it is the libsecp256k1 self-test of the plugged function, run once for each of the two contexts: 88 µs each here, about 0.5 ms each with the portable transform. Creating the verify context with `secp256k1_context_clone` before randomizing the sign context keeps the plugged function and skips the second test. From reading the code, not measuring, this matters mainly for the `secp256k1_ecdsa_signature_parse_der_lax` fuzz target, which builds a context for every input that parses. Happy to share the scripts as a gist.
fametrano (Migrated from github.com) reviewed 2026-10-25 07:40:44 +00:00
Lines 50-75
fametrano (Migrated from github.com) commented 2026-10-25 07:40:44 +00:00

Cloning the signing context before randomizing it would skip the second SHA256 self-test.

secp256k1_context_clone copies the context, compression function included, and runs no self-test. Done before secp256k1_context_randomize, the verify context ends up in the same state as now and shares no blinding. In medians of three bench_bitcoin runs on an Apple M5, ECCContextCreate drops from 169 µs to 89 µs. The parse_der_lax fuzz target builds a context for every input that parses, so it saves the same time per input. Unit tests pass.

/** Create an elliptic curve context that uses our SHA256 implementation */
static secp256k1_context* ECC_Start() {
    secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
    assert(ctx != nullptr);

    SHA256AutoDetect();
    secp256k1_context_set_sha256_compression(ctx, SHA256Transform);

    return ctx;
}

ECC_Context::ECC_Context(std::span<const unsigned char> rng_seed32)
{
    assert(g_ecc_context == nullptr);
    assert(rng_seed32.empty() || rng_seed32.size() == 32);
    m_sign_ctx = ECC_Start();
    // Clone before randomizing: the copy keeps SHA256Transform without testing it again,
    // and does not share the blinding of the signing context.
    m_verify_ctx = secp256k1_context_clone(m_sign_ctx);
    assert(m_verify_ctx != nullptr);
    if (!rng_seed32.empty()) {
        // Pass in a random blinding seed to the signing context.
        bool ret = secp256k1_context_randomize(m_sign_ctx, rng_seed32.data());
        assert(ret);
    }
    g_ecc_context = this;
}
Cloning the signing context before randomizing it would skip the second SHA256 self-test. `secp256k1_context_clone` copies the context, compression function included, and runs no self-test. Done before `secp256k1_context_randomize`, the verify context ends up in the same state as now and shares no blinding. In medians of three bench_bitcoin runs on an Apple M5, ECCContextCreate drops from 169 µs to 89 µs. The parse_der_lax fuzz target builds a context for every input that parses, so it saves the same time per input. Unit tests pass. ```suggestion /** Create an elliptic curve context that uses our SHA256 implementation */ static secp256k1_context* ECC_Start() { secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE); assert(ctx != nullptr); SHA256AutoDetect(); secp256k1_context_set_sha256_compression(ctx, SHA256Transform); return ctx; } ECC_Context::ECC_Context(std::span<const unsigned char> rng_seed32) { assert(g_ecc_context == nullptr); assert(rng_seed32.empty() || rng_seed32.size() == 32); m_sign_ctx = ECC_Start(); // Clone before randomizing: the copy keeps SHA256Transform without testing it again, // and does not share the blinding of the signing context. m_verify_ctx = secp256k1_context_clone(m_sign_ctx); assert(m_verify_ctx != nullptr); if (!rng_seed32.empty()) { // Pass in a random blinding seed to the signing context. bool ret = secp256k1_context_randomize(m_sign_ctx, rng_seed32.data()); assert(ret); } g_ecc_context = this; } ```
furszy (Migrated from github.com) reviewed 2026-10-27 15:42:53 +00:00
Lines 50-75
furszy (Migrated from github.com) commented 2026-10-27 15:42:53 +00:00

We can actually drop the ECC context creation from the parse_der_lax fuzz target, nothing there requires it.
Other than that, the concept of the change seems good to me, the only thing I would try to do is decoupling the ECC function calls out of the ECC_Context constructor, so it stays clean.

We can actually drop the ECC context creation from the `parse_der_lax` fuzz target, nothing there requires it. Other than that, the concept of the change seems good to me, the only thing I would try to do is decoupling the ECC function calls out of the `ECC_Context` constructor, so it stays clean.
w0xlt (Migrated from github.com) reviewed 2026-10-27 23:34:23 +00:00
w0xlt (Migrated from github.com) commented 2026-10-27 23:34:23 +00:00

This call appears redundant. Both bitcoind.cpp and NodeImpl::baseInitialize() construct a kernel::Context, which already runs SHA256AutoDetect() before ECC initialization.

This call appears redundant. Both `bitcoind.cpp` and `NodeImpl::baseInitialize()` construct a `kernel::Context`, which already runs `SHA256AutoDetect()` before ECC initialization. ```suggestion ```
furszy (Migrated from github.com) reviewed 2026-10-28 14:03:31 +00:00
furszy (Migrated from github.com) commented 2026-10-28 14:03:31 +00:00

This call appears redundant.

Not for benchmarks, unit and fuzz tests. It doesn't harm to keep it.

> This call appears redundant. Not for benchmarks, unit and fuzz tests. It doesn't harm to keep it.
w0xlt (Migrated from github.com) reviewed 2026-10-28 18:23:53 +00:00
w0xlt (Migrated from github.com) commented 2026-10-28 18:23:53 +00:00

bench_bitcoin already calls it in main() at ecf779fa06, and tests using BasicTestingSetup initialize it through kernel::Context.
It is redundant for those callers, although the extra overhead is negligible during normal startup.

`bench_bitcoin` already calls it in `main()` at ecf779fa06, and tests using `BasicTestingSetup` initialize it through `kernel::Context`. It is redundant for those callers, although the extra overhead is negligible during normal startup.
w0xlt (Migrated from github.com) reviewed 2026-10-28 18:24:11 +00:00
w0xlt (Migrated from github.com) left a comment
ACK ecf779fa06cef78ca668715cba21b30a1fda8a06
sedited commented 2026-10-31 17:09:02 +00:00 (Migrated from github.com)

@theStack can you take another look here?

@theStack can you take another look here?
theStack (Migrated from github.com) approved these changes 2026-11-02 08:45:43 +00:00
theStack (Migrated from github.com) left a comment

ACK ecf779fa06

nit: I think the "signing/verification" context naming is a bit imprecise, as many secp function calls in other modules (in e.g. ecdh, ellswift, musig, silentpayments) involve neither of these operations but still need (or profit from) a non-static context, and it's not obvious which one should be picked. Dropping an alternative naming suggestion from my clanker that I think might work, could be picked up in a renaming follow-up if others feel strongly (enough) about this:

/** secp256k1 context for operations involving secret data (secret keys, nonces,
 *  secret tweaks). Randomized for side-channel protection. Requires an ECC_Context. */
secp256k1_context* GetSecp256k1SecretContext();

/** secp256k1 context for operations on public data only (parsing, serialization,
 *  verification, public tweaks). Falls back to secp256k1_context_static without an ECC_Context. */
const secp256k1_context* GetSecp256k1PublicContext();
ACK ecf779fa06cef78ca668715cba21b30a1fda8a06 nit: I think the "signing/verification" context naming is a bit imprecise, as many secp function calls in other modules (in e.g. ecdh, ellswift, musig, silentpayments) involve neither of these operations but still need (or profit from) a non-static context, and it's not obvious which one should be picked. Dropping an alternative naming suggestion from my clanker that I think might work, could be picked up in a renaming follow-up if others feel strongly (enough) about this: ```C /** secp256k1 context for operations involving secret data (secret keys, nonces, * secret tweaks). Randomized for side-channel protection. Requires an ECC_Context. */ secp256k1_context* GetSecp256k1SecretContext(); /** secp256k1 context for operations on public data only (parsing, serialization, * verification, public tweaks). Falls back to secp256k1_context_static without an ECC_Context. */ const secp256k1_context* GetSecp256k1PublicContext(); ```
furszy commented 2026-11-02 15:43:17 +00:00 (Migrated from github.com)

Updated per @theStack feedback. Thanks!
Applied the GetSecp256k1PublicContext renaming and the functions' doc improvement. Left the GetSecp256k1SecretContext one for a quick scripted-diff as otherwise it requires a rework of this branch from the second commit onwards.

Updated per @theStack feedback. Thanks! Applied the `GetSecp256k1PublicContext` renaming and the functions' doc improvement. Left the `GetSecp256k1SecretContext` one for a quick scripted-diff as otherwise it requires a rework of this branch from the second commit onwards.
theStack (Migrated from github.com) approved these changes 2026-11-03 05:30:01 +00:00
theStack (Migrated from github.com) left a comment

re-ACK 02b7b76c59

re-ACK 02b7b76c59eb5f65889ba4b1e506634864e130a2
sipa (Migrated from github.com) reviewed 2026-11-03 10:50:33 +00:00
sipa (Migrated from github.com) left a comment

I think there is a simpler approach that just removes ECC_Context and uses secp contexts created on first use in static locals. Clankerbranch: https://github.com/sipa/bitcoin/commits/202611_ecc_static.

I think there is a simpler approach that just removes `ECC_Context` and uses secp contexts created on first use in static locals. Clankerbranch: https://github.com/sipa/bitcoin/commits/202611_ecc_static.
furszy commented 2026-11-05 05:06:44 +00:00 (Migrated from github.com)

I think there is a simpler approach that just removes ECC_Context and uses secp contexts created on first use in static locals. Clankerbranch: https://github.com/sipa/bitcoin/commits/202611_ecc_static.

That's hidden magic, nice. Thanks!
Went further while rebasing the branch on master and expanded it to cover silent payments as well.

> I think there is a simpler approach that just removes `ECC_Context` and uses secp contexts created on first use in static locals. Clankerbranch: https://github.com/sipa/bitcoin/commits/202611_ecc_static. That's hidden magic, nice. Thanks! Went further while rebasing the branch on master and expanded it to cover silent payments as well.
fanquake commented 2026-11-05 10:55:49 +00:00 (Migrated from github.com)

@furszy can you update the PR description, given the latest changes?

@furszy can you update the PR description, given the latest changes?
furszy commented 2026-11-05 14:22:03 +00:00 (Migrated from github.com)

@furszy can you update the PR description, given the latest changes?

Sure, thanks. Done.

> @furszy can you update the PR description, given the latest changes? Sure, thanks. Done.
theStack (Migrated from github.com) approved these changes 2026-11-05 15:40:05 +00:00
theStack (Migrated from github.com) left a comment

re-ACK 67ac80993d

Very nice simplification! It felt a bit strange at first sight that the context cleanup part (secp256k1_context_destroy call) is now completely gone, but seems fine to rely on the OS handling that, if the object intentionally lives for the duration of the process.

re-ACK 67ac80993df931040587bcebb623503216476767 Very nice simplification! It felt a bit strange at first sight that the context cleanup part (`secp256k1_context_destroy` call) is now completely gone, but seems fine to rely on the OS handling that, if the object intentionally lives for the duration of the process.
fjahr (Migrated from github.com) reviewed 2026-11-19 11:05:36 +00:00
fjahr (Migrated from github.com) left a comment

Looks good to me, saving the ACK for later since this seems to need a rebase because of the silent merge conflict I saw.

Looks good to me, saving the ACK for later since this seems to need a rebase because of the silent merge conflict I saw.
fjahr (Migrated from github.com) commented 2026-11-19 10:34:35 +00:00

There appears to be a silent merge conflict from this removal. #36475 added a new call site of ECC_Context which isn't removed here yet: https://github.com/bitcoin/bitcoin/pull/36475/files#diff-6bf59f47d71af9c1c3a2dd315228db6b820594f4a6009df7668696c310097637R38

There appears to be a silent merge conflict from this removal. #36475 added a new call site of `ECC_Context` which isn't removed here yet: https://github.com/bitcoin/bitcoin/pull/36475/files#diff-6bf59f47d71af9c1c3a2dd315228db6b820594f4a6009df7668696c310097637R38
fjahr (Migrated from github.com) commented 2026-11-19 10:40:05 +00:00

Hm, I am not sure if this works or maybe I am understanding it but if the secp256k1_context_set_sha256_compression(ctx, SHA256Transform) lines are deleted from key.cpp or pubkey.cpp the test still passes.

Hm, I am not sure if this works or maybe I am understanding it but if the `secp256k1_context_set_sha256_compression(ctx, SHA256Transform)` lines are deleted from `key.cpp` or `pubkey.cpp` the test still passes.
fjahr (Migrated from github.com) reviewed 2026-11-19 11:05:46 +00:00
fjahr (Migrated from github.com) commented 2026-11-19 11:05:46 +00:00

I would add that secp256k1_context_static aborted on any call needing ecmult_gen while this ctx doesn't anymore. So that would be another argument aside from it being "minimal-diff" but it wouldn't prevent misuse, just may be make users of the function more cautious if it's not so widely used.

I would add that `secp256k1_context_static` aborted on any call needing `ecmult_gen` while this ctx doesn't anymore. So that would be another argument aside from it being "minimal-diff" but it wouldn't prevent misuse, just may be make users of the function more cautious if it's not so widely used.
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!36188
No description provided.