rustcrypto_ff/
lib.rs

1//! This crate provides traits for working with finite fields.
2
3#![no_std]
4#![cfg_attr(docsrs, feature(doc_cfg))]
5// Catch documentation errors caused by code changes.
6#![deny(rustdoc::broken_intra_doc_links)]
7#![forbid(unsafe_code)]
8
9#[cfg(feature = "alloc")]
10extern crate alloc;
11
12mod batch;
13pub use batch::*;
14
15pub mod helpers;
16
17#[cfg(feature = "derive")]
18#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
19pub use ff_derive::PrimeField;
20
21#[cfg(feature = "bits")]
22#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
23pub use bitvec::view::BitViewSized;
24
25#[cfg(feature = "bits")]
26use bitvec::{array::BitArray, order::Lsb0};
27
28use core::convert::Infallible;
29use core::fmt;
30use core::iter::{Product, Sum};
31use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
32
33use rand_core::{RngCore, TryRngCore};
34use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
35
36/// Bit representation of a field element.
37#[cfg(feature = "bits")]
38#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
39pub type FieldBits<V> = BitArray<V, Lsb0>;
40
41/// This trait represents an element of a field.
42pub trait Field:
43    Sized
44    + Eq
45    + Copy
46    + Clone
47    + Default
48    + Send
49    + Sync
50    + fmt::Debug
51    + 'static
52    + ConditionallySelectable
53    + ConstantTimeEq
54    + Neg<Output = Self>
55    + Add<Output = Self>
56    + Sub<Output = Self>
57    + Mul<Output = Self>
58    + Sum
59    + Product
60    + for<'a> Add<&'a Self, Output = Self>
61    + for<'a> Sub<&'a Self, Output = Self>
62    + for<'a> Mul<&'a Self, Output = Self>
63    + for<'a> Sum<&'a Self>
64    + for<'a> Product<&'a Self>
65    + AddAssign
66    + SubAssign
67    + MulAssign
68    + for<'a> AddAssign<&'a Self>
69    + for<'a> SubAssign<&'a Self>
70    + for<'a> MulAssign<&'a Self>
71{
72    /// The zero element of the field, the additive identity.
73    const ZERO: Self;
74
75    /// The one element of the field, the multiplicative identity.
76    const ONE: Self;
77
78    /// Returns an element chosen uniformly at random using a user-provided RNG.
79    fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
80        Self::try_from_rng(rng)
81            .map_err(|e: Infallible| e)
82            .expect("Infallible failed")
83
84        // NOTE: once MSRV gets to 1.82 remove the map_err/expect and use
85        // let Ok(out) = Self::try_from_rng(rng);
86        // out
87        // See: https://blog.rust-lang.org/2024/10/17/Rust-1.82.0.html#omitting-empty-types-in-pattern-matching
88    }
89
90    /// Returns an element chosen uniformly at random using a user-provided RNG.
91    fn try_from_rng<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error>;
92
93    /// Returns true iff this element is zero.
94    fn is_zero(&self) -> Choice {
95        self.ct_eq(&Self::ZERO)
96    }
97
98    /// Returns true iff this element is zero.
99    ///
100    /// # Security
101    ///
102    /// This method provides **no** constant-time guarantees. Implementors of the
103    /// `Field` trait **may** optimise this method using non-constant-time logic.
104    fn is_zero_vartime(&self) -> bool {
105        self.is_zero().into()
106    }
107
108    /// Squares this element.
109    #[must_use]
110    fn square(&self) -> Self;
111
112    /// Cubes this element.
113    #[must_use]
114    fn cube(&self) -> Self {
115        self.square() * self
116    }
117
118    /// Doubles this element.
119    #[must_use]
120    fn double(&self) -> Self;
121
122    /// Computes the multiplicative inverse of this element,
123    /// failing if the element is zero.
124    fn invert(&self) -> CtOption<Self>;
125
126    /// Computes:
127    ///
128    /// - $(\textsf{true}, \sqrt{\textsf{num}/\textsf{div}})$, if $\textsf{num}$ and
129    ///   $\textsf{div}$ are nonzero and $\textsf{num}/\textsf{div}$ is a square in the
130    ///   field;
131    /// - $(\textsf{true}, 0)$, if $\textsf{num}$ is zero;
132    /// - $(\textsf{false}, 0)$, if $\textsf{num}$ is nonzero and $\textsf{div}$ is zero;
133    /// - $(\textsf{false}, \sqrt{G_S \cdot \textsf{num}/\textsf{div}})$, if
134    ///   $\textsf{num}$ and $\textsf{div}$ are nonzero and $\textsf{num}/\textsf{div}$ is
135    ///   a nonsquare in the field;
136    ///
137    /// where $G_S$ is a non-square.
138    ///
139    /// # Warnings
140    ///
141    /// - The choice of root from `sqrt` is unspecified.
142    /// - The value of $G_S$ is unspecified, and cannot be assumed to have any specific
143    ///   value in a generic context.
144    fn sqrt_ratio(num: &Self, div: &Self) -> (Choice, Self);
145
146    /// Equivalent to `Self::sqrt_ratio(self, one())`.
147    ///
148    /// The provided method is implemented in terms of [`Self::sqrt_ratio`].
149    fn sqrt_alt(&self) -> (Choice, Self) {
150        Self::sqrt_ratio(self, &Self::ONE)
151    }
152
153    /// Returns the square root of the field element, if it is
154    /// quadratic residue.
155    ///
156    /// The provided method is implemented in terms of [`Self::sqrt_ratio`].
157    fn sqrt(&self) -> CtOption<Self> {
158        let (is_square, res) = Self::sqrt_ratio(self, &Self::ONE);
159        CtOption::new(res, is_square)
160    }
161
162    /// Exponentiates `self` by `exp`, where `exp` is a little-endian order integer
163    /// exponent.
164    ///
165    /// # Guarantees
166    ///
167    /// This operation is constant time with respect to `self`, for all exponents with the
168    /// same number of digits (`exp.as_ref().len()`). It is variable time with respect to
169    /// the number of digits in the exponent.
170    fn pow<S: AsRef<[u64]>>(&self, exp: S) -> Self {
171        let mut res = Self::ONE;
172        for e in exp.as_ref().iter().rev() {
173            for i in (0..64).rev() {
174                res = res.square();
175                let mut tmp = res;
176                tmp *= self;
177                res.conditional_assign(&tmp, (((*e >> i) & 1) as u8).into());
178            }
179        }
180        res
181    }
182
183    /// Exponentiates `self` by `exp`, where `exp` is a little-endian order integer
184    /// exponent.
185    ///
186    /// # Guarantees
187    ///
188    /// **This operation is variable time with respect to `self`, for all exponent.** If
189    /// the exponent is fixed, this operation is effectively constant time. However, for
190    /// stronger constant-time guarantees, [`Field::pow`] should be used.
191    fn pow_vartime<S: AsRef<[u64]>>(&self, exp: S) -> Self {
192        let mut res = Self::ONE;
193        for e in exp.as_ref().iter().rev() {
194            for i in (0..64).rev() {
195                res = res.square();
196
197                if ((*e >> i) & 1) == 1 {
198                    res.mul_assign(self);
199                }
200            }
201        }
202
203        res
204    }
205}
206
207/// This represents an element of a non-binary prime field.
208pub trait PrimeField: Field + From<u64> {
209    /// The prime field can be converted back and forth into this binary
210    /// representation.
211    type Repr: Copy + Default + Send + Sync + 'static + AsRef<[u8]> + AsMut<[u8]>;
212
213    /// Interpret a string of numbers as a (congruent) prime field element.
214    /// Does not accept unnecessary leading zeroes or a blank string.
215    ///
216    /// # Security
217    ///
218    /// This method provides **no** constant-time guarantees.
219    fn from_str_vartime(s: &str) -> Option<Self> {
220        if s.is_empty() {
221            return None;
222        }
223
224        if s == "0" {
225            return Some(Self::ZERO);
226        }
227
228        let mut res = Self::ZERO;
229
230        let ten = Self::from(10);
231
232        let mut first_digit = true;
233
234        for c in s.chars() {
235            match c.to_digit(10) {
236                Some(c) => {
237                    if first_digit {
238                        if c == 0 {
239                            return None;
240                        }
241
242                        first_digit = false;
243                    }
244
245                    res.mul_assign(&ten);
246                    res.add_assign(&Self::from(u64::from(c)));
247                }
248                None => {
249                    return None;
250                }
251            }
252        }
253
254        Some(res)
255    }
256
257    /// Obtains a field element congruent to the integer `v`.
258    ///
259    /// For fields where `Self::CAPACITY >= 128`, this is injective and will produce a
260    /// unique field element.
261    ///
262    /// For fields where `Self::CAPACITY < 128`, this is surjective; some field elements
263    /// will be produced by multiple values of `v`.
264    ///
265    /// If you want to deterministically sample a field element representing a value, use
266    /// [`FromUniformBytes`] instead.
267    fn from_u128(v: u128) -> Self {
268        let lower = v as u64;
269        let upper = (v >> 64) as u64;
270        let mut tmp = Self::from(upper);
271        for _ in 0..64 {
272            tmp = tmp.double();
273        }
274        tmp + Self::from(lower)
275    }
276
277    /// Attempts to convert a byte representation of a field element into an element of
278    /// this prime field, failing if the input is not canonical (is not smaller than the
279    /// field's modulus).
280    ///
281    /// The byte representation is interpreted with the same endianness as elements
282    /// returned by [`PrimeField::to_repr`].
283    fn from_repr(repr: Self::Repr) -> CtOption<Self>;
284
285    /// Attempts to convert a byte representation of a field element into an element of
286    /// this prime field, failing if the input is not canonical (is not smaller than the
287    /// field's modulus).
288    ///
289    /// The byte representation is interpreted with the same endianness as elements
290    /// returned by [`PrimeField::to_repr`].
291    ///
292    /// # Security
293    ///
294    /// This method provides **no** constant-time guarantees. Implementors of the
295    /// `PrimeField` trait **may** optimise this method using non-constant-time logic.
296    fn from_repr_vartime(repr: Self::Repr) -> Option<Self> {
297        Self::from_repr(repr).into()
298    }
299
300    /// Converts an element of the prime field into the standard byte representation for
301    /// this field.
302    ///
303    /// The endianness of the byte representation is implementation-specific. Generic
304    /// encodings of field elements should be treated as opaque.
305    fn to_repr(&self) -> Self::Repr;
306
307    /// Returns true iff this element is odd.
308    fn is_odd(&self) -> Choice;
309
310    /// Returns true iff this element is even.
311    #[inline(always)]
312    fn is_even(&self) -> Choice {
313        !self.is_odd()
314    }
315
316    /// Modulus of the field written as a string for debugging purposes.
317    ///
318    /// The encoding of the modulus is implementation-specific. Generic users of the
319    /// `PrimeField` trait should treat this string as opaque.
320    const MODULUS: &'static str;
321
322    /// How many bits are needed to represent an element of this field.
323    const NUM_BITS: u32;
324
325    /// How many bits of information can be reliably stored in the field element.
326    ///
327    /// This is usually `Self::NUM_BITS - 1`.
328    const CAPACITY: u32;
329
330    /// Inverse of $2$ in the field.
331    const TWO_INV: Self;
332
333    /// A fixed multiplicative generator of `modulus - 1` order. This element must also be
334    /// a quadratic nonresidue.
335    ///
336    /// It can be calculated using [SageMath] as `GF(modulus).primitive_element()`.
337    ///
338    /// Implementations of this trait MUST ensure that this is the generator used to
339    /// derive `Self::ROOT_OF_UNITY`.
340    ///
341    /// [SageMath]: https://www.sagemath.org/
342    const MULTIPLICATIVE_GENERATOR: Self;
343
344    /// An integer `s` satisfying the equation `2^s * t = modulus - 1` with `t` odd.
345    ///
346    /// This is the number of leading zero bits in the little-endian bit representation of
347    /// `modulus - 1`.
348    const S: u32;
349
350    /// The `2^s` root of unity.
351    ///
352    /// It can be calculated by exponentiating `Self::MULTIPLICATIVE_GENERATOR` by `t`,
353    /// where `t = (modulus - 1) >> Self::S`.
354    const ROOT_OF_UNITY: Self;
355
356    /// Inverse of [`Self::ROOT_OF_UNITY`].
357    const ROOT_OF_UNITY_INV: Self;
358
359    /// Generator of the `t-order` multiplicative subgroup.
360    ///
361    /// It can be calculated by exponentiating [`Self::MULTIPLICATIVE_GENERATOR`] by `2^s`,
362    /// where `s` is [`Self::S`].
363    const DELTA: Self;
364}
365
366/// The subset of prime-order fields such that `(modulus - 1)` is divisible by `N`.
367///
368/// If `N` is prime, there will be `N - 1` valid choices of [`Self::ZETA`]. Similarly to
369/// [`PrimeField::MULTIPLICATIVE_GENERATOR`], the specific choice does not matter, as long
370/// as the choice is consistent across all uses of the field.
371pub trait WithSmallOrderMulGroup<const N: u8>: PrimeField {
372    /// A field element of small multiplicative order $N$.
373    ///
374    /// The presence of this element allows you to perform (certain types of)
375    /// endomorphisms on some elliptic curves.
376    ///
377    /// It can be calculated using [SageMath] as
378    /// `GF(modulus).primitive_element() ^ ((modulus - 1) // N)`.
379    /// Choosing the element of order $N$ that is smallest, when considered
380    /// as an integer, may help to ensure consistency.
381    ///
382    /// [SageMath]: https://www.sagemath.org/
383    const ZETA: Self;
384}
385
386/// Trait for constructing a [`PrimeField`] element from a fixed-length uniform byte
387/// array.
388///
389/// "Uniform" means that the byte array's contents must be indistinguishable from the
390/// [discrete uniform distribution]. Suitable byte arrays can be obtained:
391/// - from a cryptographically-secure randomness source (which makes this constructor
392///   equivalent to [`Field::random`]).
393/// - from a cryptographic hash function output, which enables a "random" field element to
394///   be selected deterministically. This is the primary use case for `FromUniformBytes`.
395///
396/// The length `N` of the byte array is chosen by the trait implementer such that the loss
397/// of uniformity in the mapping from byte arrays to field elements is cryptographically
398/// negligible.
399///
400/// [discrete uniform distribution]: https://en.wikipedia.org/wiki/Discrete_uniform_distribution
401///
402/// # Examples
403///
404/// ```
405/// # #[cfg(feature = "derive")] {
406/// # // Fake this so we don't actually need a dev-dependency on bls12_381.
407/// # mod bls12_381 {
408/// #     use rustcrypto_ff::{Field, PrimeField};
409/// #
410/// #     #[derive(PrimeField)]
411/// #     #[PrimeFieldModulus = "52435875175126190479447740508185965837690552500527637822603658699938581184513"]
412/// #     #[PrimeFieldGenerator = "7"]
413/// #     #[PrimeFieldReprEndianness = "little"]
414/// #     pub struct Scalar([u64; 4]);
415/// #
416/// #     impl rustcrypto_ff::FromUniformBytes<64> for Scalar {
417/// #         fn from_uniform_bytes(_bytes: &[u8; 64]) -> Self {
418/// #             // Fake impl for doctest
419/// #             Scalar::ONE
420/// #         }
421/// #     }
422/// # }
423/// #
424/// use blake2b_simd::blake2b;
425/// use bls12_381::Scalar;
426/// use rustcrypto_ff::FromUniformBytes;
427///
428/// // `bls12_381::Scalar` implements `FromUniformBytes<64>`, and BLAKE2b (by default)
429/// // produces a 64-byte hash.
430/// let hash = blake2b(b"Some message");
431/// let val = Scalar::from_uniform_bytes(hash.as_array());
432/// # }
433/// ```
434///
435/// # Implementing `FromUniformBytes`
436///
437/// [`Self::from_uniform_bytes`] should always be implemented by interpreting the provided
438/// byte array as the little endian unsigned encoding of an integer, and then reducing that
439/// integer modulo the field modulus.
440///
441/// For security, `N` must be chosen so that `N * 8 >= Self::NUM_BITS + 128`. A larger
442/// value of `N` may be chosen for convenience; for example, for a field with a 255-bit
443/// modulus, `N = 64` is convenient as it matches the output length of several common
444/// cryptographic hash functions (such as SHA-512 and BLAKE2b).
445///
446/// ## Trait design
447///
448/// This trait exists because `PrimeField::from_uniform_bytes([u8; N])` cannot currently
449/// exist (trait methods cannot use associated constants in the const positions of their
450/// type signature, and we do not want `PrimeField` to require a generic const parameter).
451/// However, this has the side-effect that `FromUniformBytes` can be implemented multiple
452/// times for different values of `N`. Most implementations of [`PrimeField`] should only
453/// need to implement `FromUniformBytes` trait for one value of `N` (chosen following the
454/// above considerations); if you find yourself needing to implement it multiple times,
455/// please [let us know about your use case](https://github.com/zkcrypto/ff/issues/new) so
456/// we can take it into consideration for future evolutions of the `ff` traits.
457pub trait FromUniformBytes<const N: usize>: PrimeField {
458    /// Returns a field element that is congruent to the provided little endian unsigned
459    /// byte representation of an integer.
460    fn from_uniform_bytes(bytes: &[u8; N]) -> Self;
461}
462
463/// This represents the bits of an element of a prime field.
464#[cfg(feature = "bits")]
465#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
466pub trait PrimeFieldBits: PrimeField {
467    /// The backing store for a bit representation of a prime field element.
468    type ReprBits: BitViewSized + Send + Sync;
469
470    /// Converts an element of the prime field into a little-endian sequence of bits.
471    fn to_le_bits(&self) -> FieldBits<Self::ReprBits>;
472
473    /// Returns the bits of the field characteristic (the modulus) in little-endian order.
474    fn char_le_bits() -> FieldBits<Self::ReprBits>;
475}
476
477/// Functions and re-exported crates used by the [`PrimeField`] derive macro.
478#[cfg(feature = "derive")]
479#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
480pub mod derive {
481    pub use crate::arith_impl::*;
482
483    pub use {byteorder, rand_core, subtle};
484
485    #[cfg(feature = "bits")]
486    pub use bitvec;
487}
488
489#[cfg(feature = "derive")]
490mod arith_impl {
491    /// Computes `a - (b + borrow)`, returning the result and the new borrow.
492    #[inline(always)]
493    pub const fn sbb(a: u64, b: u64, borrow: u64) -> (u64, u64) {
494        let ret = (a as u128).wrapping_sub((b as u128) + ((borrow >> 63) as u128));
495        (ret as u64, (ret >> 64) as u64)
496    }
497
498    /// Computes `a + b + carry`, returning the result and the new carry over.
499    #[inline(always)]
500    pub const fn adc(a: u64, b: u64, carry: u64) -> (u64, u64) {
501        let ret = (a as u128) + (b as u128) + (carry as u128);
502        (ret as u64, (ret >> 64) as u64)
503    }
504
505    /// Computes `a + (b * c) + carry`, returning the result and the new carry over.
506    #[inline(always)]
507    pub const fn mac(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) {
508        let ret = (a as u128) + ((b as u128) * (c as u128)) + (carry as u128);
509        (ret as u64, (ret >> 64) as u64)
510    }
511}