test: speed up secp256k1 fixed-base multiplication and Schnorr signing #36327

Manually merged
brunoerg merged 1 commit from 2026-09-test-crypto into master 2026-10-05 07:28:03 +00:00 AGit
brunoerg commented 2026-09-24 15:08:21 +00:00 (Migrated from github.com)

This PR speeds up the test framework’s fixed-base multiplication and Schnorr signing by:

  • Changing FastGEMul to process scalars in 4-bit windows instead of individual bits. Precompute all 16 multiples for each window position, reducing multiplication from about 128 point additions on average to 64 table lookups and about 60 nonzero point additions. This trades a larger table and additional initialization work for cheaper repeated multiplications.

On my local machine (Macbook M2 Pro) the feature_taproot.py's medium time decreased from 83.39s to 35.42s.

This PR speeds up the test framework’s fixed-base multiplication and Schnorr signing by: - Changing FastGEMul to process scalars in 4-bit windows instead of individual bits. Precompute all 16 multiples for each window position, reducing multiplication from about 128 point additions on average to 64 table lookups and about 60 nonzero point additions. This trades a larger table and additional initialization work for cheaper repeated multiplications. On my local machine (Macbook M2 Pro) the `feature_taproot.py`'s medium time decreased from 83.39s to 35.42s.
DrahtBot commented 2026-09-24 15:08:30 +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 fametrano, theStack, ViniciusCestarii
Concept ACK StephenChi-hi, real-or-random

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

<!--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/36327 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36327.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36327#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 | [fametrano](https://github.com/bitcoin/bitcoin/pull/36327#pullrequestreview-5391378350), [theStack](https://github.com/bitcoin/bitcoin/pull/36327#pullrequestreview-5393574744), [ViniciusCestarii](https://github.com/bitcoin/bitcoin/pull/36327#pullrequestreview-5395451590) | | Concept ACK | [StephenChi-hi](https://github.com/bitcoin/bitcoin/pull/36327#issuecomment-5837370616), [real-or-random](https://github.com/bitcoin/bitcoin/pull/36327#pullrequestreview-5322003982) | 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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
fanquake commented 2026-09-24 16:27:13 +00:00 (Migrated from github.com)

cc @theStack @real-or-random

cc @theStack @real-or-random
StephenChi-hi commented 2026-09-25 18:21:13 +00:00 (Migrated from github.com)

ACK

Nice, the multiplication logic looks correct

ACK Nice, the multiplication logic looks correct
real-or-random (Migrated from github.com) reviewed 2026-09-25 20:30:10 +00:00
real-or-random (Migrated from github.com) left a comment
  • Changing FastGEMul to process scalars in 4-bit windows instead of individual bits. [...] This trades a larger table and additional initialization work for cheaper repeated multiplications.

Since this is test-only code, I believe the actual trade-off here is between simplicity of the implementation vs. running time. The current implementation is probably close to the most obvious one can write whereas the windowed one is already "optimized", though it's still simple.

Concept ACK -- And yeah saving ~40s sounds like a reasonable trade-off.

Though I wonder how much comes from the caching and how much from the optimized FastGEMul.

> * Changing FastGEMul to process scalars in 4-bit windows instead of individual bits. [...] This trades a larger table and additional initialization work for cheaper repeated multiplications. Since this is test-only code, I believe the actual trade-off here is between simplicity of the implementation vs. running time. The current implementation is probably close to the most obvious one can write whereas the windowed one is already "optimized", though it's still simple. Concept ACK -- And yeah saving ~40s sounds like a reasonable trade-off. Though I wonder how much comes from the caching and how much from the optimized FastGEMul.
real-or-random (Migrated from github.com) commented 2026-09-25 20:29:18 +00:00
    The scalar is split into WINDOW-bit chunks, and for every chunk position i the table holds
    a row [(0 * 2^(WINDOW*i)) * P, (1 * 2^(WINDOW*i)) * P, ..., ((2^WINDOW-1) * 2^(WINDOW*i)) * P]:

Without this, the row variable name below may be confusing. It's not clear to the reader if the table indices are row-first or column-first.

```suggestion The scalar is split into WINDOW-bit chunks, and for every chunk position i the table holds a row [(0 * 2^(WINDOW*i)) * P, (1 * 2^(WINDOW*i)) * P, ..., ((2^WINDOW-1) * 2^(WINDOW*i)) * P]: ``` Without this, the `row` variable name below may be confusing. It's not clear to the reader if the table indices are row-first or column-first.
real-or-random (Migrated from github.com) commented 2026-09-25 19:46:44 +00:00

What about caching GE.__rmul__ instead, which is the actual expensive operation here? Other callers may benefit, and you could leave sign_schnorr untouched (which keeps it closer to the reference implementation in BIP340 also).

What about caching `GE.__rmul__` instead, which is the actual expensive operation here? Other callers may benefit, and you could leave `sign_schnorr` untouched (which keeps it closer to the reference implementation in BIP340 also).
brunoerg (Migrated from github.com) reviewed 2026-09-28 10:30:50 +00:00
brunoerg (Migrated from github.com) commented 2026-09-28 10:30:50 +00:00

