Introducing a new way to review your PRs.

Read the announcement

mratsim / constantine

Constantine: modular, high-performance, zero-dependency cryptography stack for verifiable computation, proof systems and blockchain protocols.

View on GitHub

19 documents · Updated Nov 13, 2026

docs / finite-field-arithmetic

Finite-field arithmetic

Constantine’s finite-field arithmetic supplies the number system used by its cryptographic protocols. It combines fixed-size prime and scalar fields with extension fields, then maps their operations to constant-time multi-word arithmetic that can be tuned for each compiler target and hardware platform.

Arithmetic model

Prime and scalar fields

The library defines two prime fields for each named curve. Fp uses the curve’s base-field prime, while Fr uses the curve’s subgroup order. Both field types are selected with a static Algebra value, so their modulus, size, and derived constants are known when the program is compiled. FF is the common type family used by code that can work with either field.

Field elements normally use Montgomery form internally. This form makes repeated modular multiplication efficient. Conversion at the boundary turns a fixed-size BigInt in normal form into a field element and converts it back for encoding or other integer-level work. The supported field assumptions are an odd prime modulus known at compile time. The oddness supports Montgomery arithmetic, and the prime property supports field inversion methods.

FieldMeaningModulus source
FpBase field for curve coordinates and base-field protocol valuesCurve prime p
FrScalar field for curve subgroup operationsCurve order r
FFShared arithmetic interface for Fp and FrSelected by the concrete field type

References: constantine/…/properties_fields.nim• L41-58 constantine/…/finite_fields.nim• L17-27 constantine/…/finite_fields.nim• L56-81

Extension fields

An extension field builds a larger field from a lower field by adding coordinates over a chosen irreducible polynomial. Constantine models quadratic and cubic extensions as small coordinate arrays. Named types then describe common tower shapes such as Fp2, Fp6, and Fp12.

Extension arithmetic keeps the same field contract as prime-field arithmetic. Addition, comparison, conditional moves, multiplication, inversion, square roots, and Frobenius maps operate on the tower while delegating base work to the lower field. The tower choice and its non-residues are part of the named curve properties, so the same high-level operation can use a curve-specific field shape without changing its caller. See Extension fields and towers for the tower rules and operations.

References: constantine/…/towers.nim• L33-65 constantine/…/towers.nim• L90-140 constantine/lowlevel_extension_fields.nim• L44-95

Representation boundaries

The public low-level field API exposes field operations and conversion helpers, but the internal layout is not a stable application contract. A prime-field element wraps a fixed-size multi-word value named mres; an extension element wraps two or three elements from the lower field. Code must use the field conversion and serialization operations instead of assuming that the stored words are canonical integers.

The normal byte boundary is big-endian. On input, the bytes are read into a matching BigInt and then converted into the field’s internal form. On output, the field is first converted to normal form and then encoded. This keeps wire values separate from the representation used for fast arithmetic.

References: constantine/lowlevel_fields.nim• L21-26 constantine/lowlevel_fields.nim• L55-70 constantine/…/properties_fields.nim• L42-56

Arithmetic layers

Prime-field operations

The prime-field layer provides the group and field operations needed by curve and protocol code. It includes addition, subtraction, negation, doubling, multiplication, squaring, division by two, inversion, exponentiation, and square-root checks. In-place operations are the preferred form in performance-sensitive code because field values can be large.

The layer also provides conditional operations such as copy, swap, add, subtract, and negation. These operations use secret control values and keep their access pattern independent of the selected value. This lets higher layers choose between candidate values without turning a secret bit into an ordinary branch.

Multiplication and squaring can use lazy reduction when the caller can preserve the allowed wider range. A final reduction brings the value back to the normal field range before a later operation or a representation boundary requires it. Specialized reduction is available for fields with a Crandall-style modulus; other fields use Montgomery multiplication.

References: constantine/…/finite_fields.nim• L121-141 constantine/…/finite_fields.nim• L172-292 constantine/…/finite_fields.nim• L300-405

Extension-field operations

