ff/
lib.rs

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