From c8c7ff9b70bf1a0a641554e336893669d439544f Mon Sep 17 00:00:00 2001 From: adria0 Date: Mon, 17 Jun 2024 15:58:21 +0200 Subject: [PATCH] Working --- halo2_backend/Cargo.toml | 2 +- halo2_debug/Cargo.toml | 2 +- halo2_frontend/Cargo.toml | 2 +- halo2_frontend/src/circuit/table_layouter.rs | 2 +- halo2_frontend/src/dev.rs | 15 ++- halo2_frontend/src/dev/gates.rs | 2 +- halo2_frontend/src/dev/tfp.rs | 2 +- .../src/plonk/circuit/compress_selectors.rs | 4 +- .../src/plonk/circuit/constraint_system.rs | 2 +- .../src/plonk/circuit/expression.rs | 32 +++--- halo2_middleware/Cargo.toml | 2 +- halo2_proofs/Cargo.toml | 2 +- halo2_proofs/benches/dev_lookup.rs | 3 +- halo2_proofs/benches/plonk.rs | 11 +- halo2_proofs/examples/circuit-layout.rs | 11 +- halo2_proofs/examples/simple-example.rs | 1 - halo2_proofs/examples/vector-mul.rs | 1 - halo2_proofs/src/plonk.rs | 8 +- halo2_proofs/src/plonk/prover.rs | 83 +++++++++++---- halo2_proofs/tests/compress_selectors.rs | 3 +- ...nd_split.rsx => frontend_backend_split.rs} | 36 ++++--- .../tests/{plonk_api.rsx => plonk_api.rs} | 100 ++++++++++++------ .../{serialization.rsx => serialization.rs} | 15 +-- halo2_proofs/tests/shuffle.rsx | 16 +-- .../tests/{shuffle_api.rsx => shuffle_api.rs} | 21 ++-- ...-unblinded.rsx => vector-ops-unblinded.rs} | 16 +-- 26 files changed, 234 insertions(+), 160 deletions(-) rename halo2_proofs/tests/{frontend_backend_split.rsx => frontend_backend_split.rs} (96%) rename halo2_proofs/tests/{plonk_api.rsx => plonk_api.rs} (93%) rename halo2_proofs/tests/{serialization.rsx => serialization.rs} (93%) rename halo2_proofs/tests/{shuffle_api.rsx => shuffle_api.rs} (94%) rename halo2_proofs/tests/{vector-ops-unblinded.rsx => vector-ops-unblinded.rs} (97%) diff --git a/halo2_backend/Cargo.toml b/halo2_backend/Cargo.toml index 7b24994c3..d812d97f1 100644 --- a/halo2_backend/Cargo.toml +++ b/halo2_backend/Cargo.toml @@ -9,7 +9,7 @@ authors = [ "Privacy Scaling Explorations team", ] edition = "2021" -rust-version = "1.66.0" +rust-version = "1.70.0" description = """ Halo2 backend implementation. This package implements the halo2 proof system which includes setup (key generation), proving and verifying. """ diff --git a/halo2_debug/Cargo.toml b/halo2_debug/Cargo.toml index d86ea3755..a5e1763d6 100644 --- a/halo2_debug/Cargo.toml +++ b/halo2_debug/Cargo.toml @@ -5,7 +5,7 @@ authors = [ "Privacy Scaling Explorations team", ] edition = "2021" -rust-version = "1.66.0" +rust-version = "1.70.0" description = """ Halo2 Debug. This package contains utilities for debugging and testing within the halo2 ecosystem. diff --git a/halo2_frontend/Cargo.toml b/halo2_frontend/Cargo.toml index 960d00f0b..24cc1fca7 100644 --- a/halo2_frontend/Cargo.toml +++ b/halo2_frontend/Cargo.toml @@ -9,7 +9,7 @@ authors = [ "Privacy Scaling Explorations team", ] edition = "2021" -rust-version = "1.66.0" +rust-version = "1.70.0" description = """ Halo2 frontend implementation. This package implements an API to write circuits, handles witness generation and contains the MockProver. """ diff --git a/halo2_frontend/src/circuit/table_layouter.rs b/halo2_frontend/src/circuit/table_layouter.rs index 1c871b42a..3e93bec0f 100644 --- a/halo2_frontend/src/circuit/table_layouter.rs +++ b/halo2_frontend/src/circuit/table_layouter.rs @@ -380,7 +380,7 @@ mod tests { meta.lookup("", |cells| { let a = cells.query_advice(a, Rotation::cur()); - vec![(a.clone(), table.0), (a, table.1)] + vec![(a, table.0), (a, table.1)] }); Self::Config { table } diff --git a/halo2_frontend/src/dev.rs b/halo2_frontend/src/dev.rs index 2397147f4..6262e52a2 100644 --- a/halo2_frontend/src/dev.rs +++ b/halo2_frontend/src/dev.rs @@ -184,7 +184,7 @@ impl Mul for Value { /// use halo2_frontend::{ /// circuit::{Layouter, SimpleFloorPlanner, Value}, /// dev::{FailureLocation, MockProver, VerifyFailure}, -/// plonk::{circuit::Column, Circuit, ConstraintSystem, Error, Advice, Selector}, +/// plonk::{circuit::Column, Circuit, ConstraintSystem, Error, Advice, Selector, FieldFront}, /// }; /// use halo2_middleware::circuit::{Any, ColumnMid}; /// use halo2_middleware::poly::Rotation; @@ -206,7 +206,7 @@ impl Mul for Value { /// b: Value, /// } /// -/// impl Circuit for MyCircuit { +/// impl> Circuit for MyCircuit { /// type Config = MyConfig; /// type FloorPlanner = SimpleFloorPlanner; /// #[cfg(feature = "circuit-params")] @@ -284,7 +284,7 @@ impl Mul for Value { /// MockProver::::run(2, &circuit, vec![]).unwrap_err() /// }); /// assert_eq!( -/// result.unwrap_err().downcast_rF::().unwrap(), +/// result.unwrap_err().downcast_ref::().unwrap(), /// "n=4, minimum_rows=8, k=2" /// ); /// ``` @@ -1376,13 +1376,10 @@ mod tests { // If q is enabled, a must be in the table. // When q is not enabled, lookup the default value instead. - let not_q = Expression::Constant(Fp::one()) - q.clone(); + let not_q = Expression::Constant(Fp::one()) - q; let default = Expression::Constant(Fp::from(2)); vec![ - ( - q.clone() * a.clone() + not_q.clone() * default.clone(), - table, - ), + (q * a + not_q * default, table), (q * a + not_q * default, advice_table), ] }); @@ -1540,7 +1537,7 @@ mod tests { // If q is enabled, a must be in the table. // When q is not enabled, lookup the default value instead. - let not_q = Expression::Constant(Fp::one()) - q.clone(); + let not_q = Expression::Constant(Fp::one()) - q; let default = Expression::Constant(Fp::from(2)); vec![(q * a + not_q * default, table)] }); diff --git a/halo2_frontend/src/dev/gates.rs b/halo2_frontend/src/dev/gates.rs index 54fb8c471..4ac5e7717 100644 --- a/halo2_frontend/src/dev/gates.rs +++ b/halo2_frontend/src/dev/gates.rs @@ -29,7 +29,7 @@ struct Gate { /// use halo2_frontend::{ /// circuit::{Layouter, SimpleFloorPlanner}, /// dev::CircuitGates, -/// plonk::{Circuit, ConstraintSystem, Error}, +/// plonk::{Circuit, ConstraintSystem, Error, FieldFront}, /// }; /// use halo2curves::pasta::pallas; /// diff --git a/halo2_frontend/src/dev/tfp.rs b/halo2_frontend/src/dev/tfp.rs index eecb9cb9f..892e1c4e9 100644 --- a/halo2_frontend/src/dev/tfp.rs +++ b/halo2_frontend/src/dev/tfp.rs @@ -35,7 +35,7 @@ use crate::{ /// use halo2_frontend::{ /// circuit::{floor_planner, Layouter, Value}, /// dev::TracingFloorPlanner, -/// plonk::{Circuit, ConstraintSystem, Error}, +/// plonk::{Circuit, ConstraintSystem, Error, FieldFront}, /// }; /// /// # struct MyCircuit { diff --git a/halo2_frontend/src/plonk/circuit/compress_selectors.rs b/halo2_frontend/src/plonk/circuit/compress_selectors.rs index 70c252067..406f1cc8f 100644 --- a/halo2_frontend/src/plonk/circuit/compress_selectors.rs +++ b/halo2_frontend/src/plonk/circuit/compress_selectors.rs @@ -190,11 +190,11 @@ where // which is non-zero only on rows where `combination_assignment` is set to // `assigned_root`. In particular, rows set to 0 correspond to all selectors // being disabled. - let mut expression = query.clone(); + let mut expression = query; let mut root = F::ONE; for _ in 0..combination_len { if root != assigned_root { - expression = expression * (Expression::Constant(root) - query.clone()); + expression = expression * (Expression::Constant(root) - query); } root += F::ONE; } diff --git a/halo2_frontend/src/plonk/circuit/constraint_system.rs b/halo2_frontend/src/plonk/circuit/constraint_system.rs index f7edbb6b3..68c69aa55 100644 --- a/halo2_frontend/src/plonk/circuit/constraint_system.rs +++ b/halo2_frontend/src/plonk/circuit/constraint_system.rs @@ -709,7 +709,7 @@ impl ConstraintSystem { assert!(!selector.is_simple()); } - selector_replacements[selector.0].clone() + selector_replacements[selector.0] }, &|query| Expression::Fixed(query), &|query| Expression::Advice(query), diff --git a/halo2_frontend/src/plonk/circuit/expression.rs b/halo2_frontend/src/plonk/circuit/expression.rs index 4279b7a18..bff83a0bf 100644 --- a/halo2_frontend/src/plonk/circuit/expression.rs +++ b/halo2_frontend/src/plonk/circuit/expression.rs @@ -253,7 +253,7 @@ impl SealedPhase for ThirdPhase { /// row when required: /// ``` /// use halo2_frontend::circuit::{Chip, Layouter, Value}; -/// use halo2_frontend::plonk::{Advice, Fixed, Error, Column, Selector}; +/// use halo2_frontend::plonk::{Advice, Fixed, Error, Column, Selector, FieldFront}; /// use halo2_middleware::ff::Field; /// /// struct Config { @@ -476,14 +476,14 @@ pub trait FieldFront: Field { fn alloc(expr: Expression) -> ExprRef; fn get(ref_: &ExprRef) -> Expression; fn into_field(self) -> Self::Field; - fn into_field_fr(f: Self::Field) -> Self; + fn into_fieldfront(f: Self::Field) -> Self; } #[derive(Clone, Copy, Eq, PartialEq)] pub struct ExprRef(usize, std::marker::PhantomData); -impl Into> for Expression { - fn into(self) -> ExprRef { - F::alloc(self) +impl From> for ExprRef { + fn from(val: Expression) -> Self { + F::alloc(val) } } @@ -1183,12 +1183,10 @@ impl Product for Expression { } #[allow(non_camel_case_types)] +#[derive(Default)] pub struct ExprArena(Vec>); impl ExprArena { - pub fn new() -> Self { - Self(Vec::new()) - } pub fn push(&mut self, expr: Expression) -> crate::plonk::ExprRef { let index = self.0.len(); self.0.push(expr); @@ -1205,28 +1203,27 @@ macro_rules! expression_arena { fn $arena() -> &'static std::sync::RwLock> { static LINES: std::sync::OnceLock>> = std::sync::OnceLock::new(); - LINES.get_or_init(|| std::sync::RwLock::new(ExprArena::new())) + LINES.get_or_init(|| std::sync::RwLock::new(ExprArena::default())) } - impl crate::plonk::FieldFront for $field { + impl $crate::plonk::FieldFront for $field { type Field = $field; fn into_field(self) -> Self::Field { self } - fn into_field_fr(f: Self::Field) -> Self { + fn into_fieldfront(f: Self::Field) -> Self { f } - fn alloc(expr: crate::plonk::Expression) -> crate::plonk::ExprRef { + fn alloc(expr: $crate::plonk::Expression) -> $crate::plonk::ExprRef { $arena().write().unwrap().push(expr) } - fn get(ref_: &crate::plonk::ExprRef) -> crate::plonk::Expression { + fn get(ref_: &$crate::plonk::ExprRef) -> $crate::plonk::Expression { *$arena().read().unwrap().get(*ref_) } } - - impl Into> for $field { - fn into(self) -> crate::plonk::ExprRef<$field> { - crate::plonk::FieldFront::alloc(crate::plonk::Expression::Constant(self)) + impl From<$field> for $crate::plonk::ExprRef<$field> { + fn from(f: $field) -> Self { + $crate::plonk::FieldFront::alloc($crate::plonk::Expression::Constant(f)) } } }; @@ -1236,6 +1233,7 @@ macro_rules! expression_arena { expression_arena!(arena_bn256_fr, halo2curves::bn256::Fr); expression_arena!(arena_bn256_fq, halo2curves::bn256::Fq); expression_arena!(arena_pasta_fp, halo2curves::pasta::Fp); +expression_arena!(arena_pasta_fq, halo2curves::pasta::Fq); #[cfg(test)] mod tests { diff --git a/halo2_middleware/Cargo.toml b/halo2_middleware/Cargo.toml index 1c24c77c6..c2ae45eb1 100644 --- a/halo2_middleware/Cargo.toml +++ b/halo2_middleware/Cargo.toml @@ -9,7 +9,7 @@ authors = [ "Privacy Scaling Explorations team", ] edition = "2021" -rust-version = "1.66.0" +rust-version = "1.70.0" description = """ Halo2 middleware. This package contains the types and traits required for the frontend-backend interaction. """ diff --git a/halo2_proofs/Cargo.toml b/halo2_proofs/Cargo.toml index 174bcae6c..b7f78cdc7 100644 --- a/halo2_proofs/Cargo.toml +++ b/halo2_proofs/Cargo.toml @@ -9,7 +9,7 @@ authors = [ "Privacy Scaling Explorations team", ] edition = "2021" -rust-version = "1.66.0" +rust-version = "1.70.0" description = """ Fast PLONK-based zero-knowledge proving system with no trusted setup """ diff --git a/halo2_proofs/benches/dev_lookup.rs b/halo2_proofs/benches/dev_lookup.rs index ad03956d9..d30ba1107 100644 --- a/halo2_proofs/benches/dev_lookup.rs +++ b/halo2_proofs/benches/dev_lookup.rs @@ -1,7 +1,6 @@ #[macro_use] extern crate criterion; -use ff::{Field, PrimeField}; use halo2_frontend::plonk::FieldFront; use halo2_proofs::circuit::{Layouter, SimpleFloorPlanner, Value}; use halo2_proofs::dev::MockProver; @@ -45,7 +44,7 @@ fn criterion_benchmark(c: &mut Criterion) { meta.lookup("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; 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 100c76b5f..bde08dc00 100644 --- a/halo2_proofs/benches/plonk.rs +++ b/halo2_proofs/benches/plonk.rs @@ -226,7 +226,7 @@ fn criterion_benchmark(c: &mut Criterion) { let sc = meta.query_fixed(sc, Rotation::cur()); let sm = meta.query_fixed(sm, Rotation::cur()); - vec![a.clone() * sa + b.clone() * sb + a * b * sm - (c * sc)] + vec![a * sa + b * sb + a * b * sm - (c * sc)] }); PlonkConfig { @@ -311,7 +311,14 @@ fn criterion_benchmark(c: &mut Criterion) { fn verifier(params: &ParamsIPA, vk: &VerifyingKey, proof: &[u8]) { let strategy = SingleStrategy::new(params); let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(proof); - assert!(verify_proof(params, vk, strategy, &[vec![vec![]]], &mut transcript).is_ok()); + assert!(verify_proof::<_, _, _, _, _, halo2curves::pasta::Fp>( + params, + vk, + strategy, + &[vec![vec![]]], + &mut transcript + ) + .is_ok()); } let k_range = 8..=16; diff --git a/halo2_proofs/examples/circuit-layout.rs b/halo2_proofs/examples/circuit-layout.rs index c0e206fee..8516762ad 100644 --- a/halo2_proofs/examples/circuit-layout.rs +++ b/halo2_proofs/examples/circuit-layout.rs @@ -1,7 +1,10 @@ use ff::Field; use halo2_proofs::{ circuit::{Cell, Layouter, Region, SimpleFloorPlanner, Value}, - plonk::{Advice, Assigned, Circuit, Column, ConstraintSystem, ErrorFront, Fixed, TableColumn}, + plonk::{ + Advice, Assigned, Circuit, Column, ConstraintSystem, ErrorFront, FieldFront, Fixed, + TableColumn, + }, poly::Rotation, }; use halo2curves::pasta::Fp; @@ -28,7 +31,7 @@ struct PlonkConfig { sl: TableColumn, } -trait StandardCs { +trait StandardCs { fn raw_multiply( &self, region: &mut Region, @@ -57,7 +60,7 @@ struct StandardPlonk { _marker: PhantomData, } -impl StandardPlonk { +impl StandardPlonk { fn new(config: PlonkConfig) -> Self { StandardPlonk { config, @@ -66,7 +69,7 @@ impl StandardPlonk { } } -impl StandardCs for StandardPlonk { +impl StandardCs for StandardPlonk { fn raw_multiply( &self, region: &mut Region, diff --git a/halo2_proofs/examples/simple-example.rs b/halo2_proofs/examples/simple-example.rs index 2578c36d2..f18a9c4df 100644 --- a/halo2_proofs/examples/simple-example.rs +++ b/halo2_proofs/examples/simple-example.rs @@ -2,7 +2,6 @@ use std::marker::PhantomData; use halo2_frontend::plonk::FieldFront; use halo2_proofs::{ - arithmetic::Field, circuit::{AssignedCell, Chip, Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, ErrorFront, Fixed, Instance, Selector}, poly::Rotation, diff --git a/halo2_proofs/examples/vector-mul.rs b/halo2_proofs/examples/vector-mul.rs index 28ec830a6..e6af78429 100644 --- a/halo2_proofs/examples/vector-mul.rs +++ b/halo2_proofs/examples/vector-mul.rs @@ -2,7 +2,6 @@ use std::marker::PhantomData; use halo2_frontend::plonk::FieldFront; use halo2_proofs::{ - arithmetic::Field, circuit::{AssignedCell, Chip, Layouter, Region, SimpleFloorPlanner, Value}, plonk::{Advice, Circuit, Column, ConstraintSystem, ErrorFront, Instance, Selector}, poly::Rotation, diff --git a/halo2_proofs/src/plonk.rs b/halo2_proofs/src/plonk.rs index b3d3232f9..9605afcac 100644 --- a/halo2_proofs/src/plonk.rs +++ b/halo2_proofs/src/plonk.rs @@ -8,15 +8,11 @@ mod error; mod keygen; mod prover; -mod verifier { - pub use halo2_backend::plonk::verifier::verify_proof; -} -use halo2_frontend::{circuit::compile_circuit, plonk::FieldFront}; +pub use halo2_frontend::{circuit::compile_circuit, plonk::FieldFront}; pub use keygen::{keygen_pk, keygen_pk_custom, keygen_vk, keygen_vk_custom}; -pub use prover::{create_proof, create_proof_with_engine}; -pub use verifier::verify_proof; +pub use prover::{create_proof, create_proof_with_engine, verify_proof}; pub use error::Error; pub use halo2_backend::plonk::{Error as ErrorBack, ProvingKey, VerifyingKey}; diff --git a/halo2_proofs/src/plonk/prover.rs b/halo2_proofs/src/plonk/prover.rs index e4fefb1a7..8449eb127 100644 --- a/halo2_proofs/src/plonk/prover.rs +++ b/halo2_proofs/src/plonk/prover.rs @@ -1,7 +1,11 @@ use crate::plonk::{Error, ErrorBack}; use crate::poly::commitment::{self, CommitmentScheme, Params}; use crate::transcript::{EncodedChallenge, TranscriptWrite}; +use halo2_backend::plonk::VerifyingKey; use halo2_backend::plonk::{prover::Prover, ProvingKey}; +use halo2_backend::poly::commitment::Verifier; +use halo2_backend::poly::VerificationStrategy; +use halo2_backend::transcript::TranscriptRead; use halo2_frontend::circuit::WitnessCalculator; use halo2_frontend::plonk::{Circuit, ConstraintSystem, FieldFront}; use halo2_middleware::ff::{FromUniformBytes, WithSmallOrderMulGroup}; @@ -12,6 +16,35 @@ use halo2_middleware::zal::{ use rand_core::RngCore; use std::collections::HashMap; +fn instances_frontfield_to_field( + instances: &[Vec>], +) -> Vec>> { + instances + .iter() + .map(|v| { + v.iter() + .map(|v| v.iter().map(|f| f.into_field()).collect()) + .collect() + }) + .collect() +} + +fn witnesses_frontfield_to_field( + witnesses: Vec>>>, +) -> Vec>>> { + witnesses + .iter() + .map(|v| { + v.iter() + .map(|v| { + v.as_ref() + .map(|v| v.iter().map(|f| f.into_field()).collect()) + }) + .collect() + }) + .collect() +} + /// This creates a proof for the provided `circuit` when given the public /// parameters `params` and the proving key [`ProvingKey`] that was /// generated previously for the same circuit. The provided `instances` @@ -57,14 +90,7 @@ where }) .collect(); - let instances: Vec>> = instances - .iter() - .map(|v| { - v.into_iter() - .map(|v| v.into_iter().map(|f| f.into_field()).collect()) - .collect() - }) - .collect(); + let instances = instances_frontfield_to_field(instances); let mut prover = Prover::::new_with_engine( engine, params, pk, &instances, rng, transcript, @@ -77,23 +103,13 @@ where witnesses.push(witness_calc.calc(*phase, &challenges)?); } - let witnesses: Vec>>> = witnesses - .iter() - .map(|v| { - v.into_iter() - .map(|v| { - v.as_ref() - .map(|v| v.into_iter().map(|f| f.into_field()).collect()) - }) - .collect() - }) - .collect(); + let witnesses = witnesses_frontfield_to_field(witnesses); challenges = prover .commit_phase(*phase, witnesses) .unwrap() .into_iter() - .map(|(k, v)| (k, F::into_field_fr(v))) + .map(|(k, v)| (k, F::into_fieldfront(v))) .collect(); } Ok(prover.create_proof()?) @@ -126,10 +142,35 @@ where let engine = PlonkEngineConfig::build_default(); create_proof_with_engine::( - engine, params, pk, circuits, &instances, rng, transcript, + engine, params, pk, circuits, instances, rng, transcript, ) } +/// Returns a boolean indicating whether or not the proof is valid +pub fn verify_proof< + 'params, + Scheme: CommitmentScheme, + V: Verifier<'params, Scheme>, + E: EncodedChallenge, + T: TranscriptRead, + Strategy: VerificationStrategy<'params, Scheme, V>, + F: FieldFront, +>( + params: &'params Scheme::ParamsVerifier, + vk: &VerifyingKey, + strategy: Strategy, + instances: &[Vec>], + transcript: &mut T, +) -> Result +where + Scheme::Scalar: WithSmallOrderMulGroup<3> + FromUniformBytes<64>, +{ + let instances = instances_frontfield_to_field(instances); + Ok(halo2_backend::plonk::verifier::verify_proof( + params, vk, strategy, &instances, transcript, + )?) +} + #[cfg(test)] mod test { use super::*; diff --git a/halo2_proofs/tests/compress_selectors.rs b/halo2_proofs/tests/compress_selectors.rs index b14ae5324..a90b36453 100644 --- a/halo2_proofs/tests/compress_selectors.rs +++ b/halo2_proofs/tests/compress_selectors.rs @@ -399,14 +399,13 @@ fn test_mycircuit( Blake2bRead::<_, G1Affine, Challenge255<_>>::init(proof.as_slice()); let strategy = SingleStrategy::new(&verifier_params); - verify_proof::, VerifierSHPLONK, _, _, _>( + verify_proof::, VerifierSHPLONK, _, _, _, _>( &verifier_params, &vk, strategy, instances.as_slice(), &mut verifier_transcript, ) - .map_err(halo2_proofs::plonk::Error::Backend) } /* diff --git a/halo2_proofs/tests/frontend_backend_split.rsx b/halo2_proofs/tests/frontend_backend_split.rs similarity index 96% rename from halo2_proofs/tests/frontend_backend_split.rsx rename to halo2_proofs/tests/frontend_backend_split.rs index 5c965191b..870fbd4fd 100644 --- a/halo2_proofs/tests/frontend_backend_split.rsx +++ b/halo2_proofs/tests/frontend_backend_split.rs @@ -64,7 +64,7 @@ struct MyCircuitConfig { impl MyCircuitConfig { #[allow(clippy::type_complexity)] - fn assign_gate>( + fn assign_gate>( &self, region: &mut Region<'_, F>, offset: &mut usize, @@ -103,7 +103,7 @@ struct MyCircuit { _marker: std::marker::PhantomData, } -impl, const WIDTH_FACTOR: usize> MyCircuit { +impl, const WIDTH_FACTOR: usize> MyCircuit { fn new(k: u32, input: u64) -> Self { Self { k, @@ -180,8 +180,8 @@ impl, const WIDTH_FACTOR: usize> MyCircuit let b = meta.query_advice(b, Rotation::cur()); let c = meta.query_advice(c, Rotation::cur()); let d = meta.query_fixed(d, Rotation::cur()); - let lhs = [one.clone(), a, b].map(|c| c * s_lookup.clone()); - let rhs = [one.clone(), d, c].map(|c| c * s_ltable.clone()); + let lhs = [one, a, b].map(|c| c * s_lookup); + let rhs = [one, d, c].map(|c| c * s_ltable); lhs.into_iter().zip(rhs).collect() }); @@ -190,8 +190,8 @@ impl, const WIDTH_FACTOR: usize> MyCircuit let s_stable = meta.query_fixed(s_stable, Rotation::cur()); let a = meta.query_advice(a, Rotation::cur()); let b = meta.query_advice(b, Rotation::cur()); - let lhs = [one.clone(), a].map(|c| c * s_shuffle.clone()); - let rhs = [one.clone(), b].map(|c| c * s_stable.clone()); + let lhs = [one, a].map(|c| c * s_shuffle); + let rhs = [one, b].map(|c| c * s_stable); lhs.into_iter().zip(rhs).collect() }); @@ -205,7 +205,7 @@ impl, const WIDTH_FACTOR: usize> MyCircuit let challenge = meta.query_challenge(challenge); vec![ - s_rlc.clone() * (a + challenge.clone() * b - e.clone()), + s_rlc * (a + challenge * b - e), s_rlc * (c + challenge * d - e), ] }); @@ -413,7 +413,9 @@ impl, const WIDTH_FACTOR: usize> MyCircuit } } -impl, const WIDTH_FACTOR: usize> Circuit for MyCircuit { +impl, const WIDTH_FACTOR: usize> Circuit + for MyCircuit +{ type Config = Vec; type FloorPlanner = SimpleFloorPlanner; #[cfg(feature = "circuit-params")] @@ -466,9 +468,12 @@ impl, const WIDTH_FACTOR: usize> Circuit for MyCircuit>::init(vec![]); - create_proof::, ProverSHPLONK<'_, Bn256>, _, _, _, _>( + create_proof::< + KZGCommitmentScheme, + ProverSHPLONK<'_, Bn256>, + _, + _, + _, + _, + halo2curves::bn256::Fr, + >( ¶ms, &pk, &[circuit], diff --git a/halo2_proofs/tests/plonk_api.rsx b/halo2_proofs/tests/plonk_api.rs similarity index 93% rename from halo2_proofs/tests/plonk_api.rsx rename to halo2_proofs/tests/plonk_api.rs index 5ca0fe358..2a90abe2e 100644 --- a/halo2_proofs/tests/plonk_api.rsx +++ b/halo2_proofs/tests/plonk_api.rs @@ -7,7 +7,6 @@ use halo2_middleware::zal::{ impls::{PlonkEngine, PlonkEngineConfig}, traits::MsmAccel, }; -use halo2_proofs::arithmetic::Field; use halo2_proofs::circuit::{Cell, Layouter, SimpleFloorPlanner, Value}; use halo2_proofs::dev::MockProver; use halo2_proofs::plonk::{ @@ -22,9 +21,22 @@ use halo2_proofs::transcript::{ Blake2bRead, Blake2bWrite, Challenge255, EncodedChallenge, TranscriptReadBuffer, TranscriptWriterBuffer, }; +use halo2_proofs::{arithmetic::Field, plonk::FieldFront}; use rand_core::{OsRng, RngCore}; use std::marker::PhantomData; +macro_rules! common { + ($scheme:ident) => {{ + let a = <$scheme as CommitmentScheme>::Scalar::from(2834758237) + * <$scheme as CommitmentScheme>::Scalar::ZETA; + let instance = + <$scheme as CommitmentScheme>::Scalar::ONE + <$scheme as CommitmentScheme>::Scalar::ONE; + let lookup_table = vec![instance, a, a, <$scheme as CommitmentScheme>::Scalar::ZERO]; + + (a, instance, lookup_table) + }}; +} + #[test] fn plonk_api() { const K: u32 = 5; @@ -51,7 +63,7 @@ fn plonk_api() { } #[allow(clippy::type_complexity)] - trait StandardCs { + trait StandardCs { fn raw_multiply( &self, layouter: &mut impl Layouter, @@ -97,7 +109,7 @@ fn plonk_api() { _marker: PhantomData, } - impl StandardPlonk { + impl StandardPlonk { fn new(config: PlonkConfig) -> Self { StandardPlonk { config, @@ -106,7 +118,7 @@ fn plonk_api() { } } - impl StandardCs for StandardPlonk { + impl StandardCs for StandardPlonk { fn raw_multiply( &self, layouter: &mut impl Layouter, @@ -347,7 +359,7 @@ fn plonk_api() { let sc = meta.query_fixed(sc, Rotation::cur()); let sm = meta.query_fixed(sm, Rotation::cur()); - vec![a.clone() * sa + b.clone() * sb + a * b * sm - (c * sc) + sf * (d * e)] + vec![a * sa + b * sb + a * b * sm - (c * sc) + sf * (d * e)] }); meta.create_gate("Public input", |meta| { @@ -415,17 +427,6 @@ fn plonk_api() { } } - macro_rules! common { - ($scheme:ident) => {{ - let a = <$scheme as CommitmentScheme>::Scalar::from(2834758237) - * <$scheme as CommitmentScheme>::Scalar::ZETA; - let instance = <$scheme as CommitmentScheme>::Scalar::ONE - + <$scheme as CommitmentScheme>::Scalar::ONE; - let lookup_table = vec![instance, a, a, <$scheme as CommitmentScheme>::Scalar::ZERO]; - (a, instance, lookup_table) - }}; - } - macro_rules! bad_keys { ($scheme:ident) => {{ let (_, _, lookup_table) = common!($scheme); @@ -433,7 +434,6 @@ fn plonk_api() { a: Value::unknown(), lookup_table: lookup_table.clone(), }; - // Check that we get an error if we try to initialize the proving key with a value of // k that is too small for the minimum required number of rows. let much_too_small_params= <$scheme as CommitmentScheme>::ParamsProver::new(1); @@ -456,12 +456,16 @@ fn plonk_api() { }}; } - fn keygen(params: &Scheme::ParamsProver) -> ProvingKey + fn keygen>( + params: &Scheme::ParamsProver, + ) -> ProvingKey where Scheme::Scalar: FromUniformBytes<64> + WithSmallOrderMulGroup<3>, { let (_, _, lookup_table) = common!(Scheme); - let empty_circuit: MyCircuit = MyCircuit { + let lookup_table: Vec<_> = lookup_table.into_iter().map(F::into_fieldfront).collect(); + + let empty_circuit: MyCircuit = MyCircuit { a: Value::unknown(), lookup_table, }; @@ -480,6 +484,7 @@ fn plonk_api() { R: RngCore, T: TranscriptWriterBuffer, Scheme::Curve, E>, M: MsmAccel, + F: FieldFront + FromUniformBytes<64> + Ord, >( engine: PlonkEngine, rng: R, @@ -490,8 +495,10 @@ fn plonk_api() { Scheme::Scalar: Ord + WithSmallOrderMulGroup<3> + FromUniformBytes<64>, { let (a, instance_val, lookup_table) = common!(Scheme); - - let circuit: MyCircuit = MyCircuit { + let a = F::into_fieldfront(a); + let instance_val = F::into_fieldfront(instance_val); + let lookup_table: Vec<_> = lookup_table.into_iter().map(F::into_fieldfront).collect(); + let circuit: MyCircuit = MyCircuit { a: Value::known(a), lookup_table, }; @@ -499,7 +506,7 @@ fn plonk_api() { let mut transcript = T::init(vec![]); let instance = [vec![vec![instance_val]], vec![vec![instance_val]]]; - create_plonk_proof_with_engine::( + create_plonk_proof_with_engine::( engine, params, pk, @@ -527,6 +534,7 @@ fn plonk_api() { E: EncodedChallenge, R: RngCore, T: TranscriptWriterBuffer, Scheme::Curve, E>, + F: FieldFront + FromUniformBytes<64> + Ord, >( rng: R, params: &'params Scheme::ParamsProver, @@ -536,7 +544,7 @@ fn plonk_api() { Scheme::Scalar: Ord + WithSmallOrderMulGroup<3> + FromUniformBytes<64>, { let engine = PlonkEngineConfig::build_default(); - create_proof_with_engine::(engine, rng, params, pk) + create_proof_with_engine::(engine, rng, params, pk) } fn verify_proof< @@ -547,6 +555,7 @@ fn plonk_api() { E: EncodedChallenge, T: TranscriptReadBuffer<&'a [u8], Scheme::Curve, E>, Strategy: VerificationStrategy<'params, Scheme, V, Output = Strategy>, + F: FieldFront + FromUniformBytes<64> + Ord, >( params_verifier: &'params Scheme::ParamsVerifier, vk: &VerifyingKey, @@ -555,6 +564,7 @@ fn plonk_api() { Scheme::Scalar: Ord + WithSmallOrderMulGroup<3> + FromUniformBytes<64>, { let (_, instance_val, _) = common!(Scheme); + let instance_val = F::into_fieldfront(instance_val); let mut transcript = T::init(proof); let instance = [vec![vec![instance_val]], vec![vec![instance_val]]]; @@ -573,16 +583,22 @@ fn plonk_api() { use halo2curves::bn256::Bn256; type Scheme = KZGCommitmentScheme; + bad_keys!(Scheme); let params = ParamsKZG::::new(K); let rng = OsRng; - let pk = keygen::>(¶ms); + let pk = keygen::, ::Scalar>(¶ms); - let proof = create_proof::<_, ProverGWC<_>, _, _, Blake2bWrite<_, _, Challenge255<_>>>( - rng, ¶ms, &pk, - ); + let proof = create_proof::< + _, + ProverGWC<_>, + _, + _, + Blake2bWrite<_, _, Challenge255<_>>, + ::Scalar, + >(rng, ¶ms, &pk); let verifier_params = params.verifier_params(); @@ -592,6 +608,7 @@ fn plonk_api() { _, Blake2bRead<_, _, Challenge255<_>>, AccumulatorStrategy<_>, + ::Scalar, >(&verifier_params, pk.get_vk(), &proof[..]); } @@ -607,11 +624,16 @@ fn plonk_api() { let params = ParamsKZG::::new(K); let rng = OsRng; - let pk = keygen::>(¶ms); + let pk = keygen::, ::Scalar>(¶ms); - let proof = create_proof::<_, ProverSHPLONK<_>, _, _, Blake2bWrite<_, _, Challenge255<_>>>( - rng, ¶ms, &pk, - ); + let proof = create_proof::< + _, + ProverSHPLONK<_>, + _, + _, + Blake2bWrite<_, _, Challenge255<_>>, + ::Scalar, + >(rng, ¶ms, &pk); let verifier_params = params.verifier_params(); @@ -621,6 +643,7 @@ fn plonk_api() { _, Blake2bRead<_, _, Challenge255<_>>, AccumulatorStrategy<_>, + ::Scalar, >(&verifier_params, pk.get_vk(), &proof[..]); } @@ -636,11 +659,17 @@ fn plonk_api() { let params = ParamsIPA::::new(K); let rng = OsRng; - let pk = keygen::>(¶ms); + let pk = + keygen::, ::Scalar>(¶ms); - let proof = create_proof::<_, ProverIPA<_>, _, _, Blake2bWrite<_, _, Challenge255<_>>>( - rng, ¶ms, &pk, - ); + let proof = create_proof::< + _, + ProverIPA<_>, + _, + _, + Blake2bWrite<_, _, Challenge255<_>>, + ::Scalar, + >(rng, ¶ms, &pk); let verifier_params = params; @@ -650,6 +679,7 @@ fn plonk_api() { _, Blake2bRead<_, _, Challenge255<_>>, AccumulatorStrategy<_>, + ::Scalar, >(&verifier_params, pk.get_vk(), &proof[..]); // Check that the verification key has not changed unexpectedly diff --git a/halo2_proofs/tests/serialization.rsx b/halo2_proofs/tests/serialization.rs similarity index 93% rename from halo2_proofs/tests/serialization.rsx rename to halo2_proofs/tests/serialization.rs index 93dfca7df..4c1c36379 100644 --- a/halo2_proofs/tests/serialization.rsx +++ b/halo2_proofs/tests/serialization.rs @@ -23,7 +23,7 @@ use halo2_proofs::{ }, SerdeFormat, }; -use halo2curves::bn256::{Bn256, Fr, G1Affine}; +use halo2curves::bn256::{self, Bn256, Fr, G1Affine}; use rand_core::OsRng; #[derive(Clone, Copy)] @@ -55,14 +55,7 @@ impl StandardPlonkConfig { let [q_a, q_b, q_c, q_ab, constant] = [q_a, q_b, q_c, q_ab, constant] .map(|column| meta.query_fixed(column, Rotation::cur())); let instance = meta.query_instance(instance, Rotation::cur()); - Some( - q_a * a.clone() - + q_b * b.clone() - + q_c * c - + q_ab * a * b - + constant - + instance, - ) + Some(q_a * a + q_b * b + q_c * c + q_ab * a * b + constant + instance) }, ); @@ -145,7 +138,7 @@ fn test_serialization() { let f = File::open("serialization-test.pk").unwrap(); let mut reader = BufReader::new(f); #[allow(clippy::unit_arg)] - let pk = pk_read::( + let pk = pk_read::( &mut reader, SerdeFormat::RawBytes, k, @@ -165,6 +158,7 @@ fn test_serialization() { _, Blake2bWrite, G1Affine, Challenge255<_>>, _, + bn256::Fr, >( ¶ms, &pk, @@ -185,6 +179,7 @@ fn test_serialization() { Challenge255, Blake2bRead<&[u8], G1Affine, Challenge255>, SingleStrategy, + _, >( &verifier_params, pk.get_vk(), diff --git a/halo2_proofs/tests/shuffle.rsx b/halo2_proofs/tests/shuffle.rsx index 7c35061d3..958a42648 100644 --- a/halo2_proofs/tests/shuffle.rsx +++ b/halo2_proofs/tests/shuffle.rsx @@ -1,7 +1,7 @@ use ff::{BatchInvert, FromUniformBytes}; use halo2_frontend::plonk::FieldFront; use halo2_proofs::{ - arithmetic::{CurveAffine, Field}, + arithmetic::CurveAffine, circuit::{floor_planner::V1, Layouter, Value}, dev::{metadata, FailureLocation, MockProver, VerifyFailure}, halo2curves::pasta::EqAffine, @@ -243,7 +243,7 @@ impl Circuit for MyCircuit, const W: usize, const H: usize>( +fn test_mock_prover, const W: usize, const H: usize>( k: u32, circuit: MyCircuit, expected: Result<(), Vec<(metadata::Constraint, FailureLocation)>>, @@ -270,9 +270,9 @@ fn test_mock_prover, const W: usize, const H: usiz }; } -fn test_prover( +fn test_prover, const W: usize, const H: usize>( k: u32, - circuit: MyCircuit, + circuit: MyCircuit, expected: bool, ) where C::Scalar: FromUniformBytes<64>, @@ -284,7 +284,7 @@ fn test_prover( let proof = { let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); - create_proof::, ProverIPA, _, _, _, _>( + create_proof::, ProverIPA, _, _, _, _, F>( ¶ms, &pk, &[circuit], @@ -301,7 +301,7 @@ fn test_prover( let strategy = AccumulatorStrategy::new(¶ms); let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - verify_proof::, VerifierIPA, _, _, _>( + verify_proof::, VerifierIPA, _, _, _, F>( ¶ms, pk.get_vk(), strategy, @@ -325,7 +325,7 @@ fn test_shuffle() { { test_mock_prover(K, circuit.clone(), Ok(())); - test_prover::(K, circuit.clone(), true); + test_prover::(K, circuit.clone(), true); } #[cfg(not(feature = "sanity-checks"))] @@ -349,6 +349,6 @@ fn test_shuffle() { }, )]), ); - test_prover::(K, circuit, false); + test_prover::(K, circuit, false); } } diff --git a/halo2_proofs/tests/shuffle_api.rsx b/halo2_proofs/tests/shuffle_api.rs similarity index 94% rename from halo2_proofs/tests/shuffle_api.rsx rename to halo2_proofs/tests/shuffle_api.rs index e3368fa5b..595705737 100644 --- a/halo2_proofs/tests/shuffle_api.rsx +++ b/halo2_proofs/tests/shuffle_api.rs @@ -2,13 +2,11 @@ use std::{marker::PhantomData, vec}; use ff::FromUniformBytes; use halo2_proofs::{ - arithmetic::Field, circuit::{Layouter, SimpleFloorPlanner, Value}, plonk::{ create_proof, keygen_pk, keygen_vk, verify_proof, Advice, Circuit, Column, - ConstraintSystem, ErrorFront, Fixed, Selector, + ConstraintSystem, ErrorFront, FieldFront, Fixed, Selector, }, - poly::Rotation, poly::{ commitment::ParamsProver, ipa::{ @@ -16,7 +14,7 @@ use halo2_proofs::{ multiopen::{ProverIPA, VerifierIPA}, strategy::AccumulatorStrategy, }, - VerificationStrategy, + Rotation, VerificationStrategy, }, transcript::{ Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, @@ -65,7 +63,7 @@ impl ShuffleChip { let shuffle_0 = meta.query_advice(shuffle_0, Rotation::cur()); let shuffle_1 = meta.query_advice(shuffle_1, Rotation::cur()); vec![ - (s_input.clone() * input_0, s_shuffle.clone() * shuffle_0), + (s_input * input_0, s_shuffle * shuffle_0), (s_input * input_1, s_shuffle * shuffle_1), ] }); @@ -148,8 +146,11 @@ impl Circuit for MyCircuit { } } -fn test_prover(k: u32, circuit: MyCircuit, expected: bool) -where +fn test_prover>( + k: u32, + circuit: MyCircuit, + expected: bool, +) where C::Scalar: FromUniformBytes<64>, { let params = ParamsIPA::::new(k); @@ -159,7 +160,7 @@ where let proof = { let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); - create_proof::, ProverIPA, _, _, _, _>( + create_proof::, ProverIPA, _, _, _, _, F>( ¶ms, &pk, &[circuit], @@ -176,7 +177,7 @@ where let strategy = AccumulatorStrategy::new(¶ms); let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - verify_proof::, VerifierIPA, _, _, _>( + verify_proof::, VerifierIPA, _, _, _, F>( ¶ms, pk.get_vk(), strategy, @@ -213,5 +214,5 @@ fn test_shuffle_api() { }; let prover = MockProver::run(K, &circuit, vec![]).unwrap(); prover.assert_satisfied(); - test_prover::(K, circuit, true); + test_prover::(K, circuit, true); } diff --git a/halo2_proofs/tests/vector-ops-unblinded.rsx b/halo2_proofs/tests/vector-ops-unblinded.rs similarity index 97% rename from halo2_proofs/tests/vector-ops-unblinded.rsx rename to halo2_proofs/tests/vector-ops-unblinded.rs index b33689b07..81fe7f8b9 100644 --- a/halo2_proofs/tests/vector-ops-unblinded.rsx +++ b/halo2_proofs/tests/vector-ops-unblinded.rs @@ -6,7 +6,7 @@ use std::marker::PhantomData; use ff::FromUniformBytes; use halo2_frontend::plonk::FieldFront; use halo2_proofs::{ - arithmetic::{CurveAffine, Field}, + arithmetic::CurveAffine, circuit::{AssignedCell, Chip, Layouter, Region, SimpleFloorPlanner, Value}, plonk::*, poly::{ @@ -467,11 +467,11 @@ impl Circuit for AddCircuit { } // ANCHOR_END: circuit -fn test_prover>( +fn test_prover>( k: u32, - circuit: impl Circuit, + circuit: impl Circuit, expected: bool, - instances: Vec, + instances: Vec, ) -> Vec where C::Scalar: FromUniformBytes<64>, @@ -484,7 +484,7 @@ where let proof = { let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); - create_proof::, ProverIPA, _, _, _, _, C::ScalarExt>( + create_proof::, ProverIPA, _, _, _, _, F>( ¶ms, &pk, &[circuit], @@ -501,7 +501,7 @@ where let strategy = AccumulatorStrategy::new(¶ms); let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); - verify_proof::, VerifierIPA, _, _, _>( + verify_proof::, VerifierIPA, _, _, _, F>( ¶ms, pk.get_vk(), strategy, @@ -546,9 +546,9 @@ fn test_vector_ops_unbinded() { }; // the commitments will be the first columns of the proof transcript so we can compare them easily - let proof_1 = test_prover::(k, mul_circuit, true, c_mul); + let proof_1 = test_prover::(k, mul_circuit, true, c_mul); // the commitments will be the first columns of the proof transcript so we can compare them easily - let proof_2 = test_prover::(k, add_circuit, true, c_add); + let proof_2 = test_prover::(k, add_circuit, true, c_add); // the commitments will be the first columns of the proof transcript so we can compare them easily // here we compare the first 10 bytes of the commitments