Skip to main content

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