Sounds good!

Sounds good!
brunoerg (Migrated from github.com) reviewed 2026-09-28 10:39:49 +00:00
brunoerg (Migrated from github.com) commented 2026-09-28 10:39:49 +00:00

Done

Done
brunoerg (Migrated from github.com) reviewed 2026-09-28 10:40:10 +00:00
brunoerg (Migrated from github.com) commented 2026-09-28 10:40:10 +00:00

Done

Done
brunoerg commented 2026-09-28 10:42:02 +00:00 (Migrated from github.com)
Force-pushed addressing https://github.com/bitcoin/bitcoin/pull/36327#discussion_r4108067325 and https://github.com/bitcoin/bitcoin/pull/36327#discussion_r4108374223
brunoerg commented 2026-09-28 10:42:52 +00:00 (Migrated from github.com)

Though I wonder how much comes from the caching and how much from the optimized FastGEMul.

From my bench, I guess 70% from the FastGEMul and 30% from the caching.

> Though I wonder how much comes from the caching and how much from the optimized FastGEMul. From my bench, I guess 70% from the FastGEMul and 30% from the caching.
theStack commented 2026-09-28 11:15:17 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
fametrano (Migrated from github.com) reviewed 2026-10-02 11:45:53 +00:00
fametrano (Migrated from github.com) left a comment

tACK b6fc3cf004

I checked k * G on this branch against a second implementation for about 10,000 random scalars plus edge cases (0, n-1, n, n+1, 2n, negative values, runs of ones, each 4-bit window position). All matched. sign_schnorr passes the BIP340 vectors and gave the same signatures as that implementation for 2,000 random messages and aux_rand.

On where the gain comes from: both changes matter, the window somewhat more. In my steadiest run of feature_taproot.py (shared machine, so rough), the window alone took about 35% off master, the cache alone about 30%, and both together 54% (62s to 29s).

Nit, not new here: no unit test multiplies G by a negative scalar. I suggested one inline.

tACK b6fc3cf0046d3106e0dfb30f320d48514eff6fb2 I checked `k * G` on this branch against a second implementation for about 10,000 random scalars plus edge cases (0, n-1, n, n+1, 2n, negative values, runs of ones, each 4-bit window position). All matched. `sign_schnorr` passes the BIP340 vectors and gave the same signatures as that implementation for 2,000 random messages and aux_rand. On where the gain comes from: both changes matter, the window somewhat more. In my steadiest run of `feature_taproot.py` (shared machine, so rough), the window alone took about 35% off master, the cache alone about 30%, and both together 54% (62s to 29s). Nit, not new here: no unit test multiplies G by a negative scalar. I suggested one inline.
fametrano (Migrated from github.com) commented 2026-10-02 11:45:53 +00:00

This catches the % GE.ORDER being dropped from both GE.__rmul__ and FastGEMul.mul, which the current tests miss:

class TestFrameworkSecp256k1(unittest.TestCase):
    def test_neg_mul(self):
        self.assertEqual(((-1) * G).to_bytes_compressed(), (-G).to_bytes_compressed())

This catches the `% GE.ORDER` being dropped from both `GE.__rmul__` and `FastGEMul.mul`, which the current tests miss: ```suggestion class TestFrameworkSecp256k1(unittest.TestCase): def test_neg_mul(self): self.assertEqual(((-1) * G).to_bytes_compressed(), (-G).to_bytes_compressed()) ```
First-time contributor

Base: a829aeaac1aff6cb786aab7d2514b49eb233334b
Head: b6fc3cf0046d3106e0dfb30f320d48514eff6fb2

🟡 Minor

Cached generator multiplication exposes mutable points (test/functional/test_framework/crypto/secp256k1.py:360, head)

For 3 * G, windowed multiplication selects table[0][3] and adds infinity entries for the remaining zero digits. Because GE.__add__ returns an operand unchanged when the other point is infinity, mul_G can cache and return that table object directly. Since GE.x, GE.y, and GE.infinity are writable, a caller can mutate the returned point, corrupting the cached result and precomputed table so later multiplications can return an incorrect point. Return a fresh GE from the cached value or cache an immutable representation. No tracked current caller mutating a returned GE was identified, so production impact is unconfirmed.

💡 Suggestion

Add focused differential tests for windowed multiplication (test/functional/test_framework/crypto/secp256k1.py:352, head)

The new chunk extraction and table accumulation are not directly compared with the independent GE.mul implementation. Existing signing and BIP340-vector tests exercise multiplication indirectly, but do not systematically cover window positions or scalar-reduction cases. Add deterministic comparisons for representative nonzero nibbles at each window position and for zero, negative, and order-boundary scalars. These tests would directly check that the optimization preserves multiplication semantics alongside the existing indirect cryptographic tests.

