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