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::{Rng, TryRng};
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: Rng + ?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: TryRng + ?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 /// Convert an element of the prime field into a little endian byte representation.
308 ///
309 /// The provided implementation assumes [`PrimeField::to_repr`] returns a little endian
310 /// representation and needs to be overridden if it uses big endian.
311 // TODO(tarcieri): this is largely a hack to make `group::Wnaf` work. Ideally it could go away.
312 fn to_le_repr(&self) -> Self::Repr {
313 self.to_repr()
314 }
315
316 /// Returns true iff this element is odd.
317 fn is_odd(&self) -> Choice;
318
319 /// Returns true iff this element is even.
320 #[inline(always)]
321 fn is_even(&self) -> Choice {
322 !self.is_odd()
323 }
324
325 /// Modulus of the field written as a string for debugging purposes.
326 ///
327 /// The encoding of the modulus is implementation-specific. Generic users of the
328 /// `PrimeField` trait should treat this string as opaque.
329 const MODULUS: &'static str;
330
331 /// How many bits are needed to represent an element of this field.
332 const NUM_BITS: u32;
333
334 /// How many bits of information can be reliably stored in the field element.
335 ///
336 /// This is usually `Self::NUM_BITS - 1`.
337 const CAPACITY: u32;
338
339 /// Inverse of $2$ in the field.
340 const TWO_INV: Self;
341
342 /// A fixed multiplicative generator of `modulus - 1` order. This element must also be
343 /// a quadratic nonresidue.
344 ///
345 /// It can be calculated using [SageMath] as `GF(modulus).primitive_element()`.
346 ///
347 /// Implementations of this trait MUST ensure that this is the generator used to
348 /// derive `Self::ROOT_OF_UNITY`.
349 ///
350 /// [SageMath]: https://www.sagemath.org/
351 const MULTIPLICATIVE_GENERATOR: Self;
352
353 /// An integer `s` satisfying the equation `2^s * t = modulus - 1` with `t` odd.
354 ///
355 /// This is the number of leading zero bits in the little-endian bit representation of
356 /// `modulus - 1`.
357 const S: u32;
358
359 /// The `2^s` root of unity.
360 ///
361 /// It can be calculated by exponentiating `Self::MULTIPLICATIVE_GENERATOR` by `t`,
362 /// where `t = (modulus - 1) >> Self::S`.
363 const ROOT_OF_UNITY: Self;
364
365 /// Inverse of [`Self::ROOT_OF_UNITY`].
366 const ROOT_OF_UNITY_INV: Self;
367
368 /// Generator of the `t-order` multiplicative subgroup.
369 ///
370 /// It can be calculated by exponentiating [`Self::MULTIPLICATIVE_GENERATOR`] by `2^s`,
371 /// where `s` is [`Self::S`].
372 const DELTA: Self;
373}
374
375/// The subset of prime-order fields such that `(modulus - 1)` is divisible by `N`.
376///
377/// If `N` is prime, there will be `N - 1` valid choices of [`Self::ZETA`]. Similarly to
378/// [`PrimeField::MULTIPLICATIVE_GENERATOR`], the specific choice does not matter, as long
379/// as the choice is consistent across all uses of the field.
380pub trait WithSmallOrderMulGroup<const N: u8>: PrimeField {
381 /// A field element of small multiplicative order $N$.
382 ///
383 /// The presence of this element allows you to perform (certain types of)
384 /// endomorphisms on some elliptic curves.
385 ///
386 /// It can be calculated using [SageMath] as
387 /// `GF(modulus).primitive_element() ^ ((modulus - 1) // N)`.
388 /// Choosing the element of order $N$ that is smallest, when considered
389 /// as an integer, may help to ensure consistency.
390 ///
391 /// [SageMath]: https://www.sagemath.org/
392 const ZETA: Self;
393}
394
395/// Trait for constructing a [`PrimeField`] element from a fixed-length uniform byte
396/// array.
397///
398/// "Uniform" means that the byte array's contents must be indistinguishable from the
399/// [discrete uniform distribution]. Suitable byte arrays can be obtained:
400/// - from a cryptographically-secure randomness source (which makes this constructor
401/// equivalent to [`Field::random`]).
402/// - from a cryptographic hash function output, which enables a "random" field element to
403/// be selected deterministically. This is the primary use case for `FromUniformBytes`.
404///
405/// The length `N` of the byte array is chosen by the trait implementer such that the loss
406/// of uniformity in the mapping from byte arrays to field elements is cryptographically
407/// negligible.
408///
409/// [discrete uniform distribution]: https://en.wikipedia.org/wiki/Discrete_uniform_distribution
410///
411/// # Examples
412///
413/// ```
414/// # #[cfg(feature = "derive")] {
415/// # // Fake this so we don't actually need a dev-dependency on bls12_381.
416/// # mod bls12_381 {
417/// # use rustcrypto_ff::{Field, PrimeField};
418/// #
419/// # #[derive(PrimeField)]
420/// # #[PrimeFieldModulus = "52435875175126190479447740508185965837690552500527637822603658699938581184513"]
421/// # #[PrimeFieldGenerator = "7"]
422/// # #[PrimeFieldReprEndianness = "little"]
423/// # pub struct Scalar([u64; 4]);
424/// #
425/// # impl rustcrypto_ff::FromUniformBytes<64> for Scalar {
426/// # fn from_uniform_bytes(_bytes: &[u8; 64]) -> Self {
427/// # // Fake impl for doctest
428/// # Scalar::ONE
429/// # }
430/// # }
431/// # }
432/// #
433/// use blake2b_simd::blake2b;
434/// use bls12_381::Scalar;
435/// use rustcrypto_ff::FromUniformBytes;
436///
437/// // `bls12_381::Scalar` implements `FromUniformBytes<64>`, and BLAKE2b (by default)
438/// // produces a 64-byte hash.
439/// let hash = blake2b(b"Some message");
440/// let val = Scalar::from_uniform_bytes(hash.as_array());
441/// # }
442/// ```
443///
444/// # Implementing `FromUniformBytes`
445///
446/// [`Self::from_uniform_bytes`] should always be implemented by interpreting the provided
447/// byte array as the little endian unsigned encoding of an integer, and then reducing that
448/// integer modulo the field modulus.
449///
450/// For security, `N` must be chosen so that `N * 8 >= Self::NUM_BITS + 128`. A larger
451/// value of `N` may be chosen for convenience; for example, for a field with a 255-bit
452/// modulus, `N = 64` is convenient as it matches the output length of several common
453/// cryptographic hash functions (such as SHA-512 and BLAKE2b).
454///
455/// ## Trait design
456///
457/// This trait exists because `PrimeField::from_uniform_bytes([u8; N])` cannot currently
458/// exist (trait methods cannot use associated constants in the const positions of their
459/// type signature, and we do not want `PrimeField` to require a generic const parameter).
460/// However, this has the side-effect that `FromUniformBytes` can be implemented multiple
461/// times for different values of `N`. Most implementations of [`PrimeField`] should only
462/// need to implement `FromUniformBytes` trait for one value of `N` (chosen following the
463/// above considerations); if you find yourself needing to implement it multiple times,
464/// please [let us know about your use case](https://github.com/zkcrypto/ff/issues/new) so
465/// we can take it into consideration for future evolutions of the `ff` traits.
466pub trait FromUniformBytes<const N: usize>: PrimeField {
467 /// Returns a field element that is congruent to the provided little endian unsigned
468 /// byte representation of an integer.
469 fn from_uniform_bytes(bytes: &[u8; N]) -> Self;
470}
471
472/// This represents the bits of an element of a prime field.
473#[cfg(feature = "bits")]
474#[cfg_attr(docsrs, doc(cfg(feature = "bits")))]
475pub trait PrimeFieldBits: PrimeField {
476 /// The backing store for a bit representation of a prime field element.
477 type ReprBits: BitViewSized + Send + Sync;
478
479 /// Converts an element of the prime field into a little-endian sequence of bits.
480 fn to_le_bits(&self) -> FieldBits<Self::ReprBits>;
481
482 /// Returns the bits of the field characteristic (the modulus) in little-endian order.
483 fn char_le_bits() -> FieldBits<Self::ReprBits>;
484}
485
486/// Functions and re-exported crates used by the [`PrimeField`] derive macro.
487#[cfg(feature = "derive")]
488#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
489pub mod derive {
490 pub use crate::arith_impl::*;
491
492 pub use {byteorder, rand_core, subtle};
493
494 #[cfg(feature = "bits")]
495 pub use bitvec;
496}
497
498#[cfg(feature = "derive")]
499mod arith_impl {
500 /// Computes `a - (b + borrow)`, returning the result and the new borrow.
501 #[inline(always)]
502 pub const fn sbb(a: u64, b: u64, borrow: u64) -> (u64, u64) {
503 let ret = (a as u128).wrapping_sub((b as u128) + ((borrow >> 63) as u128));
504 (ret as u64, (ret >> 64) as u64)
505 }
506
507 /// Computes `a + b + carry`, returning the result and the new carry over.
508 #[inline(always)]
509 pub const fn adc(a: u64, b: u64, carry: u64) -> (u64, u64) {
510 let ret = (a as u128) + (b as u128) + (carry as u128);
511 (ret as u64, (ret >> 64) as u64)
512 }
513
514 /// Computes `a + (b * c) + carry`, returning the result and the new carry over.
515 #[inline(always)]
516 pub const fn mac(a: u64, b: u64, c: u64, carry: u64) -> (u64, u64) {
517 let ret = (a as u128) + ((b as u128) * (c as u128)) + (carry as u128);
518 (ret as u64, (ret >> 64) as u64)
519 }
520}