From e5d5e4a6ccff2bba71baf77ab7a12b124d6364a1 Mon Sep 17 00:00:00 2001 From: Han Date: Wed, 26 Apr 2023 21:52:42 +0800 Subject: [PATCH] Upgrade `halo2curves` and `halo2_proofs` (#35) * feat: upgrade `halo2curves` to `0.3.2` and `halo2_proofs` to `v2023_04_20` * feat: support `circuit-params` feature flag --- snark-verifier/Cargo.toml | 15 ++++++--- .../examples/evm-verifier-with-accumulator.rs | 14 +++++--- snark-verifier/examples/evm-verifier.rs | 11 +++++-- snark-verifier/src/loader.rs | 24 +++++++------- snark-verifier/src/loader/evm/loader.rs | 12 +++---- snark-verifier/src/loader/evm/util.rs | 2 +- snark-verifier/src/loader/halo2/loader.rs | 18 +++++------ snark-verifier/src/loader/halo2/shim.rs | 32 +++++++++---------- snark-verifier/src/pcs/ipa.rs | 2 +- snark-verifier/src/pcs/ipa/accumulation.rs | 4 +-- snark-verifier/src/pcs/ipa/decider.rs | 2 +- snark-verifier/src/pcs/ipa/multiopen/bgh19.rs | 12 +++---- snark-verifier/src/pcs/kzg/accumulation.rs | 4 ++- snark-verifier/src/pcs/kzg/decider.rs | 3 +- .../src/pcs/kzg/multiopen/bdfg21.rs | 14 ++++---- snark-verifier/src/pcs/kzg/multiopen/gwc19.rs | 2 ++ snark-verifier/src/system/halo2.rs | 24 ++++++++------ snark-verifier/src/system/halo2/test.rs | 3 +- .../src/system/halo2/test/circuit/maingate.rs | 18 ++++++----- .../src/system/halo2/test/circuit/standard.rs | 14 ++++---- snark-verifier/src/system/halo2/test/kzg.rs | 8 +++-- .../src/system/halo2/test/kzg/halo2.rs | 2 ++ snark-verifier/src/system/halo2/transcript.rs | 27 ++++++++++++---- .../src/system/halo2/transcript/halo2.rs | 17 +++++++++- snark-verifier/src/util/arithmetic.rs | 21 ++++++------ snark-verifier/src/util/hash/poseidon.rs | 21 +++++++----- snark-verifier/src/util/poly.rs | 12 +++---- snark-verifier/src/verifier/plonk/proof.rs | 2 +- snark-verifier/src/verifier/plonk/protocol.rs | 4 +-- 29 files changed, 206 insertions(+), 138 deletions(-) diff --git a/snark-verifier/Cargo.toml b/snark-verifier/Cargo.toml index 5ce80f0d..46d4b419 100644 --- a/snark-verifier/Cargo.toml +++ b/snark-verifier/Cargo.toml @@ -11,13 +11,13 @@ num-integer = "0.1.45" num-traits = "0.2.15" rand = "0.8" hex = "0.4" -halo2_curves = { git = "https://github.com/privacy-scaling-explorations/halo2curves", tag = "0.3.1", package = "halo2curves" } +halo2_curves = { git = "https://github.com/privacy-scaling-explorations/halo2curves", tag = "0.3.2", package = "halo2curves" } # parallel rayon = { version = "1.5.3", optional = true } # system_halo2 -halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2", tag = "v2023_02_02", optional = true } +halo2_proofs = { git = "https://github.com/privacy-scaling-explorations/halo2", tag = "v2023_04_20", optional = true } # loader_evm sha3 = { version = "0.10", optional = true } @@ -27,15 +27,15 @@ rlp = { version = "0.5.2", default-features = false, features = ["std"], optiona revm = { version = "= 2.3.1", optional = true } # loader_halo2 -halo2_wrong_ecc = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2023_02_02", package = "ecc", optional = true } -poseidon = { git = "https://github.com/privacy-scaling-explorations/poseidon", tag = "v2022_10_22", optional = true } +halo2_wrong_ecc = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2023_04_20", package = "ecc", optional = true } +poseidon = { git = "https://github.com/privacy-scaling-explorations/poseidon", tag = "v2023_04_20", optional = true } [dev-dependencies] rand_chacha = "0.3.1" paste = "1.0.7" # system_halo2 -halo2_wrong_ecc = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2023_02_02", package = "ecc" } +halo2_wrong_ecc = { git = "https://github.com/privacy-scaling-explorations/halo2wrong", tag = "v2023_04_20", package = "ecc" } # loader_evm crossterm = { version = "0.25" } @@ -46,11 +46,16 @@ default = ["loader_evm", "loader_halo2", "system_halo2"] parallel = ["dep:rayon"] +# loaders loader_evm = ["dep:bytes", "dep:sha3", "dep:primitive-types", "dep:rlp", "dep:revm"] loader_halo2 = ["dep:halo2_proofs", "dep:halo2_wrong_ecc", "dep:poseidon"] +# systems system_halo2 = ["dep:halo2_proofs"] +# features of halo2 +halo2_circuit_params = ["halo2_proofs?/circuit-params", "halo2_wrong_ecc?/circuit-params"] + [[example]] name = "evm-verifier" required-features = ["loader_evm", "system_halo2"] diff --git a/snark-verifier/examples/evm-verifier-with-accumulator.rs b/snark-verifier/examples/evm-verifier-with-accumulator.rs index ba23e352..369600e3 100644 --- a/snark-verifier/examples/evm-verifier-with-accumulator.rs +++ b/snark-verifier/examples/evm-verifier-with-accumulator.rs @@ -34,7 +34,7 @@ type PlonkSuccinctVerifier = verifier::plonk::PlonkSuccinctVerifier>; mod application { - use halo2_curves::bn256::Fr; + use halo2_curves::{bn256::Fr, ff::Field}; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, Instance}, @@ -117,6 +117,8 @@ mod application { impl Circuit for StandardPlonk { type Config = StandardPlonkConfig; type FloorPlanner = SimpleFloorPlanner; + #[cfg(feature = "halo2_circuit_params")] + type Params = (); fn without_witnesses(&self) -> Self { Self::default() @@ -136,7 +138,7 @@ mod application { || "", |mut region| { region.assign_advice(|| "", config.a, 0, || Value::known(self.0))?; - region.assign_fixed(|| "", config.q_a, 0, || Value::known(-Fr::one()))?; + region.assign_fixed(|| "", config.q_a, 0, || Value::known(-Fr::ONE))?; region.assign_advice(|| "", config.a, 1, || Value::known(-Fr::from(5)))?; for (idx, column) in (1..).zip([ @@ -149,7 +151,7 @@ mod application { region.assign_fixed(|| "", column, 1, || Value::known(Fr::from(idx)))?; } - let a = region.assign_advice(|| "", config.a, 2, || Value::known(Fr::one()))?; + let a = region.assign_advice(|| "", config.a, 2, || Value::known(Fr::ONE))?; a.copy_advice(|| "", &mut region, config.b, 3)?; a.copy_advice(|| "", &mut region, config.c, 4)?; @@ -185,7 +187,7 @@ mod aggregation { AccumulationScheme, AccumulationSchemeProver, }, system, - util::arithmetic::{fe_to_limbs, FieldExt}, + util::arithmetic::{fe_to_limbs, PrimeField}, verifier::{plonk::PlonkProtocol, SnarkVerifier}, }; use std::rc::Rc; @@ -309,7 +311,7 @@ mod aggregation { } impl AggregationConfig { - pub fn configure( + pub fn configure( meta: &mut ConstraintSystem, composition_bits: Vec, overflow_bits: Vec, @@ -410,6 +412,8 @@ mod aggregation { impl Circuit for AggregationCircuit { type Config = AggregationConfig; type FloorPlanner = SimpleFloorPlanner; + #[cfg(feature = "halo2_circuit_params")] + type Params = (); fn without_witnesses(&self) -> Self { Self { diff --git a/snark-verifier/examples/evm-verifier.rs b/snark-verifier/examples/evm-verifier.rs index 58b08074..6e58d330 100644 --- a/snark-verifier/examples/evm-verifier.rs +++ b/snark-verifier/examples/evm-verifier.rs @@ -1,4 +1,7 @@ -use halo2_curves::bn256::{Bn256, Fq, Fr, G1Affine}; +use halo2_curves::{ + bn256::{Bn256, Fq, Fr, G1Affine}, + ff::Field, +}; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, dev::MockProver, @@ -103,6 +106,8 @@ impl StandardPlonk { impl Circuit for StandardPlonk { type Config = StandardPlonkConfig; type FloorPlanner = SimpleFloorPlanner; + #[cfg(feature = "halo2_circuit_params")] + type Params = (); fn without_witnesses(&self) -> Self { Self::default() @@ -122,7 +127,7 @@ impl Circuit for StandardPlonk { || "", |mut region| { region.assign_advice(|| "", config.a, 0, || Value::known(self.0))?; - region.assign_fixed(|| "", config.q_a, 0, || Value::known(-Fr::one()))?; + region.assign_fixed(|| "", config.q_a, 0, || Value::known(-Fr::ONE))?; region.assign_advice(|| "", config.a, 1, || Value::known(-Fr::from(5)))?; for (idx, column) in (1..).zip([ @@ -135,7 +140,7 @@ impl Circuit for StandardPlonk { region.assign_fixed(|| "", column, 1, || Value::known(Fr::from(idx)))?; } - let a = region.assign_advice(|| "", config.a, 2, || Value::known(Fr::one()))?; + let a = region.assign_advice(|| "", config.a, 2, || Value::known(Fr::ONE))?; a.copy_advice(|| "", &mut region, config.b, 3)?; a.copy_advice(|| "", &mut region, config.c, 4)?; diff --git a/snark-verifier/src/loader.rs b/snark-verifier/src/loader.rs index 897890b1..1481fd64 100644 --- a/snark-verifier/src/loader.rs +++ b/snark-verifier/src/loader.rs @@ -122,12 +122,12 @@ pub trait ScalarLoader { /// Load `zero` as constant. fn load_zero(&self) -> Self::LoadedScalar { - self.load_const(&F::zero()) + self.load_const(&F::ZERO) } /// Load `one` as constant. fn load_one(&self) -> Self::LoadedScalar { - self.load_const(&F::one()) + self.load_const(&F::ONE) } /// Assert lhs and rhs field elements are equal. @@ -150,13 +150,13 @@ pub trait ScalarLoader { let loader = values.first().unwrap().1.loader(); iter::empty() - .chain(if constant == F::zero() { + .chain(if constant == F::ZERO { None } else { Some(Cow::Owned(loader.load_const(&constant))) }) .chain(values.iter().map(|&(coeff, value)| { - if coeff == F::one() { + if coeff == F::ONE { Cow::Borrowed(value) } else { Cow::Owned(loader.load_const(&coeff) * value) @@ -179,13 +179,13 @@ pub trait ScalarLoader { let loader = values.first().unwrap().1.loader(); iter::empty() - .chain(if constant == F::zero() { + .chain(if constant == F::ZERO { None } else { Some(loader.load_const(&constant)) }) .chain(values.iter().map(|&(coeff, lhs, rhs)| { - if coeff == F::one() { + if coeff == F::ONE { lhs.clone() * rhs } else { loader.load_const(&coeff) * lhs * rhs @@ -197,20 +197,20 @@ pub trait ScalarLoader { /// Sum field elements with coefficients. fn sum_with_coeff(&self, values: &[(F, &Self::LoadedScalar)]) -> Self::LoadedScalar { - self.sum_with_coeff_and_const(values, F::zero()) + self.sum_with_coeff_and_const(values, F::ZERO) } /// Sum field elements and constant. fn sum_with_const(&self, values: &[&Self::LoadedScalar], constant: F) -> Self::LoadedScalar { self.sum_with_coeff_and_const( - &values.iter().map(|&value| (F::one(), value)).collect_vec(), + &values.iter().map(|&value| (F::ONE, value)).collect_vec(), constant, ) } /// Sum field elements. fn sum(&self, values: &[&Self::LoadedScalar]) -> Self::LoadedScalar { - self.sum_with_const(values, F::zero()) + self.sum_with_const(values, F::ZERO) } /// Sum product of field elements with coefficients. @@ -218,7 +218,7 @@ pub trait ScalarLoader { &self, values: &[(F, &Self::LoadedScalar, &Self::LoadedScalar)], ) -> Self::LoadedScalar { - self.sum_products_with_coeff_and_const(values, F::zero()) + self.sum_products_with_coeff_and_const(values, F::ZERO) } /// Sum product of field elements and constant. @@ -230,7 +230,7 @@ pub trait ScalarLoader { self.sum_products_with_coeff_and_const( &values .iter() - .map(|&(lhs, rhs)| (F::one(), lhs, rhs)) + .map(|&(lhs, rhs)| (F::ONE, lhs, rhs)) .collect_vec(), constant, ) @@ -241,7 +241,7 @@ pub trait ScalarLoader { &self, values: &[(&Self::LoadedScalar, &Self::LoadedScalar)], ) -> Self::LoadedScalar { - self.sum_products_with_const(values, F::zero()) + self.sum_products_with_const(values, F::ZERO) } /// Product of field elements. diff --git a/snark-verifier/src/loader/evm/loader.rs b/snark-verifier/src/loader/evm/loader.rs index 911625b6..6a756ced 100644 --- a/snark-verifier/src/loader/evm/loader.rs +++ b/snark-verifier/src/loader/evm/loader.rs @@ -721,8 +721,8 @@ impl> ScalarLoader for Rc { } let push_addend = |(coeff, value): &(F, &Scalar)| { - assert_ne!(*coeff, F::zero()); - match (*coeff == F::one(), &value.value) { + assert_ne!(*coeff, F::ZERO); + match (*coeff == F::ONE, &value.value) { (true, _) => self.push(value), (false, Value::Constant(value)) => self.push(&self.scalar(Value::Constant( fe_to_u256(*coeff * u256_to_fe::(*value)), @@ -736,7 +736,7 @@ impl> ScalarLoader for Rc { }; let mut values = values.iter(); - let initial_value = if constant == F::zero() { + let initial_value = if constant == F::ZERO { push_addend(values.next().unwrap()) } else { self.push(&self.scalar(Value::Constant(fe_to_u256(constant)))) @@ -770,8 +770,8 @@ impl> ScalarLoader for Rc { } let push_addend = |(coeff, lhs, rhs): &(F, &Scalar, &Scalar)| { - assert_ne!(*coeff, F::zero()); - match (*coeff == F::one(), &lhs.value, &rhs.value) { + assert_ne!(*coeff, F::ZERO); + match (*coeff == F::ONE, &lhs.value, &rhs.value) { (_, Value::Constant(lhs), Value::Constant(rhs)) => { self.push(&self.scalar(Value::Constant(fe_to_u256( *coeff * u256_to_fe::(*lhs) * u256_to_fe::(*rhs), @@ -800,7 +800,7 @@ impl> ScalarLoader for Rc { }; let mut values = values.iter(); - let initial_value = if constant == F::zero() { + let initial_value = if constant == F::ZERO { push_addend(values.next().unwrap()) } else { self.push(&self.scalar(Value::Constant(fe_to_u256(constant)))) diff --git a/snark-verifier/src/loader/evm/util.rs b/snark-verifier/src/loader/evm/util.rs index 62792ee8..689518da 100644 --- a/snark-verifier/src/loader/evm/util.rs +++ b/snark-verifier/src/loader/evm/util.rs @@ -74,7 +74,7 @@ pub fn modulus() -> U256 where F: PrimeField, { - U256::from_little_endian((-F::one()).to_repr().as_ref()) + 1 + U256::from_little_endian((-F::ONE).to_repr().as_ref()) + 1 } /// Encode instances and proof into calldata. diff --git a/snark-verifier/src/loader/halo2/loader.rs b/snark-verifier/src/loader/halo2/loader.rs index 17a51183..fb27ee49 100644 --- a/snark-verifier/src/loader/halo2/loader.rs +++ b/snark-verifier/src/loader/halo2/loader.rs @@ -159,7 +159,7 @@ impl<'a, C: CurveAffine, EccChip: EccInstructions<'a, C>> Halo2Loader<'a, C, Ecc .scalar_chip() .sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), assigned)], + &[(C::Scalar::ONE, assigned)], *constant, ) .map(Value::Assigned) @@ -168,8 +168,8 @@ impl<'a, C: CurveAffine, EccChip: EccInstructions<'a, C>> Halo2Loader<'a, C, Ecc .scalar_chip() .sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), lhs), (C::Scalar::one(), rhs)], - C::Scalar::zero(), + &[(C::Scalar::ONE, lhs), (C::Scalar::ONE, rhs)], + C::Scalar::ZERO, ) .map(Value::Assigned) .unwrap(), @@ -188,7 +188,7 @@ impl<'a, C: CurveAffine, EccChip: EccInstructions<'a, C>> Halo2Loader<'a, C, Ecc .scalar_chip() .sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(-C::Scalar::one(), assigned)], + &[(-C::Scalar::ONE, assigned)], *constant, ) .map(Value::Assigned) @@ -197,7 +197,7 @@ impl<'a, C: CurveAffine, EccChip: EccInstructions<'a, C>> Halo2Loader<'a, C, Ecc .scalar_chip() .sum_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), assigned)], + &[(C::Scalar::ONE, assigned)], -*constant, ) .map(Value::Assigned) @@ -224,7 +224,7 @@ impl<'a, C: CurveAffine, EccChip: EccInstructions<'a, C>> Halo2Loader<'a, C, Ecc .sum_with_coeff_and_const( &mut self.ctx_mut(), &[(*constant, assigned)], - C::Scalar::zero(), + C::Scalar::ZERO, ) .map(Value::Assigned) .unwrap(), @@ -232,8 +232,8 @@ impl<'a, C: CurveAffine, EccChip: EccInstructions<'a, C>> Halo2Loader<'a, C, Ecc .scalar_chip() .sum_products_with_coeff_and_const( &mut self.ctx_mut(), - &[(C::Scalar::one(), lhs, rhs)], - C::Scalar::zero(), + &[(C::Scalar::ONE, lhs, rhs)], + C::Scalar::ZERO, ) .map(Value::Assigned) .unwrap(), @@ -651,7 +651,7 @@ impl<'a, C: CurveAffine, EccChip: EccInstructions<'a, C>> EcPointLoader fixed_base.push((scalar, *base)) } (Value::Constant(scalar), Value::Assigned(_)) - if scalar.eq(&C::Scalar::one()) => + if scalar.eq(&C::Scalar::ONE) => { variable_base_non_scaled.push(base); } diff --git a/snark-verifier/src/loader/halo2/shim.rs b/snark-verifier/src/loader/halo2/shim.rs index 7ae65496..7a41f30a 100644 --- a/snark-verifier/src/loader/halo2/shim.rs +++ b/snark-verifier/src/loader/halo2/shim.rs @@ -1,4 +1,4 @@ -use crate::util::arithmetic::{CurveAffine, FieldExt}; +use crate::util::arithmetic::{CurveAffine, PrimeField}; use halo2_proofs::{ circuit::{Cell, Value}, plonk::Error, @@ -15,7 +15,7 @@ pub trait Context: Debug { } /// Instructions to handle field element operations. -pub trait IntegerInstructions<'a, F: FieldExt>: Clone + Debug { +pub trait IntegerInstructions<'a, F: PrimeField>: Clone + Debug { /// Context. type Context: Context; /// Assigned cell. @@ -41,8 +41,8 @@ pub trait IntegerInstructions<'a, F: FieldExt>: Clone + Debug { fn sum_with_coeff_and_const( &self, ctx: &mut Self::Context, - values: &[(F::Scalar, impl Deref)], - constant: F::Scalar, + values: &[(F, impl Deref)], + constant: F, ) -> Result; /// Sum product of integers with coefficients and constant. @@ -50,11 +50,11 @@ pub trait IntegerInstructions<'a, F: FieldExt>: Clone + Debug { &self, ctx: &mut Self::Context, values: &[( - F::Scalar, + F, impl Deref, impl Deref, )], - constant: F::Scalar, + constant: F, ) -> Result; /// Returns `lhs - rhs`. @@ -162,7 +162,7 @@ mod halo2_wrong { use crate::{ loader::halo2::{Context, EccInstructions, IntegerInstructions}, util::{ - arithmetic::{CurveAffine, FieldExt, Group}, + arithmetic::{CurveAffine, Group, PrimeField}, Itertools, }, }; @@ -181,7 +181,7 @@ mod halo2_wrong { use rand::rngs::OsRng; use std::{iter, ops::Deref}; - impl<'a, F: FieldExt> Context for RegionCtx<'a, F> { + impl<'a, F: PrimeField> Context for RegionCtx<'a, F> { fn constrain_equal(&mut self, lhs: Cell, rhs: Cell) -> Result<(), Error> { self.constrain_equal(lhs, rhs) } @@ -191,7 +191,7 @@ mod halo2_wrong { } } - impl<'a, F: FieldExt> IntegerInstructions<'a, F> for MainGate { + impl<'a, F: PrimeField> IntegerInstructions<'a, F> for MainGate { type Context = RegionCtx<'a, F>; type AssignedCell = AssignedCell; type AssignedInteger = AssignedCell; @@ -268,7 +268,7 @@ mod halo2_wrong { ctx, [Term::assigned_to_mul(lhs), Term::assigned_to_mul(rhs)], constant, - CombinationOptionCommon::CombineToNextScaleMul(-F::one(), *scalar).into(), + CombinationOptionCommon::CombineToNextScaleMul(-F::ONE, *scalar).into(), )?; let acc = Value::known(*scalar) * lhs.value() * rhs.value() + Value::known(constant); @@ -283,11 +283,11 @@ mod halo2_wrong { Term::assigned_to_mul(rhs), Term::Zero, Term::Zero, - Term::Unassigned(acc, F::one()), + Term::Unassigned(acc, F::ONE), ], - F::zero(), + F::ZERO, CombinationOptionCommon::CombineToNextScaleMul( - -F::one(), + -F::ONE, *scalar, ) .into(), @@ -303,9 +303,9 @@ mod halo2_wrong { Term::Zero, Term::Zero, Term::Zero, - Term::Unassigned(output, F::zero()), + Term::Unassigned(output, F::ZERO), ], - F::zero(), + F::ZERO, CombinationOptionCommon::OneLinerAdd.into(), ) .map(|mut outputs| outputs.swap_remove(4)) @@ -327,7 +327,7 @@ mod halo2_wrong { ctx: &mut Self::Context, value: &Self::AssignedInteger, ) -> Result { - MainGateInstructions::neg_with_constant(self, ctx, value, F::zero()) + MainGateInstructions::neg_with_constant(self, ctx, value, F::ZERO) } fn invert( diff --git a/snark-verifier/src/pcs/ipa.rs b/snark-verifier/src/pcs/ipa.rs index c782c65f..191d9410 100644 --- a/snark-verifier/src/pcs/ipa.rs +++ b/snark-verifier/src/pcs/ipa.rs @@ -401,7 +401,7 @@ fn h_eval>(xi: &[T], z: &T) -> T { fn h_coeffs(xi: &[F], scalar: F) -> Vec { assert!(!xi.is_empty()); - let mut coeffs = vec![F::zero(); 1 << xi.len()]; + let mut coeffs = vec![F::ZERO; 1 << xi.len()]; coeffs[0] = scalar; for (len, xi) in xi.iter().rev().enumerate().map(|(i, xi)| (1 << i, xi)) { diff --git a/snark-verifier/src/pcs/ipa/accumulation.rs b/snark-verifier/src/pcs/ipa/accumulation.rs index 7da4197a..feaeaae9 100644 --- a/snark-verifier/src/pcs/ipa/accumulation.rs +++ b/snark-verifier/src/pcs/ipa/accumulation.rs @@ -197,13 +197,13 @@ where let (u, h) = instances .iter() - .map(|IpaAccumulator { u, xi }| (*u, h_coeffs(xi, C::Scalar::one()))) + .map(|IpaAccumulator { u, xi }| (*u, h_coeffs(xi, C::Scalar::ONE))) .chain(a_b_u.map(|(a, b, u)| { ( u, iter::empty() .chain([b, a]) - .chain(iter::repeat_with(C::Scalar::zero).take(pk.domain.n - 2)) + .chain(iter::repeat(C::Scalar::ZERO).take(pk.domain.n - 2)) .collect(), ) })) diff --git a/snark-verifier/src/pcs/ipa/decider.rs b/snark-verifier/src/pcs/ipa/decider.rs index 933480f3..7ea6cfd0 100644 --- a/snark-verifier/src/pcs/ipa/decider.rs +++ b/snark-verifier/src/pcs/ipa/decider.rs @@ -48,7 +48,7 @@ mod native { dk: &Self::DecidingKey, IpaAccumulator { u, xi }: IpaAccumulator, ) -> Result<(), Error> { - let h = h_coeffs(&xi, C::Scalar::one()); + let h = h_coeffs(&xi, C::Scalar::ONE); (u == multi_scalar_multiplication(&h, &dk.g).to_affine()) .then_some(()) .ok_or_else(|| Error::AssertionFailure("U == commit(G, h)".to_string())) diff --git a/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs b/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs index a852267a..ee423d19 100644 --- a/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs +++ b/snark-verifier/src/pcs/ipa/multiopen/bgh19.rs @@ -5,7 +5,7 @@ use crate::{ PolynomialCommitmentScheme, Query, }, util::{ - arithmetic::{CurveAffine, FieldExt, Fraction}, + arithmetic::{CurveAffine, Fraction, PrimeField}, msm::Msm, transcript::TranscriptRead, Itertools, @@ -160,7 +160,7 @@ where fn query_sets(queries: &[Query]) -> Vec> where - F: FieldExt, + F: PrimeField + Ord, T: Clone, { let poly_shifts = queries.iter().fold( @@ -216,7 +216,7 @@ where fn query_set_coeffs(sets: &[QuerySet], x: &T, x_3: &T) -> Vec> where - F: FieldExt, + F: PrimeField + Ord, T: LoadedScalar, { let loader = x.loader(); @@ -258,7 +258,7 @@ struct QuerySet<'a, F, T> { impl<'a, F, T> QuerySet<'a, F, T> where - F: FieldExt, + F: PrimeField, T: LoadedScalar, { fn msm>( @@ -310,7 +310,7 @@ struct QuerySetCoeff { impl QuerySetCoeff where - F: FieldExt, + F: PrimeField + Ord, T: LoadedScalar, { fn new(shifts: &[F], powers_of_x: &[T], x_3: &T, x_3_minus_x_shift_i: &BTreeMap) -> Self { @@ -325,7 +325,7 @@ where .filter(|&(i, _)| i != j) .map(|(_, shift_i)| (*shift_j - shift_i)) .reduce(|acc, value| acc * value) - .unwrap_or_else(|| F::one()) + .unwrap_or(F::ONE) }) .collect_vec(); diff --git a/snark-verifier/src/pcs/kzg/accumulation.rs b/snark-verifier/src/pcs/kzg/accumulation.rs index 1f901568..5139d49e 100644 --- a/snark-verifier/src/pcs/kzg/accumulation.rs +++ b/snark-verifier/src/pcs/kzg/accumulation.rs @@ -2,7 +2,7 @@ use crate::{ loader::{native::NativeLoader, LoadedScalar, Loader}, pcs::{kzg::KzgAccumulator, AccumulationScheme, AccumulationSchemeProver}, util::{ - arithmetic::{Curve, CurveAffine, Field, MultiMillerLoop}, + arithmetic::{Curve, CurveAffine, Field, MultiMillerLoop, PrimeField}, msm::Msm, transcript::{TranscriptRead, TranscriptWrite}, }, @@ -19,6 +19,7 @@ pub struct KzgAs(PhantomData<(M, MOS)>); impl AccumulationScheme for KzgAs where M: MultiMillerLoop, + M::Scalar: PrimeField, L: Loader, MOS: Clone + Debug, { @@ -139,6 +140,7 @@ where impl AccumulationSchemeProver for KzgAs where M: MultiMillerLoop, + M::Scalar: PrimeField, MOS: Clone + Debug, { type ProvingKey = KzgAsProvingKey; diff --git a/snark-verifier/src/pcs/kzg/decider.rs b/snark-verifier/src/pcs/kzg/decider.rs index 417a39dc..7258d771 100644 --- a/snark-verifier/src/pcs/kzg/decider.rs +++ b/snark-verifier/src/pcs/kzg/decider.rs @@ -48,7 +48,7 @@ mod native { AccumulationDecider, }, util::{ - arithmetic::{Group, MillerLoopResult, MultiMillerLoop}, + arithmetic::{Group, MillerLoopResult, MultiMillerLoop, PrimeField}, Itertools, }, Error, @@ -58,6 +58,7 @@ mod native { impl AccumulationDecider for KzgAs where M: MultiMillerLoop, + M::Scalar: PrimeField, MOS: Clone + Debug, { type DecidingKey = KzgDecidingKey; diff --git a/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs b/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs index 3a448056..3f1934e3 100644 --- a/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs +++ b/snark-verifier/src/pcs/kzg/multiopen/bdfg21.rs @@ -6,7 +6,7 @@ use crate::{ PolynomialCommitmentScheme, Query, }, util::{ - arithmetic::{CurveAffine, FieldExt, Fraction, MultiMillerLoop}, + arithmetic::{CurveAffine, Fraction, MultiMillerLoop, PrimeField}, msm::Msm, transcript::TranscriptRead, Itertools, @@ -27,6 +27,7 @@ pub struct Bdfg21; impl PolynomialCommitmentScheme for KzgAs where M: MultiMillerLoop, + M::Scalar: PrimeField + Ord, L: Loader, { type VerifyingKey = KzgSuccinctVerifyingKey; @@ -114,7 +115,7 @@ where } } -fn query_sets(queries: &[Query]) -> Vec> { +fn query_sets(queries: &[Query]) -> Vec> { let poly_shifts = queries.iter().fold( Vec::<(usize, Vec, Vec<&T>)>::new(), |mut poly_shifts, query| { @@ -166,7 +167,7 @@ fn query_sets(queries: &[Query]) -> Vec>( +fn query_set_coeffs<'a, F: PrimeField + Ord, T: LoadedScalar>( sets: &[QuerySet<'a, F, T>], z: &T, z_prime: &T, @@ -225,7 +226,7 @@ struct QuerySet<'a, F, T> { evals: Vec>, } -impl<'a, F: FieldExt, T: LoadedScalar> QuerySet<'a, F, T> { +impl<'a, F: PrimeField, T: LoadedScalar> QuerySet<'a, F, T> { fn msm>( &self, coeff: &QuerySetCoeff, @@ -270,7 +271,7 @@ struct QuerySetCoeff { impl QuerySetCoeff where - F: FieldExt, + F: PrimeField + Ord, T: LoadedScalar, { fn new( @@ -292,7 +293,7 @@ where .filter(|&(i, _)| i != j) .map(|(_, shift_i)| (*shift_j - shift_i)) .reduce(|acc, value| acc * value) - .unwrap_or_else(|| F::one()) + .unwrap_or(F::ONE) }) .collect_vec(); @@ -369,6 +370,7 @@ where impl CostEstimation for KzgAs where M: MultiMillerLoop, + M::Scalar: PrimeField, { type Input = Vec>; diff --git a/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs b/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs index e5741163..b664d536 100644 --- a/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs +++ b/snark-verifier/src/pcs/kzg/multiopen/gwc19.rs @@ -23,6 +23,7 @@ pub struct Gwc19; impl PolynomialCommitmentScheme for KzgAs where M: MultiMillerLoop, + M::Scalar: PrimeField, L: Loader, { type VerifyingKey = KzgSuccinctVerifyingKey; @@ -160,6 +161,7 @@ where impl CostEstimation for KzgAs where M: MultiMillerLoop, + M::Scalar: PrimeField, { type Input = Vec>; diff --git a/snark-verifier/src/system/halo2.rs b/snark-verifier/src/system/halo2.rs index c3f0e7ef..90c72a49 100644 --- a/snark-verifier/src/system/halo2.rs +++ b/snark-verifier/src/system/halo2.rs @@ -2,7 +2,7 @@ use crate::{ util::{ - arithmetic::{root_of_unity, CurveAffine, Domain, FieldExt, Rotation}, + arithmetic::{root_of_unity, CurveAffine, Domain, FromUniformBytes, PrimeField, Rotation}, Itertools, }, verifier::plonk::protocol::{ @@ -96,7 +96,10 @@ pub fn compile<'a, C: CurveAffine, P: Params<'a, C>>( params: &P, vk: &VerifyingKey, config: Config, -) -> PlonkProtocol { +) -> PlonkProtocol +where + C::Scalar: FromUniformBytes<64>, +{ assert_eq!(vk.get_domain().k(), params.k()); let cs = vk.cs(); @@ -184,7 +187,7 @@ impl From for Rotation { } } -struct Polynomials<'a, F: FieldExt> { +struct Polynomials<'a, F: PrimeField> { cs: &'a ConstraintSystem, zk: bool, query_instance: bool, @@ -203,7 +206,7 @@ struct Polynomials<'a, F: FieldExt> { num_lookup_z: usize, } -impl<'a, F: FieldExt> Polynomials<'a, F> { +impl<'a, F: PrimeField> Polynomials<'a, F> { fn new( cs: &'a ConstraintSystem, zk: bool, @@ -538,7 +541,7 @@ impl<'a, F: FieldExt> Polynomials<'a, F> { } fn l_active(&self) -> Expression { - Expression::Constant(F::one()) - self.l_last() - self.l_blind() + Expression::Constant(F::ONE) - self.l_last() - self.l_blind() } fn system_challenge_offset(&self) -> usize { @@ -563,7 +566,7 @@ impl<'a, F: FieldExt> Polynomials<'a, F> { } fn permutation_constraints(&'a self, t: usize) -> impl IntoIterator> + 'a { - let one = &Expression::Constant(F::one()); + let one = &Expression::Constant(F::ONE); let l_0 = &Expression::::CommonPolynomial(CommonPolynomial::Lagrange(0)); let l_last = &self.l_last(); let l_active = &self.l_active(); @@ -658,7 +661,7 @@ impl<'a, F: FieldExt> Polynomials<'a, F> { } fn lookup_constraints(&'a self, t: usize) -> impl IntoIterator> + 'a { - let one = &Expression::Constant(F::one()); + let one = &Expression::Constant(F::ONE); let l_0 = &Expression::::CommonPolynomial(CommonPolynomial::Lagrange(0)); let l_last = &self.l_last(); let l_active = &self.l_active(); @@ -772,7 +775,7 @@ impl EncodedChallenge for MockChallenge { } #[derive(Default)] -struct MockTranscript(F); +struct MockTranscript(F); impl Transcript for MockTranscript { fn squeeze_challenge(&mut self) -> MockChallenge { @@ -789,7 +792,10 @@ impl Transcript for MockTranscript } } -fn transcript_initial_state(vk: &VerifyingKey) -> C::Scalar { +fn transcript_initial_state(vk: &VerifyingKey) -> C::Scalar +where + C::Scalar: FromUniformBytes<64>, +{ let mut transcript = MockTranscript::default(); vk.hash_into(&mut transcript).unwrap(); transcript.0 diff --git a/snark-verifier/src/system/halo2/test.rs b/snark-verifier/src/system/halo2/test.rs index 03e5503a..6c328dce 100644 --- a/snark-verifier/src/system/halo2/test.rs +++ b/snark-verifier/src/system/halo2/test.rs @@ -1,4 +1,4 @@ -use crate::util::arithmetic::CurveAffine; +use crate::util::arithmetic::{CurveAffine, FromUniformBytes, WithSmallOrderMulGroup}; use halo2_proofs::{ dev::MockProver, plonk::{create_proof, verify_proof, Circuit, ProvingKey}, @@ -47,6 +47,7 @@ pub fn create_proof_checked<'a, S, C, P, V, VS, TW, TR, EC, R>( ) -> Vec where S: CommitmentScheme, + S::Scalar: WithSmallOrderMulGroup<3> + FromUniformBytes<64> + Ord, S::ParamsVerifier: 'a, C: Circuit, P: Prover<'a, S>, diff --git a/snark-verifier/src/system/halo2/test/circuit/maingate.rs b/snark-verifier/src/system/halo2/test/circuit/maingate.rs index 82d63b5e..d6eb9ea9 100644 --- a/snark-verifier/src/system/halo2/test/circuit/maingate.rs +++ b/snark-verifier/src/system/halo2/test/circuit/maingate.rs @@ -1,4 +1,4 @@ -use crate::util::arithmetic::{CurveAffine, FieldExt}; +use crate::util::arithmetic::{CurveAffine, PrimeField}; use halo2_proofs::{ circuit::{floor_planner::V1, Layouter, Value}, plonk::{Circuit, ConstraintSystem, Error}, @@ -19,7 +19,7 @@ pub struct MainGateWithRangeConfig { } impl MainGateWithRangeConfig { - pub fn configure( + pub fn configure( meta: &mut ConstraintSystem, composition_bits: Vec, overflow_bits: Vec, @@ -33,11 +33,11 @@ impl MainGateWithRangeConfig { } } - pub fn main_gate(&self) -> MainGate { + pub fn main_gate(&self) -> MainGate { MainGate::new(self.main_gate_config.clone()) } - pub fn range_chip(&self) -> RangeChip { + pub fn range_chip(&self) -> RangeChip { RangeChip::new(self.range_config.clone()) } @@ -54,7 +54,7 @@ impl MainGateWithRangeConfig { #[derive(Clone, Default)] pub struct MainGateWithRange(Vec); -impl MainGateWithRange { +impl MainGateWithRange { pub fn new(inner: Vec) -> Self { Self(inner) } @@ -68,12 +68,14 @@ impl MainGateWithRange { } } -impl Circuit for MainGateWithRange { +impl Circuit for MainGateWithRange { type Config = MainGateWithRangeConfig; type FloorPlanner = V1; + #[cfg(feature = "halo2_circuit_params")] + type Params = (); fn without_witnesses(&self) -> Self { - Self(vec![F::zero()]) + Self(vec![F::ZERO]) } fn configure(meta: &mut ConstraintSystem) -> Self::Config { @@ -97,7 +99,7 @@ impl Circuit for MainGateWithRange { range_chip.decompose(&mut ctx, Value::known(F::from(u32::MAX as u64)), 8, 39)?; let a = range_chip.assign(&mut ctx, Value::known(self.0[0]), 8, 68)?; let b = main_gate.sub_sub_with_constant(&mut ctx, &a, &a, &a, F::from(2))?; - let cond = main_gate.assign_bit(&mut ctx, Value::known(F::one()))?; + let cond = main_gate.assign_bit(&mut ctx, Value::known(F::ONE))?; main_gate.select(&mut ctx, &a, &b, &cond)?; Ok(a) diff --git a/snark-verifier/src/system/halo2/test/circuit/standard.rs b/snark-verifier/src/system/halo2/test/circuit/standard.rs index 90f30f2b..51e3baf6 100644 --- a/snark-verifier/src/system/halo2/test/circuit/standard.rs +++ b/snark-verifier/src/system/halo2/test/circuit/standard.rs @@ -1,4 +1,4 @@ -use crate::util::arithmetic::FieldExt; +use crate::util::arithmetic::PrimeField; use halo2_proofs::{ circuit::{floor_planner::V1, Layouter, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Fixed, Instance}, @@ -21,7 +21,7 @@ pub struct StandardPlonkConfig { } impl StandardPlonkConfig { - pub fn configure(meta: &mut ConstraintSystem) -> Self { + pub fn configure(meta: &mut ConstraintSystem) -> Self { let [a, b, c] = [(); 3].map(|_| meta.advice_column()); let [q_a, q_b, q_c, q_ab, constant] = [(); 5].map(|_| meta.fixed_column()); let instance = meta.instance_column(); @@ -63,7 +63,7 @@ impl StandardPlonkConfig { #[derive(Clone, Default)] pub struct StandardPlonk(F); -impl StandardPlonk { +impl StandardPlonk { pub fn rand(mut rng: R) -> Self { Self(F::from(rng.next_u32() as u64)) } @@ -73,9 +73,11 @@ impl StandardPlonk { } } -impl Circuit for StandardPlonk { +impl Circuit for StandardPlonk { type Config = StandardPlonkConfig; type FloorPlanner = V1; + #[cfg(feature = "halo2_circuit_params")] + type Params = (); fn without_witnesses(&self) -> Self { Self::default() @@ -95,7 +97,7 @@ impl Circuit for StandardPlonk { || "", |mut region| { region.assign_advice(|| "", config.a, 0, || Value::known(self.0))?; - region.assign_fixed(|| "", config.q_a, 0, || Value::known(-F::one()))?; + region.assign_fixed(|| "", config.q_a, 0, || Value::known(-F::ONE))?; region.assign_advice(|| "", config.a, 1, || Value::known(-F::from(5)))?; for (column, idx) in [ @@ -111,7 +113,7 @@ impl Circuit for StandardPlonk { region.assign_fixed(|| "", *column, 1, || Value::known(F::from(idx)))?; } - let a = region.assign_advice(|| "", config.a, 2, || Value::known(F::one()))?; + let a = region.assign_advice(|| "", config.a, 2, || Value::known(F::ONE))?; a.copy_advice(|| "", &mut region, config.b, 3)?; a.copy_advice(|| "", &mut region, config.c, 4)?; diff --git a/snark-verifier/src/system/halo2/test/kzg.rs b/snark-verifier/src/system/halo2/test/kzg.rs index c8b4fc77..107af76e 100644 --- a/snark-verifier/src/system/halo2/test/kzg.rs +++ b/snark-verifier/src/system/halo2/test/kzg.rs @@ -1,6 +1,6 @@ use crate::{ system::halo2::test::{read_or_create_srs, MainGateWithRange}, - util::arithmetic::{fe_to_limbs, CurveAffine, MultiMillerLoop}, + util::arithmetic::{fe_to_limbs, CurveAffine, MultiMillerLoop, PrimeField}, }; use halo2_curves::serde::SerdeObject; use halo2_proofs::poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG}; @@ -19,13 +19,17 @@ pub const TESTDATA_DIR: &str = "./src/system/halo2/test/kzg/testdata"; pub const LIMBS: usize = 4; pub const BITS: usize = 68; -pub fn setup(k: u32) -> ParamsKZG { +pub fn setup(k: u32) -> ParamsKZG +where + M::Scalar: PrimeField, +{ ParamsKZG::::setup(k, ChaCha20Rng::from_seed(Default::default())) } pub fn main_gate_with_range_with_mock_kzg_accumulator( ) -> MainGateWithRange where + M::Scalar: PrimeField, M::G1Affine: SerdeObject, M::G2Affine: SerdeObject, { diff --git a/snark-verifier/src/system/halo2/test/kzg/halo2.rs b/snark-verifier/src/system/halo2/test/kzg/halo2.rs index 1fd461da..df297811 100644 --- a/snark-verifier/src/system/halo2/test/kzg/halo2.rs +++ b/snark-verifier/src/system/halo2/test/kzg/halo2.rs @@ -254,6 +254,8 @@ impl Accumulation { impl Circuit for Accumulation { type Config = MainGateWithRangeConfig; type FloorPlanner = V1; + #[cfg(feature = "halo2_circuit_params")] + type Params = (); fn without_witnesses(&self) -> Self { Self { diff --git a/snark-verifier/src/system/halo2/transcript.rs b/snark-verifier/src/system/halo2/transcript.rs index 6de1b739..09896029 100644 --- a/snark-verifier/src/system/halo2/transcript.rs +++ b/snark-verifier/src/system/halo2/transcript.rs @@ -3,7 +3,7 @@ use crate::{ loader::native::{self, NativeLoader}, util::{ - arithmetic::CurveAffine, + arithmetic::{CurveAffine, FromUniformBytes}, transcript::{Transcript, TranscriptRead, TranscriptWrite}, }, Error, @@ -17,7 +17,10 @@ pub mod evm; #[cfg(feature = "loader_halo2")] pub mod halo2; -impl Transcript for Blake2bRead> { +impl Transcript for Blake2bRead> +where + C::Scalar: FromUniformBytes<64>, +{ fn loader(&self) -> &NativeLoader { &native::LOADER } @@ -37,8 +40,9 @@ impl Transcript for Blake2bRead TranscriptRead - for Blake2bRead> +impl TranscriptRead for Blake2bRead> +where + C::Scalar: FromUniformBytes<64>, { fn read_scalar(&mut self) -> Result { halo2_proofs::transcript::TranscriptRead::read_scalar(self) @@ -51,7 +55,10 @@ impl TranscriptRead } } -impl Transcript for Blake2bWrite> { +impl Transcript for Blake2bWrite> +where + C::Scalar: FromUniformBytes<64>, +{ fn loader(&self) -> &NativeLoader { &native::LOADER } @@ -71,13 +78,19 @@ impl Transcript for Blake2bWrite TranscriptWrite for Blake2bWrite, C, Challenge255> { +impl TranscriptWrite for Blake2bWrite, C, Challenge255> +where + C::Scalar: FromUniformBytes<64>, +{ fn write_scalar(&mut self, scalar: C::Scalar) -> Result<(), Error> { halo2_proofs::transcript::TranscriptWrite::write_scalar(self, scalar) .map_err(|err| Error::Transcript(err.kind(), err.to_string())) } - fn write_ec_point(&mut self, ec_point: C) -> Result<(), Error> { + fn write_ec_point(&mut self, ec_point: C) -> Result<(), Error> + where + C::Scalar: FromUniformBytes<64>, + { halo2_proofs::transcript::TranscriptWrite::write_point(self, ec_point) .map_err(|err| Error::Transcript(err.kind(), err.to_string())) } diff --git a/snark-verifier/src/system/halo2/transcript/halo2.rs b/snark-verifier/src/system/halo2/transcript/halo2.rs index 8519a8ca..c05cace9 100644 --- a/snark-verifier/src/system/halo2/transcript/halo2.rs +++ b/snark-verifier/src/system/halo2/transcript/halo2.rs @@ -7,7 +7,7 @@ use crate::{ Loader, ScalarLoader, }, util::{ - arithmetic::{fe_to_fe, CurveAffine, PrimeField}, + arithmetic::{fe_to_fe, CurveAffine, FromUniformBytes, PrimeField}, hash::Poseidon, transcript::{Transcript, TranscriptRead, TranscriptWrite}, Itertools, @@ -58,6 +58,7 @@ impl<'a, C, R, EccChip, const T: usize, const RATE: usize, const R_F: usize, con PoseidonTranscript>, Value, T, RATE, R_F, R_P> where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, R: Read, EccChip: NativeEncoding<'a, C>, { @@ -77,6 +78,7 @@ impl<'a, C, R, EccChip, const T: usize, const RATE: usize, const R_F: usize, con for PoseidonTranscript>, Value, T, RATE, R_F, R_P> where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, R: Read, EccChip: NativeEncoding<'a, C>, { @@ -120,6 +122,7 @@ impl<'a, C, R, EccChip, const T: usize, const RATE: usize, const R_F: usize, con for PoseidonTranscript>, Value, T, RATE, R_F, R_P> where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, R: Read, EccChip: NativeEncoding<'a, C>, { @@ -156,6 +159,8 @@ where impl PoseidonTranscript +where + C::Scalar: FromUniformBytes<64>, { /// Initialize [`PoseidonTranscript`] given readable or writeable stream for /// verifying or proving with [`NativeLoader`]. @@ -170,6 +175,8 @@ impl Transcript for PoseidonTranscript +where + C::Scalar: FromUniformBytes<64>, { fn loader(&self) -> &NativeLoader { &native::LOADER @@ -207,6 +214,7 @@ impl for PoseidonTranscript where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, R: Read, { fn read_scalar(&mut self) -> Result { @@ -261,6 +269,7 @@ impl where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, W: Write, { fn write_scalar(&mut self, scalar: C::Scalar) -> Result<(), Error> { @@ -307,6 +316,8 @@ impl EncodedChallenge for ChallengeScalar { impl halo2_proofs::transcript::Transcript> for PoseidonTranscript +where + C::Scalar: FromUniformBytes<64>, { fn squeeze_challenge(&mut self) -> ChallengeScalar { ChallengeScalar::new(&Transcript::squeeze_challenge(self)) @@ -334,6 +345,7 @@ impl where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, R: Read, { fn read_point(&mut self) -> io::Result { @@ -358,6 +370,7 @@ impl where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, R: Read, { fn init(reader: R) -> Self { @@ -370,6 +383,7 @@ impl where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, W: Write, { fn write_point(&mut self, ec_point: C) -> io::Result<()> { @@ -392,6 +406,7 @@ impl where C: CurveAffine, + C::Scalar: FromUniformBytes<64>, W: Write, { fn init(writer: W) -> Self { diff --git a/snark-verifier/src/util/arithmetic.rs b/snark-verifier/src/util/arithmetic.rs index af32ded0..22924e00 100644 --- a/snark-verifier/src/util/arithmetic.rs +++ b/snark-verifier/src/util/arithmetic.rs @@ -11,13 +11,10 @@ use std::{ }; pub use halo2_curves::{ - group::{ - ff::{BatchInvert, Field, PrimeField}, - prime::PrimeCurveAffine, - Curve, Group, GroupEncoding, - }, + ff::{BatchInvert, Field, FromUniformBytes, PrimeField, WithSmallOrderMulGroup}, + group::{prime::PrimeCurveAffine, Curve, Group, GroupEncoding}, pairing::MillerLoopResult, - Coordinates, CurveAffine, CurveExt, FieldExt, + Coordinates, CurveAffine, CurveExt, }; /// [`halo2_curves::pairing::MultiMillerLoop`] with [`std::fmt::Debug`]. @@ -51,7 +48,7 @@ pub fn batch_invert_and_mul(values: &mut [F], coeff: &F) { let products = values .iter() .filter(|value| !value.is_zero_vartime()) - .scan(F::one(), |acc, value| { + .scan(F::ONE, |acc, value| { *acc *= value; Some(*acc) }) @@ -63,7 +60,7 @@ pub fn batch_invert_and_mul(values: &mut [F], coeff: &F) { .iter_mut() .rev() .filter(|value| !value.is_zero_vartime()) - .zip(products.into_iter().rev().skip(1).chain(Some(F::one()))) + .zip(products.into_iter().rev().skip(1).chain(Some(F::ONE))) { let mut inv = all_product_inv * product; mem::swap(value, &mut inv); @@ -73,7 +70,7 @@ pub fn batch_invert_and_mul(values: &mut [F], coeff: &F) { /// Batch invert [`PrimeField`] elements. pub fn batch_invert(values: &mut [F]) { - batch_invert_and_mul(values, &F::one()) + batch_invert_and_mul(values, &F::ONE) } /// Root of unity of 2^k-sized multiplicative subgroup of [`PrimeField`] by @@ -86,7 +83,7 @@ pub fn batch_invert(values: &mut [F]) { pub fn root_of_unity(k: usize) -> F { assert!(k <= F::S as usize); - iter::successors(Some(F::root_of_unity()), |acc| Some(acc.square())) + iter::successors(Some(F::ROOT_OF_UNITY), |acc| Some(acc.square())) .take(F::S as usize - k + 1) .last() .unwrap() @@ -244,7 +241,7 @@ impl Fraction { /// Modulus of a [`PrimeField`] pub fn modulus() -> BigUint { - fe_to_big(-F::one()) + 1usize + fe_to_big(-F::ONE) + 1usize } /// Convert a [`BigUint`] into a [`PrimeField`] . @@ -300,7 +297,7 @@ pub fn fe_to_limbs(scalar: F) -> impl Iterator { - iter::successors(Some(F::one()), move |power| Some(scalar * power)) + iter::successors(Some(F::ONE), move |power| Some(scalar * power)) } /// Compute inner product of 2 slice of [`Field`]. diff --git a/snark-verifier/src/util/hash/poseidon.rs b/snark-verifier/src/util/hash/poseidon.rs index 60d55d9f..99e2d6ac 100644 --- a/snark-verifier/src/util/hash/poseidon.rs +++ b/snark-verifier/src/util/hash/poseidon.rs @@ -1,17 +1,20 @@ use crate::{ loader::{LoadedScalar, ScalarLoader}, - util::{arithmetic::FieldExt, Itertools}, + util::{ + arithmetic::{FromUniformBytes, PrimeField}, + Itertools, + }, }; use poseidon::{self, SparseMDSMatrix, Spec}; use std::{iter, marker::PhantomData, mem}; #[derive(Debug)] -struct State { +struct State { inner: [L; T], _marker: PhantomData, } -impl, const T: usize, const RATE: usize> State { +impl, const T: usize, const RATE: usize> State { fn new(inner: [L; T]) -> Self { Self { inner, @@ -62,7 +65,7 @@ impl, const T: usize, const RATE: usize> State, const T: usize, const RATE: usize> State, const T: usize, const RATE: usize> State { +pub struct Poseidon { spec: Spec, state: State, buf: Vec, } -impl, const T: usize, const RATE: usize> Poseidon { +impl, L: LoadedScalar, const T: usize, const RATE: usize> + Poseidon +{ /// Initialize a poseidon hasher. pub fn new(loader: &L::Loader, r_f: usize, r_p: usize) -> Self { Self { @@ -179,7 +184,7 @@ impl, const T: usize, const RATE: usize> Poseido self.state.sbox_full(constants); self.state.apply_mds(&mds); } - self.state.sbox_full(&[F::zero(); T]); + self.state.sbox_full(&[F::ZERO; T]); self.state.apply_mds(&mds); } } diff --git a/snark-verifier/src/util/poly.rs b/snark-verifier/src/util/poly.rs index eef2f593..752b269d 100644 --- a/snark-verifier/src/util/poly.rs +++ b/snark-verifier/src/util/poly.rs @@ -57,7 +57,7 @@ impl Polynomial { coeffs .iter() .rev() - .fold(F::zero(), |acc, coeff| acc * x + coeff) + .fold(F::ZERO, |acc, coeff| acc * x + coeff) }; #[cfg(feature = "parallel")] @@ -71,7 +71,7 @@ impl Polynomial { } let chunk_size = Integer::div_ceil(&self.len(), &num_threads); - let mut results = vec![F::zero(); num_threads]; + let mut results = vec![F::ZERO; num_threads]; parallelize_iter( results .iter_mut() @@ -79,7 +79,7 @@ impl Polynomial { .zip(powers(x.pow_vartime(&[chunk_size as u64, 0, 0, 0]))), |((result, coeffs), scalar)| *result = evaluate_serial(coeffs) * scalar, ); - results.iter().fold(F::zero(), |acc, result| acc + result) + results.iter().fold(F::ZERO, |acc, result| acc + result) } #[cfg(not(feature = "parallel"))] evaluate_serial(&self.0) @@ -134,10 +134,10 @@ impl Mul for Polynomial { type Output = Polynomial; fn mul(mut self, rhs: F) -> Polynomial { - if rhs == F::zero() { - return Polynomial::new(vec![F::zero(); self.len()]); + if rhs == F::ZERO { + return Polynomial::new(vec![F::ZERO; self.len()]); } - if rhs == F::one() { + if rhs == F::ONE { return self; } parallelize(&mut self.0, |(lhs, _)| { diff --git a/snark-verifier/src/verifier/plonk/proof.rs b/snark-verifier/src/verifier/plonk/proof.rs index 962417ec..27123d87 100644 --- a/snark-verifier/src/verifier/plonk/proof.rs +++ b/snark-verifier/src/verifier/plonk/proof.rs @@ -175,7 +175,7 @@ where .map(|query| { let shift = protocol .domain - .rotate_scalar(C::Scalar::one(), query.rotation); + .rotate_scalar(C::Scalar::ONE, query.rotation); pcs::Query::new(query.poly, shift) }) .collect() diff --git a/snark-verifier/src/verifier/plonk/protocol.rs b/snark-verifier/src/verifier/plonk/protocol.rs index 3cf8e462..94d107ce 100644 --- a/snark-verifier/src/verifier/plonk/protocol.rs +++ b/snark-verifier/src/verifier/plonk/protocol.rs @@ -208,7 +208,7 @@ where let numer = zn_minus_one.clone() * &n_inv; let omegas = langranges .iter() - .map(|&i| loader.load_const(&domain.rotate_scalar(C::Scalar::one(), Rotation(i)))) + .map(|&i| loader.load_const(&domain.rotate_scalar(C::Scalar::ONE, Rotation(i)))) .collect_vec(); let lagrange_evals = omegas .iter() @@ -485,7 +485,7 @@ impl Sum for Expression { impl One for Expression { fn one() -> Self { - Expression::Constant(F::one()) + Expression::Constant(F::ONE) } }