Extension operations lift the prime-field contract through each coordinate of a tower. Linear operations are coordinate-wise, while multiplication and inversion use the defining non-residue and the tower shape to reduce products back into the extension field.

Some operations exist because extension fields have useful structure beyond ordinary multiplication. Conjugation supports quadratic and cubic tower steps, and Frobenius maps provide field automorphisms. Square-root and exponentiation helpers use the lower-field operations and preserve the constant-time path where protocol code needs it.

The extension layer also has wider temporary forms for lazy arithmetic. These forms keep extra words or extra range in intermediate coordinates, then reduce each coordinate back into the regular extension type. Their purpose is to avoid needless reductions inside a larger formula, not to define a second mathematical field.

References: constantine/…/towers.nim• L153-229 constantine/…/towers.nim• L286-405 constantine/…/exponentiations.nim• L104-162 constantine/…/square_root_fp2.nim• L19-43

Integer support

The field layers rely on fixed-precision BigInt values for modulus-sized integers. A BigInt[bits] has a compile-time bit width and stores its value as an array of secret words. This gives the compiler a known size for unrolling, stack layout, and carry chains. It is not a heap-sized integer type.

The integer layer supplies the raw work for field conversion and modular arithmetic. It covers limb comparison, addition, subtraction, multiplication, reduction, modular inversion, bit access, and constant-time conditional moves. Montgomery and Crandall helpers build the two main modular multiplication paths on top of these operations. See Big integers and modular arithmetic for the integer layer and its modular algorithms.

References: constantine/…/abstractions.nim• L35-50 constantine/…/abstractions.nim• L131-143 constantine/…/bigints.nim• L25-64 constantine/lowlevel_bigints.nim• L36-70

Performance abstractions

Compile-time field metadata

Curve and field properties bind a field type to its modulus, bit width, Montgomery constants, spare bits, and non-residues. These values are derived or selected at compile time. As a result, unused curves do not need to enter the generated program, and field operations can use a fixed number of words rather than a run-time size.

The metadata also controls safe use of wider intermediate values. Spare bits describe how far a value may grow during a no-carry or lazy-reduction step. The same metadata tells the arithmetic layer whether it can use a special modulus reduction or must use the general Montgomery path.

References: constantine/…/properties_fields.nim• L89-122 constantine/…/properties_fields.nim• L186-217 constantine/…/ir.nim• L154-208

Constant-time platform primitives

The platform layer gives all arithmetic layers a common word and carry model. SecretWord wraps the machine word used for sensitive values, while SecretBool carries results that must not become ordinary control flow. Limb operations use fixed loops and conditional selection for comparisons and moves.

The same interface can use hardware carry and borrow instructions or a portable fallback. Platform-specific assembly is selected for supported CPU targets. This separation lets field code describe arithmetic while the platform layer handles word size, instruction support, and constant-time primitives.

References: constantine/…/abstractions.nim• L26-58 constantine/…/abstractions.nim• L97-104 constantine/…/limbs.nim• L22-40 constantine/…/limbs.nim• L121-145

LLVM arithmetic compiler

The compiler layer exposes field operations as LLVM code for CPU and GPU targets. A FieldDescriptor carries the field width, word type, limb count, modulus, and spare-bit information. Public wrappers provide callable field operations, while internal helpers let larger generated procedures compose those operations without leaving the LLVM module.

Backend dispatch selects arithmetic suited to the target. Saturated-limb code serves targets that can use carry flags, while NVIDIA PTX code uses its own carry, multiply, and selection instructions. GPU generation also carries field metadata at run time because a GPU module may need dynamic word-size and modulus data that CPU builds normally fix at compile time.

The compiler layer is therefore a second route to the same field contract. It does not change what Fp, Fr, or an extension field means. It changes how the fixed-size operations are represented and scheduled for the selected execution target.

References: constantine/…/ir.nim• L32-56 constantine/…/ir.nim• L147-208 constantine/…/pub_fields.nim• L19-75 constantine/…/impl_fields_dispatch.nim• L15-34

Arithmetic flow

