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
15#[cfg(feature = "derive")]
16#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
17pub use ff_derive::PrimeField;
18
19#[cfg(feature = "bits")]
20#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
21pub use bitvec::view::BitViewSized;
22
23#[cfg(feature = "bits")]
24use bitvec::{array::BitArray, order::Lsb0};
25use core::fmt;
26use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
27use rand_core::RngCore;
28use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
29
30/// Bit representation of a field element.
31#[cfg(feature = "bits")]
32#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
33pub type FieldBits<V> = BitArray<V, Lsb0>;
34
35/// This trait represents an element of a field.
36pub trait Field:
37    Sized
38    + Eq
39    + Copy
40    + Clone
41    + Default
42    + Send
43    + Sync
44    + fmt::Debug
45    + 'static
46    + ConditionallySelectable
47    + ConstantTimeEq
48    + Add<Output = Self>
49    + Sub<Output = Self>
50    + Mul<Output = Self>
51    + Neg<Output = Self>
52    + for<'a> Add<&'a Self, Output = Self>
53    + for<'a> Mul<&'a Self, Output = Self>
54    + for<'a> Sub<&'a Self, Output = Self>
55    + MulAssign
56    + AddAssign
57    + SubAssign
58    + for<'a> MulAssign<&'a Self>
59    + for<'a> AddAssign<&'a Self>
60    + for<'a> SubAssign<&'a Self>
61{
62    /// Returns an element chosen uniformly at random using a user-provided RNG.
63    fn random(rng: impl RngCore) -> Self;
64
65    /// Returns the zero element of the field, the additive identity.
66    fn zero() -> Self;
67
68    /// Returns the one element of the field, the multiplicative identity.
69    fn one() -> Self;
70
71    /// Returns true iff this element is zero.
72    fn is_zero(&self) -> Choice {
73        self.ct_eq(&Self::zero())
74    }
75
76    /// Returns true iff this element is zero.
77    ///
78    /// # Security
79    ///
80    /// This method provides **no** constant-time guarantees. Implementors of the
81    /// `Field` trait **may** optimise this method using non-constant-time logic.
82    fn is_zero_vartime(&self) -> bool {
83        self.is_zero().into()
84    }
85
86    /// Squares this element.
87    #[must_use]
88    fn square(&self) -> Self;
89
90    /// Cubes this element.
91    #[must_use]
92    fn cube(&self) -> Self {
93        self.square() * self
94    }
95
96    /// Doubles this element.
97    #[must_use]
98    fn double(&self) -> Self;
99
100    /// Computes the multiplicative inverse of this element,
101    /// failing if the element is zero.
102    fn invert(&self) -> CtOption<Self>;
103
104    /// Returns the square root of the field element, if it is
105    /// quadratic residue.
106    fn sqrt(&self) -> CtOption<Self>;
107
108    /// Exponentiates `self` by `exp`, where `exp` is a little-endian order
109    /// integer exponent.
110    ///
111    /// **This operation is variable time with respect to the exponent.** If the
112    /// exponent is fixed, this operation is effectively constant time.
113    fn pow_vartime<S: AsRef<[u64]>>(&self, exp: S) -> Self {
114        let mut res = Self::one();
115        for e in exp.as_ref().iter().rev() {
116            for i in (0..64).rev() {
117                res = res.square();
118
119                if ((*e >> i) & 1) == 1 {
120                    res.mul_assign(self);
121                }
122            }
123        }
124
125        res
126    }
127}
128
129/// This represents an element of a prime field.
130pub trait PrimeField: Field + From<u64> {
131    /// The prime field can be converted back and forth into this binary
132    /// representation.
133    type Repr: Copy + Default + Send + Sync + 'static + AsRef<[u8]> + AsMut<[u8]>;
134
135    /// Interpret a string of numbers as a (congruent) prime field element.
136    /// Does not accept unnecessary leading zeroes or a blank string.
137    ///
138    /// # Security
139    ///
140    /// This method provides **no** constant-time guarantees.
141    fn from_str_vartime(s: &str) -> Option<Self> {
142        if s.is_empty() {
143            return None;
144        }
145
146        if s == "0" {
147            return Some(Self::zero());
148        }
149
150        let mut res = Self::zero();
151
152        let ten = Self::from(10);
153
154        let mut first_digit = true;
155
156        for c in s.chars() {
157            match c.to_digit(10) {
158                Some(c) => {
159                    if first_digit {
160                        if c == 0 {
161                            return None;
162                        }
163
164                        first_digit = false;
165                    }
166
167                    res.mul_assign(&ten);
168                    res.add_assign(&Self::from(u64::from(c)));
169                }
170                None => {
171                    return None;
172                }
173            }
174        }
175
176        Some(res)
177    }
178
179    /// Attempts to convert a byte representation of a field element into an element of
180    /// this prime field, failing if the input is not canonical (is not smaller than the
181    /// field's modulus).
182    ///
183    /// The byte representation is interpreted with the same endianness as elements
184    /// returned by [`PrimeField::to_repr`].
185    fn from_repr(repr: Self::Repr) -> CtOption<Self>;
186
187    /// Attempts to convert a byte representation of a field element into an element of
188    /// this prime field, failing if the input is not canonical (is not smaller than the
189    /// field's modulus).
190    ///
191    /// The byte representation is interpreted with the same endianness as elements
192    /// returned by [`PrimeField::to_repr`].
193    ///
194    /// # Security
195    ///
196    /// This method provides **no** constant-time guarantees. Implementors of the
197    /// `PrimeField` trait **may** optimise this method using non-constant-time logic.
198    fn from_repr_vartime(repr: Self::Repr) -> Option<Self> {
199        Self::from_repr(repr).into()
200    }
201
202    /// Converts an element of the prime field into the standard byte representation for
203    /// this field.
204    ///
205    /// The endianness of the byte representation is implementation-specific. Generic
206    /// encodings of field elements should be treated as opaque.
207    fn to_repr(&self) -> Self::Repr;
208
209    /// Returns true iff this element is odd.
210    fn is_odd(&self) -> Choice;
211
212    /// Returns true iff this element is even.
213    #[inline(always)]
214    fn is_even(&self) -> Choice {
215        !self.is_odd()
216    }
217
218    /// How many bits are needed to represent an element of this field.
219    const NUM_BITS: u32;
220
221    /// How many bits of information can be reliably stored in the field element.
222    ///
223    /// This is usually `Self::NUM_BITS - 1`.
224    const CAPACITY: u32;
225
226    /// Returns a fixed multiplicative generator of `modulus - 1` order. This element must
227    /// also be a quadratic nonresidue.
228    ///
229    /// It can be calculated using [SageMath] as `GF(modulus).primitive_element()`.
230    ///
231    /// Implementations of this method MUST ensure that this is the generator used to
232    /// derive `Self::root_of_unity`.
233    ///
234    /// [SageMath]: https://www.sagemath.org/
235    fn multiplicative_generator() -> Self;
236
237    /// An integer `s` satisfying the equation `2^s * t = modulus - 1` with `t` odd.
238    ///
239    /// This is the number of leading zero bits in the little-endian bit representation of
240    /// `modulus - 1`.
241    const S: u32;
242
243    /// Returns the `2^s` root of unity.
244    ///
245    /// It can be calculated by exponentiating `Self::multiplicative_generator` by `t`,
246    /// where `t = (modulus - 1) >> Self::S`.
247    fn root_of_unity() -> Self;
248}
249
250/// This represents the bits of an element of a prime field.
251#[cfg(feature = "bits")]
252#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
253pub trait PrimeFieldBits: PrimeField {
254    /// The backing store for a bit representation of a prime field element.
255    type ReprBits: BitViewSized + Send + Sync;
256
257    /// Converts an element of the prime field into a little-endian sequence of bits.
258    fn to_le_bits(&self) -> FieldBits<Self::ReprBits>;
259
260    /// Returns the bits of the field characteristic (the modulus) in little-endian order.
261    fn char_le_bits() -> FieldBits<Self::ReprBits>;
262}
263
264/// Functions and re-exported crates used by the [`PrimeField`] derive macro.
265#[cfg(feature = "derive")]
266#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
267pub mod derive {
268    pub use crate::arith_impl::*;
269
270    pub use {byteorder, rand_core, subtle};
271
272    #[cfg(feature = "bits")]
273    pub use bitvec;
274}
275
276#[cfg(feature = "derive")]
277mod arith_impl {
278    /// Computes `a - (b + borrow)`, returning the result and the new borrow.
279    #[inline(always)]
280    pub const fn sbb(a: u64, b: u64, borrow: u64) -> (u64, u64) {
281        let ret = (a as u128).wrapping_sub((b as u128) + ((borrow >> 63) as u128));
282        (ret as u64, (ret >> 64) as u64)
283    }
284
285    /// Computes `a + b + carry`, returning the result and the new carry over.
286    #[inline(always)]
287    pub const fn adc(a: u64, b: u64, carry: u64) -> (u64, u64) {
288        let ret = (a as u128) + (b as u128) + (carry as u128);
289        (ret as u64, (ret >> 64) as u64)
290    }
291
292    /// Computes `a + (b * c) + carry`, returning the result and the new carry over.
293    #[inline(always)]
294    pub const fn mac(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) {
295        let ret = (a as u128) + ((b as u128) * (c as u128)) + (carry as u128);
296        (ret as u64, (ret >> 64) as u64)
297    }
298}