Review coverage was incomplete. The adversarial_glm review did not complete.

Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> Base: `a829aeaac1aff6cb786aab7d2514b49eb233334b` Head: `b6fc3cf0046d3106e0dfb30f320d48514eff6fb2` ##### 🟡 Minor **Cached generator multiplication exposes mutable points** (test/functional/test_framework/crypto/secp256k1.py:360, head) For `3 * G`, windowed multiplication selects `table[0][3]` and adds infinity entries for the remaining zero digits. Because `GE.__add__` returns an operand unchanged when the other point is infinity, `mul_G` can cache and return that table object directly. Since `GE.x`, `GE.y`, and `GE.infinity` are writable, a caller can mutate the returned point, corrupting the cached result and precomputed table so later multiplications can return an incorrect point. Return a fresh `GE` from the cached value or cache an immutable representation. No tracked current caller mutating a returned `GE` was identified, so production impact is unconfirmed. ##### 💡 Suggestion **Add focused differential tests for windowed multiplication** (test/functional/test_framework/crypto/secp256k1.py:352, head) The new chunk extraction and table accumulation are not directly compared with the independent `GE.mul` implementation. Existing signing and BIP340-vector tests exercise multiplication indirectly, but do not systematically cover window positions or scalar-reduction cases. Add deterministic comparisons for representative nonzero nibbles at each window position and for zero, negative, and order-boundary scalars. These tests would directly check that the optimization preserves multiplication semantics alongside the existing indirect cryptographic tests. Review coverage was incomplete. The adversarial_glm review did not complete. [Full review report](<https://review.fish.foo/traces/36327-b6fc3cf0046d3106e0dfb30f320d48514eff6fb2-264-1.html>)
theStack (Migrated from github.com) approved these changes 2026-10-02 15:36:44 +00:00
theStack (Migrated from github.com) left a comment

ACK b6fc3cf004

Results on my arm64 machine: 1m16.030s master vs. 0m52.547s PR branch

nit: could update the PR description before merging, as it still mentions the caching on compute_xonly_pubkey

ACK b6fc3cf0046d3106e0dfb30f320d48514eff6fb2 Results on my arm64 machine: `1m16.030s` master vs. `0m52.547s` PR branch nit: could update the PR description before merging, as it still mentions the caching on `compute_xonly_pubkey`
theStack (Migrated from github.com) commented 2026-10-02 15:24:02 +00:00

nit: alternatively, applying the cache decorator directly on the GE.__rmul__ method (as suggested in https://github.com/bitcoin/bitcoin/pull/36327#discussion_r4108067325) seems to work fine and would include caching for other points (probably only the generator is relevant though), ~same speedup on my machine. no strong opinion on what to prefer

nit: alternatively, applying the cache decorator directly on the `GE.__rmul__` method (as suggested in https://github.com/bitcoin/bitcoin/pull/36327#discussion_r4108067325) seems to work fine and would include caching for other points (probably only the generator is relevant though), ~same speedup on my machine. no strong opinion on what to prefer
brunoerg commented 2026-10-02 17:07:17 +00:00 (Migrated from github.com)

nit: could update the PR description before merging, as it still mentions the caching on compute_xonly_pubkey

Done.

> nit: could update the PR description before merging, as it still mentions the caching on compute_xonly_pubkey Done.
brunoerg (Migrated from github.com) reviewed 2026-10-02 18:19:45 +00:00
brunoerg (Migrated from github.com) commented 2026-10-02 18:19:45 +00:00

I considered that, but I preferred to keep the cache scoped to G. I will leave as-is for now, but happy to change if others prefer.

I considered that, but I preferred to keep the cache scoped to `G`. I will leave as-is for now, but happy to change if others prefer.
ViniciusCestarii (Migrated from github.com) reviewed 2026-10-02 18:41:06 +00:00
ViniciusCestarii (Migrated from github.com) left a comment

tACK b6fc3cf004

Tested on an x86-64 machine with build/test/functional/feature_taproot.py --randomseed=1, mean of 5 runs:

Before: 51.570s
After: 27.586s

tACK b6fc3cf0046d3106e0dfb30f320d48514eff6fb2 Tested on an x86-64 machine with `build/test/functional/feature_taproot.py --randomseed=1`, mean of 5 runs: Before: 51.570s After: 27.586s
real-or-random (Migrated from github.com) reviewed 2026-10-03 11:43:51 +00:00
real-or-random (Migrated from github.com) commented 2026-10-03 11:43:51 +00:00

nit: alternatively, applying the cache decorator directly on the GE.__rmul__ method (as suggested in #36327 (comment)) seems to work fine and would include caching for other points (probably only the generator is relevant though), ~same speedup on my machine. no strong opinion on what to prefer

This is indeed what I had in mind when I suggested it. I have a slight preference for that variant. It's more general and future tests may profit from it.

(But no objections against merging as-is. :) It's certainly an improvement.)

> nit: alternatively, applying the cache decorator directly on the `GE.__rmul__` method (as suggested in [#36327 (comment)](https://github.com/bitcoin/bitcoin/pull/36327#discussion_r4108067325)) seems to work fine and would include caching for other points (probably only the generator is relevant though), ~same speedup on my machine. no strong opinion on what to prefer This is indeed what I had in mind when I suggested it. I have a slight preference for that variant. It's more general and future tests may profit from it. (But no objections against merging as-is. :) It's certainly an improvement.)
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!36327
No description provided.