The normal data path keeps encoded integers at the boundary, field values in their fast internal form during computation, and extension values as structured collections of lower-field values. This diagram shows the relationship between those layers.

flowchart LR
    A[Big-endian bytes] --> B[Fixed-size BigInt]
    B --> C[Prime field conversion]
    C --> D[Fp or Fr in internal form]
    D --> E[Prime-field operations]
    E --> F[Extension tower operations]
    F --> G[Field conversion to normal form]
    G --> H[Big-endian bytes]
    C -. lower-field coordinates .-> F

The selected field metadata supplies the modulus and precomputed constants at the conversion and arithmetic stages. The platform or LLVM backend then supplies the word-level operations underneath them.

References: constantine/lowlevel_fields.nim• L55-70 constantine/…/finite_fields.nim• L56-81 constantine/…/towers.nim• L90-110 constantine/…/ir.nim• L174-208

Change checklist

When these files or sections are changed, remember to consider these:

  • A modulus, curve bit width, or field order change affects the static BigInt width, derived Montgomery constants, spare-bit range, and compiler field descriptor.
  • A new extension tower or non-residue must agree across the named curve properties, extension type aliases, multiplication rules, and field-specific square-root data.
  • A change to lazy reduction must preserve the range expected by every consumer before redc2x or a normal field operation.
  • A new backend or word size must cover carry and borrow behavior, modular add/subtract, multiplication, and the backend dispatch cases.
  • A change from a constant-time operation to a variable-time one must keep the public-input restriction visible at every caller.
  • Changes to mres or limb layout must preserve the conversion and byte-encoding boundary. Low-level callers must not silently depend on the old layout.

Important failure modes

TriggerConsequenceGuard
Treating a Montgomery-form value as a normal integerEncoded values or integer comparisons are wrongUse fromField or toBig before normal-form work
Using variable-time inversion or exponentiation with secret inputSecret bits can leak through timing, memory access, or power useUse the constant-time operation for secret data; reserve *_vartime for public data
Passing a field value outside the range allowed by lazy reductionA later multiplication or reduction can produce an invalid resultTrack spare bits and reduce before the next operation that requires canonical range
Defining an even modulus or a modulus with the wrong declared bit widthMontgomery setup or fixed-width arithmetic assumptions failValidate oddness and exact modulus width during field configuration
Mixing extension coordinates or non-residues from different tower shapesProducts, inverses, or square roots no longer represent the named fieldKeep the named tower, non-residue constants, and specialized operations aligned
Calling an operation on an unsupported LLVM backendCode generation reaches an assertion instead of producing arithmeticAdd the backend implementation and dispatch case before exposing the operation

Key files

FileWhy to read it
constantine/named/properties_fields.nimDefines the field families and connects each named algebra to modulus metadata and derived constants.
constantine/lowlevel_fields.nimShows the low-level prime-field boundary and the operations exported to curve and protocol code.
constantine/math/arithmetic/finite_fields.nimDescribes the main field operation contract, internal representation boundary, reduction choices, and timing variants.
constantine/math/arithmetic/bigints.nimShows the fixed-width integer building block used below field arithmetic.
constantine/math/arithmetic/bigints_montgomery.nimExplains the Montgomery conversion, multiplication, squaring, and exponentiation path.
constantine/math/arithmetic/bigints_crandall.nimShows the special reduction path for Crandall-style prime moduli.
constantine/math/extension_fields/towers.nimDefines extension coordinates, named tower types, non-residue use, and wider lazy forms.
constantine/platforms/abstractions.nimDefines secret words, constant-time booleans, fixed-size integers, and platform-neutral word abstractions.
constantine/math/arithmetic/limbs.nimShows the limb-level representation and constant-time multi-word primitives.
constantine/math_compiler/ir.nimDefines the compiler-side field descriptor and target metadata used to generate LLVM arithmetic.
constantine/math_compiler/impl_fields_dispatch.nimShows how LLVM field operations select CPU, AMD GPU, or NVIDIA PTX implementations.
constantine/math_compiler/pub_fields.nimShows the compiler-facing public wrappers for generated field operations.