diff --git a/Cargo.toml b/Cargo.toml index b7878ae8..94e569ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,3 +4,7 @@ members = [ "halo2_gadgets", "halo2_proofs", ] + +[patch.crates-io] +ff = { git = "https://github.com/zkcrypto/ff.git", rev = "c555625ab4e6e26560ec5323fd99fef6eba18365" } +pasta_curves = { git = "https://github.com/zcash/pasta_curves.git", rev = "825cb944decfab4b1a64380d15a43eb93899dfad" } diff --git a/halo2_gadgets/src/ecc/chip/add.rs b/halo2_gadgets/src/ecc/chip/add.rs index 9029827b..8932b128 100644 --- a/halo2_gadgets/src/ecc/chip/add.rs +++ b/halo2_gadgets/src/ecc/chip/add.rs @@ -1,10 +1,13 @@ use super::EccPoint; + +use group::ff::PrimeField; use halo2_proofs::{ circuit::Region, plonk::{Advice, Assigned, Column, ConstraintSystem, Constraints, Error, Expression, Selector}, poly::Rotation, }; -use pasta_curves::{arithmetic::FieldExt, pallas}; +use pasta_curves::pallas; + use std::collections::HashSet; #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/halo2_gadgets/src/ecc/chip/constants.rs b/halo2_gadgets/src/ecc/chip/constants.rs index 6757a785..e543d718 100644 --- a/halo2_gadgets/src/ecc/chip/constants.rs +++ b/halo2_gadgets/src/ecc/chip/constants.rs @@ -6,10 +6,7 @@ use group::{ Curve, }; use halo2_proofs::arithmetic::lagrange_interpolate; -use pasta_curves::{ - arithmetic::{CurveAffine, FieldExt}, - pallas, -}; +use pasta_curves::{arithmetic::CurveAffine, pallas}; /// Window size for fixed-base scalar multiplication pub const FIXED_BASE_WINDOW_SIZE: usize = 3; @@ -64,7 +61,7 @@ fn compute_window_table(base: C, num_windows: usize) -> Vec<[C; // Generate window table entries for the last window, w = `num_windows - 1`. // For the last window, we compute [k * (2^3)^w - sum]B, where sum is defined // as sum = \sum_{j = 0}^{`num_windows - 2`} 2^{3j+1} - let sum = (0..(num_windows - 1)).fold(C::Scalar::zero(), |acc, j| { + let sum = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, j| { acc + C::Scalar::from(2).pow(&[FIXED_BASE_WINDOW_SIZE as u64 * j as u64 + 1, 0, 0, 0]) }); window_table.push( @@ -184,7 +181,7 @@ pub fn test_lagrange_coeffs(base: C, num_windows: usize) { .rev() .cloned() .reduce(|acc, coeff| acc * x + coeff) - .unwrap_or_else(C::Base::zero) + .unwrap_or(C::Base::ZERO) } let lagrange_coeffs = compute_lagrange_coeffs(base, num_windows); @@ -216,7 +213,7 @@ pub fn test_lagrange_coeffs(base: C, num_windows: usize) { // Compute the actual x-coordinate of the multiple [k * (8^84) - offset]B, // where offset = \sum_{j = 0}^{83} 2^{3j+1} - let offset = (0..(num_windows - 1)).fold(C::Scalar::zero(), |acc, w| { + let offset = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, w| { acc + C::Scalar::from(2).pow(&[FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0]) }); let scalar = C::Scalar::from(bits as u64) @@ -232,11 +229,9 @@ pub fn test_lagrange_coeffs(base: C, num_windows: usize) { #[cfg(test)] mod tests { + use ff::FromUniformBytes; use group::{ff::Field, Curve, Group}; - use pasta_curves::{ - arithmetic::{CurveAffine, FieldExt}, - pallas, - }; + use pasta_curves::{arithmetic::CurveAffine, pallas}; use proptest::prelude::*; use super::{compute_window_table, find_zs_and_us, test_lagrange_coeffs, H, NUM_WINDOWS}; @@ -247,7 +242,7 @@ mod tests { // Instead of rejecting out-of-range bytes, let's reduce them. let mut buf = [0; 64]; buf[..32].copy_from_slice(&bytes); - let scalar = pallas::Scalar::from_bytes_wide(&buf); + let scalar = pallas::Scalar::from_uniform_bytes(&buf); pallas::Point::generator() * scalar } } diff --git a/halo2_gadgets/src/ecc/chip/mul/incomplete.rs b/halo2_gadgets/src/ecc/chip/mul/incomplete.rs index b82ffecc..8baa115f 100644 --- a/halo2_gadgets/src/ecc/chip/mul/incomplete.rs +++ b/halo2_gadgets/src/ecc/chip/mul/incomplete.rs @@ -1,6 +1,8 @@ use super::super::NonIdentityEccPoint; use super::{X, Y, Z}; use crate::utilities::bool_check; + +use group::ff::PrimeField; use halo2_proofs::{ circuit::{Region, Value}, plonk::{ @@ -8,8 +10,7 @@ use halo2_proofs::{ }, poly::Rotation, }; - -use pasta_curves::{arithmetic::FieldExt, pallas}; +use pasta_curves::pallas; /// A helper struct for implementing single-row double-and-add using incomplete addition. #[derive(Copy, Clone, Debug, Eq, PartialEq)] diff --git a/halo2_gadgets/src/ecc/chip/mul/overflow.rs b/halo2_gadgets/src/ecc/chip/mul/overflow.rs index a80688dc..12101ae8 100644 --- a/halo2_gadgets/src/ecc/chip/mul/overflow.rs +++ b/halo2_gadgets/src/ecc/chip/mul/overflow.rs @@ -3,14 +3,14 @@ use crate::{ sinsemilla::primitives as sinsemilla, utilities::lookup_range_check::LookupRangeCheckConfig, }; +use group::ff::PrimeField; use halo2_proofs::circuit::AssignedCell; use halo2_proofs::{ circuit::Layouter, plonk::{Advice, Assigned, Column, ConstraintSystem, Constraints, Error, Expression, Selector}, poly::Rotation, }; - -use pasta_curves::{arithmetic::FieldExt, pallas}; +use pasta_curves::pallas; use std::iter; diff --git a/halo2_gadgets/src/ecc/chip/mul_fixed.rs b/halo2_gadgets/src/ecc/chip/mul_fixed.rs index c1aa5c08..b6a98620 100644 --- a/halo2_gadgets/src/ecc/chip/mul_fixed.rs +++ b/halo2_gadgets/src/ecc/chip/mul_fixed.rs @@ -7,7 +7,7 @@ use crate::utilities::decompose_running_sum::RunningSumConfig; use std::marker::PhantomData; use group::{ - ff::{PrimeField, PrimeFieldBits}, + ff::{Field, PrimeField, PrimeFieldBits}, Curve, }; use halo2_proofs::{ @@ -19,10 +19,7 @@ use halo2_proofs::{ poly::Rotation, }; use lazy_static::lazy_static; -use pasta_curves::{ - arithmetic::{CurveAffine, FieldExt}, - pallas, -}; +use pasta_curves::{arithmetic::CurveAffine, pallas}; pub mod base_field_elem; pub mod full_width; diff --git a/halo2_gadgets/src/ecc/chip/mul_fixed/base_field_elem.rs b/halo2_gadgets/src/ecc/chip/mul_fixed/base_field_elem.rs index 5563ee64..9a2b0c76 100644 --- a/halo2_gadgets/src/ecc/chip/mul_fixed/base_field_elem.rs +++ b/halo2_gadgets/src/ecc/chip/mul_fixed/base_field_elem.rs @@ -13,7 +13,7 @@ use halo2_proofs::{ plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Expression, Selector}, poly::Rotation, }; -use pasta_curves::{arithmetic::FieldExt, pallas}; +use pasta_curves::pallas; use std::convert::TryInto; diff --git a/halo2_gadgets/src/ecc/chip/mul_fixed/short.rs b/halo2_gadgets/src/ecc/chip/mul_fixed/short.rs index e500fc9c..bfdc735f 100644 --- a/halo2_gadgets/src/ecc/chip/mul_fixed/short.rs +++ b/halo2_gadgets/src/ecc/chip/mul_fixed/short.rs @@ -251,7 +251,7 @@ pub mod tests { circuit::{AssignedCell, Chip, Layouter, Value}, plonk::{Any, Error}, }; - use pasta_curves::{arithmetic::FieldExt, pallas}; + use pasta_curves::pallas; use crate::{ ecc::{ diff --git a/halo2_gadgets/src/poseidon.rs b/halo2_gadgets/src/poseidon.rs index 4913ec6c..77736c86 100644 --- a/halo2_gadgets/src/poseidon.rs +++ b/halo2_gadgets/src/poseidon.rs @@ -4,9 +4,8 @@ use std::convert::TryInto; use std::fmt; use std::marker::PhantomData; -use group::ff::Field; +use group::ff::{Field, PrimeField}; use halo2_proofs::{ - arithmetic::FieldExt, circuit::{AssignedCell, Chip, Layouter}, plonk::Error, }; @@ -267,7 +266,7 @@ impl< } impl< - F: FieldExt, + F: PrimeField, PoseidonChip: PoseidonSpongeInstructions, T, RATE>, S: Spec, const T: usize, diff --git a/halo2_gadgets/src/poseidon/pow5.rs b/halo2_gadgets/src/poseidon/pow5.rs index 6c125ea6..a8e67112 100644 --- a/halo2_gadgets/src/poseidon/pow5.rs +++ b/halo2_gadgets/src/poseidon/pow5.rs @@ -3,7 +3,6 @@ use std::iter; use group::ff::Field; use halo2_proofs::{ - arithmetic::FieldExt, circuit::{AssignedCell, Cell, Chip, Layouter, Region, Value}, plonk::{ Advice, Any, Column, ConstraintSystem, Constraints, Error, Expression, Fixed, Selector, @@ -221,7 +220,7 @@ impl Chip for Pow5Chip, const WIDTH: usize, const RATE: usize> +impl, const WIDTH: usize, const RATE: usize> PoseidonInstructions for Pow5Chip { type Word = StateWord; @@ -272,7 +271,7 @@ impl, const WIDTH: usize, const RATE: usize } impl< - F: FieldExt, + F: Field, S: Spec, D: Domain, const WIDTH: usize, @@ -301,7 +300,7 @@ impl< }; for i in 0..RATE { - load_state_word(i, F::zero())?; + load_state_word(i, F::ZERO)?; } load_state_word(RATE, D::initial_capacity_element())?; @@ -371,7 +370,7 @@ impl< .get(i) .map(|word| word.0.value().cloned()) // The capacity element is never altered by the input. - .unwrap_or_else(|| Value::known(F::zero())); + .unwrap_or_else(|| Value::known(F::ZERO)); region .assign_advice( || format!("load output_{}", i), @@ -429,7 +428,7 @@ impl Var for StateWord { #[derive(Debug)] struct Pow5State([StateWord; WIDTH]); -impl Pow5State { +impl Pow5State { fn full_round( self, region: &mut Region, @@ -449,7 +448,7 @@ impl Pow5State { r.as_ref().map(|r| { r.iter() .enumerate() - .fold(F::zero(), |acc, (j, r_j)| acc + m_i[j] * r_j) + .fold(F::ZERO, |acc, (j, r_j)| acc + m_i[j] * r_j) }) }); @@ -490,7 +489,7 @@ impl Pow5State { r.as_ref().map(|r| { m_i.iter() .zip(r.iter()) - .fold(F::zero(), |acc, (m_ij, r_j)| acc + *m_ij * r_j) + .fold(F::ZERO, |acc, (m_ij, r_j)| acc + *m_ij * r_j) }) }) .collect(); @@ -523,7 +522,7 @@ impl Pow5State { r_mid.as_ref().map(|r| { m_i.iter() .zip(r.iter()) - .fold(F::zero(), |acc, (m_ij, r_j)| acc + *m_ij * r_j) + .fold(F::ZERO, |acc, (m_ij, r_j)| acc + *m_ij * r_j) }) }) .collect(); diff --git a/halo2_gadgets/src/poseidon/primitives.rs b/halo2_gadgets/src/poseidon/primitives.rs index 90631fbb..6c8d133d 100644 --- a/halo2_gadgets/src/poseidon/primitives.rs +++ b/halo2_gadgets/src/poseidon/primitives.rs @@ -5,8 +5,7 @@ use std::fmt; use std::iter; use std::marker::PhantomData; -use group::ff::Field; -use halo2_proofs::arithmetic::FieldExt; +use group::ff::{Field, FromUniformBytes, PrimeField}; pub(crate) mod fp; pub(crate) mod fq; @@ -55,8 +54,12 @@ pub trait Spec: fmt::Debug { } /// Generates `(round_constants, mds, mds^-1)` corresponding to this specification. -pub fn generate_constants, const T: usize, const RATE: usize>( -) -> (Vec<[F; T]>, Mds, Mds) { +pub fn generate_constants< + F: FromUniformBytes<64> + Ord, + S: Spec, + const T: usize, + const RATE: usize, +>() -> (Vec<[F; T]>, Mds, Mds) { let r_f = S::full_rounds(); let r_p = S::partial_rounds(); @@ -64,7 +67,7 @@ pub fn generate_constants, const T: usize, cons let round_constants = (0..(r_f + r_p)) .map(|_| { - let mut rc_row = [F::zero(); T]; + let mut rc_row = [F::ZERO; T]; for (rc, value) in rc_row .iter_mut() .zip((0..T).map(|_| grain.next_field_element())) @@ -90,7 +93,7 @@ pub(crate) fn permute, const T: usize, const RATE: let r_p = S::partial_rounds(); let apply_mds = |state: &mut State| { - let mut new_state = [F::zero(); T]; + let mut new_state = [F::ZERO; T]; // Matrix multiplication #[allow(clippy::needless_range_loop)] for i in 0..T { @@ -206,7 +209,7 @@ impl, const T: usize, const RATE: usize> let (round_constants, mds_matrix, _) = S::constants(); let mode = Absorbing([None; RATE]); - let mut state = [F::zero(); T]; + let mut state = [F::ZERO; T]; state[RATE] = initial_capacity_element; Sponge { @@ -300,7 +303,7 @@ pub trait Domain { #[derive(Clone, Copy, Debug)] pub struct ConstantLength; -impl Domain for ConstantLength { +impl Domain for ConstantLength { type Padding = iter::Take>; fn name() -> String { @@ -320,7 +323,7 @@ impl Domain for Constan // Poseidon authors encode the constant length into the capacity element, ensuring // that inputs of different lengths do not share the same permutation. let k = (L + RATE - 1) / RATE; - iter::repeat(F::zero()).take(k * RATE - L) + iter::repeat(F::ZERO).take(k * RATE - L) } } @@ -362,7 +365,7 @@ impl, D: Domain, const T: usize, const RA } } -impl, const T: usize, const RATE: usize, const L: usize> +impl, const T: usize, const RATE: usize, const L: usize> Hash, T, RATE> { /// Hashes the given input. @@ -379,7 +382,7 @@ impl, const T: usize, const RATE: usize, const #[cfg(test)] mod tests { - use halo2_proofs::arithmetic::FieldExt; + use group::ff::PrimeField; use pasta_curves::pallas; use super::{permute, ConstantLength, Hash, P128Pow5T3 as OrchardNullifier, Spec}; diff --git a/halo2_gadgets/src/poseidon/primitives/grain.rs b/halo2_gadgets/src/poseidon/primitives/grain.rs index b4ceb672..8c8c9734 100644 --- a/halo2_gadgets/src/poseidon/primitives/grain.rs +++ b/halo2_gadgets/src/poseidon/primitives/grain.rs @@ -3,8 +3,7 @@ use std::marker::PhantomData; use bitvec::prelude::*; -use group::ff::{Field, PrimeField}; -use halo2_proofs::arithmetic::FieldExt; +use group::ff::{Field, FromUniformBytes, PrimeField}; const STATE: usize = 80; @@ -138,7 +137,7 @@ impl Grain { } } -impl Grain { +impl> Grain { /// Returns the next field element from this Grain instantiation, without using /// rejection sampling. pub(super) fn next_field_element_without_rejection(&mut self) -> F { @@ -164,7 +163,7 @@ impl Grain { view[i / 8] |= if bit { 1 << (i % 8) } else { 0 }; } - F::from_bytes_wide(&bytes) + F::from_uniform_bytes(&bytes) } } diff --git a/halo2_gadgets/src/poseidon/primitives/mds.rs b/halo2_gadgets/src/poseidon/primitives/mds.rs index 45a87c92..45718731 100644 --- a/halo2_gadgets/src/poseidon/primitives/mds.rs +++ b/halo2_gadgets/src/poseidon/primitives/mds.rs @@ -1,8 +1,8 @@ -use halo2_proofs::arithmetic::FieldExt; +use ff::FromUniformBytes; use super::{grain::Grain, Mds}; -pub(super) fn generate_mds( +pub(super) fn generate_mds + Ord, const T: usize>( grain: &mut Grain, mut select: usize, ) -> (Mds, Mds) { @@ -48,7 +48,7 @@ pub(super) fn generate_mds( // However, the Poseidon paper and reference impl use the positive formulation, // and we want to rely on the reference impl for MDS security, so we use the same // formulation. - let mut mds = [[F::zero(); T]; T]; + let mut mds = [[F::ZERO; T]; T]; #[allow(clippy::needless_range_loop)] for i in 0..T { for j in 0..T { @@ -74,10 +74,10 @@ pub(super) fn generate_mds( // where A_i(x) and B_i(x) are the Lagrange polynomials for xs and ys respectively. // // We adapt this to the positive Cauchy formulation by negating ys. - let mut mds_inv = [[F::zero(); T]; T]; + let mut mds_inv = [[F::ZERO; T]; T]; let l = |xs: &[F], j, x: F| { let x_j = xs[j]; - xs.iter().enumerate().fold(F::one(), |acc, (m, x_m)| { + xs.iter().enumerate().fold(F::ONE, |acc, (m, x_m)| { if m == j { acc } else { @@ -98,6 +98,7 @@ pub(super) fn generate_mds( #[cfg(test)] mod tests { + use group::ff::Field; use pasta_curves::Fp; use super::{generate_mds, Grain}; @@ -112,9 +113,9 @@ mod tests { #[allow(clippy::needless_range_loop)] for i in 0..T { for j in 0..T { - let expected = if i == j { Fp::one() } else { Fp::zero() }; + let expected = if i == j { Fp::ONE } else { Fp::ZERO }; assert_eq!( - (0..T).fold(Fp::zero(), |acc, k| acc + (mds[i][k] * mds_inv[k][j])), + (0..T).fold(Fp::ZERO, |acc, k| acc + (mds[i][k] * mds_inv[k][j])), expected ); } diff --git a/halo2_gadgets/src/poseidon/primitives/p128pow5t3.rs b/halo2_gadgets/src/poseidon/primitives/p128pow5t3.rs index fe98517e..ff531740 100644 --- a/halo2_gadgets/src/poseidon/primitives/p128pow5t3.rs +++ b/halo2_gadgets/src/poseidon/primitives/p128pow5t3.rs @@ -66,11 +66,9 @@ impl Spec for P128Pow5T3 { #[cfg(test)] mod tests { - use ff::{Field, PrimeField}; + use ff::{Field, FromUniformBytes, PrimeField}; use std::marker::PhantomData; - use pasta_curves::arithmetic::FieldExt; - use super::{ super::{fp, fq}, Fp, Fq, @@ -91,7 +89,9 @@ mod tests { } } - impl Spec for P128Pow5T3Gen { + impl + Ord, const SECURE_MDS: usize> Spec + for P128Pow5T3Gen + { fn full_rounds() -> usize { 8 } @@ -115,7 +115,7 @@ mod tests { #[test] fn verify_constants() { - fn verify_constants_helper( + fn verify_constants_helper + Ord>( expected_round_constants: [[F; 3]; 64], expected_mds: [[F; 3]; 3], expected_mds_inv: [[F; 3]; 3], diff --git a/halo2_gadgets/src/sha256/table16/compression/compression_gates.rs b/halo2_gadgets/src/sha256/table16/compression/compression_gates.rs index 7b4862a3..dada6bbf 100644 --- a/halo2_gadgets/src/sha256/table16/compression/compression_gates.rs +++ b/halo2_gadgets/src/sha256/table16/compression/compression_gates.rs @@ -8,7 +8,7 @@ pub struct CompressionGate(PhantomData); impl CompressionGate { fn ones() -> Expression { - Expression::Constant(F::one()) + Expression::Constant(F::ONE) } // Decompose `A,B,C,D` words @@ -58,16 +58,16 @@ impl CompressionGate { + c_mid * F::from(1 << 16) + c_hi * F::from(1 << 19) + d * F::from(1 << 22) - + word_lo * (-F::one()) - + word_hi * F::from(1 << 16) * (-F::one()); + + word_lo * (-F::ONE) + + word_hi * F::from(1 << 16) * (-F::ONE); let spread_check = spread_a + spread_b * F::from(1 << 4) + spread_c_lo * F::from(1 << 26) + spread_c_mid * F::from(1 << 32) + spread_c_hi * F::from(1 << 38) + spread_d * F::from(1 << 44) - + spread_word_lo * (-F::one()) - + spread_word_hi * F::from(1 << 32) * (-F::one()); + + spread_word_lo * (-F::ONE) + + spread_word_hi * F::from(1 << 32) * (-F::ONE); Constraints::with_selector( s_decompose_abcd, @@ -129,16 +129,16 @@ impl CompressionGate { + b_hi * F::from(1 << 8) + c * F::from(1 << 11) + d * F::from(1 << 25) - + word_lo * (-F::one()) - + word_hi * F::from(1 << 16) * (-F::one()); + + word_lo * (-F::ONE) + + word_hi * F::from(1 << 16) * (-F::ONE); let spread_check = spread_a_lo + spread_a_hi * F::from(1 << 6) + spread_b_lo * F::from(1 << 12) + spread_b_hi * F::from(1 << 16) + spread_c * F::from(1 << 22) + spread_d * F::from(1 << 50) - + spread_word_lo * (-F::one()) - + spread_word_hi * F::from(1 << 32) * (-F::one()); + + spread_word_lo * (-F::ONE) + + spread_word_hi * F::from(1 << 32) * (-F::ONE); Constraints::with_selector( s_decompose_efgh, @@ -188,7 +188,7 @@ impl CompressionGate { + spread_c_mid * F::from(1 << 52) + spread_c_hi * F::from(1 << 58); let xor = xor_0 + xor_1 + xor_2; - let check = spread_witness + (xor * -F::one()); + let check = spread_witness + (xor * -F::ONE); Some(("s_upper_sigma_0", s_upper_sigma_0 * check)) } @@ -232,7 +232,7 @@ impl CompressionGate { + spread_b_hi * F::from(1 << 30) + spread_c * F::from(1 << 36); let xor = xor_0 + xor_1 + xor_2; - let check = spread_witness + (xor * -F::one()); + let check = spread_witness + (xor * -F::ONE); Some(("s_upper_sigma_1", s_upper_sigma_1 * check)) } @@ -258,7 +258,7 @@ impl CompressionGate { let rhs_odd = spread_p0_odd + spread_p1_odd * F::from(1 << 32); let rhs = rhs_even + rhs_odd * F::from(2); - let check = lhs + rhs * -F::one(); + let check = lhs + rhs * -F::ONE; Some(("s_ch", s_ch * check)) } @@ -285,9 +285,9 @@ impl CompressionGate { let neg_check = { let evens = Self::ones() * F::from(MASK_EVEN_32 as u64); // evens - spread_e_lo = spread_e_neg_lo - let lo_check = spread_e_neg_lo.clone() + spread_e_lo + (evens.clone() * (-F::one())); + let lo_check = spread_e_neg_lo.clone() + spread_e_lo + (evens.clone() * (-F::ONE)); // evens - spread_e_hi = spread_e_neg_hi - let hi_check = spread_e_neg_hi.clone() + spread_e_hi + (evens * (-F::one())); + let hi_check = spread_e_neg_hi.clone() + spread_e_hi + (evens * (-F::ONE)); std::iter::empty() .chain(Some(("lo_check", lo_check))) diff --git a/halo2_gadgets/src/sha256/table16/gates.rs b/halo2_gadgets/src/sha256/table16/gates.rs index f9b53dc0..5c5e9da3 100644 --- a/halo2_gadgets/src/sha256/table16/gates.rs +++ b/halo2_gadgets/src/sha256/table16/gates.rs @@ -5,7 +5,7 @@ pub struct Gate(pub Expression); impl Gate { fn ones() -> Expression { - Expression::Constant(F::one()) + Expression::Constant(F::ONE) } // Helper gates @@ -33,7 +33,7 @@ impl Gate { for i in 0..deg { let i = i as u64; if i != idx { - expr = expr * (Self::ones() * (-F::one()) * F::from(i) + var.clone()); + expr = expr * (Self::ones() * (-F::ONE) * F::from(i) + var.clone()); } } expr * F::from(u64::from(eval)) @@ -47,13 +47,13 @@ impl Gate { } } if denom < 0 { - -F::one() * F::from(factor / (-denom as u64)) + -F::ONE * F::from(factor / (-denom as u64)) } else { F::from(factor / (denom as u64)) } }; - let mut expr = Self::ones() * F::zero(); + let mut expr = Self::ones() * F::ZERO; for ((idx, _), eval) in points.iter().enumerate().zip(evals.iter()) { expr = expr + numerator(var.clone(), *eval, idx as u64) * denominator(idx as i32) } @@ -64,7 +64,7 @@ impl Gate { pub fn range_check(value: Expression, lower_range: u64, upper_range: u64) -> Expression { let mut expr = Self::ones(); for i in lower_range..(upper_range + 1) { - expr = expr * (Self::ones() * (-F::one()) * F::from(i) + value.clone()) + expr = expr * (Self::ones() * (-F::ONE) * F::from(i) + value.clone()) } expr } diff --git a/halo2_gadgets/src/sha256/table16/message_schedule/schedule_gates.rs b/halo2_gadgets/src/sha256/table16/message_schedule/schedule_gates.rs index b1021a0a..c088205a 100644 --- a/halo2_gadgets/src/sha256/table16/message_schedule/schedule_gates.rs +++ b/halo2_gadgets/src/sha256/table16/message_schedule/schedule_gates.rs @@ -27,8 +27,8 @@ impl ScheduleGate { let word_check = lo + hi * F::from(1 << 16) - + (carry.clone() * F::from(1 << 32) * (-F::one())) - + (word * (-F::one())); + + (carry.clone() * F::from(1 << 32) * (-F::ONE)) + + (word * (-F::ONE)); let carry_check = Gate::range_check(carry, 0, 3); [("word_check", word_check), ("carry_check", carry_check)] @@ -60,11 +60,8 @@ impl ScheduleGate { tag_d: Expression, word: Expression, ) -> impl Iterator)> { - let decompose_check = a - + b * F::from(1 << 3) - + c * F::from(1 << 7) - + d * F::from(1 << 18) - + word * (-F::one()); + let decompose_check = + a + b * F::from(1 << 3) + c * F::from(1 << 7) + d * F::from(1 << 18) + word * (-F::ONE); let range_check_tag_c = Gate::range_check(tag_c, 0, 2); let range_check_tag_d = Gate::range_check(tag_d, 0, 4); @@ -101,7 +98,7 @@ impl ScheduleGate { + e * F::from(1 << 17) + f * F::from(1 << 18) + g * F::from(1 << 19) - + word * (-F::one()); + + word * (-F::ONE); let range_check_tag_d = Gate::range_check(tag_d, 0, 0); let range_check_tag_g = Gate::range_check(tag_g, 0, 3); @@ -131,7 +128,7 @@ impl ScheduleGate { + b * F::from(1 << 10) + c * F::from(1 << 17) + d * F::from(1 << 19) - + word * (-F::one()); + + word * (-F::ONE); let range_check_tag_a = Gate::range_check(tag_a, 0, 1); let range_check_tag_d = Gate::range_check(tag_d, 0, 3); diff --git a/halo2_gadgets/src/sha256/table16/spread_table.rs b/halo2_gadgets/src/sha256/table16/spread_table.rs index 7342e6af..9fcd7bde 100644 --- a/halo2_gadgets/src/sha256/table16/spread_table.rs +++ b/halo2_gadgets/src/sha256/table16/spread_table.rs @@ -260,34 +260,31 @@ impl SpreadTableChip { impl SpreadTableConfig { fn generate() -> impl Iterator { - (1..=(1 << 16)).scan( - (F::zero(), F::zero(), F::zero()), - |(tag, dense, spread), i| { - // We computed this table row in the previous iteration. - let res = (*tag, *dense, *spread); + (1..=(1 << 16)).scan((F::ZERO, F::ZERO, F::ZERO), |(tag, dense, spread), i| { + // We computed this table row in the previous iteration. + let res = (*tag, *dense, *spread); - // i holds the zero-indexed row number for the next table row. - match i { - BITS_7 | BITS_10 | BITS_11 | BITS_13 | BITS_14 => *tag += F::one(), - _ => (), - } - *dense += F::one(); - if i & 1 == 0 { - // On even-numbered rows we recompute the spread. - *spread = F::zero(); - for b in 0..16 { - if (i >> b) & 1 != 0 { - *spread += F::from(1 << (2 * b)); - } + // i holds the zero-indexed row number for the next table row. + match i { + BITS_7 | BITS_10 | BITS_11 | BITS_13 | BITS_14 => *tag += F::ONE, + _ => (), + } + *dense += F::ONE; + if i & 1 == 0 { + // On even-numbered rows we recompute the spread. + *spread = F::ZERO; + for b in 0..16 { + if (i >> b) & 1 != 0 { + *spread += F::from(1 << (2 * b)); } - } else { - // On odd-numbered rows we add one. - *spread += F::one(); } + } else { + // On odd-numbered rows we add one. + *spread += F::ONE; + } - Some(res) - }, - ) + Some(res) + }) } } @@ -363,20 +360,20 @@ mod tests { }; // Test the first few small values. - add_row(F::zero(), F::from(0b000), F::from(0b000000))?; - add_row(F::zero(), F::from(0b001), F::from(0b000001))?; - add_row(F::zero(), F::from(0b010), F::from(0b000100))?; - add_row(F::zero(), F::from(0b011), F::from(0b000101))?; - add_row(F::zero(), F::from(0b100), F::from(0b010000))?; - add_row(F::zero(), F::from(0b101), F::from(0b010001))?; + add_row(F::ZERO, F::from(0b000), F::from(0b000000))?; + add_row(F::ZERO, F::from(0b001), F::from(0b000001))?; + add_row(F::ZERO, F::from(0b010), F::from(0b000100))?; + add_row(F::ZERO, F::from(0b011), F::from(0b000101))?; + add_row(F::ZERO, F::from(0b100), F::from(0b010000))?; + add_row(F::ZERO, F::from(0b101), F::from(0b010001))?; // Test the tag boundaries: // 7-bit - add_row(F::zero(), F::from(0b1111111), F::from(0b01010101010101))?; - add_row(F::one(), F::from(0b10000000), F::from(0b0100000000000000))?; + add_row(F::ZERO, F::from(0b1111111), F::from(0b01010101010101))?; + add_row(F::ONE, F::from(0b10000000), F::from(0b0100000000000000))?; // - 10-bit add_row( - F::one(), + F::ONE, F::from(0b1111111111), F::from(0b01010101010101010101), )?; diff --git a/halo2_gadgets/src/sinsemilla.rs b/halo2_gadgets/src/sinsemilla.rs index 11e4b24a..3f06315a 100644 --- a/halo2_gadgets/src/sinsemilla.rs +++ b/halo2_gadgets/src/sinsemilla.rs @@ -204,9 +204,9 @@ where let to_base_field = |bits: &[Value]| -> Value { let bits: Value> = bits.iter().cloned().collect(); bits.map(|bits| { - bits.into_iter().rev().fold(C::Base::zero(), |acc, bit| { + bits.into_iter().rev().fold(C::Base::ZERO, |acc, bit| { if bit { - acc.double() + C::Base::one() + acc.double() + C::Base::ONE } else { acc.double() } @@ -244,7 +244,7 @@ where subpieces: impl IntoIterator>>, ) -> Result { let (field_elem, total_bits) = subpieces.into_iter().fold( - (Value::known(C::Base::zero()), 0), + (Value::known(C::Base::ZERO), 0), |(acc, bits), subpiece| { assert!(bits < 64); let subpiece_shifted = subpiece diff --git a/halo2_gadgets/src/sinsemilla/chip/generator_table.rs b/halo2_gadgets/src/sinsemilla/chip/generator_table.rs index b9c3ca25..a3bfa22c 100644 --- a/halo2_gadgets/src/sinsemilla/chip/generator_table.rs +++ b/halo2_gadgets/src/sinsemilla/chip/generator_table.rs @@ -1,3 +1,4 @@ +use group::ff::PrimeField; use halo2_proofs::{ circuit::{Layouter, Value}, plonk::{ConstraintSystem, Error, Expression, TableColumn}, @@ -6,7 +7,7 @@ use halo2_proofs::{ use super::{CommitDomains, FixedPoints, HashDomains}; use crate::sinsemilla::primitives::{self as sinsemilla, SINSEMILLA_S}; -use pasta_curves::{arithmetic::FieldExt, pallas}; +use pasta_curves::pallas; /// Table containing independent generators S[0..2^k] #[derive(Eq, PartialEq, Copy, Clone, Debug)] diff --git a/halo2_gadgets/src/sinsemilla/chip/hash_to_point.rs b/halo2_gadgets/src/sinsemilla/chip/hash_to_point.rs index 001ca1d8..44beaa42 100644 --- a/halo2_gadgets/src/sinsemilla/chip/hash_to_point.rs +++ b/halo2_gadgets/src/sinsemilla/chip/hash_to_point.rs @@ -5,12 +5,13 @@ use crate::{ sinsemilla::primitives::{self as sinsemilla, lebs2ip_k, INV_TWO_POW_K, SINSEMILLA_S}, }; +use ff::Field; use halo2_proofs::{ circuit::{AssignedCell, Chip, Region, Value}, plonk::{Assigned, Error}, }; -use group::ff::{Field, PrimeField, PrimeFieldBits}; +use group::ff::{PrimeField, PrimeFieldBits}; use pasta_curves::{arithmetic::CurveAffine, pallas}; use std::ops::Deref; diff --git a/halo2_gadgets/src/sinsemilla/merkle/chip.rs b/halo2_gadgets/src/sinsemilla/merkle/chip.rs index dcedb6b0..2c37fe92 100644 --- a/halo2_gadgets/src/sinsemilla/merkle/chip.rs +++ b/halo2_gadgets/src/sinsemilla/merkle/chip.rs @@ -5,7 +5,7 @@ use halo2_proofs::{ plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Selector}, poly::Rotation, }; -use pasta_curves::{arithmetic::FieldExt, pallas}; +use pasta_curves::pallas; use super::MerkleInstructions; diff --git a/halo2_gadgets/src/sinsemilla/message.rs b/halo2_gadgets/src/sinsemilla/message.rs index a8bc303c..f8ba67da 100644 --- a/halo2_gadgets/src/sinsemilla/message.rs +++ b/halo2_gadgets/src/sinsemilla/message.rs @@ -1,7 +1,6 @@ //! Gadget and chips for the Sinsemilla hash function. use ff::{Field, PrimeFieldBits}; use halo2_proofs::circuit::{AssignedCell, Cell, Value}; - use std::fmt::Debug; /// A [`Message`] composed of several [`MessagePiece`]s. diff --git a/halo2_gadgets/src/utilities.rs b/halo2_gadgets/src/utilities.rs index ae6a507d..739f4411 100644 --- a/halo2_gadgets/src/utilities.rs +++ b/halo2_gadgets/src/utilities.rs @@ -138,7 +138,7 @@ pub fn bool_check(value: Expression) -> Expression { /// /// `a` must be a boolean-constrained expression. pub fn ternary(a: Expression, b: Expression, c: Expression) -> Expression { - let one_minus_a = Expression::Constant(F::one()) - a.clone(); + let one_minus_a = Expression::Constant(F::ONE) - a.clone(); a * b + one_minus_a * c } @@ -156,9 +156,9 @@ pub fn bitrange_subset(field_elem: &F, bitrange: Range .skip(bitrange.start) .take(bitrange.end - bitrange.start) .rev() - .fold(F::zero(), |acc, bit| { + .fold(F::ZERO, |acc, bit| { if bit { - acc.double() + F::one() + acc.double() + F::ONE } else { acc.double() } @@ -240,14 +240,14 @@ pub fn i2lebsp(int: u64) -> [bool; NUM_BITS] { #[cfg(test)] mod tests { use super::*; - use group::ff::{Field, PrimeField}; + use group::ff::{Field, FromUniformBytes, PrimeField}; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner}, dev::{FailureLocation, MockProver, VerifyFailure}, plonk::{Any, Circuit, ConstraintSystem, Constraints, Error, Selector}, poly::Rotation, }; - use pasta_curves::{arithmetic::FieldExt, pallas}; + use pasta_curves::pallas; use proptest::prelude::*; use rand::rngs::OsRng; use std::convert::TryInto; @@ -358,7 +358,7 @@ mod tests { let field_elem = pallas::Base::random(rng); let bitrange = 0..0; let subset = bitrange_subset(&field_elem, bitrange); - assert_eq!(pallas::Base::zero(), subset); + assert_eq!(pallas::Base::ZERO, subset); } // Closure to decompose field element into pieces using consecutive ranges, @@ -420,7 +420,7 @@ mod tests { // Instead of rejecting out-of-range bytes, let's reduce them. let mut buf = [0; 64]; buf[..32].copy_from_slice(&bytes); - pallas::Scalar::from_bytes_wide(&buf) + pallas::Scalar::from_uniform_bytes(&buf) } } diff --git a/halo2_gadgets/src/utilities/cond_swap.rs b/halo2_gadgets/src/utilities/cond_swap.rs index 89245888..d733e6c4 100644 --- a/halo2_gadgets/src/utilities/cond_swap.rs +++ b/halo2_gadgets/src/utilities/cond_swap.rs @@ -8,7 +8,6 @@ use halo2_proofs::{ plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Selector}, poly::Rotation, }; - use std::marker::PhantomData; /// Instructions for a conditional swap gadget. diff --git a/halo2_gadgets/src/utilities/decompose_running_sum.rs b/halo2_gadgets/src/utilities/decompose_running_sum.rs index a0ee11c7..5a83e417 100644 --- a/halo2_gadgets/src/utilities/decompose_running_sum.rs +++ b/halo2_gadgets/src/utilities/decompose_running_sum.rs @@ -198,7 +198,7 @@ impl RunningSumConfig LookupRangeCheckConfig { // In the short range check, the word is directly witnessed. let short_lookup = { let short_word = z_cur; - let q_short = Expression::Constant(F::one()) - q_running; + let q_short = Expression::Constant(F::ONE) - q_running; q_short * short_word }; @@ -285,7 +285,7 @@ impl LookupRangeCheckConfig { if strict { // Constrain the final `z` to be zero. - region.constrain_constant(zs.last().unwrap().cell(), F::zero())?; + region.constrain_constant(zs.last().unwrap().cell(), F::ZERO)?; } Ok(RunningSum(zs)) @@ -434,8 +434,8 @@ mod tests { // Lookup constraining element to be no longer than num_words * K bits. let elements_and_expected_final_zs = [ - (F::from((1 << (self.num_words * K)) - 1), F::zero(), true), // a word that is within self.num_words * K bits long - (F::from(1 << (self.num_words * K)), F::one(), false), // a word that is just over self.num_words * K bits long + (F::from((1 << (self.num_words * K)) - 1), F::ZERO, true), // a word that is within self.num_words * K bits long + (F::from(1 << (self.num_words * K)), F::ONE, false), // a word that is just over self.num_words * K bits long ]; fn expected_zs( @@ -545,7 +545,7 @@ mod tests { // Edge case: zero bits { let circuit: MyCircuit = MyCircuit { - element: Value::known(pallas::Base::zero()), + element: Value::known(pallas::Base::ZERO), num_bits: 0, }; let prover = MockProver::::run(11, &circuit, vec![]).unwrap(); diff --git a/halo2_proofs/CHANGELOG.md b/halo2_proofs/CHANGELOG.md index 7ae956b4..597838a5 100644 --- a/halo2_proofs/CHANGELOG.md +++ b/halo2_proofs/CHANGELOG.md @@ -6,6 +6,7 @@ and this project adheres to Rust's notion of [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added - The following structs now derive the `Eq` trait: - `halo2_proofs::dev`: - `failure::FailureLocation` @@ -14,14 +15,13 @@ and this project adheres to Rust's notion of - `metadata::Constraint` - `metadata::Region` - `halo2_proofs::poly::Rotation` - -### Added - `halo2_proofs::arithmetic::FftGroup` - `halo2_proofs::circuit::layouter`: - `RegionLayouter::instance_value` method added to provide access to instance values within a region. ### Changed +- Migrated to `ff 0.13`. - APIs with `F: pasta_curves::arithmetic::FieldExt` bounds have been changed to use `ff` traits directly. - `halo2_proofs::arithmetic`: diff --git a/halo2_proofs/benches/dev_lookup.rs b/halo2_proofs/benches/dev_lookup.rs index 0a60a189..55057e0d 100644 --- a/halo2_proofs/benches/dev_lookup.rs +++ b/halo2_proofs/benches/dev_lookup.rs @@ -42,7 +42,7 @@ fn criterion_benchmark(c: &mut Criterion) { meta.lookup(|meta| { let selector = meta.query_selector(config.selector); - let not_selector = Expression::Constant(F::one()) - selector.clone(); + let not_selector = Expression::Constant(F::ONE) - selector.clone(); let advice = meta.query_advice(config.advice, Rotation::cur()); vec![(selector * advice + not_selector, config.table)] }); diff --git a/halo2_proofs/benches/plonk.rs b/halo2_proofs/benches/plonk.rs index 8e3dc55e..7a57be8a 100644 --- a/halo2_proofs/benches/plonk.rs +++ b/halo2_proofs/benches/plonk.rs @@ -103,15 +103,10 @@ fn criterion_benchmark(c: &mut Criterion) { || value.unwrap().map(|v| v.2), )?; - region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::zero()))?; - region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::zero()))?; - region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?; - region.assign_fixed( - || "a * b", - self.config.sm, - 0, - || Value::known(FF::one()), - )?; + region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ZERO))?; + region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ZERO))?; + region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ONE))?; Ok((lhs.cell(), rhs.cell(), out.cell())) }, ) @@ -150,14 +145,14 @@ fn criterion_benchmark(c: &mut Criterion) { || value.unwrap().map(|v| v.2), )?; - region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?; + region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?; region.assign_fixed( || "a * b", self.config.sm, 0, - || Value::known(FF::zero()), + || Value::known(FF::ZERO), )?; Ok((lhs.cell(), rhs.cell(), out.cell())) }, diff --git a/halo2_proofs/examples/circuit-layout.rs b/halo2_proofs/examples/circuit-layout.rs index 5cb05159..71e22ddc 100644 --- a/halo2_proofs/examples/circuit-layout.rs +++ b/halo2_proofs/examples/circuit-layout.rs @@ -93,10 +93,10 @@ impl StandardCs for StandardPlonk { let out = region.assign_advice(|| "out", self.config.c, 0, || value.unwrap().map(|v| v.2))?; - region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::zero()))?; - region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::zero()))?; - region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::one()))?; + region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ZERO))?; + region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ZERO))?; + region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ONE))?; Ok((lhs.cell(), rhs.cell(), out.cell())) } fn raw_add(&self, region: &mut Region, mut f: F) -> Result<(Cell, Cell, Cell), Error> @@ -130,10 +130,10 @@ impl StandardCs for StandardPlonk { let out = region.assign_advice(|| "out", self.config.c, 0, || value.unwrap().map(|v| v.2))?; - region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::zero()))?; + region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ZERO))?; Ok((lhs.cell(), rhs.cell(), out.cell())) } fn copy(&self, region: &mut Region, left: Cell, right: Cell) -> Result<(), Error> { @@ -274,7 +274,7 @@ fn main() { // Prepare the circuit you want to render. // You don't need to include any witness variables. let a = Fp::random(OsRng); - let instance = Fp::one() + Fp::one(); + let instance = Fp::ONE + Fp::ONE; let lookup_table = vec![instance, a, a, Fp::zero()]; let circuit: MyCircuit = MyCircuit { a: Value::unknown(), diff --git a/halo2_proofs/src/arithmetic.rs b/halo2_proofs/src/arithmetic.rs index 2bc2ce17..4cb0039d 100644 --- a/halo2_proofs/src/arithmetic.rs +++ b/halo2_proofs/src/arithmetic.rs @@ -207,7 +207,7 @@ pub fn best_fft>(a: &mut [G], omega: Scalar, // precompute twiddle factors let twiddles: Vec<_> = (0..(n / 2)) - .scan(Scalar::one(), |w, _| { + .scan(Scalar::ONE, |w, _| { let tw = *w; *w *= ω Some(tw) @@ -293,7 +293,7 @@ pub fn eval_polynomial(poly: &[F], point: F) -> F { // TODO: parallelize? poly.iter() .rev() - .fold(F::zero(), |acc, coeff| acc * point + coeff) + .fold(F::ZERO, |acc, coeff| acc * point + coeff) } /// This computes the inner product of two vectors `a` and `b`. @@ -303,7 +303,7 @@ pub fn compute_inner_product(a: &[F], b: &[F]) -> F { // TODO: parallelize? assert_eq!(a.len(), b.len()); - let mut acc = F::zero(); + let mut acc = F::ZERO; for (a, b) in a.iter().zip(b.iter()) { acc += (*a) * (*b); } @@ -320,9 +320,9 @@ where b = -b; let a = a.into_iter(); - let mut q = vec![F::zero(); a.len() - 1]; + let mut q = vec![F::ZERO; a.len() - 1]; - let mut tmp = F::zero(); + let mut tmp = F::ZERO; for (q, r) in q.iter_mut().rev().zip(a.rev()) { let mut lead_coeff = *r; lead_coeff.sub_assign(&tmp); @@ -392,11 +392,11 @@ pub fn lagrange_interpolate(points: &[F], evals: &[F]) -> Vec { // Compute (x_j - x_k)^(-1) for each j != i denoms.iter_mut().flat_map(|v| v.iter_mut()).batch_invert(); - let mut final_poly = vec![F::zero(); points.len()]; + let mut final_poly = vec![F::ZERO; points.len()]; for (j, (denoms, eval)) in denoms.into_iter().zip(evals.iter()).enumerate() { let mut tmp: Vec = Vec::with_capacity(points.len()); let mut product = Vec::with_capacity(points.len() - 1); - tmp.push(F::one()); + tmp.push(F::ONE); for (x_k, denom) in points .iter() .enumerate() @@ -404,11 +404,11 @@ pub fn lagrange_interpolate(points: &[F], evals: &[F]) -> Vec { .map(|a| a.1) .zip(denoms.into_iter()) { - product.resize(tmp.len() + 1, F::zero()); + product.resize(tmp.len() + 1, F::ZERO); for ((a, b), product) in tmp .iter() - .chain(std::iter::once(&F::zero())) - .zip(std::iter::once(&F::zero()).chain(tmp.iter())) + .chain(std::iter::once(&F::ZERO)) + .zip(std::iter::once(&F::ZERO).chain(tmp.iter())) .zip(product.iter_mut()) { *product = *a * (-denom * x_k) + *b * denom; diff --git a/halo2_proofs/src/dev.rs b/halo2_proofs/src/dev.rs index b9ddcb26..41e6d92f 100644 --- a/halo2_proofs/src/dev.rs +++ b/halo2_proofs/src/dev.rs @@ -9,7 +9,6 @@ use ff::Field; use crate::plonk::Assigned; use crate::{ - arithmetic::FieldExt, circuit, plonk::{ permutation, Advice, Any, Assignment, Circuit, Column, ConstraintSystem, Error, Expression, @@ -92,7 +91,7 @@ impl From> for Value { fn from(value: CellValue) -> Self { match value { // Cells that haven't been explicitly assigned to, default to zero. - CellValue::Unassigned => Value::Real(F::zero()), + CellValue::Unassigned => Value::Real(F::ZERO), CellValue::Assigned(v) => Value::Real(v), CellValue::Poison(_) => Value::Poison, } @@ -132,7 +131,7 @@ impl Mul for Value { (Value::Real(x), Value::Poison) | (Value::Poison, Value::Real(x)) if x.is_zero_vartime() => { - Value::Real(F::zero()) + Value::Real(F::ZERO) } _ => Value::Poison, } @@ -147,7 +146,7 @@ impl Mul for Value { Value::Real(lhs) => Value::Real(lhs * rhs), // If poison is multiplied by zero, then we treat the poison as unconstrained // and we don't propagate it. - Value::Poison if rhs.is_zero_vartime() => Value::Real(F::zero()), + Value::Poison if rhs.is_zero_vartime() => Value::Real(F::ZERO), _ => Value::Poison, } } @@ -164,8 +163,8 @@ impl Mul for Value { /// # Examples /// /// ``` +/// use group::ff::PrimeField; /// use halo2_proofs::{ -/// arithmetic::FieldExt, /// circuit::{Layouter, SimpleFloorPlanner, Value}, /// dev::{FailureLocation, MockProver, VerifyFailure}, /// pasta::Fp, @@ -188,7 +187,7 @@ impl Mul for Value { /// b: Value, /// } /// -/// impl Circuit for MyCircuit { +/// impl Circuit for MyCircuit { /// type Config = MyConfig; /// type FloorPlanner = SimpleFloorPlanner; /// @@ -303,7 +302,7 @@ impl InstanceValue { fn value(&self) -> F { match self { InstanceValue::Assigned(v) => *v, - InstanceValue::Padding => F::zero(), + InstanceValue::Padding => F::ZERO, } } } @@ -477,7 +476,7 @@ impl Assignment for MockProver { } } -impl MockProver { +impl MockProver { /// Runs a synthetic keygen-and-prove operation on the given circuit, collecting data /// about the constraints and their assignments. pub fn run>( @@ -918,6 +917,7 @@ impl MockProver { #[cfg(test)] mod tests { + use group::ff::Field; use pasta_curves::Fp; use super::{FailureLocation, MockProver, VerifyFailure}; @@ -979,7 +979,7 @@ mod tests { config.q.enable(&mut region, 1)?; // Assign a = 0. - region.assign_advice(|| "a", config.a, 0, || Value::known(Fp::zero()))?; + region.assign_advice(|| "a", config.a, 0, || Value::known(Fp::ZERO))?; // BUG: Forget to assign b = 0! This could go unnoticed during // development, because cell values default to zero, which in this diff --git a/halo2_proofs/src/dev/util.rs b/halo2_proofs/src/dev/util.rs index 014e8994..ee3b7cb1 100644 --- a/halo2_proofs/src/dev/util.rs +++ b/halo2_proofs/src/dev/util.rs @@ -58,9 +58,9 @@ impl From for AnyQuery { pub(super) fn format_value(v: F) -> String { if v.is_zero_vartime() { "0".into() - } else if v == F::one() { + } else if v == F::ONE { "1".into() - } else if v == -F::one() { + } else if v == -F::ONE { "-1".into() } else { // Format value as hex. diff --git a/halo2_proofs/src/plonk.rs b/halo2_proofs/src/plonk.rs index 78dd2c89..e96cf3fe 100644 --- a/halo2_proofs/src/plonk.rs +++ b/halo2_proofs/src/plonk.rs @@ -6,9 +6,9 @@ //! [plonk]: https://eprint.iacr.org/2019/953 use blake2b_simd::Params as Blake2bParams; -use group::ff::Field; +use group::ff::{Field, FromUniformBytes, PrimeField}; -use crate::arithmetic::{CurveAffine, FieldExt}; +use crate::arithmetic::CurveAffine; use crate::poly::{ Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, PinnedEvaluationDomain, Polynomial, @@ -49,7 +49,10 @@ pub struct VerifyingKey { transcript_repr: C::Scalar, } -impl VerifyingKey { +impl VerifyingKey +where + C::Scalar: FromUniformBytes<64>, +{ fn from_parts( domain: EvaluationDomain, fixed_commitments: Vec, @@ -66,7 +69,7 @@ impl VerifyingKey { cs, cs_degree, // Temporary, this is not pinned. - transcript_repr: C::Scalar::zero(), + transcript_repr: C::Scalar::ZERO, }; let mut hasher = Blake2bParams::new() @@ -80,11 +83,13 @@ impl VerifyingKey { hasher.update(s.as_bytes()); // Hash in final Blake2bState - vk.transcript_repr = C::Scalar::from_bytes_wide(hasher.finalize().as_array()); + vk.transcript_repr = C::Scalar::from_uniform_bytes(hasher.finalize().as_array()); vk } +} +impl VerifyingKey { /// Hashes a verification key into a transcript. pub fn hash_into, T: Transcript>( &self, diff --git a/halo2_proofs/src/plonk/assigned.rs b/halo2_proofs/src/plonk/assigned.rs index 27785ed4..8d874739 100644 --- a/halo2_proofs/src/plonk/assigned.rs +++ b/halo2_proofs/src/plonk/assigned.rs @@ -280,7 +280,7 @@ impl Assigned { /// Returns the numerator. pub fn numerator(&self) -> F { match self { - Self::Zero => F::zero(), + Self::Zero => F::ZERO, Self::Trivial(x) => *x, Self::Rational(numerator, _) => *numerator, } @@ -341,7 +341,7 @@ impl Assigned { pub fn invert(&self) -> Self { match self { Self::Zero => Self::Zero, - Self::Trivial(x) => Self::Rational(F::one(), *x), + Self::Trivial(x) => Self::Rational(F::ONE, *x), Self::Rational(numerator, denominator) => Self::Rational(*denominator, *numerator), } } @@ -352,13 +352,13 @@ impl Assigned { /// If the denominator is zero, this returns zero. pub fn evaluate(self) -> F { match self { - Self::Zero => F::zero(), + Self::Zero => F::ZERO, Self::Trivial(x) => x, Self::Rational(numerator, denominator) => { - if denominator == F::one() { + if denominator == F::ONE { numerator } else { - numerator * denominator.invert().unwrap_or(F::zero()) + numerator * denominator.invert().unwrap_or(F::ZERO) } } } @@ -367,6 +367,7 @@ impl Assigned { #[cfg(test)] mod tests { + use group::ff::Field; use pasta_curves::Fp; use super::Assigned; @@ -376,7 +377,7 @@ mod tests { // a = 2 // b = (1,0) let a = Assigned::Trivial(Fp::from(2)); - let b = Assigned::Rational(Fp::one(), Fp::zero()); + let b = Assigned::Rational(Fp::ONE, Fp::ZERO); // 2 + (1,0) = 2 + 0 = 2 // This fails if addition is implemented using normal rules for rationals. @@ -388,8 +389,8 @@ mod tests { fn add_rational_to_inv0_rational() { // a = (1,2) // b = (1,0) - let a = Assigned::Rational(Fp::one(), Fp::from(2)); - let b = Assigned::Rational(Fp::one(), Fp::zero()); + let a = Assigned::Rational(Fp::ONE, Fp::from(2)); + let b = Assigned::Rational(Fp::ONE, Fp::ZERO); // (1,2) + (1,0) = (1,2) + 0 = (1,2) // This fails if addition is implemented using normal rules for rationals. @@ -402,7 +403,7 @@ mod tests { // a = 2 // b = (1,0) let a = Assigned::Trivial(Fp::from(2)); - let b = Assigned::Rational(Fp::one(), Fp::zero()); + let b = Assigned::Rational(Fp::ONE, Fp::ZERO); // (1,0) - 2 = 0 - 2 = -2 // This fails if subtraction is implemented using normal rules for rationals. @@ -416,8 +417,8 @@ mod tests { fn sub_rational_from_inv0_rational() { // a = (1,2) // b = (1,0) - let a = Assigned::Rational(Fp::one(), Fp::from(2)); - let b = Assigned::Rational(Fp::one(), Fp::zero()); + let a = Assigned::Rational(Fp::ONE, Fp::from(2)); + let b = Assigned::Rational(Fp::ONE, Fp::ZERO); // (1,0) - (1,2) = 0 - (1,2) = -(1,2) // This fails if subtraction is implemented using normal rules for rationals. @@ -431,14 +432,14 @@ mod tests { fn mul_rational_by_inv0_rational() { // a = (1,2) // b = (1,0) - let a = Assigned::Rational(Fp::one(), Fp::from(2)); - let b = Assigned::Rational(Fp::one(), Fp::zero()); + let a = Assigned::Rational(Fp::ONE, Fp::from(2)); + let b = Assigned::Rational(Fp::ONE, Fp::ZERO); // (1,2) * (1,0) = (1,2) * 0 = 0 - assert_eq!((a * b).evaluate(), Fp::zero()); + assert_eq!((a * b).evaluate(), Fp::ZERO); // (1,0) * (1,2) = 0 * (1,2) = 0 - assert_eq!((b * a).evaluate(), Fp::zero()); + assert_eq!((b * a).evaluate(), Fp::ZERO); } } @@ -476,7 +477,7 @@ mod proptests { } fn inv0(&self) -> Self { - self.invert().unwrap_or(F::zero()) + self.invert().unwrap_or(F::ZERO) } } @@ -578,7 +579,7 @@ mod proptests { fn arb_rational()( numerator in arb_element(), denominator in prop_oneof![ - 1 => Just(Fp::zero()), + 1 => Just(Fp::ZERO), 2 => arb_element(), ], ) -> Assigned { diff --git a/halo2_proofs/src/plonk/circuit.rs b/halo2_proofs/src/plonk/circuit.rs index ce5f4e98..d16f3b7e 100644 --- a/halo2_proofs/src/plonk/circuit.rs +++ b/halo2_proofs/src/plonk/circuit.rs @@ -228,12 +228,11 @@ impl TryFrom> for Column { /// Selectors are disabled on all rows by default, and must be explicitly enabled on each /// row when required: /// ``` +/// use group::ff::Field; /// use halo2_proofs::{ -/// arithmetic::FieldExt, /// circuit::{Chip, Layouter, Value}, /// plonk::{Advice, Column, Error, Selector}, /// }; -/// # use ff::Field; /// # use halo2_proofs::plonk::Fixed; /// /// struct Config { @@ -242,12 +241,12 @@ impl TryFrom> for Column { /// s: Selector, /// } /// -/// fn circuit_logic>(chip: C, mut layouter: impl Layouter) -> Result<(), Error> { +/// fn circuit_logic>(chip: C, mut layouter: impl Layouter) -> Result<(), Error> { /// let config = chip.config(); /// # let config: Config = todo!(); /// layouter.assign_region(|| "bar", |mut region| { -/// region.assign_advice(|| "a", config.a, 0, || Value::known(F::one()))?; -/// region.assign_advice(|| "a", config.b, 1, || Value::known(F::one()))?; +/// region.assign_advice(|| "a", config.a, 0, || Value::known(F::ONE))?; +/// region.assign_advice(|| "a", config.b, 1, || Value::known(F::ONE))?; /// config.s.enable(&mut region, 1) /// })?; /// Ok(()) @@ -816,6 +815,7 @@ impl From> for Vec> { /// A set of polynomial constraints with a common selector. /// /// ``` +/// use group::ff::Field; /// use halo2_proofs::{pasta::Fp, plonk::{Constraints, Expression}, poly::Rotation}; /// # use halo2_proofs::plonk::ConstraintSystem; /// @@ -832,7 +832,7 @@ impl From> for Vec> { /// let c = meta.query_advice(c, Rotation::cur()); /// let s_ternary = meta.query_selector(s); /// -/// let one_minus_a = Expression::Constant(Fp::one()) - a.clone(); +/// let one_minus_a = Expression::Constant(Fp::ONE) - a.clone(); /// /// Constraints::with_selector( /// s_ternary, diff --git a/halo2_proofs/src/plonk/circuit/compress_selectors.rs b/halo2_proofs/src/plonk/circuit/compress_selectors.rs index 81dc27d2..01cca9bc 100644 --- a/halo2_proofs/src/plonk/circuit/compress_selectors.rs +++ b/halo2_proofs/src/plonk/circuit/compress_selectors.rs @@ -79,7 +79,7 @@ where let combination_assignment = selector .activations .iter() - .map(|b| if *b { F::one() } else { F::zero() }) + .map(|b| if *b { F::ONE } else { F::ZERO }) .collect::>(); let combination_index = combination_assignments.len(); combination_assignments.push(combination_assignment); @@ -177,12 +177,12 @@ where } // Now, compute the selector and combination assignments. - let mut combination_assignment = vec![F::zero(); n]; + let mut combination_assignment = vec![F::ZERO; n]; let combination_len = combination.len(); let combination_index = combination_assignments.len(); let query = allocate_fixed_column(); - let mut assigned_root = F::one(); + let mut assigned_root = F::ONE; selector_assignments.extend(combination.into_iter().map(|selector| { // Compute the expression for substitution. This produces an expression of the // form @@ -192,12 +192,12 @@ where // `assigned_root`. In particular, rows set to 0 correspond to all selectors // being disabled. let mut expression = query.clone(); - let mut root = F::one(); + let mut root = F::ONE; for _ in 0..combination_len { if root != assigned_root { expression = expression * (Expression::Constant(root) - query.clone()); } - root += F::one(); + root += F::ONE; } // Update the combination assignment @@ -212,7 +212,7 @@ where } } - assigned_root += F::one(); + assigned_root += F::ONE; SelectorAssignment { selector: selector.selector, diff --git a/halo2_proofs/src/plonk/keygen.rs b/halo2_proofs/src/plonk/keygen.rs index baab69d8..bb26d5a6 100644 --- a/halo2_proofs/src/plonk/keygen.rs +++ b/halo2_proofs/src/plonk/keygen.rs @@ -2,7 +2,7 @@ use std::ops::Range; -use ff::Field; +use ff::{Field, FromUniformBytes}; use group::Curve; use super::{ @@ -192,6 +192,7 @@ pub fn keygen_vk( ) -> Result, Error> where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, ConcreteCircuit: Circuit, { let (domain, cs, config) = create_domain::(params); @@ -303,7 +304,7 @@ where // Compute l_0(X) // TODO: this can be done more efficiently let mut l0 = vk.domain.empty_lagrange(); - l0[0] = C::Scalar::one(); + l0[0] = C::Scalar::ONE; let l0 = vk.domain.lagrange_to_coeff(l0); let l0 = vk.domain.coeff_to_extended(l0); @@ -311,7 +312,7 @@ where // and 0 otherwise over the domain. let mut l_blind = vk.domain.empty_lagrange(); for evaluation in l_blind[..].iter_mut().rev().take(cs.blinding_factors()) { - *evaluation = C::Scalar::one(); + *evaluation = C::Scalar::ONE; } let l_blind = vk.domain.lagrange_to_coeff(l_blind); let l_blind = vk.domain.coeff_to_extended(l_blind); @@ -319,7 +320,7 @@ where // Compute l_last(X) which evaluates to 1 on the first inactive row (just // before the blinding factors) and 0 otherwise over the domain let mut l_last = vk.domain.empty_lagrange(); - l_last[params.n as usize - cs.blinding_factors() - 1] = C::Scalar::one(); + l_last[params.n as usize - cs.blinding_factors() - 1] = C::Scalar::ONE; let l_last = vk.domain.lagrange_to_coeff(l_last); let l_last = vk.domain.coeff_to_extended(l_last); diff --git a/halo2_proofs/src/plonk/lookup/prover.rs b/halo2_proofs/src/plonk/lookup/prover.rs index 2b08bf14..a6ad4a62 100644 --- a/halo2_proofs/src/plonk/lookup/prover.rs +++ b/halo2_proofs/src/plonk/lookup/prover.rs @@ -4,7 +4,7 @@ use super::super::{ }; use super::Argument; use crate::{ - arithmetic::{eval_polynomial, parallelize, CurveAffine, FieldExt}, + arithmetic::{eval_polynomial, parallelize, CurveAffine}, poly::{ self, commitment::{Blind, Params}, @@ -13,6 +13,7 @@ use crate::{ }, transcript::{EncodedChallenge, TranscriptWrite}, }; +use ff::WithSmallOrderMulGroup; use group::{ ff::{BatchInvert, Field}, Curve, @@ -61,7 +62,7 @@ pub(in crate::plonk) struct Evaluated { constructed: Constructed, } -impl Argument { +impl> Argument { /// Given a Lookup with input expressions [A_0, A_1, ..., A_{m-1}] and table expressions /// [S_0, S_1, ..., S_{m-1}], this method /// - constructs A_compressed = \theta^{m-1} A_0 + theta^{m-2} A_1 + ... + \theta A_{m-2} + A_{m-1} @@ -164,13 +165,13 @@ impl Argument { // Compressed version of expressions let compressed_expression = unpermuted_expressions.iter().fold( - poly::Ast::ConstantTerm(C::Scalar::zero()), + poly::Ast::ConstantTerm(C::Scalar::ZERO), |acc, expression| &(acc * *theta) + expression, ); // Compressed version of cosets let compressed_coset = unpermuted_cosets.iter().fold( - poly::Ast::<_, _, ExtendedLagrangeCoeff>::ConstantTerm(C::Scalar::zero()), + poly::Ast::<_, _, ExtendedLagrangeCoeff>::ConstantTerm(C::Scalar::ZERO), |acc, eval| acc * poly::Ast::ConstantTerm(*theta) + eval.clone(), ); @@ -275,7 +276,7 @@ impl Permuted { // s_j(X) is the jth table expression in this lookup, // s'(X) is the compression of the permuted table expressions, // and i is the ith row of the expression. - let mut lookup_product = vec![C::Scalar::zero(); params.n as usize]; + let mut lookup_product = vec![C::Scalar::ZERO; params.n as usize]; // Denominator uses the permuted input expression and permuted table expression parallelize(&mut lookup_product, |lookup_product, start| { for ((lookup_product, permuted_input_value), permuted_table_value) in lookup_product @@ -320,9 +321,9 @@ impl Permuted { // Compute the evaluations of the lookup product polynomial // over our domain, starting with z[0] = 1 - let z = iter::once(C::Scalar::one()) + let z = iter::once(C::Scalar::ONE) .chain(lookup_product) - .scan(C::Scalar::one(), |state, cur| { + .scan(C::Scalar::ONE, |state, cur| { *state *= &cur; Some(*state) }) @@ -343,7 +344,7 @@ impl Permuted { let u = (params.n as usize) - (blinding_factors + 1); // l_0(X) * (1 - z(X)) = 0 - assert_eq!(z[0], C::Scalar::one()); + assert_eq!(z[0], C::Scalar::ONE); // z(\omega X) (a'(X) + \beta) (s'(X) + \gamma) // - z(X) (\theta^{m-1} a_0(X) + ... + a_{m-1}(X) + \beta) (\theta^{m-1} s_0(X) + ... + s_{m-1}(X) + \gamma) @@ -371,7 +372,7 @@ impl Permuted { // l_last(X) * (z(X)^2 - z(X)) = 0 // Assertion will fail only when soundness is broken, in which // case this z[u] value will be zero. (bad!) - assert_eq!(z[u], C::Scalar::one()); + assert_eq!(z[u], C::Scalar::ONE); } let product_blind = Blind(C::Scalar::random(rng)); @@ -584,7 +585,7 @@ fn permute_expression_pair( *acc.entry(*coeff).or_insert(0) += 1; acc }); - let mut permuted_table_coeffs = vec![C::Scalar::zero(); usable_rows]; + let mut permuted_table_coeffs = vec![C::Scalar::ZERO; usable_rows]; let mut repeated_input_rows = permuted_input_expression .iter() diff --git a/halo2_proofs/src/plonk/lookup/verifier.rs b/halo2_proofs/src/plonk/lookup/verifier.rs index df2c37f3..0e066549 100644 --- a/halo2_proofs/src/plonk/lookup/verifier.rs +++ b/halo2_proofs/src/plonk/lookup/verifier.rs @@ -104,7 +104,7 @@ impl Evaluated { fixed_evals: &[C::Scalar], instance_evals: &[C::Scalar], ) -> impl Iterator + 'a { - let active_rows = C::Scalar::one() - (l_last + l_blind); + let active_rows = C::Scalar::ONE - (l_last + l_blind); let product_expression = || { // z(\omega X) (a'(X) + \beta) (s'(X) + \gamma) @@ -129,7 +129,7 @@ impl Evaluated { &|a, scalar| a * &scalar, ) }) - .fold(C::Scalar::zero(), |acc, eval| acc * &*theta + &eval) + .fold(C::Scalar::ZERO, |acc, eval| acc * &*theta + &eval) }; let right = self.product_eval * &(compress_expressions(&argument.input_expressions) + &*beta) @@ -141,7 +141,7 @@ impl Evaluated { std::iter::empty() .chain( // l_0(X) * (1 - z(X)) = 0 - Some(l_0 * &(C::Scalar::one() - &self.product_eval)), + Some(l_0 * &(C::Scalar::ONE - &self.product_eval)), ) .chain( // l_last(X) * (z(X)^2 - z(X)) = 0 diff --git a/halo2_proofs/src/plonk/permutation/keygen.rs b/halo2_proofs/src/plonk/permutation/keygen.rs index 6c77b5ab..95bcb2a1 100644 --- a/halo2_proofs/src/plonk/permutation/keygen.rs +++ b/halo2_proofs/src/plonk/permutation/keygen.rs @@ -1,9 +1,11 @@ -use ff::Field; -use group::Curve; +use group::{ + ff::{Field, PrimeField}, + Curve, +}; use super::{Argument, ProvingKey, VerifyingKey}; use crate::{ - arithmetic::{CurveAffine, FieldExt}, + arithmetic::CurveAffine, plonk::{Any, Column, Error}, poly::{ commitment::{Blind, Params}, @@ -106,7 +108,7 @@ impl Assembly { // Compute [omega^0, omega^1, ..., omega^{params.n - 1}] let mut omega_powers = Vec::with_capacity(params.n as usize); { - let mut cur = C::Scalar::one(); + let mut cur = C::Scalar::ONE; for _ in 0..params.n { omega_powers.push(cur); cur *= &domain.get_omega(); @@ -116,7 +118,7 @@ impl Assembly { // Compute [omega_powers * \delta^0, omega_powers * \delta^1, ..., omega_powers * \delta^m] let mut deltaomega = Vec::with_capacity(p.columns.len()); { - let mut cur = C::Scalar::one(); + let mut cur = C::Scalar::ONE; for _ in 0..p.columns.len() { let mut omega_powers = omega_powers.clone(); for o in &mut omega_powers { @@ -159,7 +161,7 @@ impl Assembly { // Compute [omega^0, omega^1, ..., omega^{params.n - 1}] let mut omega_powers = Vec::with_capacity(params.n as usize); { - let mut cur = C::Scalar::one(); + let mut cur = C::Scalar::ONE; for _ in 0..params.n { omega_powers.push(cur); cur *= &domain.get_omega(); @@ -169,7 +171,7 @@ impl Assembly { // Compute [omega_powers * \delta^0, omega_powers * \delta^1, ..., omega_powers * \delta^m] let mut deltaomega = Vec::with_capacity(p.columns.len()); { - let mut cur = C::Scalar::one(); + let mut cur = C::Scalar::ONE; for _ in 0..p.columns.len() { let mut omega_powers = omega_powers.clone(); for o in &mut omega_powers { diff --git a/halo2_proofs/src/plonk/permutation/prover.rs b/halo2_proofs/src/plonk/permutation/prover.rs index 2d792d60..7e72378b 100644 --- a/halo2_proofs/src/plonk/permutation/prover.rs +++ b/halo2_proofs/src/plonk/permutation/prover.rs @@ -1,5 +1,5 @@ use group::{ - ff::{BatchInvert, Field}, + ff::{BatchInvert, Field, PrimeField}, Curve, }; use rand_core::RngCore; @@ -8,7 +8,7 @@ use std::iter::{self, ExactSizeIterator}; use super::super::{circuit::Any, ChallengeBeta, ChallengeGamma, ChallengeX}; use super::{Argument, ProvingKey}; use crate::{ - arithmetic::{eval_polynomial, parallelize, CurveAffine, FieldExt}, + arithmetic::{eval_polynomial, parallelize, CurveAffine}, plonk::{self, Error}, poly::{ self, @@ -75,10 +75,10 @@ impl Argument { let blinding_factors = pk.vk.cs.blinding_factors(); // Each column gets its own delta power. - let mut deltaomega = C::Scalar::one(); + let mut deltaomega = C::Scalar::ONE; // Track the "last" value from the previous column set - let mut last_z = C::Scalar::one(); + let mut last_z = C::Scalar::ONE; let mut sets = vec![]; @@ -95,7 +95,7 @@ impl Argument { // where p_j(X) is the jth column in this permutation, // and i is the ith row of the column. - let mut modified_values = vec![C::Scalar::one(); params.n as usize]; + let mut modified_values = vec![C::Scalar::ONE; params.n as usize]; // Iterate over each column of the permutation for (&column, permuted_column_values) in columns.iter().zip(permutations.iter()) { diff --git a/halo2_proofs/src/plonk/permutation/verifier.rs b/halo2_proofs/src/plonk/permutation/verifier.rs index d3e8808c..903efb9e 100644 --- a/halo2_proofs/src/plonk/permutation/verifier.rs +++ b/halo2_proofs/src/plonk/permutation/verifier.rs @@ -1,10 +1,11 @@ -use ff::Field; +use group::ff::{Field, PrimeField}; + use std::iter; use super::super::{circuit::Any, ChallengeBeta, ChallengeGamma, ChallengeX}; use super::{Argument, VerifyingKey}; use crate::{ - arithmetic::{CurveAffine, FieldExt}, + arithmetic::CurveAffine, plonk::{self, Error}, poly::{multiopen::VerifierQuery, Rotation}, transcript::{EncodedChallenge, TranscriptRead}, @@ -120,9 +121,9 @@ impl Evaluated { // Enforce only for the first set. // l_0(X) * (1 - z_0(X)) = 0 .chain( - self.sets.first().map(|first_set| { - l_0 * &(C::Scalar::one() - &first_set.permutation_product_eval) - }), + self.sets + .first() + .map(|first_set| l_0 * &(C::Scalar::ONE - &first_set.permutation_product_eval)), ) // Enforce only for the last set. // l_last(X) * (z_l(X)^2 - z_l(X)) = 0 @@ -195,7 +196,7 @@ impl Evaluated { current_delta *= &C::Scalar::DELTA; } - (left - &right) * (C::Scalar::one() - &(l_last + &l_blind)) + (left - &right) * (C::Scalar::ONE - &(l_last + &l_blind)) }), ) } diff --git a/halo2_proofs/src/plonk/prover.rs b/halo2_proofs/src/plonk/prover.rs index 304244e8..e54f2129 100644 --- a/halo2_proofs/src/plonk/prover.rs +++ b/halo2_proofs/src/plonk/prover.rs @@ -13,7 +13,7 @@ use super::{ ChallengeY, Error, ProvingKey, }; use crate::{ - arithmetic::{eval_polynomial, CurveAffine, FieldExt}, + arithmetic::{eval_polynomial, CurveAffine}, circuit::Value, plonk::Assigned, poly::{ diff --git a/halo2_proofs/src/plonk/vanishing/prover.rs b/halo2_proofs/src/plonk/vanishing/prover.rs index f144bb81..15b90f1c 100644 --- a/halo2_proofs/src/plonk/vanishing/prover.rs +++ b/halo2_proofs/src/plonk/vanishing/prover.rs @@ -139,9 +139,7 @@ impl Constructed { .h_blinds .iter() .rev() - .fold(Blind(C::Scalar::zero()), |acc, eval| { - acc * Blind(xn) + *eval - }); + .fold(Blind(C::Scalar::ZERO), |acc, eval| acc * Blind(xn) + *eval); let random_eval = eval_polynomial(&self.committed.random_poly, *x); transcript.write_scalar(random_eval)?; diff --git a/halo2_proofs/src/plonk/vanishing/verifier.rs b/halo2_proofs/src/plonk/vanishing/verifier.rs index c2e3700d..905b94e1 100644 --- a/halo2_proofs/src/plonk/vanishing/verifier.rs +++ b/halo2_proofs/src/plonk/vanishing/verifier.rs @@ -94,8 +94,8 @@ impl PartiallyEvaluated { y: ChallengeY, xn: C::Scalar, ) -> Evaluated { - let expected_h_eval = expressions.fold(C::Scalar::zero(), |h_eval, v| h_eval * &*y + &v); - let expected_h_eval = expected_h_eval * ((xn - C::Scalar::one()).invert().unwrap()); + let expected_h_eval = expressions.fold(C::Scalar::ZERO, |h_eval, v| h_eval * &*y + &v); + let expected_h_eval = expected_h_eval * ((xn - C::Scalar::ONE).invert().unwrap()); let h_commitment = self.h_commitments @@ -103,7 +103,7 @@ impl PartiallyEvaluated { .rev() .fold(params.empty_msm(), |mut acc, commitment| { acc.scale(xn); - acc.append_term(C::Scalar::one(), *commitment); + acc.append_term(C::Scalar::ONE, *commitment); acc }); diff --git a/halo2_proofs/src/plonk/verifier.rs b/halo2_proofs/src/plonk/verifier.rs index 98916cbb..f141ebaf 100644 --- a/halo2_proofs/src/plonk/verifier.rs +++ b/halo2_proofs/src/plonk/verifier.rs @@ -6,7 +6,7 @@ use super::{ vanishing, ChallengeBeta, ChallengeGamma, ChallengeTheta, ChallengeX, ChallengeY, Error, VerifyingKey, }; -use crate::arithmetic::{CurveAffine, FieldExt}; +use crate::arithmetic::CurveAffine; use crate::poly::{ commitment::{Blind, Guard, Params, MSM}, multiopen::{self, VerifierQuery}, @@ -94,7 +94,7 @@ pub fn verify_proof< return Err(Error::InstanceTooLarge); } let mut poly = instance.to_vec(); - poly.resize(params.n as usize, C::Scalar::zero()); + poly.resize(params.n as usize, C::Scalar::ZERO); let poly = vk.domain.lagrange_from_vec(poly); Ok(params.commit_lagrange(&poly, Blind::default()).to_affine()) @@ -213,7 +213,7 @@ pub fn verify_proof< let l_last = l_evals[0]; let l_blind: C::Scalar = l_evals[1..(1 + blinding_factors)] .iter() - .fold(C::Scalar::zero(), |acc, eval| acc + eval); + .fold(C::Scalar::ZERO, |acc, eval| acc + eval); let l_0 = l_evals[1 + blinding_factors]; // Compute the expected value of h(x) diff --git a/halo2_proofs/src/plonk/verifier/batch.rs b/halo2_proofs/src/plonk/verifier/batch.rs index f579681f..f0d1d57a 100644 --- a/halo2_proofs/src/plonk/verifier/batch.rs +++ b/halo2_proofs/src/plonk/verifier/batch.rs @@ -1,4 +1,4 @@ -use group::ff::Field; +use group::ff::{Field, FromUniformBytes}; use pasta_curves::arithmetic::CurveAffine; use rand_core::OsRng; @@ -61,7 +61,12 @@ impl BatchVerifier { pub fn add_proof(&mut self, instances: Vec>>, proof: Vec) { self.items.push(BatchItem { instances, proof }) } +} +impl BatchVerifier +where + C::Scalar: FromUniformBytes<64>, +{ /// Finalizes the batch and checks its validity. /// /// Returns `false` if *some* proof was invalid. If the caller needs to identify diff --git a/halo2_proofs/src/poly.rs b/halo2_proofs/src/poly.rs index 95170a06..f8f6784f 100644 --- a/halo2_proofs/src/poly.rs +++ b/halo2_proofs/src/poly.rs @@ -157,9 +157,7 @@ pub(crate) fn batch_invert_assigned( assigned .iter() .zip(assigned_denominators.into_iter()) - .map(|(poly, inv_denoms)| { - poly.invert(inv_denoms.into_iter().map(|d| d.unwrap_or_else(F::one))) - }) + .map(|(poly, inv_denoms)| poly.invert(inv_denoms.into_iter().map(|d| d.unwrap_or(F::ONE)))) .collect() } diff --git a/halo2_proofs/src/poly/commitment.rs b/halo2_proofs/src/poly/commitment.rs index 80c8b093..b10a2528 100644 --- a/halo2_proofs/src/poly/commitment.rs +++ b/halo2_proofs/src/poly/commitment.rs @@ -4,13 +4,11 @@ //! [halo]: https://eprint.iacr.org/2019/1021 use super::{Coeff, LagrangeCoeff, Polynomial}; -use crate::arithmetic::{ - best_fft, best_multiexp, parallelize, CurveAffine, CurveExt, FieldExt, Group, -}; +use crate::arithmetic::{best_fft, best_multiexp, parallelize, CurveAffine, CurveExt}; use crate::helpers::CurveRead; use ff::{Field, PrimeField}; -use group::{prime::PrimeCurveAffine, Curve, Group as _}; +use group::{prime::PrimeCurveAffine, Curve, Group}; use std::ops::{Add, AddAssign, Mul, MulAssign}; mod msm; @@ -208,7 +206,7 @@ pub struct Blind(pub F); impl Default for Blind { fn default() -> Self { - Blind(F::one()) + Blind(F::ONE) } } @@ -357,7 +355,7 @@ fn test_opening_proof() { assert_eq!(v, v_prime); let mut commitment_msm = params.empty_msm(); - commitment_msm.append_term(Field::one(), p); + commitment_msm.append_term(Field::ONE, p); let guard = verify_proof(¶ms, commitment_msm, &mut transcript, *x, v).unwrap(); let ch_verifier = transcript.squeeze_challenge(); assert_eq!(*ch_prover, *ch_verifier); diff --git a/halo2_proofs/src/poly/commitment/msm.rs b/halo2_proofs/src/poly/commitment/msm.rs index 8140ab3d..71b50d9d 100644 --- a/halo2_proofs/src/poly/commitment/msm.rs +++ b/halo2_proofs/src/poly/commitment/msm.rs @@ -88,7 +88,7 @@ impl<'a, C: CurveAffine> MSM<'a, C> { if let Some(g_scalars) = self.g_scalars.as_mut() { g_scalars[0] += &constant; } else { - let mut g_scalars = vec![C::Scalar::zero(); self.params.n as usize]; + let mut g_scalars = vec![C::Scalar::ZERO; self.params.n as usize]; g_scalars[0] += &constant; self.g_scalars = Some(g_scalars); } diff --git a/halo2_proofs/src/poly/commitment/prover.rs b/halo2_proofs/src/poly/commitment/prover.rs index b7e27df0..6ded02b7 100644 --- a/halo2_proofs/src/poly/commitment/prover.rs +++ b/halo2_proofs/src/poly/commitment/prover.rs @@ -85,7 +85,7 @@ pub fn create_proof< // `p_prime` and `b` is the evaluation of the polynomial at `x_3`. let mut b = Vec::with_capacity(1 << params.k); { - let mut cur = C::Scalar::one(); + let mut cur = C::Scalar::ONE; for _ in 0..(1 << params.k) { b.push(cur); cur *= &x_3; diff --git a/halo2_proofs/src/poly/commitment/verifier.rs b/halo2_proofs/src/poly/commitment/verifier.rs index 72a28761..07d6c137 100644 --- a/halo2_proofs/src/poly/commitment/verifier.rs +++ b/halo2_proofs/src/poly/commitment/verifier.rs @@ -54,7 +54,7 @@ impl<'a, C: CurveAffine, E: EncodedChallenge> Guard<'a, C, E> { /// Computes G = ⟨s, params.g⟩ pub fn compute_g(&self) -> C { - let s = compute_s(&self.u, C::Scalar::one()); + let s = compute_s(&self.u, C::Scalar::ONE); best_multiexp(&s, &self.msm.params.g).to_affine() } @@ -143,10 +143,10 @@ pub fn verify_proof<'a, C: CurveAffine, E: EncodedChallenge, T: TranscriptRea /// Computes $\prod\limits_{i=0}^{k-1} (1 + u_{k - 1 - i} x^{2^i})$. fn compute_b(x: F, u: &[F]) -> F { - let mut tmp = F::one(); + let mut tmp = F::ONE; let mut cur = x; for u_j in u.iter().rev() { - tmp *= F::one() + &(*u_j * &cur); + tmp *= F::ONE + &(*u_j * &cur); cur *= cur; } tmp @@ -155,7 +155,7 @@ fn compute_b(x: F, u: &[F]) -> F { /// Computes the coefficients of $g(X) = \prod\limits_{i=0}^{k-1} (1 + u_{k - 1 - i} X^{2^i})$. fn compute_s(u: &[F], init: F) -> Vec { assert!(!u.is_empty()); - let mut v = vec![F::zero(); 1 << u.len()]; + let mut v = vec![F::ZERO; 1 << u.len()]; v[0] = init; for (len, u_j) in u.iter().rev().enumerate().map(|(i, u_j)| (1 << i, u_j)) { diff --git a/halo2_proofs/src/poly/domain.rs b/halo2_proofs/src/poly/domain.rs index 9e0398b7..fb76af65 100644 --- a/halo2_proofs/src/poly/domain.rs +++ b/halo2_proofs/src/poly/domain.rs @@ -2,12 +2,13 @@ //! domain that is of a suitable size for the application. use crate::{ - arithmetic::{best_fft, parallelize, FieldExt}, + arithmetic::{best_fft, parallelize}, plonk::Assigned, }; use super::{Coeff, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, Rotation}; +use ff::WithSmallOrderMulGroup; use group::ff::{BatchInvert, Field}; use std::marker::PhantomData; @@ -33,7 +34,7 @@ pub struct EvaluationDomain { barycentric_weight: F, } -impl EvaluationDomain { +impl> EvaluationDomain { /// This constructs a new evaluation domain object based on the provided /// values $j, k$. pub fn new(j: u32, k: u32) -> Self { @@ -51,7 +52,7 @@ impl EvaluationDomain { extended_k += 1; } - let mut extended_omega = F::root_of_unity(); + let mut extended_omega = F::ROOT_OF_UNITY; // Get extended_omega, the 2^{extended_k}'th root of unity // The loop computes extended_omega = omega^{2 ^ (S - extended_k)} @@ -99,7 +100,7 @@ impl EvaluationDomain { // Subtract 1 from each to give us t_evaluations[i] = t(zeta * extended_omega^i) for coeff in &mut t_evaluations { - *coeff -= &F::one(); + *coeff -= &F::ONE; } // Invert, because we're dividing by this polynomial. @@ -168,7 +169,7 @@ impl EvaluationDomain { /// Returns an empty (zero) polynomial in the coefficient basis pub fn empty_coeff(&self) -> Polynomial { Polynomial { - values: vec![F::zero(); self.n as usize], + values: vec![F::ZERO; self.n as usize], _marker: PhantomData, } } @@ -176,7 +177,7 @@ impl EvaluationDomain { /// Returns an empty (zero) polynomial in the Lagrange coefficient basis pub fn empty_lagrange(&self) -> Polynomial { Polynomial { - values: vec![F::zero(); self.n as usize], + values: vec![F::ZERO; self.n as usize], _marker: PhantomData, } } @@ -185,7 +186,7 @@ impl EvaluationDomain { /// deferred inversions. pub(crate) fn empty_lagrange_assigned(&self) -> Polynomial, LagrangeCoeff> { Polynomial { - values: vec![F::zero().into(); self.n as usize], + values: vec![F::ZERO.into(); self.n as usize], _marker: PhantomData, } } @@ -202,7 +203,7 @@ impl EvaluationDomain { /// basis pub fn empty_extended(&self) -> Polynomial { Polynomial { - values: vec![F::zero(); self.extended_len()], + values: vec![F::ZERO; self.extended_len()], _marker: PhantomData, } } @@ -241,7 +242,7 @@ impl EvaluationDomain { assert_eq!(a.values.len(), 1 << self.k); self.distribute_powers_zeta(&mut a.values, true); - a.values.resize(self.extended_len(), F::zero()); + a.values.resize(self.extended_len(), F::ZERO); best_fft(&mut a.values, self.extended_omega, self.extended_k); Polynomial { @@ -452,13 +453,13 @@ impl EvaluationDomain { results = Vec::with_capacity(rotations.size_hint().1.unwrap_or(0)); for rotation in rotations { let rotation = Rotation(rotation); - let result = x - self.rotate_omega(F::one(), rotation); + let result = x - self.rotate_omega(F::ONE, rotation); results.push(result); } results.iter_mut().batch_invert(); } - let common = (xn - F::one()) * self.barycentric_weight; + let common = (xn - F::ONE) * self.barycentric_weight; for (rotation, result) in rotations.into_iter().zip(results.iter_mut()) { let rotation = Rotation(rotation); *result = self.rotate_omega(*result * common, rotation); @@ -549,7 +550,7 @@ fn test_l_i() { } for i in 0..8 { let mut l_i = vec![Scalar::zero(); 8]; - l_i[i] = Scalar::one(); + l_i[i] = Scalar::ONE; let l_i = lagrange_interpolate(&points[..], &l_i[..]); l.push(l_i); } diff --git a/halo2_proofs/src/poly/evaluator.rs b/halo2_proofs/src/poly/evaluator.rs index 04f509d3..53349451 100644 --- a/halo2_proofs/src/poly/evaluator.rs +++ b/halo2_proofs/src/poly/evaluator.rs @@ -6,8 +6,8 @@ use std::{ sync::Arc, }; +use ff::WithSmallOrderMulGroup; use group::ff::Field; -use pasta_curves::arithmetic::FieldExt; use super::{ Basis, Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, Rotation, @@ -133,7 +133,7 @@ impl Evaluator { ) -> Polynomial where E: Copy + Send + Sync, - F: FieldExt, + F: WithSmallOrderMulGroup<3>, B: BasisOps, { // We're working in a single basis, so all polynomials are the same length. @@ -148,7 +148,7 @@ impl Evaluator { polys: &'a [Polynomial], } - fn recurse( + fn recurse, B: BasisOps>( ast: &Ast, ctx: &AstContext<'_, F, B>, ) -> Vec { @@ -184,7 +184,7 @@ impl Evaluator { lhs } Ast::DistributePowers(terms, base) => terms.iter().fold( - B::constant_term(ctx.poly_len, ctx.chunk_size, ctx.chunk_index, F::zero()), + B::constant_term(ctx.poly_len, ctx.chunk_size, ctx.chunk_index, F::ZERO), |mut acc, term| { let term = recurse(term, ctx); for (acc, term) in acc.iter_mut().zip(term) { @@ -299,7 +299,7 @@ impl From> for Ast { impl Ast { pub(crate) fn one() -> Self { - Self::ConstantTerm(F::one()) + Self::ConstantTerm(F::ONE) } } @@ -307,7 +307,7 @@ impl Neg for Ast { type Output = Ast; fn neg(self) -> Self::Output { - Ast::Scale(Arc::new(self), -F::one()) + Ast::Scale(Arc::new(self), -F::ONE) } } @@ -441,21 +441,23 @@ impl MulAssign for Ast { /// Operations which can be performed over a given basis. pub(crate) trait BasisOps: Basis { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial; + fn empty_poly>( + domain: &EvaluationDomain, + ) -> Polynomial; fn constant_term( poly_len: usize, chunk_size: usize, chunk_index: usize, scalar: F, ) -> Vec; - fn linear_term( + fn linear_term>( domain: &EvaluationDomain, poly_len: usize, chunk_size: usize, chunk_index: usize, scalar: F, ) -> Vec; - fn get_chunk_of_rotated( + fn get_chunk_of_rotated>( domain: &EvaluationDomain, chunk_size: usize, chunk_index: usize, @@ -465,7 +467,9 @@ pub(crate) trait BasisOps: Basis { } impl BasisOps for Coeff { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial { + fn empty_poly>( + domain: &EvaluationDomain, + ) -> Polynomial { domain.empty_coeff() } @@ -475,21 +479,21 @@ impl BasisOps for Coeff { chunk_index: usize, scalar: F, ) -> Vec { - let mut chunk = vec![F::zero(); cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]; + let mut chunk = vec![F::ZERO; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]; if chunk_index == 0 { chunk[0] = scalar; } chunk } - fn linear_term( + fn linear_term>( _: &EvaluationDomain, poly_len: usize, chunk_size: usize, chunk_index: usize, scalar: F, ) -> Vec { - let mut chunk = vec![F::zero(); cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]; + let mut chunk = vec![F::ZERO; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]; // If the chunk size is 1 (e.g. if we have a small k and many threads), then the // linear coefficient is the second chunk. Otherwise, the chunk size is greater // than one, and the linear coefficient is the second element of the first chunk. @@ -504,7 +508,7 @@ impl BasisOps for Coeff { chunk } - fn get_chunk_of_rotated( + fn get_chunk_of_rotated>( _: &EvaluationDomain, _: usize, _: usize, @@ -516,7 +520,9 @@ impl BasisOps for Coeff { } impl BasisOps for LagrangeCoeff { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial { + fn empty_poly>( + domain: &EvaluationDomain, + ) -> Polynomial { domain.empty_lagrange() } @@ -529,7 +535,7 @@ impl BasisOps for LagrangeCoeff { vec![scalar; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)] } - fn linear_term( + fn linear_term>( domain: &EvaluationDomain, poly_len: usize, chunk_size: usize, @@ -548,7 +554,7 @@ impl BasisOps for LagrangeCoeff { .collect() } - fn get_chunk_of_rotated( + fn get_chunk_of_rotated>( _: &EvaluationDomain, chunk_size: usize, chunk_index: usize, @@ -560,7 +566,9 @@ impl BasisOps for LagrangeCoeff { } impl BasisOps for ExtendedLagrangeCoeff { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial { + fn empty_poly>( + domain: &EvaluationDomain, + ) -> Polynomial { domain.empty_extended() } @@ -573,7 +581,7 @@ impl BasisOps for ExtendedLagrangeCoeff { vec![scalar; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)] } - fn linear_term( + fn linear_term>( domain: &EvaluationDomain, poly_len: usize, chunk_size: usize, @@ -595,7 +603,7 @@ impl BasisOps for ExtendedLagrangeCoeff { .collect() } - fn get_chunk_of_rotated( + fn get_chunk_of_rotated>( domain: &EvaluationDomain, chunk_size: usize, chunk_index: usize, @@ -608,6 +616,7 @@ impl BasisOps for ExtendedLagrangeCoeff { #[cfg(test)] mod tests { + use group::ff::Field; use pasta_curves::pallas; use super::{get_chunk_params, new_evaluator, Ast, BasisOps, Evaluator}; @@ -643,8 +652,8 @@ mod tests { evaluator.register_poly(B::empty_poly(&domain)); // With the bug present, these will panic. - let _ = evaluator.evaluate(&Ast::ConstantTerm(pallas::Base::zero()), &domain); - let _ = evaluator.evaluate(&Ast::LinearTerm(pallas::Base::zero()), &domain); + let _ = evaluator.evaluate(&Ast::ConstantTerm(pallas::Base::ZERO), &domain); + let _ = evaluator.evaluate(&Ast::LinearTerm(pallas::Base::ZERO), &domain); } test_case(k, new_evaluator::<_, _, Coeff>(|| {})); diff --git a/halo2_proofs/src/poly/multiopen.rs b/halo2_proofs/src/poly/multiopen.rs index 11e10908..ba2c3bca 100644 --- a/halo2_proofs/src/poly/multiopen.rs +++ b/halo2_proofs/src/poly/multiopen.rs @@ -386,10 +386,11 @@ mod tests { #[cfg(test)] mod proptests { + use group::ff::FromUniformBytes; use proptest::{collection::vec, prelude::*, sample::select}; use super::construct_intermediate_sets; - use pasta_curves::{arithmetic::FieldExt, Fp}; + use pasta_curves::Fp; use std::convert::TryFrom; @@ -421,7 +422,7 @@ mod proptests { fn arb_point()( bytes in vec(any::(), 64) ) -> Fp { - Fp::from_bytes_wide(&<[u8; 64]>::try_from(bytes).unwrap()) + Fp::from_uniform_bytes(&<[u8; 64]>::try_from(bytes).unwrap()) } } diff --git a/halo2_proofs/src/poly/multiopen/prover.rs b/halo2_proofs/src/poly/multiopen/prover.rs index 6f4015df..4796a52a 100644 --- a/halo2_proofs/src/poly/multiopen/prover.rs +++ b/halo2_proofs/src/poly/multiopen/prover.rs @@ -41,7 +41,7 @@ where // Collapse openings at same point sets together into single openings using // x_1 challenge. let mut q_polys: Vec>> = vec![None; point_sets.len()]; - let mut q_blinds = vec![Blind(C::Scalar::zero()); point_sets.len()]; + let mut q_blinds = vec![Blind(C::Scalar::ZERO); point_sets.len()]; { let mut accumulate = @@ -73,7 +73,7 @@ where .fold(poly.clone().unwrap().values, |poly, point| { kate_division(&poly, *point) }); - poly.resize(params.n as usize, C::Scalar::zero()); + poly.resize(params.n as usize, C::Scalar::ZERO); let poly = Polynomial { values: poly, _marker: PhantomData, diff --git a/halo2_proofs/src/poly/multiopen/verifier.rs b/halo2_proofs/src/poly/multiopen/verifier.rs index f6b67439..9e9798b6 100644 --- a/halo2_proofs/src/poly/multiopen/verifier.rs +++ b/halo2_proofs/src/poly/multiopen/verifier.rs @@ -40,14 +40,14 @@ where // Compress the commitments and expected evaluations at x together. // using the challenge x_1 let mut q_commitments: Vec<_> = vec![ - (params.empty_msm(), C::Scalar::one()); // (accumulator, next x_1 power). + (params.empty_msm(), C::Scalar::ONE); // (accumulator, next x_1 power). point_sets.len()]; // A vec of vecs of evals. The outer vec corresponds to the point set, // while the inner vec corresponds to the points in a particular set. let mut q_eval_sets = Vec::with_capacity(point_sets.len()); for point_set in point_sets.iter() { - q_eval_sets.push(vec![C::Scalar::zero(); point_set.len()]); + q_eval_sets.push(vec![C::Scalar::ZERO; point_set.len()]); } { @@ -102,7 +102,7 @@ where .zip(q_eval_sets.iter()) .zip(u.iter()) .fold( - C::Scalar::zero(), + C::Scalar::ZERO, |msm_eval, ((points, evals), proof_eval)| { let r_poly = lagrange_interpolate(points, evals); let r_eval = eval_polynomial(&r_poly, *x_3); @@ -118,7 +118,7 @@ where let x_4: ChallengeX4<_> = transcript.squeeze_challenge_scalar(); // Compute the final commitment that has to be opened - msm.append_term(C::Scalar::one(), q_prime_commitment); + msm.append_term(C::Scalar::ONE, q_prime_commitment); let (msm, v) = q_commitments.into_iter().zip(u.iter()).fold( (msm, msm_eval), |(mut msm, msm_eval), ((q_commitment, _), q_eval)| { diff --git a/halo2_proofs/src/transcript.rs b/halo2_proofs/src/transcript.rs index 0570dd59..b6b3d3e7 100644 --- a/halo2_proofs/src/transcript.rs +++ b/halo2_proofs/src/transcript.rs @@ -2,10 +2,10 @@ //! transcripts. use blake2b_simd::{Params as Blake2bParams, State as Blake2bState}; -use group::ff::PrimeField; +use group::ff::{FromUniformBytes, PrimeField}; use std::convert::TryInto; -use crate::arithmetic::{Coordinates, CurveAffine, FieldExt}; +use crate::arithmetic::{Coordinates, CurveAffine}; use std::io::{self, Read, Write}; use std::marker::PhantomData; @@ -85,6 +85,8 @@ impl> Blake2bRead { impl TranscriptRead> for Blake2bRead> +where + C::Scalar: FromUniformBytes<64>, { fn read_point(&mut self) -> io::Result { let mut compressed = C::Repr::default(); @@ -112,8 +114,9 @@ impl TranscriptRead> } } -impl Transcript> - for Blake2bRead> +impl Transcript> for Blake2bRead> +where + C::Scalar: FromUniformBytes<64>, { fn squeeze_challenge(&mut self) -> Challenge255 { self.state.update(&[BLAKE2B_PREFIX_CHALLENGE]); @@ -174,6 +177,8 @@ impl> Blake2bWrite { impl TranscriptWrite> for Blake2bWrite> +where + C::Scalar: FromUniformBytes<64>, { fn write_point(&mut self, point: C) -> io::Result<()> { self.common_point(point)?; @@ -189,6 +194,8 @@ impl TranscriptWrite> impl Transcript> for Blake2bWrite> +where + C::Scalar: FromUniformBytes<64>, { fn squeeze_challenge(&mut self) -> Challenge255 { self.state.update(&[BLAKE2B_PREFIX_CHALLENGE]); @@ -273,12 +280,15 @@ impl std::ops::Deref for Challenge255 { } } -impl EncodedChallenge for Challenge255 { +impl EncodedChallenge for Challenge255 +where + C::Scalar: FromUniformBytes<64>, +{ type Input = [u8; 64]; fn new(challenge_input: &[u8; 64]) -> Self { Challenge255( - C::Scalar::from_bytes_wide(challenge_input) + C::Scalar::from_uniform_bytes(challenge_input) .to_repr() .as_ref() .try_into() diff --git a/halo2_proofs/tests/plonk_api.rs b/halo2_proofs/tests/plonk_api.rs index c70b9067..72d59bb9 100644 --- a/halo2_proofs/tests/plonk_api.rs +++ b/halo2_proofs/tests/plonk_api.rs @@ -2,8 +2,8 @@ #![allow(clippy::op_ref)] use assert_matches::assert_matches; -use group::ff::Field; -use halo2_proofs::arithmetic::{CurveAffine, FieldExt}; +use group::ff::{Field, WithSmallOrderMulGroup}; +use halo2_proofs::arithmetic::CurveAffine; use halo2_proofs::circuit::{Cell, Layouter, SimpleFloorPlanner, Value}; use halo2_proofs::dev::MockProver; use halo2_proofs::pasta::{Eq, EqAffine, Fp}; @@ -138,15 +138,10 @@ fn plonk_api() { || value.unwrap().map(|v| v.2), )?; - region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::zero()))?; - region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::zero()))?; - region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?; - region.assign_fixed( - || "a * b", - self.config.sm, - 0, - || Value::known(FF::one()), - )?; + region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ZERO))?; + region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ZERO))?; + region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "a * b", self.config.sm, 0, || Value::known(FF::ONE))?; Ok((lhs.cell(), rhs.cell(), out.cell())) }, ) @@ -197,14 +192,14 @@ fn plonk_api() { || value.unwrap().map(|v| v.2), )?; - region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::one()))?; - region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::one()))?; + region.assign_fixed(|| "a", self.config.sa, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "b", self.config.sb, 0, || Value::known(FF::ONE))?; + region.assign_fixed(|| "c", self.config.sc, 0, || Value::known(FF::ONE))?; region.assign_fixed( || "a * b", self.config.sm, 0, - || Value::known(FF::zero()), + || Value::known(FF::ZERO), )?; Ok((lhs.cell(), rhs.cell(), out.cell())) }, @@ -236,7 +231,7 @@ fn plonk_api() { || "public", self.config.sp, 0, - || Value::known(FF::one()), + || Value::known(FF::ONE), )?; Ok(value.cell()) @@ -374,7 +369,7 @@ fn plonk_api() { ) -> Result<(), Error> { let cs = StandardPlonk::new(config); - let _ = cs.public_input(&mut layouter, || Value::known(F::one() + F::one()))?; + let _ = cs.public_input(&mut layouter, || Value::known(F::ONE + F::ONE))?; for _ in 0..10 { let a: Value> = self.a.into(); @@ -400,8 +395,8 @@ fn plonk_api() { } let a = Fp::from(2834758237) * Fp::ZETA; - let instance = Fp::one() + Fp::one(); - let lookup_table = vec![instance, a, a, Fp::zero()]; + let instance = Fp::ONE + Fp::ONE; + let lookup_table = vec![instance, a, a, Fp::ZERO]; let empty_circuit: MyCircuit = MyCircuit { a: Value::unknown(),