Skip to content

feat(fields): fast secp256k1 fields on the eight-limb Montgomery stack - #389

Merged
dhsorens merged 5 commits into
Verified-zkEVM:mainfrom
graikos:mont-full-width-secp
Oct 20, 2026
Merged

dhsorens merged 5 commits into
Verified-zkEVM:mainfrom
graikos:mont-full-width-secp

Conversation

@graikos

@graikos graikos commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

Fast secp256k1 scalar and base field arithmetic on the shared eight-limb Montgomery stack, in pure Lean, no externs, no native_decide.

  • the stack no longer requires 2*modulus < 2^256: add keeps the top carry and CIOS ends in condSubWide, which reads the head limb; below 2^255 the code path is the original condSub verbatim
  • class field two_mul_modulus_lt removed, modulus_lt derived from limb boundedness; no instance file changed
  • secp256k1 = two Mont64x8Field + GcdData instances of decide-checked constants in Secp256k1/Fast.lean; canonical fields moved to Secp256k1/Basic.lean, size constants renamed scalarFieldSize / baseFieldSize like the other fields
  • #guard tests incl. the carry cases and GCD-candidate exactness; fields-secp256k1-{scalar,base}-{mul,add} and fields-mont64x8-secp256k1-{scalar,base}-inv bench groups, plus fields-{bn254,bls12-381,bls12-377}-add
  • existing fields unchanged: pinned A/B against master, all 43 rows "same" (mul 1.00-1.02, add 0.98-1.01, GCD inv 0.98-1.00)
  • secp256k1: mul ~32ns, add ~7.5ns, GCD inv ~6us (vs ZMod: ~130ns / ~97ns / ~48us); base field within a few percent of scalar

Earlier drafts folded the carry into the existing branch (short-circuit || and a single flag word); both cost 5-8% on mul or add through a join point or a serialized select, so the carry got its own never-taken branch. The 4x64 special-form secp reduction from PR #271 was benched against this: mul 3-5% faster at the secp order, add 4x slower, Fermat inverse 8x slower, so it was dropped.

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🤖 PR Summary

This pull request adds fast secp256k1 scalar and base field arithmetic using the shared eight-limb Montgomery stack, while simultaneously generalizing the stack to support moduli up to 2^256 (previously capped at 2^255). The change touches core arithmetic definitions, proofs, type classes, and adds new module files, benchmarks, and regression tests.


Statistics

Metric Count
📝 Files Changed 21
✅ Lines Added 749
❌ Lines Removed 264

Lean Declarations

✏️ Removed: 9 declaration(s)

CompPoly/Fields/Montgomery/Native64x8.lean (1)

  • private theorem carry_top_zero {S A B Q c : ℕ} (h : S + 2 ^ 256 * c = A + B)

CompPoly/Fields/Montgomery/Native64x8Field.lean (1)

  • theorem two_mul_q_lt : 2 * P.modulusLimbs.toNat < 2 ^ 256

CompPoly/Fields/Secp256k1.lean (7)

  • abbrev BaseField
  • abbrev ScalarField
  • def BASE_FIELD_CARD : Nat
  • def SCALAR_FIELD_CARD : Nat
  • example :
  • theorem BaseField_is_prime : Nat.Prime BASE_FIELD_CARD
  • theorem ScalarField_is_prime : Nat.Prime SCALAR_FIELD_CARD
✏️ Added: 40 declaration(s)

CompPoly/Fields/Montgomery/Native64x8.lean (6)

  • private theorem add_of_carry {S A B Q D bo : ℕ} (hchain : S + 2 ^ 256 * 1 = A + B)
  • private theorem wide_of_head {T L t8 Q D bo : ℕ} (hdec : T = L + 2 ^ 256 * t8)
  • theorem addLimbs_spec (a b : Limbs8) (ha : a.Bounded) (hb : b.Bounded) :
  • theorem condSubWide_bounded (q : Limbs8) (t : State9) (ht : t.Bounded) :
  • theorem condSubWide_lt (q : Limbs8) (t : State9) (hq : q.Bounded) (ht : t.Bounded)
  • theorem condSubWide_toNat (q : Limbs8) (t : State9) (hq : q.Bounded) (ht : t.Bounded)

CompPoly/Fields/Montgomery/Native64x8Defs.lean (2)

  • @[inline] def addCarry (a b : Limbs8) : UInt64
  • @[inline] def condSubWide (q : Limbs8) (t : State9) : Limbs8

CompPoly/Fields/Secp256k1/Basic.lean (7)

  • abbrev BaseField
  • abbrev ScalarField
  • def baseFieldSize : Nat
  • def scalarFieldSize : Nat
  • example :
  • theorem BaseField_is_prime : Nat.Prime baseFieldSize
  • theorem ScalarField_is_prime : Nat.Prime scalarFieldSize

