Skip to content

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

Open
furszy wants to merge 9 commits into
bitcoin:masterfrom
furszy:2026_secp_pluggable_sha
Open

furszy wants to merge 9 commits into
bitcoin:masterfrom
furszy:2026_secp_pluggable_sha

Conversation

@furszy

@furszy furszy commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

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 (43c9bdb) 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

DrahtBot commented Sep 7, 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
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

@DrahtBot

DrahtBot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

🚧 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.

@furszy
furszy force-pushed the 2026_secp_pluggable_sha branch from da657fa to 1c216a0 Compare September 7, 2026 23:06
@DrahtBot DrahtBot removed the CI failed label Sep 8, 2026
@w0xlt

w0xlt commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

1 similar comment
@fjahr

fjahr commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Concept ACK

@sedited

sedited commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Finally! Concept ACK

@ismaelsadeeq

Copy link
Copy Markdown
Member

Awesome Concept ACK

@theStack

theStack commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Splendid Concept ACK

@fanquake

fanquake commented Sep 9, 2026

Copy link
Copy Markdown
Member

cc @real-or-random

@hebasto hebasto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Concept ACK.

@theStack theStack 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.

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.

Comment thread src/pubkey.cpp Outdated
if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data())) return false;
return secp256k1_schnorrsig_verify(secp256k1_context_static, sigbytes.data(), msg.begin(), 32, &pubkey);
if (!secp256k1_xonly_pubkey_parse(GetSecp256k1VerifyContext(), &pubkey, m_keydata.data())) return false;
return secp256k1_schnorrsig_verify(GetSecp256k1VerifyContext(), sigbytes.data(), msg.begin(), 32, &pubkey);

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.

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

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 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.

Comment thread src/ecc_context.h Outdated
~ECC_Context();

secp256k1_context* SignContext() const { return m_sign_ctx; }
const secp256k1_context* VerifyContext() const { return m_verify_ctx; }

@theStack theStack Sep 30, 2026 •

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.

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, ...?).

@furszy furszy Sep 30, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

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.

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.

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.

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.

@furszy furszy Oct 1, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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
furszy force-pushed the 2026_secp_pluggable_sha branch from 1c216a0 to b11ea3d Compare October 15, 2026 04:43
@sedited

sedited commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

@theStack can you take another look here?

@theStack theStack 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 ecf779f

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();

@furszy
furszy force-pushed the 2026_secp_pluggable_sha branch from ecf779f to 02b7b76 Compare November 2, 2026 15:39
@furszy

furszy commented Nov 2, 2026 •

Copy link
Copy Markdown
Member Author

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 theStack 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.

re-ACK 02b7b76

@DrahtBot
DrahtBot requested review from fametrano and w0xlt November 3, 2026 05:30

@sipa sipa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

sipa and others added 9 commits November 4, 2026 16:27
Instead of requiring an ECC_Context to exist while signing, create the
secp256k1 signing context in a function-local static, the first time
GetSecp256k1SignContext() is called. It is never destroyed, so it stays
valid for threads still running at exit.

The RNG this depends on already initializes itself on first use, so no
explicit initialization order is needed. The blinding seed is obtained
through GetStrongRandBytes rather than GetRandBytes: the latter draws
from the deterministic RNG in tests, and consuming from it at whatever
point the context is first used would make test and fuzz results depend
on whether an earlier test or input happened to sign. Blinding does not
affect any outputs, so real randomness is harmless there. As a side
effect, BasicTestingSetup no longer consumes 32 bytes of the
deterministic RNG stream.

The context is never modified after creation, so return it as const.

ECC_Context is kept for now, merely creating the context eagerly. It is
removed in the next commit.
It is no longer needed, as the signing context is created on first use.

The fuzz harness still creates the signing context up front, before the
coverage counters are reset, so that its one-time setup is not counted
as coverage of whichever input happens to sign first.
Low-level signature creation and validation benchmarks.
libsecp256k1 lets a context use an external SHA256 compression
function. With ours, ECDSA signing gets ~15% faster on CPUs with
SHA extensions, Schnorr signing ~3%.

SHA256Transform dispatches to whichever implementation is selected at
the time of the call, so there is no need to run SHA256AutoDetect()
before creating the context. Doing so lazily would race with other
threads hashing, and override any explicitly selected implementation.

Also use the signing context instead of the static one for the BIP324
ECDH, which hashes inside libsecp256k1 too.
Verification uses secp256k1_context_static, which can't take our
optimized SHA256 compression function. Rather than reusing the signing
context, which blinds certain calculations, for no benefit to public
data, verification gets its own context. Like the signing context, it
is created on first use. As it needs no randomness, it lives next to
the verification code in pubkey.cpp, so users of the kernel library get
it without any setup.

Around 1% faster Schnorr signature verification. ECDSA remains equal
as hashing is done outside libsecp.

Co-authored-by: Pieter Wuille <[email protected]>
Every use of secp256k1_context_static in pubkey.cpp uses public
data, so all of them can use the verification context, which
contains our optimized SHA256 compression plugged in.

-BEGIN VERIFY SCRIPT-
sed -i -e '/\/\*/! s/secp256k1_context_static/GetSecp256k1PublicContext()/g' src/pubkey.cpp
-END VERIFY SCRIPT-
…contexts

Temporarily install a call-counting SHA256 compression function in each
context, to check that ECDSA signing goes through the signing context
and Schnorr verification through the public one. Also check that both
contexts are distinct from each other and from the static one, and stay
the same across calls.
secp256k1_musig_partial_sign() and secp256k1_silentpayments_recipient_scan_outputs()
take data that is not public, like the nonce or the scan key, so they should match
the rule operations on private data should use the signing context.
So all functions make use of our hardware optimized SHA256.

-BEGIN VERIFY SCRIPT-
sed -i -e '/\/\*/! s/secp256k1_context_static/GetSecp256k1PublicContext()/g' src/musig.cpp
sed -i -e '/\/\*/! s/secp256k1_context_static/GetSecp256k1PublicContext()/g' src/common/bip352.cpp
-END VERIFY SCRIPT-
@furszy
furszy force-pushed the 2026_secp_pluggable_sha branch from 02b7b76 to 67ac809 Compare November 5, 2026 04:56
@furszy

furszy commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

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

fanquake commented Nov 5, 2026

Copy link
Copy Markdown
Member

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

@furszy

furszy commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

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

Sure, thanks. Done.

@theStack theStack 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.

re-ACK 67ac809

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 fjahr 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.

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

Comment thread src/key.h
* Creates the secp256k1 signing context, if it does not exist yet. This is not
* necessary anymore, as GetSecp256k1SignContext() creates it on first use.
*/
class ECC_Context

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.

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

Comment thread src/test/key_tests.cpp
std::vector<unsigned char> sig(64);
BOOST_REQUIRE(key.SignSchnorr(uint256::ONE, sig, /*merkle_root=*/nullptr, uint256::ZERO));

// Check that both contexts use our SHA256 implementation, by temporarily wrapping it with a

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.

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.

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.