Skip to content

feat(crypto): Grumpkin affine point arithmetic - #729

Merged
brozorec merged 6 commits into
mainfrom
feat/grumpkin-arithmetic
May 27, 2026
Merged

brozorec merged 6 commits into
mainfrom
feat/grumpkin-arithmetic

Conversation

@brozorec

@brozorec brozorec commented May 26, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds Grumpkin (y² = x³ − 17 over BN254's scalar field F_r) affine point arithmetic to packages/contract-utils/src/crypto/, intended as a building block for on-chain Pedersen commitments, ECDH, and any other Grumpkin-based primitive built on top of CAP-80.

Resolves #700.

  • Grumpkin::{add, sub, neg} — affine add/sub/neg with full identity handling (left/right identity, inverse, doubling, generic), implemented on top of the BN254 Fr host calls (bn254_fr_{add, sub, mul, inv}).
  • Grumpkin::{is_on_curve, is_identity, is_not_identity} — validation helpers for points entering the system without a soundness proof. is_on_curve enforces both the curve equation and the canonical 32-byte representative of each coordinate (mirroring the SDK's own Bn254Fp validation), so byte equality on validated points is sound for uniqueness / nullifier / commitment-log keys.
  • Point is a 64-byte BytesN<64> laid out as be(x) || be(y); identity is the all-zero encoding.

Out of scope (per the issue)

  • Scalar multiplication — handled in-circuit via Noir's multi_scalar_mul.
  • Batched multi_add — sequential add is fine for v0.8; revisit if benchmarks justify.

Commits

  1. bump soroban-sdk to 26.0.0 — additive: CAP-80 BN254 Fr arithmetic + CAP-78/79/82.
  2. feat(crypto): on-chain Grumpkin affine point arithmetic — the module + 24 tests.
  3. fix(grumpkin): reject non-canonical coordinate encodings in is_on_curve — a self-review caught that Bn254Fr::from_bytes silently reduces mod r, which would have let two distinct byte encodings of the same logical commitment slip past the validator. Fix + 3 additional tests.

Test plan

  • cargo +nightly fmt --all -- --check
  • cargo clippy --release --locked --all-targets -- -D warnings
  • cargo test --workspace
  • 27 Grumpkin tests pass (16 unit + 11 proptest): each branch (left/right identity, inverse, doubling, generic), neg/sub/identity edges, on-curve / off-curve / non-canonical / identity-encoding rejection, plus the algebraic identities from the issue — commutativity, associativity, identity law, inversion, Pedersen homomorphism. Ground-truth points come from ark-grumpkin (dev-dep).

Notes for reviewers

  • SDK 25 → 26 bump: required for Bn254Fr Add/Sub/Mul/inv (no equivalent surface in 25). Bump is additive per the SDK migration notes; the full workspace builds and tests pass unchanged. Worth a glance at the Cargo.lock diff in the first commit.
  • No on-curve check inside add/sub/neg: documented precondition, matches the design's "validate at the trust boundary" stance. The validator is the line of defence; arithmetic is hot-path.
  • Cost benchmarks: not produced here. Happy to add per-op CPU/memory numbers in a follow-up if maintainers want them in the PR description.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added Grumpkin elliptic curve point arithmetic operations for advanced cryptographic support, including point addition, negation, subtraction, identity validation, and on-curve verification.
  • Dependencies

    • Updated soroban-sdk to version 26.0.0.
    • Added ark-* cryptographic libraries for curve operations.

Review Change Stack

brozorec added 3 commits May 26, 2026 14:28
Brings in CAP-80 BN254 scalar field arithmetic (Bn254Fr Add/Sub/Mul,
pow, inv), CAP-82 checked U256/I256 arithmetic, CAP-78 bounded TTL
extensions, and CAP-79 muxed-address strkey conversions. Changes are
additive — workspace builds, clippy passes, and the full test suite
remains green.
Adds Grumpkin (y² = x³ - 17 over BN254's scalar field) affine point
add/sub/neg and on-curve / non-identity validators, implemented on top
of the BN254 Fr host calls exposed by CAP-80.

Coordinates use the 64-byte (be(x) || be(y)) encoding with (0, 0) as
the identity. The five addition cases (left/right identity, inverse,
doubling, generic) are each branched explicitly; the inverse case is
detected before the slope formula to avoid division by zero.

Tested with 16 unit tests plus 8 proptests covering commutativity,
associativity, identity, inversion, Pedersen homomorphism, and
on-curve validation. Ground-truth point values come from ark-grumpkin
(dev-dep) to keep the tests independent of the implementation.
Bn254Fr::from_bytes silently reduces mod r, so be(x+r) || be(y) and
be(x) || be(y) decode to the same logical point but compare unequal
as BytesN<64>. A downstream contract keyed on raw Point bytes (the
idiomatic Soroban pattern for uniqueness / nullifier / commitment-log
checks) would accept both encodings and double-record the same
commitment.

is_on_curve now rejects any 32-byte half that is >= r, mirroring the
SDK's own Bn254Fp validation. Coordinates that already passed the
validator are now guaranteed canonical, making BytesN<64> equality
sound for uniqueness on validated points.
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8ca40ca9-1f57-4a53-8487-12889cb8f4d3

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

This PR implements Grumpkin elliptic curve point arithmetic for the Soroban contract wrapper by adding a new grumpkin module that exposes affine point addition, subtraction, negation, and validation over Soroban's native BN254 scalar field. The implementation uses explicit case-by-case handling of edge cases (identity, inversion, doubling) and includes comprehensive property-based tests verifying algebraic correctness.

Changes

Grumpkin point arithmetic implementation

Layer / File(s) Summary
Dependencies and module wiring
Cargo.toml, packages/contract-utils/Cargo.toml, packages/contract-utils/src/crypto/mod.rs, packages/contract-utils/src/crypto/test/mod.rs
Upgrade soroban-sdk to 26.0.0; add ark-grumpkin, ark-ec, ark-ff, ark-serialize at 0.6 with default-features disabled; export grumpkin submodule in crypto and test indices.
Point type and Grumpkin public API
packages/contract-utils/src/crypto/grumpkin.rs
Point is a 64-byte big-endian (x, y) encoding with (0, 0) as identity. Grumpkin struct provides identity(), is_identity(), is_not_identity(), is_on_curve() (canonical coordinates + curve equation), neg(), add() (five cases: identity handling, inversion detection, doubling, generic affine addition), sub(), from_xy(), and coordinates().
Field helpers and canonical verification
packages/contract-utils/src/crypto/grumpkin.rs
Private constructors fr_zero(), fr_from_u32(); BN254 modulus constant; is_canonical_coord() enforces canonical 32-byte field representatives via byte-lexicographic comparison.
Arithmetic and validation unit tests
packages/contract-utils/src/crypto/test/grumpkin.rs
Test add() branch-by-branch (identity, inversion, doubling, generic); neg() identity-preservation; sub() self-subtraction; is_on_curve() acceptance of real points and rejection of identity/off-curve/corrupted points; is_not_identity() discrimination; coordinate round-trip via from_xy() and coordinates().
Property-based and canonical encoding tests
packages/contract-utils/src/crypto/test/grumpkin.rs
Verify commutativity, associativity, identity law, inversion, Pedersen homomorphism, and doubling equivalence via property tests. Reject non-canonical encodings (bit-flipped y, (value + r) payloads) and check boundary case x == modulus.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • ozgunozerk

Poem

🐰 A Grumpkin hops across the field so fine,
With points encoded in a sixty-four-byte line,
Each add and sub builds balance with great care,
Properties tested everywhere!
Security minted in crypto's trusted lair! 🔐

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(crypto): Grumpkin affine point arithmetic' clearly and specifically summarizes the main change: implementing Grumpkin point arithmetic functionality in the crypto module.
Description check ✅ Passed The PR description comprehensively covers the implementation details, test coverage (27 tests including unit and property-based), commit structure, and validation approach. It addresses the template sections with a detailed summary and notes for reviewers.
Linked Issues check ✅ Passed The PR fully implements all coding requirements from issue #700: Grumpkin affine point arithmetic (add/sub/neg), validation helpers (is_on_curve, is_identity, is_not_identity), canonical 64-byte point encoding, explicit branching for five addition cases, and comprehensive property-based tests covering algebraic identities.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue objectives: SDK bump to 26.0.0 for BN254 Fr arithmetic, Grumpkin module implementation with arithmetic and validation, comprehensive test suite, and no unrelated modifications to other subsystems.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/grumpkin-arithmetic

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.49%. Comparing base (22ca114) to head (3543494).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #729      +/-   ##
==========================================
+ Coverage   96.44%   96.49%   +0.04%     
==========================================
  Files          60       61       +1     
  Lines        6356     6440      +84     
==========================================
+ Hits         6130     6214      +84     
  Misses        226      226              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
packages/contract-utils/src/crypto/test/grumpkin.rs (1)

364-382: 💤 Low value

Minor: Comment overstates overflow likelihood.

For canonical coordinates (< r), the sum coord + r is always < 2r ≈ 2^255 < 2^256, so overflow cannot occur. The None branch is purely defensive and will never trigger for valid test inputs from to_point. The current comment suggests overflow is "unlikely" when it's actually impossible for canonical inputs.

This is cosmetic and doesn't affect correctness.

📝 Suggested documentation fix
 /// Adds the BN254 scalar field modulus `r` to a canonical 32-byte big-endian
 /// coordinate, producing a non-canonical encoding that reduces to the same
 /// field element under `Bn254Fr::from_bytes`. Returns `None` if the sum
-/// overflows 32 bytes (only happens for `coord` very close to `r`, which is
-/// extremely unlikely for randomly generated points).
+/// overflows 32 bytes (cannot happen for canonical coordinates < r, since
+/// coord + r < 2r < 2^256; the check is purely defensive).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/contract-utils/src/crypto/test/grumpkin.rs` around lines 364 - 382,
The comment on add_modulus_be overstates overflow likelihood; update the
docstring to state that for canonical coordinates (coord < r) coord + r < 2r <
2^256 so byte overflow cannot occur and the None branch is purely defensive,
while keeping the implementation intact; reference add_modulus_be and
FR_MODULUS_BE in the comment to clarify that None is only reachable for
non-canonical/invalid inputs.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/contract-utils/src/crypto/test/grumpkin.rs`:
- Around line 364-382: The comment on add_modulus_be overstates overflow
likelihood; update the docstring to state that for canonical coordinates (coord
< r) coord + r < 2r < 2^256 so byte overflow cannot occur and the None branch is
purely defensive, while keeping the implementation intact; reference
add_modulus_be and FR_MODULUS_BE in the comment to clarify that None is only
reachable for non-canonical/invalid inputs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 98adeeee-a9f0-4e7f-9299-7b34a8dd30c5

📥 Commits

Reviewing files that changed from the base of the PR and between 22ca114 and 528da2c.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • Cargo.toml
  • packages/contract-utils/Cargo.toml
  • packages/contract-utils/src/crypto/grumpkin.rs
  • packages/contract-utils/src/crypto/mod.rs
  • packages/contract-utils/src/crypto/test/grumpkin.rs
  • packages/contract-utils/src/crypto/test/mod.rs

@bidzyyys bidzyyys left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

LGTM

@brozorec
brozorec merged commit c81b9ac into main May 27, 2026
8 checks passed
@brozorec
brozorec deleted the feat/grumpkin-arithmetic branch May 27, 2026 11:52
@github-project-automation github-project-automation Bot moved this from Todo to Done in Stellar Contracts May 27, 2026
@bidzyyys bidzyyys moved this to Done in Stellar Contracts Aug 17, 2026
@bidzyyys bidzyyys moved this to Done in Stellar Contracts Aug 17, 2026
@bidzyyys bidzyyys moved this to Done in Stellar Contracts Aug 17, 2026
@bidzyyys bidzyyys moved this to Done in Stellar Contracts Aug 17, 2026
@bidzyyys bidzyyys moved this to Done in Stellar Contracts Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

On-chain Grumpkin point arithmetic for Soroban wrapper

2 participants