mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 12:20:38 +00:00
crypto: plug hardware optimized SHA256 into libsecp256k1's context #36188
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36188
Loading…
Reference in a new issue
No description provided.
Delete branch "2026_secp_pluggable_sha"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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_shaniimplementationECDSASignSchnorrSignECDSAVerifySchnorrVerifyEllSwiftCreateBIP324_ECDHThe 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.
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:
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++, andfunc(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
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/34159538723/job/101858273499LLM 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.
Concept ACK
Concept ACK
Finally! Concept ACK
Awesome Concept ACK
Splendid Concept ACK
cc @real-or-random
Concept ACK.
🐙 This pull request conflicts with the target branch and needs rebase.
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.
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, ...?).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🔵 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 reportspermalink
What if we ever want to re-seed the context rng? (
secp256k1_context_randomizedocs 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.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.
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.
conflicts solved, ready for review
🚧 At least one of the CI tasks failed.
Task
iwyu: https://github.com/bitcoin/bitcoin/actions/runs/38682946486/job/116251332091LLM 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.
tACK
ecf779fa06On 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_clonebefore randomizing the sign context keeps the plugged function and skips the second test. From reading the code, not measuring, this matters mainly for thesecp256k1_ecdsa_signature_parse_der_laxfuzz target, which builds a context for every input that parses. Happy to share the scripts as a gist.Cloning the signing context before randomizing it would skip the second SHA256 self-test.
secp256k1_context_clonecopies the context, compression function included, and runs no self-test. Done beforesecp256k1_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.We can actually drop the ECC context creation from the
parse_der_laxfuzz 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_Contextconstructor, so it stays clean.This call appears redundant. Both
bitcoind.cppandNodeImpl::baseInitialize()construct akernel::Context, which already runsSHA256AutoDetect()before ECC initialization.Not for benchmarks, unit and fuzz tests. It doesn't harm to keep it.
bench_bitcoinalready calls it inmain()atecf779fa06, and tests usingBasicTestingSetupinitialize it throughkernel::Context.It is redundant for those callers, although the extra overhead is negligible during normal startup.
ACK
ecf779fa06@theStack can you take another look here?
ACK
ecf779fa06nit: 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:
Updated per @theStack feedback. Thanks!
Applied the
GetSecp256k1PublicContextrenaming and the functions' doc improvement. Left theGetSecp256k1SecretContextone for a quick scripted-diff as otherwise it requires a rework of this branch from the second commit onwards.re-ACK
02b7b76c59I think there is a simpler approach that just removes
ECC_Contextand 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.
@furszy can you update the PR description, given the latest changes?
Sure, thanks. Done.
re-ACK
67ac80993dVery nice simplification! It felt a bit strange at first sight that the context cleanup part (
secp256k1_context_destroycall) 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.Looks good to me, saving the ACK for later since this seems to need a rebase because of the silent merge conflict I saw.
There appears to be a silent merge conflict from this removal. #36475 added a new call site of
ECC_Contextwhich isn't removed here yet: https://github.com/bitcoin/bitcoin/pull/36475/files#diff-6bf59f47d71af9c1c3a2dd315228db6b820594f4a6009df7668696c310097637R38Hm, 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 fromkey.cpporpubkey.cppthe test still passes.I would add that
secp256k1_context_staticaborted on any call needingecmult_genwhile 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.