Skip to content

Reduce scalar reduction from byte-wise to limb-wise arithmetic - #12

Merged
samkim-crypto merged 2 commits into
solana-program:mainfrom
samkim-crypto:opt2
Aug 31, 2026
Merged

samkim-crypto merged 2 commits into
solana-program:mainfrom
samkim-crypto:opt2

Conversation

@samkim-crypto

@samkim-crypto samkim-crypto commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Summary of Changes

Currently, the reduce_wide function performs 512-iteration long division over [u8; 32], doing a 32-byte shift and a 32-byte borrow thereby propagating subtract per iteration. I tried carrying the remainder as [u64; 4] and fusing the comparison with the subtraction, which cut per-iteration cost from ~418 CU to ~52 CU.

Verifying one signature over a 38-byte message got reduced significantly 217,045 → 29,858 CU (7.3×). One can test this by calling make cu-program on the main branch and in this PR branch.

On a follow-up, I want to try replacing the 512-iteration loop with Barrett reduction. I think our CUs are still quite high compared to other similar cryptographic libraries.

@samkim-crypto
samkim-crypto requested a review from zz-sol August 28, 2026 03:21
///
/// Evaluated at compile time so that limb constants are derived from their byte
/// counterparts rather than transcribed by hand a second time.
const fn to_le_limbs(bytes: [u8; 32]) -> [u64; 4] {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

For my own learning. my instinct is to do a unsafe transmute here -- but LLM told me that this would not save anything as for SBF programs, const functions are always 0 cost. Interesting!

// chain, so it is cross-checked against curve25519-dalek's own wide
// reduction rather than against a second copy of the same reasoning.
#[test]
fn matches_curve25519_dalek_wide_reduction() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

should we add a few randomized tests with inputs >= order?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, yep I'll add this in a follow-up PR since I still need to add Barret Reduction.

@samkim-crypto
samkim-crypto merged commit ffc2296 into solana-program:main Aug 31, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants