prio/
field.rs

1// Copyright (c) 2020 Apple Inc.
2// SPDX-License-Identifier: MPL-2.0
3
4//! Finite field arithmetic.
5//!
6//! Basic field arithmetic is captured in the [`FieldElement`] trait. Fields used in Prio implement
7//! [`FftFriendlyFieldElement`], and have an associated element called the "generator" that
8//! generates a multiplicative subgroup of order `2^n` for some `n`.
9
10use crate::{
11    codec::{CodecError, Decode, Encode},
12    fp::{FieldOps, FieldParameters, FP128, FP32, FP64},
13    prng::{Prng, PrngError},
14};
15use rand::{
16    distributions::{Distribution, Standard},
17    Rng,
18};
19use rand_core::RngCore;
20use serde::{
21    de::{DeserializeOwned, Visitor},
22    Deserialize, Deserializer, Serialize, Serializer,
23};
24use std::{
25    cmp::min,
26    convert::{TryFrom, TryInto},
27    fmt::{self, Debug, Display, Formatter},
28    hash::{Hash, Hasher},
29    io::{Cursor, Read},
30    marker::PhantomData,
31    ops::{
32        Add, AddAssign, BitAnd, ControlFlow, Div, DivAssign, Mul, MulAssign, Neg, Range, Shl, Shr,
33        Sub, SubAssign,
34    },
35};
36use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable, ConstantTimeEq};
37
38#[cfg(feature = "experimental")]
39mod field255;
40
41#[cfg(feature = "experimental")]
42pub use field255::Field255;
43
44/// Possible errors from finite field operations.
45#[derive(Debug, thiserror::Error)]
46#[non_exhaustive]
47pub enum FieldError {
48    /// Input sizes do not match.
49    #[error("input sizes do not match")]
50    InputSizeMismatch,
51    /// Returned when decoding a [`FieldElement`] from a too-short byte string.
52    #[error("short read from bytes")]
53    ShortRead,
54    /// Returned when converting an integer to a [`FieldElement`] if the integer is greater than or
55    /// equal to the field modulus.
56    #[error("input value exceeds modulus")]
57    ModulusOverflow,
58    /// Error while performing I/O.
59    #[error("I/O error")]
60    Io(#[from] std::io::Error),
61    /// Error encoding or decoding a field.
62    #[error("Codec error")]
63    #[deprecated]
64    Codec(CodecError),
65    /// Error converting to [`FieldElementWithInteger::Integer`].
66    #[error("Integer TryFrom error")]
67    IntegerTryFrom,
68    /// Returned when encoding an integer to "bitvector representation", or decoding from the same,
69    /// if the number of bits is larger than the bit length of the field's modulus.
70    #[error("bit vector length exceeds modulus bit length")]
71    BitVectorTooLong,
72}
73
74/// Objects with this trait represent an element of `GF(p)` for some prime `p`.
75pub trait FieldElement:
76    Sized
77    + Debug
78    + Copy
79    + PartialEq
80    + Eq
81    + ConstantTimeEq
82    + ConditionallySelectable
83    + ConditionallyNegatable
84    + Add<Output = Self>
85    + AddAssign
86    + Sub<Output = Self>
87    + SubAssign
88    + Mul<Output = Self>
89    + MulAssign
90    + Div<Output = Self>
91    + DivAssign
92    + Neg<Output = Self>
93    + Display
94    + for<'a> TryFrom<&'a [u8], Error = FieldError>
95    // NOTE Ideally we would require `Into<[u8; Self::ENCODED_SIZE]>` instead of `Into<Vec<u8>>`,
96    // since the former avoids a heap allocation and can easily be converted into Vec<u8>, but that
97    // isn't possible yet[1]. However we can provide the impl on FieldElement implementations.
98    // [1]: https://github.com/rust-lang/rust/issues/60551
99    + Into<Vec<u8>>
100    + Serialize
101    + DeserializeOwned
102    + Encode
103    + Decode
104    + 'static // NOTE This bound is needed for downcasting a `dyn Gadget<F>>` to a concrete type.
105{
106    /// Size in bytes of an encoded field element.
107    const ENCODED_SIZE: usize;
108
109    /// Modular inversion, i.e., `self^-1 (mod p)`. If `self` is 0, then the output is undefined.
110    fn inv(&self) -> Self;
111
112    /// Returns 1/2.
113    fn half() -> Self;
114
115    /// Interprets the next [`Self::ENCODED_SIZE`] bytes from the input slice as an element of the
116    /// field. Any of the most significant bits beyond the bit length of the modulus will be
117    /// cleared, in order to minimize the amount of rejection sampling needed.
118    ///
119    /// # Errors
120    ///
121    /// An error is returned if the provided slice is too small to encode a field element or if the
122    /// result encodes an integer larger than or equal to the field modulus.
123    ///
124    /// # Warnings
125    ///
126    /// This function should only be used internally to convert a random byte string into
127    /// a field element. Use [`Decode::decode`] to deserialize field elements. Use
128    /// [`random_vector`] to randomly generate field elements.
129    #[doc(hidden)]
130    fn try_from_random(bytes: &[u8]) -> Result<Self, FieldError>;
131
132    /// Returns the additive identity.
133    fn zero() -> Self;
134
135    /// Returns the multiplicative identity.
136    fn one() -> Self;
137
138    /// Convert a slice of field elements into a vector of bytes.
139    ///
140    /// # Notes
141    ///
142    /// Ideally we would implement `From<&[F: FieldElement]> for Vec<u8>` or the corresponding
143    /// `Into`, but the orphan rule and the stdlib's blanket implementations of `Into` make this
144    /// impossible.
145    #[deprecated]
146    fn slice_into_byte_vec(values: &[Self]) -> Vec<u8> {
147        let mut vec = Vec::with_capacity(values.len() * Self::ENCODED_SIZE);
148        encode_fieldvec(values, &mut vec).unwrap();
149        vec
150    }
151
152    /// Convert a slice of bytes into a vector of field elements. The slice is interpreted as a
153    /// sequence of [`Self::ENCODED_SIZE`]-byte sequences.
154    ///
155    /// # Errors
156    ///
157    /// Returns an error if the length of the provided byte slice is not a multiple of the size of a
158    /// field element, or if any of the values in the byte slice are invalid encodings of a field
159    /// element, because the encoded integer is larger than or equal to the field modulus.
160    ///
161    /// # Notes
162    ///
163    /// Ideally we would implement `From<&[u8]> for Vec<F: FieldElement>` or the corresponding
164    /// `Into`, but the orphan rule and the stdlib's blanket implementations of `Into` make this
165    /// impossible.
166    #[deprecated]
167    fn byte_slice_into_vec(bytes: &[u8]) -> Result<Vec<Self>, FieldError> {
168        if bytes.len() % Self::ENCODED_SIZE != 0 {
169            return Err(FieldError::ShortRead);
170        }
171        let mut vec = Vec::with_capacity(bytes.len() / Self::ENCODED_SIZE);
172        for chunk in bytes.chunks_exact(Self::ENCODED_SIZE) {
173            #[allow(deprecated)]
174            vec.push(Self::get_decoded(chunk).map_err(FieldError::Codec)?);
175        }
176        Ok(vec)
177    }
178}
179
180/// An integer type that accompanies a finite field. Integers and field elements may be converted
181/// back and forth via the natural map between residue classes modulo 'p' and integers between 0
182/// and p - 1.
183pub trait Integer:
184    Debug
185    + Eq
186    + Ord
187    + BitAnd<Output = Self>
188    + Div<Output = Self>
189    + Shl<usize, Output = Self>
190    + Shr<usize, Output = Self>
191    + Add<Output = Self>
192    + Sub<Output = Self>
193    + TryFrom<usize, Error = Self::TryFromUsizeError>
194    + TryInto<u64, Error = Self::TryIntoU64Error>
195{
196    /// The error returned if converting `usize` to this integer type fails.
197    type TryFromUsizeError: std::error::Error;
198
199    /// The error returned if converting this integer type to a `u64` fails.
200    type TryIntoU64Error: std::error::Error;
201
202    /// Returns zero.
203    fn zero() -> Self;
204
205    /// Returns one.
206    fn one() -> Self;
207}
208
209/// Extension trait for field elements that can be converted back and forth to an integer type.
210///
211/// The `Integer` associated type is an integer (primitive or otherwise) that supports various
212/// arithmetic operations. The order of the field is guaranteed to fit inside the range of the
213/// integer type. This trait also defines methods on field elements, `pow` and `modulus`, that make
214/// use of the associated integer type.
215pub trait FieldElementWithInteger: FieldElement + From<Self::Integer> {
216    /// The integer representation of a field element.
217    type Integer: Integer + From<Self> + Copy;
218
219    /// Modular exponentation, i.e., `self^exp (mod p)`.
220    fn pow(&self, exp: Self::Integer) -> Self;
221
222    /// Returns the prime modulus `p`.
223    fn modulus() -> Self::Integer;
224    /// Encode the integer `input` as a sequence of bits in two's complement representation, least
225    /// significant bit first, and then map each bit to a field element.
226    ///
227    /// Returns an error if `input` cannot be represented with `bits` many bits, or if `bits`
228    /// is larger than the bit width of the field's modulus.
229    fn encode_as_bitvector(
230        input: Self::Integer,
231        bits: usize,
232    ) -> Result<BitvectorRepresentationIter<Self>, FieldError> {
233        // Check if `bits` is too large for this field.
234        if !Self::valid_integer_bitlength(bits) {
235            return Err(FieldError::BitVectorTooLong);
236        }
237
238        // Check if the input value can be represented in the requested number of bits by shifting
239        // it. The above check on `bits` ensures this shift won't panic due to the shift width
240        // being too large.
241        if input >> bits != Self::Integer::zero() {
242            return Err(FieldError::InputSizeMismatch);
243        }
244
245        Ok(BitvectorRepresentationIter {
246            inner: 0..bits,
247            input,
248        })
249    }
250
251    /// Inverts the encoding done by [`Self::encode_as_bitvector`], and returns a single field
252    /// element.
253    ///
254    /// This performs an inner product between the input vector of field elements and successive
255    /// powers of two (starting with 2^0 = 1). If the input came from [`Self::encode_as_bitvector`],
256    /// then the result will be equal to the originally encoded integer, projected into the field.
257    ///
258    /// Note that this decoding operation is linear, so it can be applied to secret shares of an
259    /// encoded integer, and if the results are summed up, it will be equal to the encoded integer.
260    ///
261    /// Returns an error if the length of the input is larger than the bit width of the field's
262    /// modulus.
263    fn decode_bitvector(input: &[Self]) -> Result<Self, FieldError> {
264        if !Self::valid_integer_bitlength(input.len()) {
265            return Err(FieldError::BitVectorTooLong);
266        }
267
268        let mut decoded = Self::zero();
269        let one = Self::one();
270        let two = one + one;
271        let mut power_of_two = one;
272        for value in input.iter() {
273            decoded += *value * power_of_two;
274            power_of_two *= two;
275        }
276        Ok(decoded)
277    }
278}
279
280/// This iterator returns a sequence of field elements that are equal to zero or one, representing
281/// some integer in two's complement form. See [`FieldElementWithInteger::encode_as_bitvector`].
282// Note that this is implemented with a separate struct, instead of using the map combinator,
283// because return_position_impl_trait_in_trait is not yet stable.
284#[derive(Debug, Clone)]
285pub struct BitvectorRepresentationIter<F: FieldElementWithInteger> {
286    inner: Range<usize>,
287    input: F::Integer,
288}
289
290impl<F> Iterator for BitvectorRepresentationIter<F>
291where
292    F: FieldElementWithInteger,
293{
294    type Item = F;
295
296    #[inline]
297    fn next(&mut self) -> Option<Self::Item> {
298        let bit_offset = self.inner.next()?;
299        Some(F::from((self.input >> bit_offset) & F::Integer::one()))
300    }
301}
302
303/// Methods common to all `FieldElementWithInteger` implementations that are private to the crate.
304pub(crate) trait FieldElementWithIntegerExt: FieldElementWithInteger {
305    /// Interpret `i` as [`FieldElementWithInteger::Integer`] if it's representable in that type and
306    /// smaller than the field modulus.
307    fn valid_integer_try_from<N>(i: N) -> Result<Self::Integer, FieldError>
308    where
309        Self::Integer: TryFrom<N>,
310    {
311        let i_int = Self::Integer::try_from(i).map_err(|_| FieldError::IntegerTryFrom)?;
312        if Self::modulus() <= i_int {
313            return Err(FieldError::ModulusOverflow);
314        }
315        Ok(i_int)
316    }
317
318    /// Check if the largest number representable with `bits` bits (i.e. 2^bits - 1) is
319    /// representable in this field.
320    fn valid_integer_bitlength(bits: usize) -> bool {
321        if bits >= 8 * Self::ENCODED_SIZE {
322            return false;
323        }
324        if Self::modulus() >> bits != Self::Integer::zero() {
325            return true;
326        }
327        false
328    }
329}
330
331impl<F: FieldElementWithInteger> FieldElementWithIntegerExt for F {}
332
333/// Methods common to all `FieldElement` implementations that are private to the crate.
334pub(crate) trait FieldElementExt: FieldElement {
335    /// Try to interpret a slice of [`FieldElement::ENCODED_SIZE`] random bytes as an element in the
336    /// field. If the input represents an integer greater than or equal to the field modulus, then
337    /// [`ControlFlow::Continue`] is returned instead, to indicate that an enclosing rejection
338    /// sampling loop should try again with different random bytes.
339    ///
340    /// # Panics
341    ///
342    /// Panics if `bytes` is not of length [`FieldElement::ENCODED_SIZE`].
343    fn from_random_rejection(bytes: &[u8]) -> ControlFlow<Self, ()> {
344        match Self::try_from_random(bytes) {
345            Ok(x) => ControlFlow::Break(x),
346            Err(FieldError::ModulusOverflow) => ControlFlow::Continue(()),
347            Err(err) => panic!("unexpected error: {err}"),
348        }
349    }
350
351    /// Generate a uniformly random field element from the provided source of random bytes using
352    /// rejection sampling.
353    fn generate_random<S: RngCore + ?Sized>(seed_stream: &mut S) -> Self {
354        // This is analogous to `Prng::get()`, but does not make use of a persistent buffer of
355        // output.
356        let mut buffer = [0u8; 64];
357        assert!(
358            buffer.len() >= Self::ENCODED_SIZE,
359            "field is too big for buffer"
360        );
361        loop {
362            seed_stream.fill_bytes(&mut buffer[..Self::ENCODED_SIZE]);
363            match Self::from_random_rejection(&buffer[..Self::ENCODED_SIZE]) {
364                ControlFlow::Break(x) => return x,
365                ControlFlow::Continue(()) => continue,
366            }
367        }
368    }
369}
370
371impl<F: FieldElement> FieldElementExt for F {}
372
373/// serde Visitor implementation used to generically deserialize `FieldElement`
374/// values from byte arrays.
375pub(crate) struct FieldElementVisitor<F: FieldElement> {
376    pub(crate) phantom: PhantomData<F>,
377}
378
379impl<'de, F: FieldElement> Visitor<'de> for FieldElementVisitor<F> {
380    type Value = F;
381
382    fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
383        formatter.write_fmt(format_args!("an array of {} bytes", F::ENCODED_SIZE))
384    }
385
386    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
387    where
388        E: serde::de::Error,
389    {
390        Self::Value::try_from(v).map_err(E::custom)
391    }
392
393    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
394    where
395        A: serde::de::SeqAccess<'de>,
396    {
397        let mut bytes = vec![];
398        while let Some(byte) = seq.next_element()? {
399            bytes.push(byte);
400        }
401
402        self.visit_bytes(&bytes)
403    }
404}
405
406/// Objects with this trait represent an element of `GF(p)`, where `p` is some prime and the
407/// field's multiplicative group has a subgroup with an order that is a power of 2, and at least
408/// `2^20`.
409pub trait FftFriendlyFieldElement: FieldElementWithInteger {
410    /// Returns the size of the multiplicative subgroup generated by
411    /// [`FftFriendlyFieldElement::generator`].
412    fn generator_order() -> Self::Integer;
413
414    /// Returns the generator of the multiplicative subgroup of size
415    /// [`FftFriendlyFieldElement::generator_order`].
416    fn generator() -> Self;
417
418    /// Returns the `2^l`-th principal root of unity for any `l <= 20`. Note that the `2^0`-th
419    /// prinicpal root of unity is `1` by definition.
420    fn root(l: usize) -> Option<Self>;
421}
422
423macro_rules! make_field {
424    (
425        $(#[$meta:meta])*
426        $elem:ident, $int_internal:ident, $int_conversion:ident, $fp:ident, $encoding_size:literal,
427    ) => {
428        $(#[$meta])*
429        ///
430        /// This structure represents a field element in a prime order field. The concrete
431        /// representation of the element is via the Montgomery domain. For an element `n` in
432        /// `GF(p)`, we store `n * R^-1 mod p` (where `R` is a given power of two). This
433        /// representation enables using a more efficient (and branchless) multiplication algorithm,
434        /// at the expense of having to convert elements between their Montgomery domain
435        /// representation and natural representation. For calculations with many multiplications or
436        /// exponentiations, this is worthwhile.
437        ///
438        /// As an invariant, this integer representing the field element in the Montgomery domain
439        /// must be less than the field modulus, `p`.
440        #[derive(Clone, Copy, Default)]
441        pub struct $elem($int_internal);
442
443        impl $elem {
444            /// Attempts to instantiate an `$elem` from the first `Self::ENCODED_SIZE` bytes in the
445            /// provided slice. The decoded value will be bitwise-ANDed with `mask` before reducing
446            /// it using the field modulus.
447            ///
448            /// # Errors
449            ///
450            /// An error is returned if the provided slice is not long enough to encode a field
451            /// element or if the decoded value is greater than the field prime.
452            ///
453            /// # Notes
454            ///
455            /// We cannot use `u128::from_le_bytes` or `u128::from_be_bytes` because those functions
456            /// expect inputs to be exactly 16 bytes long. Our encoding of most field elements is
457            /// more compact.
458            fn try_from_bytes(bytes: &[u8], mask: $int_internal) -> Result<Self, FieldError> {
459                if Self::ENCODED_SIZE > bytes.len() {
460                    return Err(FieldError::ShortRead);
461                }
462
463                let mut int = 0;
464                for i in 0..Self::ENCODED_SIZE {
465                    int |= (bytes[i] as $int_internal) << (i << 3);
466                }
467
468                int &= mask;
469
470                if int >= $fp::PRIME {
471                    return Err(FieldError::ModulusOverflow);
472                }
473                // FieldParameters::montgomery() will return a value that has been fully reduced
474                // mod p, satisfying the invariant on Self.
475                Ok(Self($fp::montgomery(int)))
476            }
477        }
478
479        impl PartialEq for $elem {
480            fn eq(&self, rhs: &Self) -> bool {
481                // The fields included in this comparison MUST match the fields
482                // used in Hash::hash
483                // https://doc.rust-lang.org/std/hash/trait.Hash.html#hash-and-eq
484
485                // Check the invariant that the integer representation is fully reduced.
486                debug_assert!(self.0 < $fp::PRIME);
487                debug_assert!(rhs.0 < $fp::PRIME);
488
489                self.0 == rhs.0
490            }
491        }
492
493        impl ConstantTimeEq for $elem {
494            fn ct_eq(&self, rhs: &Self) -> Choice {
495                self.0.ct_eq(&rhs.0)
496            }
497        }
498
499        impl ConditionallySelectable for $elem {
500            fn conditional_select(a: &Self, b: &Self, choice: subtle::Choice) -> Self {
501                Self($int_internal::conditional_select(&a.0, &b.0, choice))
502            }
503        }
504
505        impl Hash for $elem {
506            fn hash<H: Hasher>(&self, state: &mut H) {
507                // The fields included in this hash MUST match the fields used
508                // in PartialEq::eq
509                // https://doc.rust-lang.org/std/hash/trait.Hash.html#hash-and-eq
510
511                // Check the invariant that the integer representation is fully reduced.
512                debug_assert!(self.0 < $fp::PRIME);
513
514                self.0.hash(state);
515            }
516        }
517
518        impl Eq for $elem {}
519
520        impl Add for $elem {
521            type Output = $elem;
522            fn add(self, rhs: Self) -> Self {
523                // FieldParameters::add() returns a value that has been fully reduced
524                // mod p, satisfying the invariant on Self.
525                Self($fp::add(self.0, rhs.0))
526            }
527        }
528
529        impl Add for &$elem {
530            type Output = $elem;
531            fn add(self, rhs: Self) -> $elem {
532                *self + *rhs
533            }
534        }
535
536        impl AddAssign for $elem {
537            fn add_assign(&mut self, rhs: Self) {
538                *self = *self + rhs;
539            }
540        }
541
542        impl Sub for $elem {
543            type Output = $elem;
544            fn sub(self, rhs: Self) -> Self {
545                // We know that self.0 and rhs.0 are both less than p, thus FieldParameters::sub()
546                // returns a value less than p, satisfying the invariant on Self.
547                Self($fp::sub(self.0, rhs.0))
548            }
549        }
550
551        impl Sub for &$elem {
552            type Output = $elem;
553            fn sub(self, rhs: Self) -> $elem {
554                *self - *rhs
555            }
556        }
557
558        impl SubAssign for $elem {
559            fn sub_assign(&mut self, rhs: Self) {
560                *self = *self - rhs;
561            }
562        }
563
564        impl Mul for $elem {
565            type Output = $elem;
566            fn mul(self, rhs: Self) -> Self {
567                // FieldParameters::mul() always returns a value less than p, so the invariant on
568                // Self is satisfied.
569                Self($fp::mul(self.0, rhs.0))
570            }
571        }
572
573        impl Mul for &$elem {
574            type Output = $elem;
575            fn mul(self, rhs: Self) -> $elem {
576                *self * *rhs
577            }
578        }
579
580        impl MulAssign for $elem {
581            fn mul_assign(&mut self, rhs: Self) {
582                *self = *self * rhs;
583            }
584        }
585
586        impl Div for $elem {
587            type Output = $elem;
588            #[allow(clippy::suspicious_arithmetic_impl)]
589            fn div(self, rhs: Self) -> Self {
590                self * rhs.inv()
591            }
592        }
593
594        impl Div for &$elem {
595            type Output = $elem;
596            fn div(self, rhs: Self) -> $elem {
597                *self / *rhs
598            }
599        }
600
601        impl DivAssign for $elem {
602            fn div_assign(&mut self, rhs: Self) {
603                *self = *self / rhs;
604            }
605        }
606
607        impl Neg for $elem {
608            type Output = $elem;
609            fn neg(self) -> Self {
610                // FieldParameters::neg() will return a value less than p because self.0 is less
611                // than p, and neg() dispatches to sub().
612                Self($fp::neg(self.0))
613            }
614        }
615
616        impl Neg for &$elem {
617            type Output = $elem;
618            fn neg(self) -> $elem {
619                -(*self)
620            }
621        }
622
623        impl From<$int_conversion> for $elem {
624            fn from(x: $int_conversion) -> Self {
625                // FieldParameters::montgomery() will return a value that has been fully reduced
626                // mod p, satisfying the invariant on Self.
627                Self($fp::montgomery($int_internal::try_from(x).unwrap()))
628            }
629        }
630
631        impl From<$elem> for $int_conversion {
632            fn from(x: $elem) -> Self {
633                $int_conversion::try_from($fp::residue(x.0)).unwrap()
634            }
635        }
636
637        impl PartialEq<$int_conversion> for $elem {
638            fn eq(&self, rhs: &$int_conversion) -> bool {
639                $fp::residue(self.0) == $int_internal::try_from(*rhs).unwrap()
640            }
641        }
642
643        impl<'a> TryFrom<&'a [u8]> for $elem {
644            type Error = FieldError;
645
646            fn try_from(bytes: &[u8]) -> Result<Self, FieldError> {
647                Self::try_from_bytes(bytes, $int_internal::MAX)
648            }
649        }
650
651        impl From<$elem> for [u8; $elem::ENCODED_SIZE] {
652            fn from(elem: $elem) -> Self {
653                let int = $fp::residue(elem.0);
654                let mut slice = [0; $elem::ENCODED_SIZE];
655                for i in 0..$elem::ENCODED_SIZE {
656                    slice[i] = ((int >> (i << 3)) & 0xff) as u8;
657                }
658                slice
659            }
660        }
661
662        impl From<$elem> for Vec<u8> {
663            fn from(elem: $elem) -> Self {
664                <[u8; $elem::ENCODED_SIZE]>::from(elem).to_vec()
665            }
666        }
667
668        impl Display for $elem {
669            fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
670                write!(f, "{}", $fp::residue(self.0))
671            }
672        }
673
674        impl Debug for $elem {
675            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
676                write!(f, "{}", $fp::residue(self.0))
677            }
678        }
679
680        // We provide custom [`serde::Serialize`] and [`serde::Deserialize`] implementations because
681        // the derived implementations would represent `FieldElement` values as the backing integer,
682        // which is not what we want because (1) we can be more efficient in all cases and (2) in
683        // some circumstances, [some serializers don't support `u128`](https://github.com/serde-rs/json/issues/625).
684        impl Serialize for $elem {
685            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
686                let bytes: [u8; $elem::ENCODED_SIZE] = (*self).into();
687                serializer.serialize_bytes(&bytes)
688            }
689        }
690
691        impl<'de> Deserialize<'de> for $elem {
692            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<$elem, D::Error> {
693                deserializer.deserialize_bytes(FieldElementVisitor { phantom: PhantomData })
694            }
695        }
696
697        impl Encode for $elem {
698            fn encode(&self, bytes: &mut Vec<u8>) -> Result<(), CodecError> {
699                let slice = <[u8; $elem::ENCODED_SIZE]>::from(*self);
700                bytes.extend_from_slice(&slice);
701                Ok(())
702            }
703
704            fn encoded_len(&self) -> Option<usize> {
705                Some(Self::ENCODED_SIZE)
706            }
707        }
708
709        impl Decode for $elem {
710            fn decode(bytes: &mut Cursor<&[u8]>) -> Result<Self, CodecError> {
711                let mut value = [0u8; $elem::ENCODED_SIZE];
712                bytes.read_exact(&mut value)?;
713                $elem::try_from_bytes(&value, $int_internal::MAX).map_err(|e| {
714                    CodecError::Other(Box::new(e) as Box<dyn std::error::Error + 'static + Send + Sync>)
715                })
716            }
717        }
718
719        impl FieldElement for $elem {
720            const ENCODED_SIZE: usize = $encoding_size;
721            fn inv(&self) -> Self {
722                // FieldParameters::inv() ultimately relies on mul(), and will always return a
723                // value less than p.
724                Self($fp::inv(self.0))
725            }
726
727            fn try_from_random(bytes: &[u8]) -> Result<Self, FieldError> {
728                $elem::try_from_bytes(bytes, $fp::BIT_MASK)
729            }
730
731            fn zero() -> Self {
732                Self(0)
733            }
734
735            fn one() -> Self {
736                Self($fp::ROOTS[0])
737            }
738
739            fn half() -> Self {
740                Self($fp::HALF)
741            }
742        }
743
744        impl FieldElementWithInteger for $elem {
745            type Integer = $int_conversion;
746
747            fn pow(&self, exp: Self::Integer) -> Self {
748                // FieldParameters::pow() relies on mul(), and will always return a value less
749                // than p.
750                Self($fp::pow(self.0, $int_internal::try_from(exp).unwrap()))
751            }
752
753            fn modulus() -> Self::Integer {
754                $fp::PRIME as $int_conversion
755            }
756        }
757
758        impl FftFriendlyFieldElement for $elem {
759            fn generator() -> Self {
760                Self($fp::G)
761            }
762
763            fn generator_order() -> Self::Integer {
764                1 << (Self::Integer::try_from($fp::NUM_ROOTS).unwrap())
765            }
766
767            fn root(l: usize) -> Option<Self> {
768                if l < min($fp::ROOTS.len(), $fp::NUM_ROOTS+1) {
769                    Some(Self($fp::ROOTS[l]))
770                } else {
771                    None
772                }
773            }
774        }
775
776        impl Distribution<$elem> for Standard {
777            fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $elem {
778                $elem::generate_random(rng)
779            }
780        }
781    };
782}
783
784impl Integer for u32 {
785    type TryFromUsizeError = <Self as TryFrom<usize>>::Error;
786    type TryIntoU64Error = <Self as TryInto<u64>>::Error;
787
788    fn zero() -> Self {
789        0
790    }
791
792    fn one() -> Self {
793        1
794    }
795}
796
797impl Integer for u64 {
798    type TryFromUsizeError = <Self as TryFrom<usize>>::Error;
799    type TryIntoU64Error = <Self as TryInto<u64>>::Error;
800
801    fn zero() -> Self {
802        0
803    }
804
805    fn one() -> Self {
806        1
807    }
808}
809
810impl Integer for u128 {
811    type TryFromUsizeError = <Self as TryFrom<usize>>::Error;
812    type TryIntoU64Error = <Self as TryInto<u64>>::Error;
813
814    fn zero() -> Self {
815        0
816    }
817
818    fn one() -> Self {
819        1
820    }
821}
822
823make_field!(
824    /// `GF(4293918721)`, a 32-bit field.
825    FieldPrio2,
826    u32,
827    u32,
828    FP32,
829    4,
830);
831
832make_field!(
833    /// `GF(18446744069414584321)`, a 64-bit field.
834    Field64,
835    u64,
836    u64,
837    FP64,
838    8,
839);
840
841make_field!(
842    /// `GF(340282366920938462946865773367900766209)`, a 128-bit field.
843    Field128,
844    u128,
845    u128,
846    FP128,
847    16,
848);
849
850/// Merge two vectors of fields by summing other_vector into accumulator.
851///
852/// # Errors
853///
854/// Fails if the two vectors do not have the same length.
855pub(crate) fn merge_vector<F: FieldElement>(
856    accumulator: &mut [F],
857    other_vector: &[F],
858) -> Result<(), FieldError> {
859    if accumulator.len() != other_vector.len() {
860        return Err(FieldError::InputSizeMismatch);
861    }
862    for (a, o) in accumulator.iter_mut().zip(other_vector.iter()) {
863        *a += *o;
864    }
865
866    Ok(())
867}
868
869/// Outputs an additive secret sharing of the input.
870#[cfg(test)]
871pub(crate) fn split_vector<F: FieldElement>(
872    inp: &[F],
873    num_shares: usize,
874) -> Result<Vec<Vec<F>>, PrngError> {
875    if num_shares == 0 {
876        return Ok(vec![]);
877    }
878
879    let mut outp = Vec::with_capacity(num_shares);
880    outp.push(inp.to_vec());
881
882    for _ in 1..num_shares {
883        let share: Vec<F> = random_vector(inp.len())?;
884        for (x, y) in outp[0].iter_mut().zip(&share) {
885            *x -= *y;
886        }
887        outp.push(share);
888    }
889
890    Ok(outp)
891}
892
893/// Generate a vector of uniformly distributed random field elements.
894pub fn random_vector<F: FieldElement>(len: usize) -> Result<Vec<F>, PrngError> {
895    Ok(Prng::new()?.take(len).collect())
896}
897
898/// `encode_fieldvec` serializes a type that is equivalent to a vector of field elements.
899#[inline(always)]
900pub(crate) fn encode_fieldvec<F: FieldElement, T: AsRef<[F]>>(
901    val: T,
902    bytes: &mut Vec<u8>,
903) -> Result<(), CodecError> {
904    for elem in val.as_ref() {
905        elem.encode(bytes)?;
906    }
907    Ok(())
908}
909
910/// `decode_fieldvec` deserializes some number of field elements from a cursor, and advances the
911/// cursor's position.
912pub(crate) fn decode_fieldvec<F: FieldElement>(
913    count: usize,
914    input: &mut Cursor<&[u8]>,
915) -> Result<Vec<F>, CodecError> {
916    let mut vec = Vec::with_capacity(count);
917    let mut buffer = [0u8; 64];
918    assert!(
919        buffer.len() >= F::ENCODED_SIZE,
920        "field is too big for buffer"
921    );
922    for _ in 0..count {
923        input.read_exact(&mut buffer[..F::ENCODED_SIZE])?;
924        vec.push(
925            F::try_from(&buffer[..F::ENCODED_SIZE]).map_err(|e| CodecError::Other(Box::new(e)))?,
926        );
927    }
928    Ok(vec)
929}
930
931#[cfg(test)]
932pub(crate) mod test_utils {
933    use super::{FieldElement, FieldElementWithInteger, Integer};
934    use crate::{codec::CodecError, field::FieldError, prng::Prng};
935    use assert_matches::assert_matches;
936    use std::{
937        collections::hash_map::DefaultHasher,
938        convert::TryFrom,
939        hash::{Hash, Hasher},
940        io::Cursor,
941    };
942
943    /// A test-only copy of `FieldElementWithInteger`.
944    ///
945    /// This trait is only used in tests, and it is implemented on some fields that do not have
946    /// `FieldElementWithInteger` implementations. This separate trait is used in order to avoid
947    /// affecting trait resolution with conditional compilation. Additionally, this trait only
948    /// requires the `Integer` associated type satisfy `Clone`, not `Copy`, so that it may be used
949    /// with arbitrary precision integer implementations.
950    pub(crate) trait TestFieldElementWithInteger:
951        FieldElement + From<Self::TestInteger>
952    {
953        type IntegerTryFromError: std::error::Error;
954        type TryIntoU64Error: std::error::Error;
955        type TestInteger: Integer + From<Self> + Clone;
956
957        fn modulus() -> Self::TestInteger;
958    }
959
960    impl<F> TestFieldElementWithInteger for F
961    where
962        F: FieldElementWithInteger,
963    {
964        type IntegerTryFromError = <F::Integer as Integer>::TryFromUsizeError;
965        type TryIntoU64Error = <F::Integer as Integer>::TryIntoU64Error;
966        type TestInteger = F::Integer;
967
968        fn modulus() -> Self::TestInteger {
969            <F as FieldElementWithInteger>::modulus()
970        }
971    }
972
973    pub(crate) fn field_element_test_common<F: TestFieldElementWithInteger>() {
974        let mut prng: Prng<F, _> = Prng::new().unwrap();
975        let int_modulus = F::modulus();
976        let int_one = F::TestInteger::try_from(1).unwrap();
977        let zero = F::zero();
978        let one = F::one();
979        let half = F::half();
980        let two = F::from(F::TestInteger::try_from(2).unwrap());
981        let four = F::from(F::TestInteger::try_from(4).unwrap());
982
983        // add
984        assert_eq!(F::from(int_modulus.clone() - int_one.clone()) + one, zero);
985        assert_eq!(one + one, two);
986        assert_eq!(two + F::from(int_modulus.clone()), two);
987
988        // add w/ assignment
989        let mut a = prng.get();
990        let b = prng.get();
991        let c = a + b;
992        a += b;
993        assert_eq!(a, c);
994
995        // sub
996        assert_eq!(zero - one, F::from(int_modulus.clone() - int_one.clone()));
997        #[allow(clippy::eq_op)]
998        {
999            assert_eq!(one - one, zero);
1000        }
1001        assert_eq!(one + (-one), zero);
1002        assert_eq!(two - F::from(int_modulus.clone()), two);
1003        assert_eq!(one - F::from(int_modulus.clone() - int_one.clone()), two);
1004
1005        // sub w/ assignment
1006        let mut a = prng.get();
1007        let b = prng.get();
1008        let c = a - b;
1009        a -= b;
1010        assert_eq!(a, c);
1011
1012        // add + sub
1013        for _ in 0..100 {
1014            let f = prng.get();
1015            let g = prng.get();
1016            assert_eq!(f + g - f - g, zero);
1017            assert_eq!(f + g - g, f);
1018            assert_eq!(f + g - f, g);
1019        }
1020
1021        // mul
1022        assert_eq!(two * two, four);
1023        assert_eq!(two * one, two);
1024        assert_eq!(two * half, one);
1025        assert_eq!(two * zero, zero);
1026        assert_eq!(one * F::from(int_modulus.clone()), zero);
1027
1028        // mul w/ assignment
1029        let mut a = prng.get();
1030        let b = prng.get();
1031        let c = a * b;
1032        a *= b;
1033        assert_eq!(a, c);
1034
1035        // integer conversion
1036        assert_eq!(
1037            F::TestInteger::from(zero),
1038            F::TestInteger::try_from(0).unwrap()
1039        );
1040        assert_eq!(
1041            F::TestInteger::from(one),
1042            F::TestInteger::try_from(1).unwrap()
1043        );
1044        assert_eq!(
1045            F::TestInteger::from(two),
1046            F::TestInteger::try_from(2).unwrap()
1047        );
1048        assert_eq!(
1049            F::TestInteger::from(four),
1050            F::TestInteger::try_from(4).unwrap()
1051        );
1052
1053        // serialization
1054        let test_inputs = vec![
1055            zero,
1056            one,
1057            prng.get(),
1058            F::from(int_modulus.clone() - int_one.clone()),
1059        ];
1060        for want in test_inputs.iter() {
1061            let mut bytes = vec![];
1062            want.encode(&mut bytes).unwrap();
1063
1064            assert_eq!(bytes.len(), F::ENCODED_SIZE);
1065            assert_eq!(want.encoded_len().unwrap(), F::ENCODED_SIZE);
1066
1067            let got = F::get_decoded(&bytes).unwrap();
1068            assert_eq!(got, *want);
1069        }
1070
1071        #[allow(deprecated)]
1072        {
1073            let serialized_vec = F::slice_into_byte_vec(&test_inputs);
1074            let deserialized = F::byte_slice_into_vec(&serialized_vec).unwrap();
1075            assert_eq!(deserialized, test_inputs);
1076        }
1077
1078        let test_input = prng.get();
1079        let json = serde_json::to_string(&test_input).unwrap();
1080        let deserialized = serde_json::from_str::<F>(&json).unwrap();
1081        assert_eq!(deserialized, test_input);
1082
1083        let value = serde_json::from_str::<serde_json::Value>(&json).unwrap();
1084        let array = value.as_array().unwrap();
1085        for element in array {
1086            element.as_u64().unwrap();
1087        }
1088
1089        #[allow(deprecated)]
1090        {
1091            let err = F::byte_slice_into_vec(&[0]).unwrap_err();
1092            assert_matches!(err, FieldError::ShortRead);
1093
1094            let err = F::byte_slice_into_vec(&vec![0xffu8; F::ENCODED_SIZE]).unwrap_err();
1095            assert_matches!(err, FieldError::Codec(CodecError::Other(err)) => {
1096                assert_matches!(err.downcast_ref::<FieldError>(), Some(FieldError::ModulusOverflow));
1097            });
1098        }
1099
1100        let insufficient = vec![0u8; F::ENCODED_SIZE - 1];
1101        let err = F::try_from(insufficient.as_ref()).unwrap_err();
1102        assert_matches!(err, FieldError::ShortRead);
1103        let err = F::decode(&mut Cursor::new(&insufficient)).unwrap_err();
1104        assert_matches!(err, CodecError::Io(_));
1105
1106        let err = F::decode(&mut Cursor::new(&vec![0xffu8; F::ENCODED_SIZE])).unwrap_err();
1107        assert_matches!(err, CodecError::Other(err) => {
1108            assert_matches!(err.downcast_ref::<FieldError>(), Some(FieldError::ModulusOverflow));
1109        });
1110
1111        // equality and hash: Generate many elements, confirm they are not equal, and confirm
1112        // various products that should be equal have the same hash. Three is chosen as a generator
1113        // here because it happens to generate fairly large subgroups of (Z/pZ)* for all four
1114        // primes.
1115        let three = F::from(F::TestInteger::try_from(3).unwrap());
1116        let mut powers_of_three = Vec::with_capacity(500);
1117        let mut power = one;
1118        for _ in 0..500 {
1119            powers_of_three.push(power);
1120            power *= three;
1121        }
1122        // Check all these elements are mutually not equal.
1123        for i in 0..powers_of_three.len() {
1124            let first = &powers_of_three[i];
1125            for second in &powers_of_three[0..i] {
1126                assert_ne!(first, second);
1127            }
1128        }
1129
1130        // Construct an element from a number that needs to be reduced, and test comparisons on it,
1131        // confirming that it is reduced correctly.
1132        let p = F::from(int_modulus.clone());
1133        assert_eq!(p, zero);
1134        let p_plus_one = F::from(int_modulus + int_one);
1135        assert_eq!(p_plus_one, one);
1136    }
1137
1138    pub(super) fn hash_helper<H: Hash>(input: H) -> u64 {
1139        let mut hasher = DefaultHasher::new();
1140        input.hash(&mut hasher);
1141        hasher.finish()
1142    }
1143}
1144
1145#[cfg(test)]
1146mod tests {
1147    use super::*;
1148    use crate::field::test_utils::{field_element_test_common, hash_helper};
1149    use crate::fp::MAX_ROOTS;
1150    use crate::prng::Prng;
1151    use assert_matches::assert_matches;
1152
1153    #[test]
1154    fn test_accumulate() {
1155        let mut lhs = vec![FieldPrio2(1); 10];
1156        let rhs = vec![FieldPrio2(2); 10];
1157
1158        merge_vector(&mut lhs, &rhs).unwrap();
1159
1160        lhs.iter().for_each(|f| assert_eq!(*f, FieldPrio2(3)));
1161        rhs.iter().for_each(|f| assert_eq!(*f, FieldPrio2(2)));
1162
1163        let wrong_len = vec![FieldPrio2::zero(); 9];
1164        let result = merge_vector(&mut lhs, &wrong_len);
1165        assert_matches!(result, Err(FieldError::InputSizeMismatch));
1166    }
1167
1168    fn field_element_test<F: FftFriendlyFieldElement + Hash>() {
1169        field_element_test_common::<F>();
1170
1171        let mut prng: Prng<F, _> = Prng::new().unwrap();
1172        let int_modulus = F::modulus();
1173        let int_one = F::Integer::try_from(1).unwrap();
1174        let zero = F::zero();
1175        let one = F::one();
1176        let two = F::from(F::Integer::try_from(2).unwrap());
1177        let four = F::from(F::Integer::try_from(4).unwrap());
1178
1179        // div
1180        assert_eq!(four / two, two);
1181        #[allow(clippy::eq_op)]
1182        {
1183            assert_eq!(two / two, one);
1184        }
1185        assert_eq!(zero / two, zero);
1186        assert_eq!(two / zero, zero); // Undefined behavior
1187        assert_eq!(zero.inv(), zero); // Undefined behavior
1188
1189        // div w/ assignment
1190        let mut a = prng.get();
1191        let b = prng.get();
1192        let c = a / b;
1193        a /= b;
1194        assert_eq!(a, c);
1195        assert_eq!(hash_helper(a), hash_helper(c));
1196
1197        // mul + div
1198        for _ in 0..100 {
1199            let f = prng.get();
1200            if f == zero {
1201                continue;
1202            }
1203            assert_eq!(f * f.inv(), one);
1204            assert_eq!(f.inv() * f, one);
1205        }
1206
1207        // pow
1208        assert_eq!(two.pow(F::Integer::try_from(0).unwrap()), one);
1209        assert_eq!(two.pow(int_one), two);
1210        assert_eq!(two.pow(F::Integer::try_from(2).unwrap()), four);
1211        assert_eq!(two.pow(int_modulus - int_one), one);
1212        assert_eq!(two.pow(int_modulus), two);
1213
1214        // roots
1215        let mut int_order = F::generator_order();
1216        for l in 0..MAX_ROOTS + 1 {
1217            assert_eq!(
1218                F::generator().pow(int_order),
1219                F::root(l).unwrap(),
1220                "failure for F::root({l})"
1221            );
1222            int_order = int_order >> 1;
1223        }
1224
1225        // formatting
1226        assert_eq!(format!("{zero}"), "0");
1227        assert_eq!(format!("{one}"), "1");
1228        assert_eq!(format!("{zero:?}"), "0");
1229        assert_eq!(format!("{one:?}"), "1");
1230
1231        let three = F::from(F::Integer::try_from(3).unwrap());
1232        let mut powers_of_three = Vec::with_capacity(500);
1233        let mut power = one;
1234        for _ in 0..500 {
1235            powers_of_three.push(power);
1236            power *= three;
1237        }
1238
1239        // Check that 3^i is the same whether it's calculated with pow() or repeated
1240        // multiplication, with both equality and hash equality.
1241        for (i, power) in powers_of_three.iter().enumerate() {
1242            let result = three.pow(F::Integer::try_from(i).unwrap());
1243            assert_eq!(result, *power);
1244            let hash1 = hash_helper(power);
1245            let hash2 = hash_helper(result);
1246            assert_eq!(hash1, hash2);
1247        }
1248
1249        // Check that 3^n = (3^i)*(3^(n-i)), via both equality and hash equality.
1250        let expected_product = powers_of_three[powers_of_three.len() - 1];
1251        let expected_hash = hash_helper(expected_product);
1252        for i in 0..powers_of_three.len() {
1253            let a = powers_of_three[i];
1254            let b = powers_of_three[powers_of_three.len() - 1 - i];
1255            let product = a * b;
1256            assert_eq!(product, expected_product);
1257            assert_eq!(hash_helper(product), expected_hash);
1258        }
1259    }
1260
1261    #[test]
1262    fn test_field_prio2() {
1263        field_element_test::<FieldPrio2>();
1264    }
1265
1266    #[test]
1267    fn test_field64() {
1268        field_element_test::<Field64>();
1269    }
1270
1271    #[test]
1272    fn test_field128() {
1273        field_element_test::<Field128>();
1274    }
1275
1276    #[test]
1277    fn test_encode_into_bitvector() {
1278        let zero = Field128::zero();
1279        let one = Field128::one();
1280        let zero_enc = Field128::encode_as_bitvector(0, 4)
1281            .unwrap()
1282            .collect::<Vec<_>>();
1283        let one_enc = Field128::encode_as_bitvector(1, 4)
1284            .unwrap()
1285            .collect::<Vec<_>>();
1286        let fifteen_enc = Field128::encode_as_bitvector(15, 4)
1287            .unwrap()
1288            .collect::<Vec<_>>();
1289        assert_eq!(zero_enc, [zero; 4]);
1290        assert_eq!(one_enc, [one, zero, zero, zero]);
1291        assert_eq!(fifteen_enc, [one; 4]);
1292        Field128::encode_as_bitvector(16, 4).unwrap_err();
1293        Field128::encode_as_bitvector(0, 129).unwrap_err();
1294    }
1295}