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