Merge pull request #228 from str4d/ff-more-trait-refactoring

ff: More trait refactoring
This commit is contained in:
str4d 2020-05-13 09:18:11 +12:00 committed by GitHub
commit 37270776be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
49 changed files with 426 additions and 731 deletions

View File

@ -11,7 +11,7 @@
//! [`EvaluationDomain`]: crate::domain::EvaluationDomain
//! [Groth16]: https://eprint.iacr.org/2016/260
use ff::{Field, PowVartime, PrimeField, ScalarEngine};
use ff::{Field, PrimeField, ScalarEngine};
use group::CurveProjective;
use std::ops::{AddAssign, MulAssign, SubAssign};
@ -221,7 +221,7 @@ impl<G: CurveProjective> Group<G::Engine> for Point<G> {
Point(G::zero())
}
fn group_mul_assign(&mut self, by: &G::Scalar) {
self.0.mul_assign(by.into_repr());
self.0.mul_assign(by.to_repr());
}
fn group_add_assign(&mut self, other: &Self) {
self.0.add_assign(&other.0);

View File

@ -318,7 +318,7 @@ pub fn field_into_allocated_bits_le<E: ScalarEngine, CS: ConstraintSystem<E>, F:
let mut tmp = Vec::with_capacity(F::NUM_BITS as usize);
let mut found_one = false;
for b in BitIterator::<u8, _>::new(value.into_repr()) {
for b in BitIterator::<u8, _>::new(value.to_repr()) {
// Skip leading bits
found_one |= field_char.next().unwrap();
if !found_one {

View File

@ -1,4 +1,4 @@
use ff::{PowVartime, PrimeField, ScalarEngine};
use ff::{Field, PrimeField, ScalarEngine};
use crate::{ConstraintSystem, LinearCombination, SynthesisError, Variable};

View File

@ -103,8 +103,8 @@ impl<E: ScalarEngine> AllocatedNum<E> {
// We want to ensure that the bit representation of a is
// less than or equal to r - 1.
let mut a = self.value.map(|e| BitIterator::<u8, _>::new(e.into_repr()));
let b = (-E::Fr::one()).into_repr();
let mut a = self.value.map(|e| BitIterator::<u8, _>::new(e.to_repr()));
let b = (-E::Fr::one()).to_repr();
let mut result = vec![];
@ -557,7 +557,7 @@ mod test {
assert!(cs.is_satisfied());
for (b, a) in BitIterator::<u8, _>::new(r.into_repr())
for (b, a) in BitIterator::<u8, _>::new(r.to_repr())
.skip(1)
.zip(bits.iter().rev())
{

View File

@ -1,6 +1,6 @@
//! Helpers for testing circuit implementations.
use ff::{Field, PowVartime, PrimeField, ScalarEngine};
use ff::{Endianness, Field, PrimeField, ScalarEngine};
use crate::{ConstraintSystem, Index, LinearCombination, SynthesisError, Variable};
@ -106,11 +106,9 @@ fn hash_lc<E: ScalarEngine>(terms: &[(Variable, E::Fr)], h: &mut Blake2sState) {
}
}
// BLS12-381's Fr is canonically serialized in little-endian, but the hasher
// writes its coefficients in big endian. For now, we flip the endianness
// manually, which is not necessarily correct for circuits using other curves.
// TODO: Fix this in a standalone commit, and document the no-op change.
let coeff_be: Vec<_> = coeff.into_repr().as_ref().iter().cloned().rev().collect();
let mut coeff_repr = coeff.to_repr();
<E::Fr as PrimeField>::ReprEndianness::toggle_little_endian(&mut coeff_repr);
let coeff_be: Vec<_> = coeff_repr.as_ref().iter().cloned().rev().collect();
buf[9..].copy_from_slice(&coeff_be[..]);
h.update(&buf);

View File

@ -2,7 +2,7 @@ use rand_core::RngCore;
use std::ops::{AddAssign, MulAssign};
use std::sync::Arc;
use ff::{Field, PowVartime};
use ff::Field;
use group::{CurveAffine, CurveProjective, Wnaf};
use pairing::Engine;

View File

@ -1,9 +1,8 @@
use ff::{Field, PowVartime, PrimeField, ScalarEngine, SqrtField};
use ff::{Field, PrimeField, ScalarEngine};
use group::{CurveAffine, CurveProjective, EncodedPoint, GroupDecodingError};
use pairing::{Engine, PairingCurveAffine};
use rand_core::RngCore;
use std::cmp::Ordering;
use std::fmt;
use std::num::Wrapping;
use std::ops::{Add, AddAssign, BitAnd, Mul, MulAssign, Neg, Shr, Sub, SubAssign};
@ -48,18 +47,6 @@ impl ConditionallySelectable for Fr {
}
}
impl Ord for Fr {
fn cmp(&self, other: &Fr) -> Ordering {
(self.0).0.cmp(&(other.0).0)
}
}
impl PartialOrd for Fr {
fn partial_cmp(&self, other: &Fr) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Neg for Fr {
type Output = Self;
@ -214,12 +201,6 @@ impl Field for Fr {
}
}
fn frobenius_map(&mut self, _: usize) {
// identity
}
}
impl SqrtField for Fr {
fn sqrt(&self) -> CtOption<Self> {
// Tonelli-Shank's algorithm for q mod 16 = 1
// https://eprint.iacr.org/2012/685.pdf (page 12, algorithm 5)
@ -291,6 +272,7 @@ impl Default for FrRepr {
impl PrimeField for Fr {
type Repr = FrRepr;
type ReprEndianness = byteorder::LittleEndian;
const NUM_BITS: u32 = 16;
const CAPACITY: u32 = 15;
@ -305,7 +287,7 @@ impl PrimeField for Fr {
}
}
fn into_repr(&self) -> FrRepr {
fn to_repr(&self) -> FrRepr {
FrRepr::from(*self)
}

View File

@ -1,4 +1,4 @@
use ff::{Field, PowVartime, PrimeField};
use ff::{Field, PrimeField};
use pairing::Engine;
mod dummy_engine;

View File

@ -31,7 +31,7 @@ pub fn verify_proof<'a, E: Engine>(
let mut acc = pvk.ic[0].into_projective();
for (i, b) in public_inputs.iter().zip(pvk.ic.iter().skip(1)) {
AddAssign::<&E::G1>::add_assign(&mut acc, &b.mul(i.into_repr()));
AddAssign::<&E::G1>::add_assign(&mut acc, &b.mul(i.to_repr()));
}
// The original verification equation is:

View File

@ -1,6 +1,6 @@
use super::multicore::Worker;
use bit_vec::{self, BitVec};
use ff::{Field, PrimeField, ScalarEngine};
use ff::{Endianness, Field, PrimeField, ScalarEngine};
use futures::Future;
use group::{CurveAffine, CurveProjective};
use std::io;
@ -195,8 +195,18 @@ where
bases.skip(1)?;
}
} else {
let exp = exp >> skip;
let exp = exp & ((1 << c) - 1);
let mut exp = exp.to_repr();
<<G::Engine as ScalarEngine>::Fr as PrimeField>::ReprEndianness::toggle_little_endian(&mut exp);
let exp = exp
.as_ref()
.into_iter()
.map(|b| (0..8).map(move |i| (b >> i) & 1u8))
.flatten()
.skip(skip as usize)
.take(c as usize)
.enumerate()
.fold(0u64, |acc, (i, b)| acc + ((b as u64) << i));
if exp != 0 {
(&mut buckets[(exp - 1) as usize])
@ -295,7 +305,7 @@ fn test_with_bls12() {
let mut acc = G::zero();
for (base, exp) in bases.iter().zip(exponents.iter()) {
AddAssign::<&G>::add_assign(&mut acc, &base.mul(exp.into_repr()));
AddAssign::<&G>::add_assign(&mut acc, &base.mul(exp.to_repr()));
}
acc

View File

@ -11,7 +11,7 @@ repository = "https://github.com/ebfull/ff"
edition = "2018"
[dependencies]
byteorder = { version = "1", optional = true }
byteorder = { version = "1", default-features = false }
ff_derive = { version = "0.6", path = "ff_derive", optional = true }
rand_core = { version = "0.5", default-features = false }
subtle = { version = "2.2.1", default-features = false, features = ["i128"] }
@ -19,7 +19,7 @@ subtle = { version = "2.2.1", default-features = false, features = ["i128"] }
[features]
default = ["std"]
derive = ["ff_derive"]
std = ["byteorder"]
std = []
[badges]
maintenance = { status = "actively-developed" }

View File

@ -31,6 +31,30 @@ impl FromStr for ReprEndianness {
}
impl ReprEndianness {
fn repr_endianness(&self) -> proc_macro2::TokenStream {
match self {
ReprEndianness::Big => quote! {::byteorder::BigEndian},
ReprEndianness::Little => quote! {::byteorder::LittleEndian},
}
}
fn modulus_repr(&self, modulus: &BigUint, bytes: usize) -> Vec<u8> {
match self {
ReprEndianness::Big => {
let buf = modulus.to_bytes_be();
iter::repeat(0)
.take(bytes - buf.len())
.chain(buf.into_iter())
.collect()
}
ReprEndianness::Little => {
let mut buf = modulus.to_bytes_le();
buf.extend(iter::repeat(0).take(bytes - buf.len()));
buf
}
}
}
fn from_repr(&self, name: &syn::Ident, limbs: usize) -> proc_macro2::TokenStream {
let read_repr = match self {
ReprEndianness::Big => quote! {
@ -59,7 +83,7 @@ impl ReprEndianness {
}
}
fn into_repr(
fn to_repr(
&self,
repr: &syn::Ident,
mont_reduce_self_params: &proc_macro2::TokenStream,
@ -152,8 +176,14 @@ pub fn prime_field(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let mut gen = proc_macro2::TokenStream::new();
let (constants_impl, sqrt_impl) =
prime_field_constants_and_sqrt(&ast.ident, &repr_ident, &modulus, limbs, generator);
let (constants_impl, sqrt_impl) = prime_field_constants_and_sqrt(
&ast.ident,
&repr_ident,
&modulus,
&endianness,
limbs,
generator,
);
gen.extend(constants_impl);
gen.extend(prime_field_repr_impl(&repr_ident, &endianness, limbs * 8));
@ -163,8 +193,8 @@ pub fn prime_field(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
&modulus,
&endianness,
limbs,
sqrt_impl,
));
gen.extend(sqrt_impl);
// Return the generated impl
gen.into()
@ -459,6 +489,7 @@ fn prime_field_constants_and_sqrt(
name: &syn::Ident,
repr: &syn::Ident,
modulus: &BigUint,
endianness: &ReprEndianness,
limbs: usize,
generator: BigUint,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
@ -486,99 +517,90 @@ fn prime_field_constants_and_sqrt(
biguint_to_u64_vec((exp(generator.clone(), &t, &modulus) * &r) % modulus, limbs);
let generator = biguint_to_u64_vec((generator.clone() * &r) % modulus, limbs);
let sqrt_impl = if (modulus % BigUint::from_str("4").unwrap())
== BigUint::from_str("3").unwrap()
{
// Addition chain for (r + 1) // 4
let mod_plus_1_over_4 = pow_fixed::generate(
&quote! {self},
(modulus + BigUint::from_str("1").unwrap()) >> 2,
);
let sqrt_impl =
if (modulus % BigUint::from_str("4").unwrap()) == BigUint::from_str("3").unwrap() {
// Addition chain for (r + 1) // 4
let mod_plus_1_over_4 = pow_fixed::generate(
&quote! {self},
(modulus + BigUint::from_str("1").unwrap()) >> 2,
);
quote! {
impl ::ff::SqrtField for #name {
fn sqrt(&self) -> ::subtle::CtOption<Self> {
use ::subtle::ConstantTimeEq;
quote! {
use ::subtle::ConstantTimeEq;
// Because r = 3 (mod 4)
// sqrt can be done with only one exponentiation,
// via the computation of self^((r + 1) // 4) (mod r)
let sqrt = {
#mod_plus_1_over_4
};
// Because r = 3 (mod 4)
// sqrt can be done with only one exponentiation,
// via the computation of self^((r + 1) // 4) (mod r)
let sqrt = {
#mod_plus_1_over_4
};
::subtle::CtOption::new(
sqrt,
(sqrt * &sqrt).ct_eq(self), // Only return Some if it's the square root.
)
}
::subtle::CtOption::new(
sqrt,
(sqrt * &sqrt).ct_eq(self), // Only return Some if it's the square root.
)
}
}
} else if (modulus % BigUint::from_str("16").unwrap()) == BigUint::from_str("1").unwrap() {
// Addition chain for (t - 1) // 2
let t_minus_1_over_2 = pow_fixed::generate(&quote! {self}, (&t - BigUint::one()) >> 1);
} else if (modulus % BigUint::from_str("16").unwrap()) == BigUint::from_str("1").unwrap() {
// Addition chain for (t - 1) // 2
let t_minus_1_over_2 = pow_fixed::generate(&quote! {self}, (&t - BigUint::one()) >> 1);
quote! {
impl ::ff::SqrtField for #name {
fn sqrt(&self) -> ::subtle::CtOption<Self> {
// Tonelli-Shank's algorithm for q mod 16 = 1
// https://eprint.iacr.org/2012/685.pdf (page 12, algorithm 5)
use ::subtle::{ConditionallySelectable, ConstantTimeEq};
quote! {
// Tonelli-Shank's algorithm for q mod 16 = 1
// https://eprint.iacr.org/2012/685.pdf (page 12, algorithm 5)
use ::subtle::{ConditionallySelectable, ConstantTimeEq};
// w = self^((t - 1) // 2)
let w = {
#t_minus_1_over_2
};
// w = self^((t - 1) // 2)
let w = {
#t_minus_1_over_2
};
let mut v = S;
let mut x = *self * &w;
let mut b = x * &w;
let mut v = S;
let mut x = *self * &w;
let mut b = x * &w;
// Initialize z as the 2^S root of unity.
let mut z = ROOT_OF_UNITY;
// Initialize z as the 2^S root of unity.
let mut z = ROOT_OF_UNITY;
for max_v in (1..=S).rev() {
let mut k = 1;
let mut tmp = b.square();
let mut j_less_than_v: ::subtle::Choice = 1.into();
for max_v in (1..=S).rev() {
let mut k = 1;
let mut tmp = b.square();
let mut j_less_than_v: ::subtle::Choice = 1.into();
for j in 2..max_v {
let tmp_is_one = tmp.ct_eq(&#name::one());
let squared = #name::conditional_select(&tmp, &z, tmp_is_one).square();
tmp = #name::conditional_select(&squared, &tmp, tmp_is_one);
let new_z = #name::conditional_select(&z, &squared, tmp_is_one);
j_less_than_v &= !j.ct_eq(&v);
k = u32::conditional_select(&j, &k, tmp_is_one);
z = #name::conditional_select(&z, &new_z, j_less_than_v);
}
let result = x * &z;
x = #name::conditional_select(&result, &x, b.ct_eq(&#name::one()));
z = z.square();
b *= &z;
v = k;
for j in 2..max_v {
let tmp_is_one = tmp.ct_eq(&#name::one());
let squared = #name::conditional_select(&tmp, &z, tmp_is_one).square();
tmp = #name::conditional_select(&squared, &tmp, tmp_is_one);
let new_z = #name::conditional_select(&z, &squared, tmp_is_one);
j_less_than_v &= !j.ct_eq(&v);
k = u32::conditional_select(&j, &k, tmp_is_one);
z = #name::conditional_select(&z, &new_z, j_less_than_v);
}
::subtle::CtOption::new(
x,
(x * &x).ct_eq(self), // Only return Some if it's the square root.
)
let result = x * &z;
x = #name::conditional_select(&result, &x, b.ct_eq(&#name::one()));
z = z.square();
b *= &z;
v = k;
}
::subtle::CtOption::new(
x,
(x * &x).ct_eq(self), // Only return Some if it's the square root.
)
}
}
} else {
quote! {}
};
} else {
syn::Error::new_spanned(
&name,
"ff_derive can't generate a square root function for this field.",
)
.to_compile_error()
};
// Compute R^2 mod m
let r2 = biguint_to_u64_vec((&r * &r) % modulus, limbs);
let r = biguint_to_u64_vec(r, limbs);
let modulus_repr = {
let mut buf = modulus.to_bytes_le();
buf.extend(iter::repeat(0).take((limbs * 8) - buf.len()));
buf
};
let modulus_repr = endianness.modulus_repr(modulus, limbs * 8);
let modulus = biguint_to_real_u64_vec(modulus.clone(), limbs);
// Compute -m^-1 mod 2**64 by exponentiating by totient(2**64) - 1
@ -634,6 +656,7 @@ fn prime_field_impl(
modulus: &BigUint,
endianness: &ReprEndianness,
limbs: usize,
sqrt_impl: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
// Returns r{n} as an ident.
fn get_temp(n: usize) -> syn::Ident {
@ -889,8 +912,9 @@ fn prime_field_impl(
let mont_reduce_self_params = mont_reduce_params(quote! {self}, limbs);
let mont_reduce_other_params = mont_reduce_params(quote! {other}, limbs);
let repr_endianness = endianness.repr_endianness();
let from_repr_impl = endianness.from_repr(name, limbs);
let into_repr_impl = endianness.into_repr(repr, &mont_reduce_self_params, limbs);
let to_repr_impl = endianness.to_repr(repr, &mont_reduce_self_params, limbs);
let top_limb_index = limbs - 1;
@ -911,7 +935,7 @@ fn prime_field_impl(
impl ::subtle::ConstantTimeEq for #name {
fn ct_eq(&self, other: &#name) -> ::subtle::Choice {
self.into_repr().ct_eq(&other.into_repr())
self.to_repr().ct_eq(&other.to_repr())
}
}
@ -927,7 +951,7 @@ fn prime_field_impl(
impl ::core::fmt::Debug for #name
{
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({:?})", stringify!(#name), self.into_repr())
write!(f, "{}({:?})", stringify!(#name), self.to_repr())
}
}
@ -958,7 +982,7 @@ fn prime_field_impl(
impl ::core::fmt::Display for #name {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
write!(f, "{}({})", stringify!(#name), self.into_repr())
write!(f, "{}({})", stringify!(#name), self.to_repr())
}
}
@ -973,13 +997,13 @@ fn prime_field_impl(
impl From<#name> for #repr {
fn from(e: #name) -> #repr {
e.into_repr()
e.to_repr()
}
}
impl<'a> From<&'a #name> for #repr {
fn from(e: &'a #name) -> #repr {
e.into_repr()
e.to_repr()
}
}
@ -1121,65 +1145,16 @@ fn prime_field_impl(
}
}
impl ::core::ops::BitAnd<u64> for #name {
type Output = u64;
#[inline(always)]
fn bitand(mut self, rhs: u64) -> u64 {
self.mont_reduce(
#mont_reduce_self_params
);
self.0[0] & rhs
}
}
impl ::core::ops::Shr<u32> for #name {
type Output = #name;
#[inline(always)]
fn shr(mut self, mut n: u32) -> #name {
if n as usize >= 64 * #limbs {
return Self::from(0);
}
// Convert from Montgomery to native representation.
self.mont_reduce(
#mont_reduce_self_params
);
while n >= 64 {
let mut t = 0;
for i in self.0.iter_mut().rev() {
::core::mem::swap(&mut t, i);
}
n -= 64;
}
if n > 0 {
let mut t = 0;
for i in self.0.iter_mut().rev() {
let t2 = *i << (64 - n);
*i >>= n;
*i |= t;
t = t2;
}
}
// Convert back to Montgomery representation
self * R2
}
}
impl ::ff::PrimeField for #name {
type Repr = #repr;
type ReprEndianness = #repr_endianness;
fn from_repr(r: #repr) -> Option<#name> {
#from_repr_impl
}
fn into_repr(&self) -> #repr {
#into_repr_impl
fn to_repr(&self) -> #repr {
#to_repr_impl
}
#[inline(always)]
@ -1270,16 +1245,15 @@ fn prime_field_impl(
#invert_impl
}
#[inline(always)]
fn frobenius_map(&mut self, _: usize) {
// This has no effect in a prime field.
}
#[inline]
fn square(&self) -> Self
{
#squaring_impl
}
fn sqrt(&self) -> ::subtle::CtOption<Self> {
#sqrt_impl
}
}
impl #name {

View File

@ -12,6 +12,7 @@ extern crate std;
#[cfg(feature = "derive")]
pub use ff_derive::*;
use byteorder::ByteOrder;
use core::convert::TryFrom;
use core::fmt;
use core::marker::PhantomData;
@ -72,39 +73,24 @@ pub trait Field:
/// failing if the element is zero.
fn invert(&self) -> CtOption<Self>;
/// Exponentiates this element by a power of the base prime modulus via
/// the Frobenius automorphism.
fn frobenius_map(&mut self, power: usize);
}
pub trait PowVartime<L>: Field
where
L: Copy + PartialEq + PartialOrd + AddAssign,
L: BitAnd<Output = L>,
L: Shr<Output = L>,
L: Sub<Output = L>,
{
const ZERO: L;
const ONE: L;
const LIMB_SIZE: L;
/// Returns the square root of the field element, if it is
/// quadratic residue.
fn sqrt(&self) -> CtOption<Self>;
/// Exponentiates `self` by `exp`, where `exp` is a little-endian order
/// integer exponent.
///
/// **This operation is variable time with respect to the exponent.** If the
/// exponent is fixed, this operation is effectively constant time.
fn pow_vartime<S: AsRef<[L]>>(&self, exp: S) -> Self {
fn pow_vartime<S: AsRef<[u64]>>(&self, exp: S) -> Self {
let mut res = Self::one();
for e in exp.as_ref().iter().rev() {
let mut i = Self::ZERO;
while i < Self::LIMB_SIZE {
for i in (0..64).rev() {
res = res.square();
if ((*e >> (Self::LIMB_SIZE - Self::ONE - i)) & Self::ONE) == Self::ONE {
if ((*e >> i) & 1) == 1 {
res.mul_assign(self);
}
i += Self::ONE;
}
}
@ -112,33 +98,36 @@ where
}
}
impl<T: Field> PowVartime<u8> for T {
const ZERO: u8 = 0;
const ONE: u8 = 1;
const LIMB_SIZE: u8 = 8;
/// Helper trait for converting the binary representation of a prime field element into a
/// specific endianness. This is useful when you need to act on the bit representation
/// of an element generically, as the native binary representation of a prime field is
/// field-dependent.
pub trait Endianness: ByteOrder {
/// Converts the provided representation between native and little-endian.
fn toggle_little_endian<T: AsMut<[u8]>>(t: &mut T);
}
impl<T: Field> PowVartime<u64> for T {
const ZERO: u64 = 0;
const ONE: u64 = 1;
const LIMB_SIZE: u64 = 64;
impl Endianness for byteorder::BigEndian {
fn toggle_little_endian<T: AsMut<[u8]>>(t: &mut T) {
t.as_mut().reverse();
}
}
/// This trait represents an element of a field that has a square root operation described for it.
pub trait SqrtField: Field {
/// Returns the square root of the field element, if it is
/// quadratic residue.
fn sqrt(&self) -> CtOption<Self>;
impl Endianness for byteorder::LittleEndian {
fn toggle_little_endian<T: AsMut<[u8]>>(_: &mut T) {
// No-op
}
}
/// This represents an element of a prime field.
pub trait PrimeField:
Field + Ord + From<u64> + BitAnd<u64, Output = u64> + Shr<u32, Output = Self>
{
pub trait PrimeField: Field + From<u64> {
/// The prime field can be converted back and forth into this binary
/// representation.
type Repr: Default + AsRef<[u8]> + AsMut<[u8]> + From<Self> + for<'r> From<&'r Self>;
/// This indicates the endianness of [`PrimeField::Repr`].
type ReprEndianness: Endianness;
/// Interpret a string of numbers as a (congruent) prime field element.
/// Does not accept unnecessary leading zeroes or a blank string.
fn from_str(s: &str) -> Option<Self> {
@ -183,17 +172,16 @@ pub trait PrimeField:
/// this prime field, failing if the input is not canonical (is not smaller than the
/// field's modulus).
///
/// The byte representation is interpreted with the same endianness as is returned
/// by [`PrimeField::into_repr`].
/// The byte representation is interpreted with the endianness defined by
/// [`PrimeField::ReprEndianness`].
fn from_repr(_: Self::Repr) -> Option<Self>;
/// Converts an element of the prime field into the standard byte representation for
/// this field.
///
/// Endianness of the byte representation is defined by the field implementation.
/// Callers should assume that it is the standard endianness used to represent encoded
/// elements of this particular field.
fn into_repr(&self) -> Self::Repr;
/// The endianness of the byte representation is defined by
/// [`PrimeField::ReprEndianness`].
fn to_repr(&self) -> Self::Repr;
/// Returns true iff this element is odd.
fn is_odd(&self) -> bool;
@ -230,7 +218,7 @@ pub trait PrimeField:
/// pairing-friendly curve) can be defined in a subtrait.
pub trait ScalarEngine: Sized + 'static + Clone {
/// This is the scalar field of the engine's groups.
type Fr: PrimeField + SqrtField;
type Fr: PrimeField;
}
#[derive(Debug)]

View File

@ -1,7 +1,7 @@
// Catch documentation errors caused by code changes.
#![deny(intra_doc_link_resolution_failure)]
use ff::{PrimeField, ScalarEngine, SqrtField};
use ff::{Field, PrimeField, ScalarEngine};
use rand::RngCore;
use std::error::Error;
use std::fmt;
@ -47,8 +47,8 @@ pub trait CurveProjective:
+ CurveOpsOwned<<Self as CurveProjective>::Affine>
{
type Engine: ScalarEngine<Fr = Self::Scalar>;
type Scalar: PrimeField + SqrtField;
type Base: SqrtField;
type Scalar: PrimeField;
type Base: Field;
type Affine: CurveAffine<Projective = Self, Scalar = Self::Scalar>;
/// Returns an element chosen uniformly at random using a user-provided RNG.
@ -105,8 +105,8 @@ pub trait CurveAffine:
+ Neg<Output = Self>
{
type Engine: ScalarEngine<Fr = Self::Scalar>;
type Scalar: PrimeField + SqrtField;
type Base: SqrtField;
type Scalar: PrimeField;
type Base: Field;
type Projective: CurveProjective<Affine = Self, Scalar = Self::Scalar>;
type Uncompressed: EncodedPoint<Affine = Self>;
type Compressed: EncodedPoint<Affine = Self>;

View File

@ -90,7 +90,7 @@ fn random_wnaf_tests<G: CurveProjective>() {
g1.mul_assign(s);
wnaf_table(&mut table, g, w);
wnaf_form(&mut wnaf, s.into_repr(), w);
wnaf_form(&mut wnaf, s.to_repr(), w);
let g2 = wnaf_exp(&table, &wnaf);
assert_eq!(g1, g2);

View File

@ -149,7 +149,7 @@ impl<G: CurveProjective> Wnaf<(), Vec<G>, Vec<i64>> {
let window_size = G::recommended_wnaf_for_scalar(&scalar);
// Compute the wNAF form of the scalar.
wnaf_form(&mut self.scalar, scalar.into_repr(), window_size);
wnaf_form(&mut self.scalar, scalar.to_repr(), window_size);
// Return a Wnaf object that mutably borrows the base storage location, but
// immutably borrows the computed wNAF form scalar location.
@ -203,7 +203,7 @@ impl<B, S: AsMut<Vec<i64>>> Wnaf<usize, B, S> {
where
B: AsRef<[G]>,
{
wnaf_form(self.scalar.as_mut(), scalar.into_repr(), self.window_size);
wnaf_form(self.scalar.as_mut(), scalar.to_repr(), self.window_size);
wnaf_exp(self.base.as_ref(), self.scalar.as_mut())
}
}

View File

@ -3,7 +3,7 @@ use rand_core::SeedableRng;
use rand_xorshift::XorShiftRng;
use std::ops::{AddAssign, MulAssign, Neg, SubAssign};
use ff::{Field, PrimeField, SqrtField};
use ff::{Field, PrimeField};
use pairing::bls12_381::*;
fn bench_fq_add_assign(c: &mut Criterion) {
@ -155,7 +155,7 @@ fn bench_fq_sqrt(c: &mut Criterion) {
});
}
fn bench_fq_into_repr(c: &mut Criterion) {
fn bench_fq_to_repr(c: &mut Criterion) {
const SAMPLES: usize = 1000;
let mut rng = XorShiftRng::from_seed([
@ -166,10 +166,10 @@ fn bench_fq_into_repr(c: &mut Criterion) {
let v: Vec<Fq> = (0..SAMPLES).map(|_| Fq::random(&mut rng)).collect();
let mut count = 0;
c.bench_function("Fq::into_repr", |b| {
c.bench_function("Fq::to_repr", |b| {
b.iter(|| {
count = (count + 1) % SAMPLES;
v[count].into_repr()
v[count].to_repr()
})
});
}
@ -183,7 +183,7 @@ fn bench_fq_from_repr(c: &mut Criterion) {
]);
let v: Vec<FqRepr> = (0..SAMPLES)
.map(|_| Fq::random(&mut rng).into_repr())
.map(|_| Fq::random(&mut rng).to_repr())
.collect();
let mut count = 0;
@ -204,6 +204,6 @@ criterion_group!(
bench_fq_invert,
bench_fq_neg,
bench_fq_sqrt,
bench_fq_into_repr,
bench_fq_to_repr,
bench_fq_from_repr,
);

View File

@ -3,7 +3,7 @@ use rand_core::SeedableRng;
use rand_xorshift::XorShiftRng;
use std::ops::{AddAssign, MulAssign, SubAssign};
use ff::{Field, SqrtField};
use ff::Field;
use pairing::bls12_381::*;
fn bench_fq2_add_assign(c: &mut Criterion) {

View File

@ -3,7 +3,7 @@ use rand_core::SeedableRng;
use rand_xorshift::XorShiftRng;
use std::ops::{AddAssign, MulAssign, Neg, SubAssign};
use ff::{Field, PrimeField, SqrtField};
use ff::{Field, PrimeField};
use pairing::bls12_381::*;
fn bench_fr_add_assign(c: &mut Criterion) {
@ -155,7 +155,7 @@ fn bench_fr_sqrt(c: &mut Criterion) {
});
}
fn bench_fr_into_repr(c: &mut Criterion) {
fn bench_fr_to_repr(c: &mut Criterion) {
const SAMPLES: usize = 1000;
let mut rng = XorShiftRng::from_seed([
@ -166,10 +166,10 @@ fn bench_fr_into_repr(c: &mut Criterion) {
let v: Vec<Fr> = (0..SAMPLES).map(|_| Fr::random(&mut rng)).collect();
let mut count = 0;
c.bench_function("Fr::into_repr", |b| {
c.bench_function("Fr::to_repr", |b| {
b.iter(|| {
count = (count + 1) % SAMPLES;
v[count].into_repr()
v[count].to_repr()
})
});
}
@ -183,7 +183,7 @@ fn bench_fr_from_repr(c: &mut Criterion) {
]);
let v: Vec<FrRepr> = (0..SAMPLES)
.map(|_| Fr::random(&mut rng).into_repr())
.map(|_| Fr::random(&mut rng).to_repr())
.collect();
let mut count = 0;
@ -204,6 +204,6 @@ criterion_group!(
bench_fr_invert,
bench_fr_neg,
bench_fr_sqrt,
bench_fr_into_repr,
bench_fr_to_repr,
bench_fr_from_repr,
);

View File

@ -754,7 +754,7 @@ pub mod g1 {
use super::super::{Bls12, Fq, Fq12, FqRepr, Fr};
use super::g2::G2Affine;
use crate::{Engine, PairingCurveAffine};
use ff::{BitIterator, Field, PrimeField, SqrtField};
use ff::{BitIterator, Field, PrimeField};
use group::{CurveAffine, CurveProjective, EncodedPoint, GroupDecodingError};
use rand_core::RngCore;
use std::fmt;
@ -872,8 +872,8 @@ pub mod g1 {
// is at infinity.
res.0[0] |= 1 << 6;
} else {
res.0[..48].copy_from_slice(&affine.x.into_repr().0);
res.0[48..].copy_from_slice(&affine.y.into_repr().0);
res.0[..48].copy_from_slice(&affine.x.to_repr().0);
res.0[48..].copy_from_slice(&affine.y.to_repr().0);
}
res
@ -969,7 +969,7 @@ pub mod g1 {
// is at infinity.
res.0[0] |= 1 << 6;
} else {
res.0 = affine.x.into_repr().0;
res.0 = affine.x.to_repr().0;
let negy = affine.y.neg();
@ -1054,8 +1054,6 @@ pub mod g1 {
#[test]
fn g1_generator() {
use crate::SqrtField;
let mut x = Fq::zero();
let mut i = 0;
loop {
@ -1366,7 +1364,7 @@ pub mod g2 {
use super::super::{Bls12, Fq, Fq12, Fq2, FqRepr, Fr};
use super::g1::G1Affine;
use crate::{Engine, PairingCurveAffine};
use ff::{BitIterator, Field, PrimeField, SqrtField};
use ff::{BitIterator, Field, PrimeField};
use group::{CurveAffine, CurveProjective, EncodedPoint, GroupDecodingError};
use rand_core::RngCore;
use std::fmt;
@ -1496,10 +1494,10 @@ pub mod g2 {
// is at infinity.
res.0[0] |= 1 << 6;
} else {
res.0[0..48].copy_from_slice(&affine.x.c1.into_repr().0);
res.0[48..96].copy_from_slice(&affine.x.c0.into_repr().0);
res.0[96..144].copy_from_slice(&affine.y.c1.into_repr().0);
res.0[144..192].copy_from_slice(&affine.y.c0.into_repr().0);
res.0[0..48].copy_from_slice(&affine.x.c1.to_repr().0);
res.0[48..96].copy_from_slice(&affine.x.c0.to_repr().0);
res.0[96..144].copy_from_slice(&affine.y.c1.to_repr().0);
res.0[144..192].copy_from_slice(&affine.y.c0.to_repr().0);
}
res
@ -1610,8 +1608,8 @@ pub mod g2 {
// is at infinity.
res.0[0] |= 1 << 6;
} else {
res.0[..48].copy_from_slice(&affine.x.c1.into_repr().0);
res.0[48..].copy_from_slice(&affine.x.c0.into_repr().0);
res.0[..48].copy_from_slice(&affine.x.c1.to_repr().0);
res.0[48..].copy_from_slice(&affine.x.c0.to_repr().0);
let negy = affine.y.neg();
@ -1708,8 +1706,6 @@ pub mod g2 {
#[test]
fn g2_generator() {
use crate::SqrtField;
let mut x = Fq2::zero();
let mut i = 0;
loop {

View File

@ -2,8 +2,6 @@ use super::fq2::Fq2;
use ff::{Field, PrimeField};
use std::ops::{AddAssign, MulAssign, SubAssign};
#[cfg(test)]
use ff::PowVartime;
#[cfg(test)]
use std::ops::Neg;
@ -1534,67 +1532,6 @@ fn test_fq_mul_assign() {
}
}
#[test]
fn test_fq_shr() {
let mut a = Fq::from_repr(FqRepr([
0x12, 0x25, 0xf2, 0x90, 0x1a, 0xea, 0x51, 0x4e, 0x16, 0x08, 0x0c, 0xf4, 0x07, 0x1e, 0x0b,
0x05, 0xc5, 0x54, 0x1f, 0xd4, 0x80, 0x46, 0xb7, 0xe7, 0x9d, 0xdd, 0x5b, 0x31, 0x2f, 0x3d,
0xd1, 0x04, 0x43, 0x24, 0x2c, 0x06, 0xae, 0xd5, 0x52, 0x87, 0xaa, 0x5c, 0xdd, 0x61, 0x72,
0x84, 0x7f, 0xfd,
]))
.unwrap();
a = a >> 0;
assert_eq!(
a.into_repr(),
FqRepr([
0x12, 0x25, 0xf2, 0x90, 0x1a, 0xea, 0x51, 0x4e, 0x16, 0x08, 0x0c, 0xf4, 0x07, 0x1e,
0x0b, 0x05, 0xc5, 0x54, 0x1f, 0xd4, 0x80, 0x46, 0xb7, 0xe7, 0x9d, 0xdd, 0x5b, 0x31,
0x2f, 0x3d, 0xd1, 0x04, 0x43, 0x24, 0x2c, 0x06, 0xae, 0xd5, 0x52, 0x87, 0xaa, 0x5c,
0xdd, 0x61, 0x72, 0x84, 0x7f, 0xfd,
])
);
a = a >> 1;
assert_eq!(
a.into_repr(),
FqRepr([
0x09, 0x12, 0xf9, 0x48, 0x0d, 0x75, 0x28, 0xa7, 0x0b, 0x04, 0x06, 0x7a, 0x03, 0x8f,
0x05, 0x82, 0xe2, 0xaa, 0x0f, 0xea, 0x40, 0x23, 0x5b, 0xf3, 0xce, 0xee, 0xad, 0x98,
0x97, 0x9e, 0xe8, 0x82, 0x21, 0x92, 0x16, 0x03, 0x57, 0x6a, 0xa9, 0x43, 0xd5, 0x2e,
0x6e, 0xb0, 0xb9, 0x42, 0x3f, 0xfe,
])
);
a = a >> 50;
assert_eq!(
a.into_repr(),
FqRepr([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x44, 0xbe, 0x52, 0x03, 0x5d, 0x4a, 0x29,
0xc2, 0xc1, 0x01, 0x9e, 0x80, 0xe3, 0xc1, 0x60, 0xb8, 0xaa, 0x83, 0xfa, 0x90, 0x08,
0xd6, 0xfc, 0xf3, 0xbb, 0xab, 0x66, 0x25, 0xe7, 0xba, 0x20, 0x88, 0x64, 0x85, 0x80,
0xd5, 0xda, 0xaa, 0x50, 0xf5, 0x4b,
])
);
a = a >> 130;
assert_eq!(
a.into_repr(),
FqRepr([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x91, 0x2f, 0x94, 0x80, 0xd7,
0x52, 0x8a, 0x70, 0xb0, 0x40, 0x67, 0xa0, 0x38, 0xf0, 0x58, 0x2e, 0x2a, 0xa0, 0xfe,
0xa4, 0x02, 0x35, 0xbf, 0x3c, 0xee,
])
);
a = a >> 64;
assert_eq!(
a.into_repr(),
FqRepr([
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x91, 0x2f, 0x94, 0x80, 0xd7, 0x52, 0x8a, 0x70, 0xb0, 0x40, 0x67,
0xa0, 0x38, 0xf0, 0x58, 0x2e, 0x2a,
])
);
}
#[test]
fn test_fq_squaring() {
let a = Fq([
@ -1705,18 +1642,21 @@ fn test_fq_pow() {
assert_eq!(c, target);
}
use byteorder::ByteOrder;
let mut char_limbs = [0; 6];
byteorder::BigEndian::read_u64_into(Fq::char().as_ref(), &mut char_limbs);
char_limbs.reverse();
for _ in 0..1000 {
// Exponentiating by the modulus should have no effect in a prime field.
let a = Fq::random(&mut rng);
assert_eq!(a, a.pow_vartime(Fq::char()));
assert_eq!(a, a.pow_vartime(char_limbs));
}
}
#[test]
fn test_fq_sqrt() {
use ff::SqrtField;
let mut rng = XorShiftRng::from_seed([
0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc,
0xe5,
@ -1747,7 +1687,7 @@ fn test_fq_sqrt() {
}
#[test]
fn test_fq_from_into_repr() {
fn test_fq_from_to_repr() {
// q + 1 should not be in the field
assert!(Fq::from_repr(FqRepr([
0x1a, 0x01, 0x11, 0xea, 0x39, 0x7f, 0xe6, 0x9a, 0x4b, 0x1b, 0xa7, 0xb6, 0x43, 0x4b, 0xac,
@ -1782,7 +1722,7 @@ fn test_fq_from_into_repr() {
0x17, 0x91, 0x4c,
]);
a_fq.mul_assign(&b_fq);
assert_eq!(a_fq.into_repr(), c);
assert_eq!(a_fq.to_repr(), c);
// Zero should be in the field.
assert!(Fq::from_repr(FqRepr([0; 48])).unwrap().is_zero());
@ -1795,7 +1735,7 @@ fn test_fq_from_into_repr() {
for _ in 0..1000 {
// Try to turn Fq elements into representations and back again, and compare.
let a = Fq::random(&mut rng);
let a_repr = a.into_repr();
let a_repr = a.to_repr();
let b_repr = FqRepr::from(a);
assert_eq!(a_repr, b_repr);
let a_again = Fq::from_repr(a_repr).unwrap();
@ -1846,8 +1786,6 @@ fn test_fq_num_bits() {
#[test]
fn test_fq_root_of_unity() {
use ff::SqrtField;
assert_eq!(Fq::S, 1);
assert_eq!(Fq::multiplicative_generator(), Fq::from(2));
assert_eq!(
@ -1869,7 +1807,6 @@ fn test_fq_root_of_unity() {
fn fq_field_tests() {
crate::tests::field::random_field_tests::<Fq>();
crate::tests::field::random_sqrt_tests::<Fq>();
crate::tests::field::random_frobenius_tests::<Fq, _>(Fq::char(), 13);
crate::tests::field::from_str_tests::<Fq>();
}

View File

@ -39,6 +39,15 @@ impl Fq12 {
self.c0.mul_by_nonresidue();
self.c0.add_assign(&aa);
}
pub fn frobenius_map(&mut self, power: usize) {
self.c0.frobenius_map(power);
self.c1.frobenius_map(power);
self.c1.c0.mul_assign(&FROBENIUS_COEFF_FQ12_C1[power % 12]);
self.c1.c1.mul_assign(&FROBENIUS_COEFF_FQ12_C1[power % 12]);
self.c1.c2.mul_assign(&FROBENIUS_COEFF_FQ12_C1[power % 12]);
}
}
impl ConditionallySelectable for Fq12 {
@ -200,15 +209,6 @@ impl Field for Fq12 {
}
}
fn frobenius_map(&mut self, power: usize) {
self.c0.frobenius_map(power);
self.c1.frobenius_map(power);
self.c1.c0.mul_assign(&FROBENIUS_COEFF_FQ12_C1[power % 12]);
self.c1.c1.mul_assign(&FROBENIUS_COEFF_FQ12_C1[power % 12]);
self.c1.c2.mul_assign(&FROBENIUS_COEFF_FQ12_C1[power % 12]);
}
fn square(&self) -> Self {
let mut ab = self.c0;
ab.mul_assign(&self.c1);
@ -237,6 +237,10 @@ impl Field for Fq12 {
c1: t.mul(&self.c1).neg(),
})
}
fn sqrt(&self) -> CtOption<Self> {
unimplemented!()
}
}
#[cfg(test)]
@ -278,8 +282,5 @@ fn test_fq12_mul_by_014() {
#[test]
fn fq12_field_tests() {
use ff::PrimeField;
crate::tests::field::random_field_tests::<Fq12>();
crate::tests::field::random_frobenius_tests::<Fq12, _>(super::fq::Fq::char(), 13);
}

View File

@ -1,5 +1,5 @@
use super::fq::{Fq, FROBENIUS_COEFF_FQ2_C1, NEGATIVE_ONE};
use ff::{Field, PowVartime, SqrtField};
use ff::Field;
use rand_core::RngCore;
use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
@ -53,6 +53,10 @@ impl Fq2 {
t1
}
pub fn frobenius_map(&mut self, power: usize) {
self.c1.mul_assign(&FROBENIUS_COEFF_FQ2_C1[power % 2]);
}
}
impl ConditionallySelectable for Fq2 {
@ -238,12 +242,6 @@ impl Field for Fq2 {
})
}
fn frobenius_map(&mut self, power: usize) {
self.c1.mul_assign(&FROBENIUS_COEFF_FQ2_C1[power % 2]);
}
}
impl SqrtField for Fq2 {
/// WARNING: THIS IS NOT ACTUALLY CONSTANT TIME YET!
/// THIS WILL BE REPLACED BY THE bls12_381 CRATE, WHICH IS CONSTANT TIME!
fn sqrt(&self) -> CtOption<Self> {
@ -922,9 +920,6 @@ fn test_fq2_mul_nonresidue() {
#[test]
fn fq2_field_tests() {
use ff::PrimeField;
crate::tests::field::random_field_tests::<Fq2>();
crate::tests::field::random_sqrt_tests::<Fq2>();
crate::tests::field::random_frobenius_tests::<Fq2, _>(super::fq::Fq::char(), 13);
}

View File

@ -99,6 +99,15 @@ impl Fq6 {
self.c1 = t2;
self.c2 = t3;
}
pub fn frobenius_map(&mut self, power: usize) {
self.c0.frobenius_map(power);
self.c1.frobenius_map(power);
self.c2.frobenius_map(power);
self.c1.mul_assign(&FROBENIUS_COEFF_FQ6_C1[power % 6]);
self.c2.mul_assign(&FROBENIUS_COEFF_FQ6_C2[power % 6]);
}
}
impl ConditionallySelectable for Fq6 {
@ -305,15 +314,6 @@ impl Field for Fq6 {
}
}
fn frobenius_map(&mut self, power: usize) {
self.c0.frobenius_map(power);
self.c1.frobenius_map(power);
self.c2.frobenius_map(power);
self.c1.mul_assign(&FROBENIUS_COEFF_FQ6_C1[power % 6]);
self.c2.mul_assign(&FROBENIUS_COEFF_FQ6_C2[power % 6]);
}
fn square(&self) -> Self {
let s0 = self.c0.square();
let mut ab = self.c0;
@ -391,6 +391,10 @@ impl Field for Fq6 {
tmp
})
}
fn sqrt(&self) -> CtOption<Self> {
unimplemented!()
}
}
#[cfg(test)]
@ -470,8 +474,5 @@ fn test_fq6_mul_by_01() {
#[test]
fn fq6_field_tests() {
use ff::PrimeField;
crate::tests::field::random_field_tests::<Fq6>();
crate::tests::field::random_frobenius_tests::<Fq6, _>(super::fq::Fq::char(), 13);
}

View File

@ -7,8 +7,6 @@ use std::ops::{AddAssign, MulAssign, SubAssign};
#[PrimeFieldReprEndianness = "little"]
pub struct Fr([u64; 4]);
#[cfg(test)]
use ff::PowVartime;
#[cfg(test)]
use rand_core::SeedableRng;
#[cfg(test)]
@ -323,61 +321,6 @@ fn test_fr_mul_assign() {
}
}
#[test]
fn test_fr_shr() {
let mut a = Fr::from_repr(FrRepr([
0x3f, 0x28, 0x2a, 0x48, 0xec, 0xba, 0x3f, 0xb3, 0xdf, 0xb3, 0x8c, 0xa8, 0xd3, 0xe0, 0x7d,
0x99, 0x25, 0x55, 0x0e, 0x9a, 0x2a, 0x2d, 0xf6, 0x9a, 0xa1, 0x0d, 0xe7, 0x8d, 0xb0, 0x3a,
0x00, 0x36,
]))
.unwrap();
a = a >> 0;
assert_eq!(
a.into_repr(),
FrRepr([
0x3f, 0x28, 0x2a, 0x48, 0xec, 0xba, 0x3f, 0xb3, 0xdf, 0xb3, 0x8c, 0xa8, 0xd3, 0xe0,
0x7d, 0x99, 0x25, 0x55, 0x0e, 0x9a, 0x2a, 0x2d, 0xf6, 0x9a, 0xa1, 0x0d, 0xe7, 0x8d,
0xb0, 0x3a, 0x00, 0x36,
])
);
a = a >> 1;
assert_eq!(
a.into_repr(),
FrRepr([
0x1f, 0x14, 0x15, 0x24, 0x76, 0xdd, 0x9f, 0xd9, 0xef, 0x59, 0x46, 0xd4, 0x69, 0xf0,
0xbe, 0xcc, 0x92, 0x2a, 0x07, 0x4d, 0x95, 0x16, 0x7b, 0xcd, 0xd0, 0x86, 0xf3, 0x46,
0x58, 0x1d, 0x00, 0x1b,
])
);
a = a >> 50;
assert_eq!(
a.into_repr(),
FrRepr([
0x67, 0xf6, 0x7b, 0x96, 0x11, 0x75, 0x1a, 0xbc, 0x2f, 0xb3, 0xa4, 0xca, 0x41, 0x53,
0xa5, 0xc5, 0x5e, 0x33, 0xb4, 0xe1, 0xbc, 0x11, 0x56, 0x07, 0xc0, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
);
a = a >> 130;
assert_eq!(
a.into_repr(),
FrRepr([
0xd7, 0x0c, 0x6d, 0x38, 0x6f, 0x84, 0xd5, 0x01, 0xb0, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
);
a = a >> 64;
assert_eq!(
a.into_repr(),
FrRepr([
0xb0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
);
}
#[test]
fn test_fr_squaring() {
let a = Fr([
@ -485,18 +428,20 @@ fn test_fr_pow() {
assert_eq!(c, target);
}
use byteorder::ByteOrder;
let mut char_limbs = [0; 4];
byteorder::LittleEndian::read_u64_into(Fr::char().as_ref(), &mut char_limbs);
for _ in 0..1000 {
// Exponentiating by the modulus should have no effect in a prime field.
let a = Fr::random(&mut rng);
assert_eq!(a, a.pow_vartime(Fr::char()));
assert_eq!(a, a.pow_vartime(char_limbs));
}
}
#[test]
fn test_fr_sqrt() {
use ff::SqrtField;
let mut rng = XorShiftRng::from_seed([
0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc,
0xe5,
@ -527,7 +472,7 @@ fn test_fr_sqrt() {
}
#[test]
fn test_fr_from_into_repr() {
fn test_fr_from_to_repr() {
// r + 1 should not be in the field
assert!(Fr::from_repr(FrRepr([
0x02, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x5b, 0xfe, 0xff, 0x02, 0xa4, 0xbd,
@ -558,7 +503,7 @@ fn test_fr_from_into_repr() {
0x61, 0x71,
]);
a_fr.mul_assign(&b_fr);
assert_eq!(a_fr.into_repr(), c);
assert_eq!(a_fr.to_repr(), c);
// Zero should be in the field.
assert!(Fr::from_repr(FrRepr([0; 32])).unwrap().is_zero());
@ -571,7 +516,7 @@ fn test_fr_from_into_repr() {
for _ in 0..1000 {
// Try to turn Fr elements into representations and back again, and compare.
let a = Fr::random(&mut rng);
let a_repr = a.into_repr();
let a_repr = a.to_repr();
let b_repr = FrRepr::from(a);
assert_eq!(a_repr, b_repr);
let a_again = Fr::from_repr(a_repr).unwrap();
@ -628,8 +573,6 @@ fn test_fr_num_bits() {
#[test]
fn test_fr_root_of_unity() {
use ff::SqrtField;
assert_eq!(Fr::S, 32);
assert_eq!(Fr::multiplicative_generator(), Fr::from(7));
assert_eq!(
@ -649,7 +592,6 @@ fn test_fr_root_of_unity() {
fn fr_field_tests() {
crate::tests::field::random_field_tests::<Fr>();
crate::tests::field::random_sqrt_tests::<Fr>();
crate::tests::field::random_frobenius_tests::<Fr, _>(Fr::char(), 13);
crate::tests::field::from_str_tests::<Fr>();
}

View File

@ -23,7 +23,7 @@ pub use self::fr::{Fr, FrRepr};
use super::{Engine, PairingCurveAffine};
use ff::{BitIterator, Field, PowVartime, ScalarEngine};
use ff::{BitIterator, Field, ScalarEngine};
use group::CurveAffine;
use std::ops::{AddAssign, MulAssign, Neg, SubAssign};
use subtle::CtOption;

View File

@ -147,13 +147,11 @@ fn test_g1_uncompressed_invalid_vectors() {
}
}
// PrimeField::char() returns the modulus in its little-endian byte representation,
// but Fq field elements use big-endian encoding, so flip the endianness.
let m: Vec<_> = Fq::char().as_ref().iter().cloned().rev().collect();
let m = Fq::char();
{
let mut o = o;
o.as_mut()[..48].copy_from_slice(&m[..]);
o.as_mut()[..48].copy_from_slice(m.as_ref());
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
assert_eq!(coordinate, "x coordinate");
@ -164,7 +162,7 @@ fn test_g1_uncompressed_invalid_vectors() {
{
let mut o = o;
o.as_mut()[48..].copy_from_slice(&m[..]);
o.as_mut()[48..].copy_from_slice(m.as_ref());
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
assert_eq!(coordinate, "y coordinate");
@ -174,7 +172,7 @@ fn test_g1_uncompressed_invalid_vectors() {
}
{
let m = Fq::zero().into_repr();
let m = Fq::zero().to_repr();
let mut o = o;
o.as_mut()[..48].copy_from_slice(m.as_ref());
@ -200,8 +198,8 @@ fn test_g1_uncompressed_invalid_vectors() {
let y = y.unwrap();
// We know this is on the curve, but it's likely not going to be in the correct subgroup.
o.as_mut()[..48].copy_from_slice(x.into_repr().as_ref());
o.as_mut()[48..].copy_from_slice(y.into_repr().as_ref());
o.as_mut()[..48].copy_from_slice(x.to_repr().as_ref());
o.as_mut()[48..].copy_from_slice(y.to_repr().as_ref());
if let Err(GroupDecodingError::NotInSubgroup) = o.into_affine() {
break;
@ -265,13 +263,11 @@ fn test_g2_uncompressed_invalid_vectors() {
}
}
// PrimeField::char() returns the modulus in its little-endian byte representation,
// but Fq field elements use big-endian encoding, so flip the endianness.
let m: Vec<_> = Fq::char().as_ref().iter().cloned().rev().collect();
let m = Fq::char();
{
let mut o = o;
o.as_mut()[..48].copy_from_slice(&m[..]);
o.as_mut()[..48].copy_from_slice(m.as_ref());
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
assert_eq!(coordinate, "x coordinate (c1)");
@ -282,7 +278,7 @@ fn test_g2_uncompressed_invalid_vectors() {
{
let mut o = o;
o.as_mut()[48..96].copy_from_slice(&m[..]);
o.as_mut()[48..96].copy_from_slice(m.as_ref());
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
assert_eq!(coordinate, "x coordinate (c0)");
@ -293,7 +289,7 @@ fn test_g2_uncompressed_invalid_vectors() {
{
let mut o = o;
o.as_mut()[96..144].copy_from_slice(&m[..]);
o.as_mut()[96..144].copy_from_slice(m.as_ref());
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
assert_eq!(coordinate, "y coordinate (c1)");
@ -304,7 +300,7 @@ fn test_g2_uncompressed_invalid_vectors() {
{
let mut o = o;
o.as_mut()[144..].copy_from_slice(&m[..]);
o.as_mut()[144..].copy_from_slice(m.as_ref());
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
assert_eq!(coordinate, "y coordinate (c0)");
@ -314,7 +310,7 @@ fn test_g2_uncompressed_invalid_vectors() {
}
{
let m = Fq::zero().into_repr();
let m = Fq::zero().to_repr();
let mut o = o;
o.as_mut()[..48].copy_from_slice(m.as_ref());
@ -344,10 +340,10 @@ fn test_g2_uncompressed_invalid_vectors() {
let y = y.unwrap();
// We know this is on the curve, but it's likely not going to be in the correct subgroup.
o.as_mut()[..48].copy_from_slice(x.c1.into_repr().as_ref());
o.as_mut()[48..96].copy_from_slice(x.c0.into_repr().as_ref());
o.as_mut()[96..144].copy_from_slice(y.c1.into_repr().as_ref());
o.as_mut()[144..].copy_from_slice(y.c0.into_repr().as_ref());
o.as_mut()[..48].copy_from_slice(x.c1.to_repr().as_ref());
o.as_mut()[48..96].copy_from_slice(x.c0.to_repr().as_ref());
o.as_mut()[96..144].copy_from_slice(y.c1.to_repr().as_ref());
o.as_mut()[144..].copy_from_slice(y.c0.to_repr().as_ref());
if let Err(GroupDecodingError::NotInSubgroup) = o.into_affine() {
break;
@ -411,13 +407,11 @@ fn test_g1_compressed_invalid_vectors() {
}
}
// PrimeField::char() returns the modulus in its little-endian byte representation,
// but Fq field elements use big-endian encoding, so flip the endianness.
let m: Vec<_> = Fq::char().as_ref().iter().cloned().rev().collect();
let m = Fq::char();
{
let mut o = o;
o.as_mut()[..48].copy_from_slice(&m[..]);
o.as_mut()[..48].copy_from_slice(m.as_ref());
o.as_mut()[0] |= 0b1000_0000;
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
@ -439,7 +433,7 @@ fn test_g1_compressed_invalid_vectors() {
if x3b.sqrt().is_some().into() {
x.add_assign(&Fq::one());
} else {
o.as_mut().copy_from_slice(x.into_repr().as_ref());
o.as_mut().copy_from_slice(x.to_repr().as_ref());
o.as_mut()[0] |= 0b1000_0000;
if let Err(GroupDecodingError::NotOnCurve) = o.into_affine() {
@ -462,7 +456,7 @@ fn test_g1_compressed_invalid_vectors() {
if x3b.sqrt().is_some().into() {
// We know this is on the curve, but it's likely not going to be in the correct subgroup.
o.as_mut().copy_from_slice(x.into_repr().as_ref());
o.as_mut().copy_from_slice(x.to_repr().as_ref());
o.as_mut()[0] |= 0b1000_0000;
if let Err(GroupDecodingError::NotInSubgroup) = o.into_affine() {
@ -527,13 +521,11 @@ fn test_g2_compressed_invalid_vectors() {
}
}
// PrimeField::char() returns the modulus in its little-endian byte representation,
// but Fq field elements use big-endian encoding, so flip the endianness.
let m: Vec<_> = Fq::char().as_ref().iter().cloned().rev().collect();
let m = Fq::char();
{
let mut o = o;
o.as_mut()[..48].copy_from_slice(&m[..]);
o.as_mut()[..48].copy_from_slice(m.as_ref());
o.as_mut()[0] |= 0b1000_0000;
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
@ -545,7 +537,7 @@ fn test_g2_compressed_invalid_vectors() {
{
let mut o = o;
o.as_mut()[48..96].copy_from_slice(&m[..]);
o.as_mut()[48..96].copy_from_slice(m.as_ref());
o.as_mut()[0] |= 0b1000_0000;
if let Err(GroupDecodingError::CoordinateDecodingError(coordinate)) = o.into_affine() {
@ -573,8 +565,8 @@ fn test_g2_compressed_invalid_vectors() {
if x3b.sqrt().is_some().into() {
x.add_assign(&Fq2::one());
} else {
o.as_mut()[..48].copy_from_slice(x.c1.into_repr().as_ref());
o.as_mut()[48..].copy_from_slice(x.c0.into_repr().as_ref());
o.as_mut()[..48].copy_from_slice(x.c1.to_repr().as_ref());
o.as_mut()[48..].copy_from_slice(x.c0.to_repr().as_ref());
o.as_mut()[0] |= 0b1000_0000;
if let Err(GroupDecodingError::NotOnCurve) = o.into_affine() {
@ -603,8 +595,8 @@ fn test_g2_compressed_invalid_vectors() {
if x3b.sqrt().is_some().into() {
// We know this is on the curve, but it's likely not going to be in the correct subgroup.
o.as_mut()[..48].copy_from_slice(x.c1.into_repr().as_ref());
o.as_mut()[48..].copy_from_slice(x.c0.into_repr().as_ref());
o.as_mut()[..48].copy_from_slice(x.c1.to_repr().as_ref());
o.as_mut()[48..].copy_from_slice(x.c0.to_repr().as_ref());
o.as_mut()[0] |= 0b1000_0000;
if let Err(GroupDecodingError::NotInSubgroup) = o.into_affine() {

View File

@ -20,7 +20,7 @@ pub mod tests;
pub mod bls12_381;
use ff::{Field, PrimeField, ScalarEngine, SqrtField};
use ff::{Field, PrimeField, ScalarEngine};
use group::{CurveAffine, CurveOps, CurveOpsOwned, CurveProjective};
use subtle::CtOption;
@ -61,10 +61,10 @@ pub trait Engine: ScalarEngine {
> + From<Self::G2>;
/// The base field that hosts G1.
type Fq: PrimeField + SqrtField;
type Fq: PrimeField;
/// The extension field that hosts G2.
type Fqe: SqrtField;
type Fqe: Field;
/// The extension field that hosts the target group of the pairing.
type Fqk: Field;

View File

@ -1,10 +1,10 @@
use ff::PowVartime;
use ff::{Endianness, Field, PrimeField};
use group::{CurveAffine, CurveProjective};
use rand_core::SeedableRng;
use rand_xorshift::XorShiftRng;
use std::ops::MulAssign;
use crate::{Engine, Field, PairingCurveAffine, PrimeField};
use crate::{Engine, PairingCurveAffine};
pub fn engine_tests<E: Engine>() {
let mut rng = XorShiftRng::from_seed([
@ -130,8 +130,14 @@ fn random_bilinearity_tests<E: Engine>() {
let mut cd = c;
cd.mul_assign(&d);
let mut cd = cd.to_repr();
<E::Fr as PrimeField>::ReprEndianness::toggle_little_endian(&mut cd);
let abcd = E::pairing(a, b).pow_vartime(cd.into_repr());
use byteorder::ByteOrder;
let mut cd_limbs = [0; 4];
byteorder::LittleEndian::read_u64_into(cd.as_ref(), &mut cd_limbs);
let abcd = E::pairing(a, b).pow_vartime(cd_limbs);
assert_eq!(acbd, adbc);
assert_eq!(acbd, abcd);

View File

@ -1,29 +1,8 @@
use ff::{Field, PowVartime, PrimeField, SqrtField};
use ff::{Field, PrimeField};
use rand_core::{RngCore, SeedableRng};
use rand_xorshift::XorShiftRng;
pub fn random_frobenius_tests<F: Field, C: AsRef<[u8]>>(characteristic: C, maxpower: usize) {
let mut rng = XorShiftRng::from_seed([
0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc,
0xe5,
]);
for _ in 0..100 {
for i in 0..=maxpower {
let mut a = F::random(&mut rng);
let mut b = a;
for _ in 0..i {
a = a.pow_vartime(&characteristic);
}
b.frobenius_map(i);
assert_eq!(a, b);
}
}
}
pub fn random_sqrt_tests<F: SqrtField>() {
pub fn random_sqrt_tests<F: Field>() {
let mut rng = XorShiftRng::from_seed([
0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc,
0xe5,

View File

@ -4,7 +4,6 @@ use rand_xorshift::XorShiftRng;
pub fn random_repr_tests<P: PrimeField>() {
random_encoding_tests::<P>();
random_shr_tests::<P>();
}
fn random_encoding_tests<P: PrimeField>() {
@ -16,36 +15,9 @@ fn random_encoding_tests<P: PrimeField>() {
for _ in 0..1000 {
let r = P::random(&mut rng);
let v = r.into_repr();
let v = r.to_repr();
let rdecoded = P::from_repr(v).unwrap();
assert_eq!(r, rdecoded);
}
}
fn random_shr_tests<P: PrimeField>() {
let mut rng = XorShiftRng::from_seed([
0x59, 0x62, 0xbe, 0x5d, 0x76, 0x3d, 0x31, 0x8d, 0x17, 0xdb, 0x37, 0x32, 0x54, 0x06, 0xbc,
0xe5,
]);
for _ in 0..100 {
let r = P::random(&mut rng);
for shift in 0..P::NUM_BITS {
let r1 = r >> shift;
// Doubling the shifted element inserts zeros on the right; re-shifting should
// undo the doubling.
let mut r2 = r1;
for _ in 0..shift {
r2 = r2.double();
}
r2 = r2 >> shift;
assert_eq!(r1, r2);
}
assert_eq!(r >> P::NUM_BITS, P::zero());
}
}

View File

@ -36,7 +36,7 @@ fn scan_output(
let ct = output.ciphertext;
// Increment tree and witnesses
let node = Node::new(cmu.into_repr());
let node = Node::new(cmu.to_repr());
for witness in existing_witnesses {
witness.append(node).unwrap();
}
@ -207,7 +207,7 @@ mod tests {
};
let fake_cmu = {
let fake_cmu = Fr::random(rng);
fake_cmu.into_repr().as_ref().to_owned()
fake_cmu.to_repr().as_ref().to_owned()
};
let fake_epk = {
let mut buffer = vec![0; 64];
@ -262,7 +262,7 @@ mod tests {
Memo::default(),
&mut rng,
);
let cmu = note.cm(&JUBJUB).into_repr().as_ref().to_owned();
let cmu = note.cm(&JUBJUB).to_repr().as_ref().to_owned();
let mut epk = vec![];
encryptor.epk().write(&mut epk).unwrap();
let enc_ciphertext = encryptor.encrypt_note_plaintext();

View File

@ -1,4 +1,4 @@
use ff::{BitIterator, Field, PrimeField, SqrtField};
use ff::{BitIterator, Field, PrimeField};
use std::ops::{AddAssign, MulAssign, Neg, SubAssign};
use subtle::CtOption;
@ -172,7 +172,7 @@ impl<E: JubjubEngine, Subgroup> Point<E, Subgroup> {
assert_eq!(E::Fr::NUM_BITS, 255);
let mut y_repr = y.into_repr();
let mut y_repr = y.to_repr();
if x.is_odd() {
y_repr.as_mut()[31] |= 0x80;
}

View File

@ -1,8 +1,7 @@
use byteorder::{ByteOrder, LittleEndian};
use ff::{adc, mac_with_carry, sbb, BitIterator, Field, PowVartime, PrimeField, SqrtField};
use ff::{adc, mac_with_carry, sbb, BitIterator, Field, PrimeField};
use rand_core::RngCore;
use std::mem;
use std::ops::{Add, AddAssign, BitAnd, Mul, MulAssign, Neg, Shr, Sub, SubAssign};
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
use super::ToUniform;
@ -121,29 +120,9 @@ impl ConstantTimeEq for Fs {
}
}
impl Ord for Fs {
#[inline(always)]
fn cmp(&self, other: &Fs) -> ::std::cmp::Ordering {
let mut a = *self;
a.mont_reduce(self.0[0], self.0[1], self.0[2], self.0[3], 0, 0, 0, 0);
let mut b = *other;
b.mont_reduce(other.0[0], other.0[1], other.0[2], other.0[3], 0, 0, 0, 0);
a.cmp_native(&b)
}
}
impl PartialOrd for Fs {
#[inline(always)]
fn partial_cmp(&self, other: &Fs) -> Option<::std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl ::std::fmt::Display for Fs {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "Fs({})", self.into_repr())
write!(f, "Fs({})", self.to_repr())
}
}
@ -158,13 +137,13 @@ impl From<u64> for Fs {
impl From<Fs> for FsRepr {
fn from(e: Fs) -> FsRepr {
e.into_repr()
e.to_repr()
}
}
impl<'a> From<&'a Fs> for FsRepr {
fn from(e: &'a Fs) -> FsRepr {
e.into_repr()
e.to_repr()
}
}
@ -328,53 +307,9 @@ impl MulAssign for Fs {
}
}
impl BitAnd<u64> for Fs {
type Output = u64;
#[inline(always)]
fn bitand(mut self, rhs: u64) -> u64 {
self.mont_reduce(self.0[0], self.0[1], self.0[2], self.0[3], 0, 0, 0, 0);
self.0[0] & rhs
}
}
impl Shr<u32> for Fs {
type Output = Self;
#[inline(always)]
fn shr(mut self, mut n: u32) -> Self {
if n as usize >= 64 * 4 {
return Self::from(0);
}
// Convert from Montgomery to native representation.
self.mont_reduce(self.0[0], self.0[1], self.0[2], self.0[3], 0, 0, 0, 0);
while n >= 64 {
let mut t = 0;
for i in self.0.iter_mut().rev() {
mem::swap(&mut t, i);
}
n -= 64;
}
if n > 0 {
let mut t = 0;
for i in self.0.iter_mut().rev() {
let t2 = *i << (64 - n);
*i >>= n;
*i |= t;
t = t2;
}
}
// Convert back to Montgomery representation
self * R2
}
}
impl PrimeField for Fs {
type Repr = FsRepr;
type ReprEndianness = byteorder::LittleEndian;
fn from_repr(r: FsRepr) -> Option<Fs> {
let r = {
@ -390,7 +325,7 @@ impl PrimeField for Fs {
}
}
fn into_repr(&self) -> FsRepr {
fn to_repr(&self) -> FsRepr {
let mut r = *self;
r.mont_reduce(self.0[0], self.0[1], self.0[2], self.0[3], 0, 0, 0, 0);
@ -499,11 +434,6 @@ impl Field for Fs {
CtOption::new(inverse, Choice::from(if self.is_zero() { 0 } else { 1 }))
}
#[inline(always)]
fn frobenius_map(&mut self, _: usize) {
// This has no effect in a prime field.
}
#[inline]
fn square(&self) -> Self {
let mut carry = 0;
@ -541,6 +471,24 @@ impl Field for Fs {
ret.mont_reduce(r0, r1, r2, r3, r4, r5, r6, r7);
ret
}
fn sqrt(&self) -> CtOption<Self> {
// Shank's algorithm for s mod 4 = 3
// https://eprint.iacr.org/2012/685.pdf (page 9, algorithm 2)
// a1 = self^((s - 3) // 4)
let mut a1 = self.pow_vartime([
0xb425c397b5bdcb2du64,
0x299a0824f3320420,
0x4199cec0404d0ec0,
0x39f6d3a994cebea,
]);
let mut a0 = a1.square();
a0.mul_assign(self);
a1.mul_assign(self);
CtOption::new(a1, !a0.ct_eq(&NEGATIVE_ONE))
}
}
impl Fs {
@ -673,26 +621,6 @@ impl ToUniform for Fs {
}
}
impl SqrtField for Fs {
fn sqrt(&self) -> CtOption<Self> {
// Shank's algorithm for s mod 4 = 3
// https://eprint.iacr.org/2012/685.pdf (page 9, algorithm 2)
// a1 = self^((s - 3) // 4)
let mut a1 = self.pow_vartime([
0xb425c397b5bdcb2du64,
0x299a0824f3320420,
0x4199cec0404d0ec0,
0x39f6d3a994cebea,
]);
let mut a0 = a1.square();
a0.mul_assign(self);
a1.mul_assign(self);
CtOption::new(a1, !a0.ct_eq(&NEGATIVE_ONE))
}
}
#[test]
fn test_neg_one() {
let o = Fs::one().neg();
@ -1010,61 +938,6 @@ fn test_fs_mul_assign() {
}
}
#[test]
fn test_fs_shr() {
let mut a = Fs::from_repr(FsRepr([
0x3f, 0x28, 0x2a, 0x48, 0xec, 0xba, 0x3f, 0xb3, 0xdf, 0xb3, 0x8c, 0xa8, 0xd3, 0xe0, 0x7d,
0x99, 0x25, 0x55, 0x0e, 0x9a, 0x2a, 0x2d, 0xf6, 0x9a, 0xa1, 0x0d, 0xe7, 0x8d, 0xb0, 0x3a,
0x00, 0x06,
]))
.unwrap();
a = a >> 0;
assert_eq!(
a.into_repr(),
FsRepr([
0x3f, 0x28, 0x2a, 0x48, 0xec, 0xba, 0x3f, 0xb3, 0xdf, 0xb3, 0x8c, 0xa8, 0xd3, 0xe0,
0x7d, 0x99, 0x25, 0x55, 0x0e, 0x9a, 0x2a, 0x2d, 0xf6, 0x9a, 0xa1, 0x0d, 0xe7, 0x8d,
0xb0, 0x3a, 0x00, 0x06,
])
);
a = a >> 1;
assert_eq!(
a.into_repr(),
FsRepr([
0x1f, 0x14, 0x15, 0x24, 0x76, 0xdd, 0x9f, 0xd9, 0xef, 0x59, 0x46, 0xd4, 0x69, 0xf0,
0xbe, 0xcc, 0x92, 0x2a, 0x07, 0x4d, 0x95, 0x16, 0x7b, 0xcd, 0xd0, 0x86, 0xf3, 0x46,
0x58, 0x1d, 0x00, 0x03,
])
);
a = a >> 50;
assert_eq!(
a.into_repr(),
FsRepr([
0x67, 0xf6, 0x7b, 0x96, 0x11, 0x75, 0x1a, 0xbc, 0x2f, 0xb3, 0xa4, 0xca, 0x41, 0x53,
0xa5, 0xc5, 0x5e, 0x33, 0xb4, 0xe1, 0xbc, 0x11, 0x56, 0x07, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
);
a = a >> 130;
assert_eq!(
a.into_repr(),
FsRepr([
0xd7, 0x0c, 0x6d, 0x38, 0x6f, 0x84, 0xd5, 0x01, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
);
a = a >> 64;
assert_eq!(
a.into_repr(),
FsRepr([
0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
])
);
}
#[test]
fn test_fs_squaring() {
let a = Fs([
@ -1178,11 +1051,15 @@ fn test_fs_pow() {
assert_eq!(c, target);
}
use byteorder::ByteOrder;
let mut char_limbs = [0; 4];
byteorder::LittleEndian::read_u64_into(Fs::char().as_ref(), &mut char_limbs);
for _ in 0..1000 {
// Exponentiating by the modulus should have no effect in a prime field.
let a = Fs::random(&mut rng);
assert_eq!(a, a.pow_vartime(Fs::char()));
assert_eq!(a, a.pow_vartime(char_limbs));
}
}
@ -1218,7 +1095,7 @@ fn test_fs_sqrt() {
}
#[test]
fn test_fs_from_into_repr() {
fn test_fs_from_to_repr() {
// r + 1 should not be in the field
assert!(Fs::from_repr(FsRepr([
0xb8, 0x2c, 0xf7, 0xd6, 0x5e, 0x0e, 0x97, 0xd0, 0x82, 0x10, 0xc8, 0xcc, 0x93, 0x20, 0x68,
@ -1263,7 +1140,7 @@ fn test_fs_from_into_repr() {
for _ in 0..1000 {
// Try to turn Fs elements into representations and back again, and compare.
let a = Fs::random(&mut rng);
let a_repr = a.into_repr();
let a_repr = a.to_repr();
let b_repr = FsRepr::from(a);
assert_eq!(a_repr, b_repr);
let a_again = Fs::from_repr(a_repr).unwrap();

View File

@ -23,7 +23,7 @@
//! [Jubjub]: https://zips.z.cash/protocol/protocol.pdf#jubjub
//! [BLS12-381]: pairing::bls12_381
use ff::{Field, PrimeField, SqrtField};
use ff::{Field, PrimeField};
use pairing::Engine;
use crate::group_hash::group_hash;
@ -95,7 +95,7 @@ pub trait ToUniform {
/// and some pre-computed parameters.
pub trait JubjubEngine: Engine {
/// The scalar field of the Jubjub curve
type Fs: PrimeField + SqrtField + ToUniform;
type Fs: PrimeField + ToUniform;
/// The parameters of Jubjub and the Sapling protocol
type Params: JubjubParams<Self>;
}

View File

@ -1,4 +1,4 @@
use ff::{BitIterator, Field, PrimeField, SqrtField};
use ff::{BitIterator, Field, PrimeField};
use std::ops::{AddAssign, MulAssign, Neg, SubAssign};
use subtle::CtOption;

View File

@ -1,6 +1,6 @@
use super::{edwards, montgomery, JubjubEngine, JubjubParams, PrimeOrder};
use ff::{Field, PrimeField, SqrtField};
use ff::{Endianness, Field, PrimeField};
use std::ops::{AddAssign, MulAssign, Neg, SubAssign};
use rand_core::{RngCore, SeedableRng};
@ -372,7 +372,22 @@ fn test_jubjub_params<E: JubjubEngine>(params: &E::Params) {
let mut cur = E::Fs::one();
let max = (-E::Fs::one()) >> 1;
let max = {
// Grab char - 1 in little endian.
let mut tmp = (-E::Fs::one()).to_repr();
<E::Fs as PrimeField>::ReprEndianness::toggle_little_endian(&mut tmp);
// Shift right by 1 bit.
let mut borrow = 0;
for b in tmp.as_mut().iter_mut().rev() {
let new_borrow = *b & 1;
*b = (borrow << 7) | (*b >> 1);
borrow = new_borrow;
}
// Turns out we want this in little endian!
tmp
};
let mut pacc = E::Fs::zero();
let mut nacc = E::Fs::zero();
@ -384,8 +399,22 @@ fn test_jubjub_params<E: JubjubEngine>(params: &E::Params) {
pacc += &tmp;
nacc -= &tmp; // The first subtraction wraps intentionally.
assert!(pacc < max);
assert!(pacc < nacc);
let mut pacc_repr = pacc.to_repr();
let mut nacc_repr = nacc.to_repr();
<E::Fs as PrimeField>::ReprEndianness::toggle_little_endian(&mut pacc_repr);
<E::Fs as PrimeField>::ReprEndianness::toggle_little_endian(&mut nacc_repr);
fn less_than(val: &[u8], bound: &[u8]) -> bool {
for (a, b) in val.iter().rev().zip(bound.iter().rev()) {
if a < b {
return true;
}
}
false
}
assert!(less_than(pacc_repr.as_ref(), max.as_ref()));
assert!(less_than(pacc_repr.as_ref(), nacc_repr.as_ref()));
// cur = cur * 16
for _ in 0..4 {

View File

@ -91,8 +91,8 @@ impl<E: JubjubEngine> ExpandedSpendingKey<E> {
}
pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
writer.write_all(self.ask.into_repr().as_ref())?;
writer.write_all(self.nsk.into_repr().as_ref())?;
writer.write_all(self.ask.to_repr().as_ref())?;
writer.write_all(self.nsk.to_repr().as_ref())?;
writer.write_all(&self.ovk.0)?;
Ok(())

View File

@ -211,13 +211,13 @@ impl<Node: Hashable> CommitmentTree<Node> {
///
/// let mut tree = CommitmentTree::<Node>::new();
///
/// tree.append(Node::new(Fr::random(&mut rng).into_repr()));
/// tree.append(Node::new(Fr::random(&mut rng).into_repr()));
/// tree.append(Node::new(Fr::random(&mut rng).to_repr()));
/// tree.append(Node::new(Fr::random(&mut rng).to_repr()));
/// let mut witness = IncrementalWitness::from_tree(&tree);
/// assert_eq!(witness.position(), 1);
/// assert_eq!(tree.root(), witness.root());
///
/// let cmu = Node::new(Fr::random(&mut rng).into_repr());
/// let cmu = Node::new(Fr::random(&mut rng).to_repr());
/// tree.append(cmu);
/// witness.append(cmu);
/// assert_eq!(tree.root(), witness.root());

View File

@ -193,7 +193,7 @@ fn prf_ock(
let mut ock_input = [0u8; 128];
ock_input[0..32].copy_from_slice(&ovk.0);
cv.write(&mut ock_input[32..64]).unwrap();
ock_input[64..96].copy_from_slice(cmu.into_repr().as_ref());
ock_input[64..96].copy_from_slice(cmu.to_repr().as_ref());
epk.write(&mut ock_input[96..128]).unwrap();
Blake2bParams::new()
@ -303,7 +303,7 @@ impl SaplingNoteEncryption {
(&mut input[12..20])
.write_u64::<LittleEndian>(self.note.value)
.unwrap();
input[20..COMPACT_NOTE_SIZE].copy_from_slice(self.note.r.into_repr().as_ref());
input[20..COMPACT_NOTE_SIZE].copy_from_slice(self.note.r.to_repr().as_ref());
input[COMPACT_NOTE_SIZE..NOTE_PLAINTEXT_SIZE].copy_from_slice(&self.memo.0);
let mut output = [0u8; ENC_CIPHERTEXT_SIZE];
@ -327,7 +327,7 @@ impl SaplingNoteEncryption {
let mut input = [0u8; OUT_PLAINTEXT_SIZE];
self.note.pk_d.write(&mut input[0..32]).unwrap();
input[32..OUT_PLAINTEXT_SIZE].copy_from_slice(self.esk.into_repr().as_ref());
input[32..OUT_PLAINTEXT_SIZE].copy_from_slice(self.esk.to_repr().as_ref());
let mut output = [0u8; OUT_CIPHERTEXT_SIZE];
assert_eq!(
@ -366,7 +366,7 @@ fn parse_note_plaintext_without_memo(
let diversifier = Diversifier(d);
let pk_d = diversifier
.g_d::<Bls12>(&JUBJUB)?
.mul(ivk.into_repr(), &JUBJUB);
.mul(ivk.to_repr(), &JUBJUB);
let to = PaymentAddress::from_parts(diversifier, pk_d)?;
let note = to.create_note(v, rcm, &JUBJUB).unwrap();
@ -525,7 +525,7 @@ pub fn try_sapling_output_recovery(
let diversifier = Diversifier(d);
if diversifier
.g_d::<Bls12>(&JUBJUB)?
.mul(esk.into_repr(), &JUBJUB)
.mul(esk.to_repr(), &JUBJUB)
!= *epk
{
// Published epk doesn't match calculated epk

View File

@ -1,7 +1,8 @@
//! Implementation of the Pedersen hash function used in Sapling.
use crate::jubjub::*;
use ff::Field;
use byteorder::{ByteOrder, LittleEndian};
use ff::{Endianness, Field, PrimeField};
use std::ops::{AddAssign, Neg};
#[derive(Copy, Clone)]
@ -85,17 +86,32 @@ where
let mut table: &[Vec<edwards::Point<E, _>>] =
&generators.next().expect("we don't have enough generators");
let window = JubjubBls12::pedersen_hash_exp_window_size();
let window_mask = (1 << window) - 1;
let window = JubjubBls12::pedersen_hash_exp_window_size() as usize;
let window_mask = (1u64 << window) - 1;
let mut acc = acc.to_repr();
<E::Fs as PrimeField>::ReprEndianness::toggle_little_endian(&mut acc);
let num_limbs: usize = acc.as_ref().len() / 8;
let mut limbs = vec![0u64; num_limbs + 1];
LittleEndian::read_u64_into(acc.as_ref(), &mut limbs[..num_limbs]);
let mut tmp = edwards::Point::zero();
while !acc.is_zero() {
let i = (acc & window_mask) as usize;
let mut pos = 0;
while pos < E::Fs::NUM_BITS as usize {
let u64_idx = pos / 64;
let bit_idx = pos % 64;
let i = (if bit_idx + window < 64 {
// This window's bits are contained in a single u64.
limbs[u64_idx] >> bit_idx
} else {
// Combine the current u64's bits with the bits from the next u64.
(limbs[u64_idx] >> bit_idx) | (limbs[u64_idx + 1] << (64 - bit_idx))
} & window_mask) as usize;
tmp = tmp.add(&table[0][i], params);
acc = acc >> window;
pos += window;
table = &table[1..];
}

View File

@ -20,7 +20,7 @@ fn read_scalar<E: JubjubEngine, R: Read>(mut reader: R) -> io::Result<E::Fs> {
}
fn write_scalar<E: JubjubEngine, W: Write>(s: &E::Fs, mut writer: W) -> io::Result<()> {
writer.write_all(s.into_repr().as_ref())
writer.write_all(s.to_repr().as_ref())
}
fn h_star<E: JubjubEngine>(a: &[u8], b: &[u8]) -> E::Fs {

View File

@ -45,7 +45,7 @@ pub fn merkle_hash(depth: usize, lhs: &FrRepr, rhs: &FrRepr) -> FrRepr {
)
.to_xy()
.0
.into_repr()
.to_repr()
}
/// A node within the Sapling commitment tree.
@ -79,7 +79,7 @@ impl Hashable for Node {
fn blank() -> Self {
Node {
repr: Note::<Bls12>::uncommitted().into_repr(),
repr: Note::<Bls12>::uncommitted().to_repr(),
}
}

View File

@ -745,7 +745,7 @@ mod tests {
let note1 = to
.create_note(50000, Fs::random(&mut rng), &JUBJUB)
.unwrap();
let cm1 = Node::new(note1.cm(&JUBJUB).into_repr());
let cm1 = Node::new(note1.cm(&JUBJUB).to_repr());
let mut tree = CommitmentTree::new();
tree.append(cm1).unwrap();
let witness1 = IncrementalWitness::from_tree(&tree);
@ -844,7 +844,7 @@ mod tests {
let note1 = to
.create_note(59999, Fs::random(&mut rng), &JUBJUB)
.unwrap();
let cm1 = Node::new(note1.cm(&JUBJUB).into_repr());
let cm1 = Node::new(note1.cm(&JUBJUB).to_repr());
let mut tree = CommitmentTree::new();
tree.append(cm1).unwrap();
let mut witness1 = IncrementalWitness::from_tree(&tree);
@ -882,7 +882,7 @@ mod tests {
}
let note2 = to.create_note(1, Fs::random(&mut rng), &JUBJUB).unwrap();
let cm2 = Node::new(note2.cm(&JUBJUB).into_repr());
let cm2 = Node::new(note2.cm(&JUBJUB).to_repr());
tree.append(cm2).unwrap();
witness1.append(cm2).unwrap();
let witness2 = IncrementalWitness::from_tree(&tree);

View File

@ -176,7 +176,7 @@ impl SpendDescription {
pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
self.cv.write(&mut writer)?;
writer.write_all(self.anchor.into_repr().as_ref())?;
writer.write_all(self.anchor.to_repr().as_ref())?;
writer.write_all(&self.nullifier)?;
self.rk.write(&mut writer)?;
writer.write_all(&self.zkproof)?;
@ -254,7 +254,7 @@ impl OutputDescription {
pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
self.cv.write(&mut writer)?;
writer.write_all(self.cmu.into_repr().as_ref())?;
writer.write_all(self.cmu.to_repr().as_ref())?;
self.ephemeral_key.write(&mut writer)?;
writer.write_all(&self.enc_ciphertext)?;
writer.write_all(&self.out_ciphertext)?;

View File

@ -128,7 +128,7 @@ fn shielded_spends_hash(tx: &TransactionData) -> Blake2bHash {
let mut data = Vec::with_capacity(tx.shielded_spends.len() * 384);
for s_spend in &tx.shielded_spends {
s_spend.cv.write(&mut data).unwrap();
data.extend_from_slice(s_spend.anchor.into_repr().as_ref());
data.extend_from_slice(s_spend.anchor.to_repr().as_ref());
data.extend_from_slice(&s_spend.nullifier);
s_spend.rk.write(&mut data).unwrap();
data.extend_from_slice(&s_spend.zkproof);

View File

@ -1014,8 +1014,8 @@ mod tests {
let xsk = &xsks[j];
let tv = &test_vectors[j];
assert_eq!(xsk.expsk.ask.into_repr().as_ref(), tv.ask.unwrap());
assert_eq!(xsk.expsk.nsk.into_repr().as_ref(), tv.nsk.unwrap());
assert_eq!(xsk.expsk.ask.to_repr().as_ref(), tv.ask.unwrap());
assert_eq!(xsk.expsk.nsk.to_repr().as_ref(), tv.nsk.unwrap());
assert_eq!(xsk.expsk.ovk.0, tv.ovk);
assert_eq!(xsk.dk.0, tv.dk);
@ -1040,7 +1040,7 @@ mod tests {
assert_eq!(xfvk.dk.0, tv.dk);
assert_eq!(xfvk.chain_code.0, tv.c);
assert_eq!(xfvk.fvk.vk.ivk().into_repr().as_ref(), tv.ivk);
assert_eq!(xfvk.fvk.vk.ivk().to_repr().as_ref(), tv.ivk);
let mut ser = vec![];
xfvk.write(&mut ser).unwrap();

View File

@ -769,7 +769,7 @@ mod test {
let q = p.mul(s, params);
let (x1, y1) = q.to_xy();
let mut s_bits = BitIterator::<u8, _>::new(s.into_repr()).collect::<Vec<_>>();
let mut s_bits = BitIterator::<u8, _>::new(s.to_repr()).collect::<Vec<_>>();
s_bits.reverse();
s_bits.truncate(Fs::NUM_BITS as usize);
@ -822,7 +822,7 @@ mod test {
y: num_y0,
};
let mut s_bits = BitIterator::<u8, _>::new(s.into_repr()).collect::<Vec<_>>();
let mut s_bits = BitIterator::<u8, _>::new(s.to_repr()).collect::<Vec<_>>();
s_bits.reverse();
s_bits.truncate(Fs::NUM_BITS as usize);

View File

@ -615,8 +615,8 @@ fn test_input_circuit_with_bls12_381() {
::std::mem::swap(&mut lhs, &mut rhs);
}
let mut lhs: Vec<bool> = BitIterator::<u8, _>::new(lhs.into_repr()).collect();
let mut rhs: Vec<bool> = BitIterator::<u8, _>::new(rhs.into_repr()).collect();
let mut lhs: Vec<bool> = BitIterator::<u8, _>::new(lhs.to_repr()).collect();
let mut rhs: Vec<bool> = BitIterator::<u8, _>::new(rhs.to_repr()).collect();
lhs.reverse();
rhs.reverse();
@ -799,8 +799,8 @@ fn test_input_circuit_with_bls12_381_external_test_vectors() {
::std::mem::swap(&mut lhs, &mut rhs);
}
let mut lhs: Vec<bool> = BitIterator::<u8, _>::new(lhs.into_repr()).collect();
let mut rhs: Vec<bool> = BitIterator::<u8, _>::new(rhs.into_repr()).collect();
let mut lhs: Vec<bool> = BitIterator::<u8, _>::new(lhs.to_repr()).collect();
let mut rhs: Vec<bool> = BitIterator::<u8, _>::new(rhs.to_repr()).collect();
lhs.reverse();
rhs.reverse();