CompPoly/Fields/Secp256k1/Fast.lean (10)

  • abbrev BaseField : Type
  • abbrev ScalarField : Type
  • def baseRingEquiv : BaseField ≃+* Secp256k1.BaseField
  • def ofBaseField (x : Secp256k1.BaseField) : BaseField
  • def ofScalarField (x : Secp256k1.ScalarField) : ScalarField
  • def scalarRingEquiv : ScalarField ≃+* Secp256k1.ScalarField
  • instance instBaseGcdData : GcdData Secp256k1.baseFieldSize where
  • instance instBaseMont64x8Field : Mont64x8Field Secp256k1.baseFieldSize where
  • instance instScalarGcdData : GcdData Secp256k1.scalarFieldSize where
  • instance instScalarMont64x8Field : Mont64x8Field Secp256k1.scalarFieldSize where

bench/CompPolyBench/Fields/Arith.lean (9)

  • private def runBls12_377Add (preset : BenchPreset) (gen : StdGen) :
  • private def runBls12_381Add (preset : BenchPreset) (gen : StdGen) :
  • private def runBn254Add (preset : BenchPreset) (gen : StdGen) :
  • private def runSecp256k1BaseAdd (preset : BenchPreset) (gen : StdGen) :
  • private def runSecp256k1BaseMul (preset : BenchPreset) (gen : StdGen) :
  • private def runSecp256k1ScalarAdd (preset : BenchPreset) (gen : StdGen) :
  • private def runSecp256k1ScalarMul (preset : BenchPreset) (gen : StdGen) :
  • private def secp256k1BaseReps (gen : StdGen) :
  • private def secp256k1ScalarReps (gen : StdGen) :

bench/CompPolyBench/Fields/Inputs.lean (4)

  • def checksumSecp256k1BaseFast (x : Secp256k1.Fast.BaseField) : Nat
  • def checksumSecp256k1ScalarFast (x : Secp256k1.Fast.ScalarField) : Nat
  • def secp256k1BaseFastArray (xs : Array Secp256k1.BaseField) :
  • def secp256k1ScalarFastArray (xs : Array Secp256k1.ScalarField) :

bench/CompPolyBench/Fields/Montgomery.lean (2)

  • private def runSecp256k1BaseInv (preset : BenchPreset) (gen : StdGen) :
  • private def runSecp256k1ScalarInv (preset : BenchPreset) (gen : StdGen) :
✏️ Affected: 3 declaration(s) (line number changed)
  • theorem addLimbs_toNat (a b : Limbs8) (ha : a.Bounded) (hb : b.Bounded) : in CompPoly/Fields/Montgomery/Native64x8.lean moved from L278 to L318
  • theorem add_bounded (q a b : Limbs8) : (add q a b).Bounded in CompPoly/Fields/Montgomery/Native64x8.lean moved from L372 to L417
  • @[inline] def add (q a b : Limbs8) : Limbs8 in CompPoly/Fields/Montgomery/Native64x8Defs.lean moved from L149 to L161

sorry Tracking

  • No sorrys were added, removed, or affected.

📋 **Additional Analysis**

The diff is relevant to the supplied instructions. Below are findings organized by the categories emphasized in the deployment-supplied guidelines.


