Big integers and modular arithmetic
Constantine uses big integers as the numeric base for finite fields and cryptographic work. The arithmetic layer supports values with a fixed public width for field code and caller-sized buffers for bounded arbitrary-precision work. It then supplies modular reduction, inversion, exponentiation, and special fast-reduction paths while keeping secret-dependent operations suitable for constant-time use. This page provides the numeric foundation for finite-field arithmetic.
Numeric representations
The arithmetic model separates a number's mathematical value from the word array used to store it. A limb is one machine-sized word in that array; the least significant limb comes first. The BigInt[bits] type fixes the announced width at compile time, so field code can select a width that matches a modulus and the compiler can build a predictable operation shape. SecretWord and SecretBool mark words and decisions that may carry secret data.
References: constantine/…/abstractions.nim• L26-50 constantine/…/abstractions.nim• L131-143 constantine/…/limbs.nim• L22-40
The fixed-width form is not an unbounded integer type. A result can carry or borrow beyond its declared width, and multiplication can be truncated when the destination is too small. Callers therefore choose a destination wide enough for the mathematical result or use a modular operation that reduces it. The width is public, while the value held in the limbs can remain secret.
References: constantine/…/bigints.nim• L267-318 constantine/…/bigints.nim• L473-483
Fixed-width operations
Fixed-width operations provide the basic building blocks for field elements and cryptographic scalars. They cover initialization, comparison, addition, subtraction, multiplication, squaring, shifts, bit access, conditional copy, conditional swap, and conditional arithmetic. Operations that return a carry or borrow let higher layers decide whether a value crossed the fixed-width boundary.
References: constantine/…/bigints.nim• L67-112 constantine/…/bigints.nim• L114-240 constantine/…/bigints.nim• L241-377
Conditional operations perform the same memory work for either control value. This lets higher layers select or update a value without making a secret bit a normal branch condition. Table lookup follows the same model by scanning all entries and conditionally copying the selected one.
References: constantine/…/limbs.nim• L88-119 constantine/…/abstractions.nim• L97-104
Arbitrary-precision views
Arbitrary-precision arithmetic works on caller-provided word arrays rather than a heap-managed integer object. This model covers bounded workloads such as RSA-sized values and EVM-sized values without making allocation part of the arithmetic contract. A LimbsView gives low-level routines a type-erased view of such a buffer, while separate mutable and immutable views preserve the direction of access.
References: constantine/…/bigints_views.nim• L23-42 constantine/…/limbs_views.nim• L19-38
The view-based layer supports different operand sizes. It can shift, add, subtract, multiply, and divide arrays whose lengths do not match, with the caller responsible for buffer size and alias rules. It also reports the active bit length when a variable-time path needs to inspect the public shape of a value.
References: constantine/…/limbs_multiprec.nim• L22-39 constantine/…/limbs_multiprec.nim• L67-150 constantine/…/limbs_multiprec.nim• L165-228 constantine/…/limbs_views.nim• L108-142
Modular arithmetic
Modular arithmetic maps an integer to its representative in the range below a modulus. This is the central link between integer operations and field operations: additions and products are formed on limbs, then reduced so that the result remains a valid residue. The fixed-width reduction path has a public modulus width and does not use data-dependent control flow. The variable-time path returns a failure signal for invalid division or reduction inputs and is intended for values whose timing does not reveal a secret.
References: constantine/…/bigints.nim• L467-483 constantine/…/limbs_divmod.nim• L143-183 constantine/…/limbs_divmod_vartime.nim• L144-215
When a modulus fits the declared width, the fixed-width API requires the modulus to use that width. When the input is already smaller than the modulus, reduction can copy it directly. Larger inputs are consumed from the high end through repeated modular shift-and-add steps. This gives callers one reduction contract for field-sized values and wider products.
References: constantine/…/bigints.nim• L473-483 constantine/…/limbs_divmod.nim• L143-183
The variable-time path also supports ordinary quotient-and-remainder work. It checks buffer capacity and division by zero, then returns the remainder in the caller's buffer. The arbitrary-precision facade uses this path for general modulus handling when timing is acceptable.
References: constantine/…/limbs_divmod_vartime.nim• L144-215 constantine/…/bigints_views.nim• L114-158
Modular addition
Modular addition assumes both inputs are already in the range [0, M). It adds the inputs into a temporary wide enough to observe overflow, then selects the value before or after subtracting the modulus. The same rule supplies modular doubling by adding an operand to itself.
References: constantine/…/limbs_mod.nim• L20-48
Modular inversion
Modular inversion produces a value x such that a*x is congruent to one modulo M, when the inverse exists. The fixed-width API supports odd moduli that need not be prime and requires the input to be below the modulus. It offers constant-time and variable-time forms, so the caller must match the form to the secrecy of the input and modulus.
References: constantine/…/bigints.nim• L485-560 constantine/lowlevel_bigints.nim• L60-69
The inversion layer also handles powers of two as a separate arithmetic case. An odd value has an inverse modulo 2^k; the inverse is refined one word or group of bits at a time. This path is useful when a general even modulus is split into an odd part and a power-of-two part.
References: constantine/…/limbs_mod2k.nim• L170-230 constantine/…/limbs_exgcd.nim• L41-78
Modular exponentiation
Modular exponentiation raises a residue to an exponent and reduces after each multiplication. For odd moduli, the arbitrary-precision path uses Montgomery arithmetic. For a modulus that is a power of two, it uses direct reduction modulo 2^k. For a general even modulus, it computes the odd and power-of-two residues separately and recombines them with the Chinese Remainder Theorem.
References: constantine/…/bigints_views.nim• L71-112 constantine/…/bigints_views.nim• L114-220
The constant-time exponentiation form uses a fixed window. It performs a fixed pattern of squarings and multiplications and selects precomputed powers without exposing the exponent bits through the table choice. The variable-time form is an optimization for public exponents only; using it with a secret exponent can expose information through timing, memory access, or power use.
References: constantine/…/bigints_montgomery.nim• L83-163 constantine/…/limbs_montgomery.nim• L161-188 constantine/…/bigints_crandall.nim• L41-125
Montgomery residues
Montgomery arithmetic represents a residue in a transformed domain so that modular products avoid a general division by the modulus. The domain uses R, a power of the machine-word base larger than the modulus, and represents a as a*R mod M. Conversion into and out of this domain is explicit. Values must not be mixed across the two domains without conversion.
References: constantine/…/bigints_montgomery.nim• L26-59 constantine/…/limbs_montgomery.nim• L93-143
The Montgomery path needs constants derived from the modulus. One constant gives the low-word negative inverse of the modulus, and another gives R² mod M for conversion. A Montgomery product can use lazy reduction when its caller accepts a result in a wider residue range; the normal form finishes with a reduction to [0, M).
References: constantine/…/bigints_montgomery.nim• L26-67 constantine/…/limbs_montgomery.nim• L26-91
Montgomery multiplication is the main general-purpose product path for odd field moduli. It also supports squaring, sum-of-products, and fixed-window exponentiation. Higher field layers use these operations to build multiplication, inversion, and other field rules without performing a division for every product. For the relation to extension-field values, see Extension fields and towers.
References: constantine/…/bigints_montgomery.nim• L53-100 constantine/…/limbs_montgomery.nim• L38-91
Special modulus forms
Some cryptographic moduli have a form that makes reduction cheaper than general division. Constantine exposes a Crandall path for primes of the form p = 2^m - c. Since 2^m is congruent to c modulo p, high product bits can be folded into low bits by multiplying them by c. A final conditional subtraction produces the canonical range.
References: constantine/…/limbs_crandall.nim• L21-75 constantine/…/limbs_crandall.nim• L160-188
The Crandall path supports partial reduction for lazy products and full reduction for canonical residues. It is selected by the modulus shape and platform support, not by the secret value. If the modulus does not meet the path's fixed size and constant bounds, the general modular path is the appropriate model.
References: constantine/…/limbs_crandall.nim• L111-158 constantine/…/limbs_crandall.nim• L190-220
Serialization boundary
Big integers cross public interfaces as fixed-size big-endian byte strings. The marshal and unmarshal operations report whether the destination can hold the source, while the internal limb order remains an implementation detail. The C curve header exposes the same boundary for common widths such as 253, 254, 255, and 381 bits.
References: constantine/lowlevel_bigints.nim• L36-47 constantine/…/io_bigints.nim• L1-120 include/…/bigints.h• L18-30
Serialization is separate from modular validity. A byte string can fit the width but still represent a value that is not below the field modulus. The field or protocol layer must apply its own range and canonical-form rules after decoding.
References: constantine/…/bigints.nim• L473-483 constantine/lowlevel_bigints.nim• L39-47
Change checklist
When these files or sections are changed, remember to consider these:
- A change to
BigInt[bits]width rules must stay aligned withwordsRequired, field modulus declarations, and the public serialization widths. - A change to Montgomery conversion constants or residue ranges must be checked against every caller that stores values in the Montgomery domain.
- A change to lazy reduction bounds must be checked at the next multiplication or addition that consumes the wider residue.
- A change to variable-time exponentiation or inversion must preserve the rule that secret exponents and secret inputs use constant-time paths.
- A change to even-modulus exponentiation must keep the odd-part result, power-of-two result, and Chinese Remainder recombination consistent.
- A change to special-form modulus parameters must be checked against the platform word size and the assumptions of the Crandall reduction path.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A product is written to a BigInt that is narrower than the product | High limbs are truncated and the mathematical value is lost | Use a destination wide enough for the product or reduce through the intended modular path |
| A modulus does not fill the declared fixed width | The fixed-width reduction contract is invalid | Declare the modulus width from its highest set bit and satisfy the reduction precondition |
| Natural and Montgomery residues are mixed | Products and comparisons produce incorrect field values | Convert at the boundary and keep each operation within one residue domain |
A lazy residue is passed to code that expects [0, M) | A later subtraction or comparison can use the wrong range | Track lazy bounds through the call chain and canonicalize before range-sensitive use |
| A variable-time inverse or exponentiation receives a secret input | Timing or memory behavior can reveal the input | Use the constant-time API for secret data; reserve variable-time forms for public data |
| A zero modulus or divisor reaches variable-time reduction | The operation reports failure and the output is not a valid reduction | Check the returned success value and reject invalid modulus input |
| A non-invertible value is given to modular inversion | No multiplicative inverse exists | Ensure the input is coprime to the modulus before relying on the result |
Key files
| File | Why to read it |
|---|---|
constantine/platforms/abstractions.nim | Defines BigInt, secret words, limb widths, and the public width model |
constantine/math/arithmetic/bigints.nim | Shows the fixed-width integer and modular operation contract |
constantine/math/arithmetic/limbs.nim | Defines the low-level limb behavior and constant-time selection primitives |
constantine/math_arbitrary_precision/arithmetic/bigints_views.nim | Connects caller-owned arbitrary-precision buffers to modular exponentiation |
constantine/math_arbitrary_precision/arithmetic/limbs_divmod.nim | Explains fixed-width modular reduction for wide inputs |
constantine/math_arbitrary_precision/arithmetic/limbs_divmod_vartime.nim | Explains variable-time division and remainder handling |
constantine/math/arithmetic/bigints_montgomery.nim | Defines the fixed-width Montgomery domain and exponentiation interface |
constantine/math_arbitrary_precision/arithmetic/limbs_montgomery.nim | Shows the arbitrary-precision Montgomery model and residue conversion |
constantine/math/arithmetic/limbs_crandall.nim | Explains fast reduction for pseudo-Mersenne primes |
constantine/math_arbitrary_precision/arithmetic/limbs_mod2k.nim | Covers power-of-two modular arithmetic and inversion |
constantine/lowlevel_bigints.nim | Shows the low-level public exports and big-endian serialization boundary |
| include/…/bigints.h | Shows the C-facing fixed-width big-integer types and byte APIs |