📄 **Per-File Summaries**
  • CompPoly.lean: Two new imports have been added: CompPoly.Fields.Secp256k1.Basic and CompPoly.Fields.Secp256k1.Fast, exposed as public imports alongside the existing CompPoly.Fields.Secp256k1. This makes the Basic and Fast submodules of the secp256k1 field implementation available to downstream code that imports this file.
  • CompPoly/Fields/Montgomery/Native64x8.lean: The file's documentation and module header were updated to change the modulus bound from 2 ^ 255 to 2 ^ 256 and to list condSubWide_toNat and subLimbs_spec as main results. Two new private lemmas add_of_carry and wide_of_head were added to support the new condSubWide operation and the revised addition proof, while the private carry_top_zero was removed and the hypothesis of sub_of_borrow_one was relaxed from 2 * Q < 2 ^ 256 to Q < 2 ^ 256. The theorem addLimbs_spec was introduced as a stronger replacement for addLimbs_toNat, with the latter now a corollary. Three new public theorems condSubWide_bounded, condSubWide_toNat, and condSubWide_lt were added to establish boundedness and correctness for the wide conditional subtraction function condSubWide. The hypotheses of add_toNat, add_lt, sub_toNat, sub_lt, neg_toNat, and neg_lt were weakened by removing the requirement 2 * q.toNat < 2 ^ 256; their proofs were refactored accordingly, and add_bounded was restructured to branch on the carry using subLimbs_bounded when the carry is zero.
  • CompPoly/Fields/Montgomery/Native64x8Defs.lean: The diff adds a new function addCarry that returns the carry out of the top limb of addLimbs, and a new function condSubWide that performs conditional subtraction on a State9 accumulator (using its high limb t.t8 to decide). The existing add function is revised to use addCarry: if a carry occurs, it performs unconditional subtraction via subLimbs s q instead of the original condSub q s; the comment notes this carry never happens for moduli below 2^255. The mul function now uses condSubWide q t in place of condSub q t.toLimbs8, so that the accumulator’s high limb is taken into account during the final reduction. No sorry or admit are introduced.
  • CompPoly/Fields/Montgomery/Native64x8Field.lean: Removed the two_mul_modulus_lt field from the Mont64x8Field type class (which previously required 2 * modulus < 2^256) and the derived theorem two_mul_q_lt. Rewrote the proof of modulus_lt to use Limbs8.toNat_lt and modulusLimbs_bounded instead of the removed field. Updated the module doc comment from “for prime moduli below 2 ^ 255” to “for any prime modulus below 2 ^ 256”. Adjusted all uses of two_mul_q_lt in the proofs of add, sub, neg, mul, ofCanonicalNat, mul_cast, toNat_lt, toField_add, toField_sub, and toField_neg by removing that argument from calls to helper lemmas (add_lt, sub_lt, neg_lt, mul_spec, etc.), reflecting the relaxed interface. No sorry or admit was introduced.
  • CompPoly/Fields/Montgomery/Native64x8Inv.lean: This diff refines the Montgomery GCD inversion proofs in Native64x8Inv.lean by dropping the hq2 : 2 * q.toNat < 2 ^ 256 hypothesis from lincomb_stack_lt, gcdLinearCombMontyRed_lt, gcdMainLoop_bounded, gcdFinalChunks_lt, and gcdInvCandidate_lt, updating all call sites accordingly. It also changes lincomb_stack_lt to use the wider condSubWide operation (instead of condSub on the toLimbs8 cast) and its associated condSubWide_bounded/condSubWide_lt lemmas, making the boundedness/canonicality conclusion directly about the wide subtraction. No sorry or admit was introduced.
  • CompPoly/Fields/Montgomery/Native64x8InvDefs.lean: The implementation of gcdLinearCombMontyRed was changed: the result of mulReduce q negInv s is no longer converted to Limbs8 via .toLimbs8 before being passed to condSub, but is now passed directly as a WideLimbs8 to condSubWide. This modifies the return type and the reduction operation of the function.
  • CompPoly/Fields/Montgomery/Native64x8Mul.lean: The diff removes the hypothesis hq2 : 2 * q.toNat < 2 ^ 256 from both mul_finish and mul_spec, relaxing a precondition. Internally, mul_finish now calls condSubWide instead of condSub, and the proof uses the corresponding condSubWide_bounded, condSubWide_lt, and condSubWide_toNat lemmas. This change makes the Montgomery multiplication work for any bounded q without requiring that 2*q fits in 256 bits.
  • CompPoly/Fields/Secp256k1.lean: The file CompPoly/Fields/Secp256k1.lean was entirely rewritten from a monolithic file containing the definitions of BASE_FIELD_CARD, SCALAR_FIELD_CARD, the associated BaseField and ScalarField types, and full Pratt-certificate proofs of primality (BaseField_is_prime, ScalarField_is_prime) along with Fact and Field instances, to a facade module that re‑exports the same field types from two new submodules: CompPoly.Fields.Secp256k1.Basic (canonical ZMod models) and CompPoly.Fields.Secp256k1.Fast (native‑word Montgomery implementations). The old file's Secp256k1 namespace and @[expose] public section are removed. The update adds Georgios Raikos as an author and updates the module docstring to describe the new facade role. No sorry or admit are present in the new content.
  • CompPoly/Fields/Secp256k1/Basic.lean: The new file CompPoly/Fields/Secp256k1/Basic.lean defines the Secp256k1 base field prime (baseFieldSize) and scalar field prime (scalarFieldSize) as hex constants, provides abbrev definitions BaseField and ScalarField as ZMod over those primes, and proves both primes are prime using PrattCertificate' (via BaseField_is_prime and ScalarField_is_prime). It also registers Fact and Field instances for each field. No sorry or admit are present.
  • CompPoly/Fields/Secp256k1/Fast.lean: Adds file CompPoly/Fields/Secp256k1/Fast.lean, defining the Secp256k1.Fast module with fast eight-limb Montgomery field representations for the secp256k1 scalar and base fields. It provides instances instScalarGcdData and instBaseGcdData (divstep schedules with finalRounds := 45 and initU constants), instScalarMont64x8Field and instBaseMont64x8Field (prime proofs, modulus limbs, rModModulus, r2ModModulus, montgomeryNegInv), abbreviations ScalarField and BaseField as FastField types, conversion functions ofScalarField, scalarRingEquiv, ofBaseField, baseRingEquiv, and public imports of the corresponding Basic and Montgomery.Native64x8Inv modules. No sorry or admit appear.
  • bench/CompPolyBench/Fields/Arith.lean: The file extends its eight-limb pairing scalar field benchmarks from multiplication-only to include addition for BN254, BLS12-381, and BLS12-377 (new runBn254Add, runBls12_381Add, runBls12_377Add), and adds secp256k1 scalar‑field and base‑field multiplcation and addition (runSecp256k1ScalarMul, runSecp256k1ScalarAdd, runSecp256k1BaseMul, runSecp256k1BaseAdd), backed by two new operand generation functions secp256k1ScalarReps and secp256k1BaseReps. The section comment is updated to reflect the broader scope, and all eight new runners are registered in fieldArithTasks.
  • bench/CompPolyBench/Fields/Inputs.lean: Added public import CompPoly.Fields.Secp256k1 to bring the Secp256k1 field definitions into scope. Updated the module-level docstring to list "the two secp256k1 fields". Added four new definitions: secp256k1ScalarFastArray (maps Secp256k1.ScalarField to Secp256k1.Fast.ScalarField via Secp256k1.Fast.ofScalarField), checksumSecp256k1ScalarFast (computes a checksum as x.toNat), secp256k1BaseFastArray (maps Secp256k1.BaseField to Secp256k1.Fast.BaseField via Secp256k1.Fast.ofBaseField), and checksumSecp256k1BaseFast (computes a checksum as x.toNat). These additions extend the per-field benchmark scaffolding to cover the Secp256k1 scalar and base fields.
  • bench/CompPolyBench/Fields/Montgomery.lean: The diff adds two new benchmark tasks for secp256k1 field inversion (scalar-field and base-field) to the montgomeryInvTasks registry. Two new private runner functions, runSecp256k1ScalarInv and runSecp256k1BaseInv, are defined, each calling runScalarInv with the appropriate Secp256k1.scalarFieldSize/Secp256k1.baseFieldSize, a unique benchmark ID, a human-readable label, and the Secp256k1.ScalarField/Secp256k1.Fast.ScalarField (or BaseField) type identifiers. The existing BLS12-377 entry in the list now has a trailing comma, and the public import CompPoly.Fields.Secp256k1 line is added to bring the secp256k1 field definitions into scope. These changes extend the inversion benchmark suite to cover the secp256k1 elliptic curve.
  • tests/CompPolyTests.lean: In tests/CompPolyTests.lean, a public import statement for CompPolyTests.Fields.Secp256k1.Fast was added, which makes the test suite now include tests for the fast implementation of the secp256k1 elliptic curve field. This extends the coverage of field arithmetic tests to include a widely-used cryptographic curve.
  • tests/CompPolyTests/Fields/Secp256k1/Fast.lean: Added a new regression test file tests/CompPolyTests/Fields/Secp256k1/Fast.lean that exercises the eight-limb Montgomery scalar and base field implementations (ScalarField and BaseField) from CompPoly.Fields.Secp256k1.Fast. The file contains #guard checks for stored residues, literal round trips via toNat, addition/subtraction with wraparound, negation, multiplication, exponentiation, Fermat inversion/division (including ⁻¹, /, ^ with integer exponents), and the checked binary-GCD inversion invGcd—all compared against the canonical ZMod-based fields (Secp256k1.ScalarField/BaseField) where applicable. It also directly exercises the Fermat fallback montPow. No sorry or admit appear.
  • 6 file(s) filtered as noise (lockfiles, generated, or trivial): CompPoly/Fields/README.md, README.md, bench/README.md, bench/ci-groups.txt, docs/wiki/autoresearch.md, docs/wiki/serialization.md

Last updated: 2026-10-20 10:50 UTC.

@mitschabaude-bot mitschabaude-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.

great!

@alexanderlhicks

Copy link
Copy Markdown
Collaborator

Thanks! I actually needed this today and was about to work on a PR for this!

dhsorens and others added 2 commits October 20, 2026 11:44
The merge with main kept main's imports in Secp256k1.lean, so the facade no longer re-exported Secp256k1.Basic and Secp256k1.Fast. Restore them, and move the Mathlib.Algebra.Field.ZMod import that the Lean v4.35.0 bump (Verified-zkEVM#400) added to Secp256k1/Basic.lean, which now holds the ZMod models.
@dhsorens
dhsorens enabled auto-merge (squash) October 20, 2026 10:47

@dhsorens dhsorens left a comment

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.

awesome, thank for this! merging

@dhsorens
dhsorens merged commit 1cb8f5c into Verified-zkEVM:main Oct 20, 2026
6 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.

5 participants