From 4bac5150d62d195d1e26126277465fee908652e2 Mon Sep 17 00:00:00 2001 From: zhenfei Date: Mon, 23 Oct 2023 15:56:45 -0400 Subject: [PATCH] fix examples --- snark-verifier-sdk/examples/k_as_witness.rs | 7 +- snark-verifier-sdk/src/evm.rs | 12 +- snark-verifier-sdk/src/file_io.rs | 82 ----- snark-verifier-sdk/src/halo2.rs | 23 +- snark-verifier-sdk/src/halo2_api.rs | 322 ------------------ snark-verifier-sdk/src/lib.rs | 2 + snark-verifier-sdk/src/param.rs | 10 - snark-verifier-sdk/src/snark.rs | 68 ---- snark-verifier-sdk/src/snarks.rs | 68 ---- snark-verifier-sdk/src/tests/evm_verifier.rs | 11 +- snark-verifier-sdk/src/tests/mod.rs | 4 +- .../src/tests/single_layer_aggregation.rs | 32 +- .../src/tests/test_circuit_1.rs | 3 +- .../src/tests/test_circuit_2.rs | 3 +- snark-verifier-sdk/src/types.rs | 52 --- 15 files changed, 64 insertions(+), 635 deletions(-) delete mode 100644 snark-verifier-sdk/src/file_io.rs delete mode 100644 snark-verifier-sdk/src/halo2_api.rs delete mode 100644 snark-verifier-sdk/src/param.rs delete mode 100644 snark-verifier-sdk/src/snark.rs delete mode 100644 snark-verifier-sdk/src/snarks.rs delete mode 100644 snark-verifier-sdk/src/types.rs diff --git a/snark-verifier-sdk/examples/k_as_witness.rs b/snark-verifier-sdk/examples/k_as_witness.rs index e9994d8d..a4c3ce6f 100644 --- a/snark-verifier-sdk/examples/k_as_witness.rs +++ b/snark-verifier-sdk/examples/k_as_witness.rs @@ -116,7 +116,12 @@ mod application { config.q_ab, config.constant, ]) { - region.assign_fixed(|| "", column, 1, ||Value::known(Fr::from(idx as u64))); + region.assign_fixed( + || "", + column, + 1, + || Value::known(Fr::from(idx as u64)), + ); } let a = region.assign_advice(|| "", config.a, 2, || Value::known(Fr::one()))?; a.copy_advice(|| "", &mut region, config.b, 3); diff --git a/snark-verifier-sdk/src/evm.rs b/snark-verifier-sdk/src/evm.rs index 0b24db4c..01287527 100644 --- a/snark-verifier-sdk/src/evm.rs +++ b/snark-verifier-sdk/src/evm.rs @@ -19,7 +19,7 @@ use halo2_base::halo2_proofs::{ transcript::{TranscriptReadBuffer, TranscriptWriterBuffer}, }; use itertools::Itertools; -use rand::{rngs::StdRng, SeedableRng}; +use rand::{rngs::StdRng, Rng, SeedableRng}; pub use snark_verifier::loader::evm::encode_calldata; use snark_verifier::{ loader::evm::{compile_solidity, deploy_and_call, EvmLoader}, @@ -38,6 +38,7 @@ pub fn gen_evm_proof<'params, C, P, V>( pk: &'params ProvingKey, circuit: C, instances: Vec>, + rng: &mut (impl Rng + Send), ) -> Vec where C: Circuit, @@ -53,7 +54,6 @@ where #[cfg(feature = "display")] let proof_time = start_timer!(|| "Create EVM proof"); - let rng = StdRng::from_entropy(); let proof = { let mut transcript = TranscriptWriterBuffer::<_, G1Affine, _>::init(Vec::new()); create_proof::, P, _, _, EvmTranscript<_, _, _, _>, _>( @@ -93,8 +93,9 @@ pub fn gen_evm_proof_gwc<'params, C: Circuit>( pk: &'params ProvingKey, circuit: C, instances: Vec>, + rng: &mut (impl Rng + Send), ) -> Vec { - gen_evm_proof::, VerifierGWC<_>>(params, pk, circuit, instances) + gen_evm_proof::, VerifierGWC<_>>(params, pk, circuit, instances, rng) } pub fn gen_evm_proof_shplonk<'params, C: Circuit>( @@ -102,8 +103,9 @@ pub fn gen_evm_proof_shplonk<'params, C: Circuit>( pk: &'params ProvingKey, circuit: C, instances: Vec>, + rng: &mut (impl Rng + Send), ) -> Vec { - gen_evm_proof::, VerifierSHPLONK<_>>(params, pk, circuit, instances) + gen_evm_proof::, VerifierSHPLONK<_>>(params, pk, circuit, instances, rng) } pub trait EvmKzgAccumulationScheme = PolynomialCommitmentScheme< @@ -185,4 +187,4 @@ pub fn write_calldata(instances: &[Vec], proof: &[u8], path: &Path) -> io::R let calldata = hex::encode(calldata); fs::write(path, &calldata)?; Ok(calldata) -} \ No newline at end of file +} diff --git a/snark-verifier-sdk/src/file_io.rs b/snark-verifier-sdk/src/file_io.rs deleted file mode 100644 index bdc707cb..00000000 --- a/snark-verifier-sdk/src/file_io.rs +++ /dev/null @@ -1,82 +0,0 @@ -use std::{ - fs::{write, File}, - io::{BufReader, BufWriter}, - path::Path, -}; - -use halo2_base::halo2_proofs::{ - halo2curves::bn256::{Fr, G1Affine}, - plonk::{Circuit, ProvingKey}, - SerdeFormat, -}; -use itertools::Itertools; -use snark_verifier::loader::evm::encode_calldata; - -use crate::Snark; - -/// Read instances from the disk -pub fn read_instances(path: impl AsRef) -> Result>, bincode::Error> { - let f = File::open(path)?; - let reader = BufReader::new(f); - let instances: Vec> = bincode::deserialize_from(reader)?; - instances - .into_iter() - .map(|instance_column| { - instance_column - .iter() - .map(|bytes| { - Option::from(Fr::from_bytes(bytes)).ok_or(Box::new(bincode::ErrorKind::Custom( - "Invalid finite field point".to_owned(), - ))) - }) - .collect::, _>>() - }) - .collect() -} - -/// Write instances to the disk -pub fn write_instances(instances: &[&[Fr]], path: impl AsRef) { - let instances: Vec> = instances - .iter() - .map(|instance_column| instance_column.iter().map(|x| x.to_bytes()).collect_vec()) - .collect_vec(); - let f = BufWriter::new(File::create(path).unwrap()); - bincode::serialize_into(f, &instances).unwrap(); -} - -/// Read proving key from the disk -pub fn read_pk>(path: &Path) -> std::io::Result> { - let f = File::open(path)?; - #[cfg(feature = "display")] - let read_time = start_timer!(|| format!("Reading pkey from {path:?}")); - - // BufReader is indeed MUCH faster than Read - let mut bufreader = BufReader::new(f); - // But it's even faster to load the whole file into memory first and then process, - // HOWEVER this requires twice as much memory to initialize - // let initial_buffer_size = f.metadata().map(|m| m.len() as usize + 1).unwrap_or(0); - // let mut bufreader = Vec::with_capacity(initial_buffer_size); - // f.read_to_end(&mut bufreader)?; - let pk = ProvingKey::read::<_, C>(&mut bufreader, SerdeFormat::RawBytesUnchecked).unwrap(); - - #[cfg(feature = "display")] - end_timer!(read_time); - - Ok(pk) -} - -/// Tries to deserialize a SNARK from the specified `path` using `bincode`. -/// -/// WARNING: The user must keep track of whether the SNARK was generated using the GWC or SHPLONK multi-open scheme. -pub fn read_snark(path: impl AsRef) -> Result { - let f = File::open(path).map_err(Box::::from)?; - bincode::deserialize_from(f) -} - -/// Write the calldata to disk -pub fn write_calldata(instances: &[Vec], proof: &[u8], path: &Path) -> std::io::Result { - let calldata = encode_calldata(instances, proof); - let calldata = hex::encode(calldata); - write(path, &calldata)?; - Ok(calldata) -} \ No newline at end of file diff --git a/snark-verifier-sdk/src/halo2.rs b/snark-verifier-sdk/src/halo2.rs index 52c87407..92bb7518 100644 --- a/snark-verifier-sdk/src/halo2.rs +++ b/snark-verifier-sdk/src/halo2.rs @@ -26,7 +26,7 @@ use halo2_proofs::{ }; use itertools::Itertools; use lazy_static::lazy_static; -use rand::{rngs::StdRng, SeedableRng}; +use rand::{rngs::StdRng, Rng, SeedableRng}; use snark_verifier::{ cost::CostEstimation, loader::native::NativeLoader, @@ -81,6 +81,7 @@ pub fn gen_proof<'params, C, P, V>( pk: &ProvingKey, circuit: C, instances: Vec>, + rng: &mut (impl Rng + Send), path: Option<(&Path, &Path)>, ) -> Vec where @@ -114,7 +115,6 @@ where let mut transcript = PoseidonTranscript::>::from_spec(vec![], POSEIDON_SPEC.clone()); - let rng = StdRng::from_entropy(); create_proof::<_, P, _, _, _, _>(params, pk, &[circuit], &[&instances], rng, &mut transcript) .unwrap(); let proof = transcript.finalize(); @@ -159,9 +159,11 @@ pub fn gen_proof_gwc>( pk: &ProvingKey, circuit: C, instances: Vec>, + + rng: &mut (impl Rng + Send), path: Option<(&Path, &Path)>, ) -> Vec { - gen_proof::, VerifierGWC<_>>(params, pk, circuit, instances, path) + gen_proof::, VerifierGWC<_>>(params, pk, circuit, instances, rng, path) } /// Generates a native proof using SHPLONK multi-open scheme. Uses Poseidon for Fiat-Shamir. @@ -172,9 +174,11 @@ pub fn gen_proof_shplonk>( pk: &ProvingKey, circuit: C, instances: Vec>, + + rng: &mut (impl Rng + Send), path: Option<(&Path, &Path)>, ) -> Vec { - gen_proof::, VerifierSHPLONK<_>>(params, pk, circuit, instances, path) + gen_proof::, VerifierSHPLONK<_>>(params, pk, circuit, instances, rng, path) } /// Generates a SNARK using either SHPLONK or GWC multi-open scheme. Uses Poseidon for Fiat-Shamir. @@ -185,6 +189,7 @@ pub fn gen_snark<'params, ConcreteCircuit, P, V>( params: &'params ParamsKZG, pk: &ProvingKey, circuit: ConcreteCircuit, + rng: &mut (impl Rng + Send), path: Option>, ) -> Snark where @@ -222,7 +227,7 @@ where (format!("{path}.instances"), format!("{path}.proof")) }); let paths = path.as_ref().map(|path| (Path::new(&path.0), Path::new(&path.1))); - gen_proof::(params, pk, circuit, instances.clone(), paths) + gen_proof::(params, pk, circuit, instances.clone(), rng, paths) }; let snark = Snark::new(protocol, instances, proof); @@ -247,9 +252,10 @@ pub fn gen_snark_gwc>( params: &ParamsKZG, pk: &ProvingKey, circuit: ConcreteCircuit, + rng: &mut (impl Rng + Send), path: Option>, ) -> Snark { - gen_snark::, VerifierGWC<_>>(params, pk, circuit, path) + gen_snark::, VerifierGWC<_>>(params, pk, circuit, rng, path) } /// Generates a SNARK using SHPLONK multi-open scheme. Uses Poseidon for Fiat-Shamir. @@ -260,9 +266,12 @@ pub fn gen_snark_shplonk>( params: &ParamsKZG, pk: &ProvingKey, circuit: ConcreteCircuit, + rng: &mut (impl Rng + Send), path: Option>, ) -> Snark { - gen_snark::, VerifierSHPLONK<_>>(params, pk, circuit, path) + gen_snark::, VerifierSHPLONK<_>>( + params, pk, circuit, rng, path, + ) } /// Tries to deserialize a SNARK from the specified `path` using `bincode`. diff --git a/snark-verifier-sdk/src/halo2_api.rs b/snark-verifier-sdk/src/halo2_api.rs deleted file mode 100644 index 2a444b92..00000000 --- a/snark-verifier-sdk/src/halo2_api.rs +++ /dev/null @@ -1,322 +0,0 @@ -use std::{ - fs::{self, File}, - io::BufWriter, - path::Path, -}; - -use crate::{ - circuit_ext::CircuitExt, - file_io::{read_pk, read_snark}, - read_instances, - types::{PoseidonTranscript, POSEIDON_SPEC}, - write_instances, Snark, -}; - -#[cfg(feature = "display")] -use ark_std::end_timer; -#[cfg(feature = "display")] -use ark_std::start_timer; -use halo2_base::halo2_proofs::{ - halo2curves::bn256::{Bn256, Fr, G1Affine}, - plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, Circuit, ProvingKey, VerifyingKey}, - poly::{ - commitment::{ParamsProver, Prover, Verifier}, - kzg::{ - commitment::{KZGCommitmentScheme, ParamsKZG}, - msm::DualMSM, - multiopen::{ProverGWC, ProverSHPLONK, VerifierGWC, VerifierSHPLONK}, - strategy::{AccumulatorStrategy, GuardKZG, SingleStrategy}, - }, - VerificationStrategy, - }, - transcript::TranscriptReadBuffer, - SerdeFormat, {self}, -}; -use itertools::Itertools; -use rand::Rng; -use snark_verifier::{ - loader::native::NativeLoader, - system::halo2::{compile, Config}, -}; - -#[allow(clippy::let_and_return)] -pub fn gen_pk>( - params: &ParamsKZG, // TODO: read pk without params - circuit: &C, - path: Option<&Path>, -) -> ProvingKey { - if let Some(path) = path { - if let Ok(pk) = read_pk::(path) { - return pk; - } - } - #[cfg(feature = "display")] - let pk_time = start_timer!(|| "Generating vkey & pkey"); - - let vk = keygen_vk(params, circuit).unwrap(); - let pk = keygen_pk(params, vk, circuit).unwrap(); - - #[cfg(feature = "display")] - end_timer!(pk_time); - - if let Some(path) = path { - #[cfg(feature = "display")] - let write_time = start_timer!(|| format!("Writing pkey to {path:?}")); - - path.parent().and_then(|dir| fs::create_dir_all(dir).ok()).unwrap(); - let mut f = BufWriter::new(File::create(path).unwrap()); - pk.write(&mut f, SerdeFormat::RawBytesUnchecked).unwrap(); - - #[cfg(feature = "display")] - end_timer!(write_time); - } - pk -} - -/// Generates a native proof using either SHPLONK or GWC proving method. Uses Poseidon for Fiat-Shamir. -/// -/// Caches the instances and proof if `path = Some(instance_path, proof_path)` is specified. -pub fn gen_proof<'params, C, P, V>( - // TODO: pass Option<&'params ParamsKZG> but hard to get lifetimes to work with `Cow` - params: &'params ParamsKZG, - pk: &ProvingKey, - circuit: C, - instances: Vec>, - rng: &mut (impl Rng + Send), - path: Option<(&Path, &Path)>, -) -> Vec -where - C: Circuit, - P: Prover<'params, KZGCommitmentScheme>, - V: Verifier< - 'params, - KZGCommitmentScheme, - Guard = GuardKZG<'params, Bn256>, - MSMAccumulator = DualMSM<'params, Bn256>, - >, -{ - /* - #[cfg(debug_assertions)] - { - use halo2_proofs::poly::commitment::Params; - halo2_proofs::dev::MockProver::run(params.k(), &circuit, instances.clone()) - .unwrap() - .assert_satisfied_par(); - } - */ - - if let Some((instance_path, proof_path)) = path { - let cached_instances = read_instances(instance_path); - if matches!(cached_instances, Ok(tmp) if tmp == instances) && proof_path.exists() { - #[cfg(feature = "display")] - let read_time = start_timer!(|| format!("Reading proof from {proof_path:?}")); - - let proof = fs::read(proof_path).unwrap(); - - #[cfg(feature = "display")] - end_timer!(read_time); - return proof; - } - } - - let instances = instances.iter().map(Vec::as_slice).collect_vec(); - - #[cfg(feature = "display")] - let proof_time = start_timer!(|| "Create proof"); - - let mut transcript = - PoseidonTranscript::>::from_spec(vec![], POSEIDON_SPEC.clone()); - create_proof::<_, P, _, _, _, _>(params, pk, &[circuit], &[&instances], rng, &mut transcript) - .unwrap(); - let proof = transcript.finalize(); - - #[cfg(feature = "display")] - end_timer!(proof_time); - - if let Some((instance_path, proof_path)) = path { - write_instances(&instances, instance_path); - fs::write(proof_path, &proof).unwrap(); - } - - debug_assert!({ - let mut transcript_read = PoseidonTranscript::::new(proof.as_slice()); - VerificationStrategy::<_, V>::finalize( - verify_proof::<_, V, _, _, _>( - params.verifier_params(), - pk.get_vk(), - AccumulatorStrategy::new(params.verifier_params()), - &[instances.as_slice()], - &mut transcript_read, - ) - .unwrap(), - ) - }); - - proof -} - -/// Generates a native proof using original Plonk (GWC '19) multi-open scheme. Uses Poseidon for Fiat-Shamir. -/// -/// Caches the instances and proof if `path = Some(instance_path, proof_path)` is specified. -pub fn gen_proof_gwc>( - params: &ParamsKZG, - pk: &ProvingKey, - circuit: C, - instances: Vec>, - rng: &mut (impl Rng + Send), - path: Option<(&Path, &Path)>, -) -> Vec { - gen_proof::, VerifierGWC<_>>(params, pk, circuit, instances, rng, path) -} - -/// Generates a native proof using SHPLONK multi-open scheme. Uses Poseidon for Fiat-Shamir. -/// -/// Caches the instances and proof if `path` is specified. -pub fn gen_proof_shplonk>( - params: &ParamsKZG, - pk: &ProvingKey, - circuit: C, - instances: Vec>, - rng: &mut (impl Rng + Send), - path: Option<(&Path, &Path)>, -) -> Vec { - gen_proof::, VerifierSHPLONK<_>>(params, pk, circuit, instances, rng, path) -} - -/// Generates a SNARK using either SHPLONK or GWC multi-open scheme. Uses Poseidon for Fiat-Shamir. -/// -/// Tries to first deserialize from / later serialize the entire SNARK into `path` if specified. -/// Serialization is done using `bincode`. -pub fn gen_snark<'params, ConcreteCircuit, P, V>( - params: &'params ParamsKZG, - pk: &ProvingKey, - circuit: ConcreteCircuit, - rng: &mut (impl Rng + Send), - path: Option>, -) -> Snark -where - ConcreteCircuit: CircuitExt, - P: Prover<'params, KZGCommitmentScheme>, - V: Verifier< - 'params, - KZGCommitmentScheme, - Guard = GuardKZG<'params, Bn256>, - MSMAccumulator = DualMSM<'params, Bn256>, - >, -{ - if let Some(path) = &path { - if let Ok(snark) = read_snark(path) { - return snark; - } - } - let protocol = compile( - params, - pk.get_vk(), - Config::kzg() - .with_num_instance(circuit.num_instance()) - .with_accumulator_indices(ConcreteCircuit::accumulator_indices()), - ); - - let instances = circuit.instances(); - let proof = - gen_proof::(params, pk, circuit, instances.clone(), rng, None); - - let snark = Snark::new(protocol, instances, proof); - if let Some(path) = &path { - let f = File::create(path).unwrap(); - #[cfg(feature = "display")] - let write_time = start_timer!(|| "Write SNARK"); - bincode::serialize_into(f, &snark).unwrap(); - #[cfg(feature = "display")] - end_timer!(write_time); - } - snark -} - -/// Generates a SNARK using GWC multi-open scheme. Uses Poseidon for Fiat-Shamir. -/// -/// Tries to first deserialize from / later serialize the entire SNARK into `path` if specified. -/// Serialization is done using `bincode`. -pub fn gen_snark_gwc>( - params: &ParamsKZG, - pk: &ProvingKey, - circuit: ConcreteCircuit, - rng: &mut (impl Rng + Send), - path: Option>, -) -> Snark { - gen_snark::, VerifierGWC<_>>(params, pk, circuit, rng, path) -} - -/// Generates a SNARK using SHPLONK multi-open scheme. Uses Poseidon for Fiat-Shamir. -/// -/// Tries to first deserialize from / later serialize the entire SNARK into `path` if specified. -/// Serialization is done using `bincode`. -pub fn gen_snark_shplonk>( - params: &ParamsKZG, - pk: &ProvingKey, - circuit: ConcreteCircuit, - rng: &mut (impl Rng + Send), - path: Option>, -) -> Snark { - gen_snark::, VerifierSHPLONK<_>>( - params, pk, circuit, rng, path, - ) -} - -/// Verifies a native proof using either SHPLONK or GWC proving method. Uses Poseidon for Fiat-Shamir. -/// -pub fn verify_snark<'params, ConcreteCircuit, V>( - verifier_params: &'params ParamsKZG, - snark: Snark, - vk: &VerifyingKey, -) -> bool -where - ConcreteCircuit: CircuitExt, - V: Verifier< - 'params, - KZGCommitmentScheme, - Guard = GuardKZG<'params, Bn256>, - MSMAccumulator = DualMSM<'params, Bn256>, - >, -{ - let mut transcript: PoseidonTranscript<_, _> = - TranscriptReadBuffer::<_, G1Affine, _>::init(snark.proof.as_slice()); - let strategy = SingleStrategy::new(verifier_params); - let instance_slice = snark.instances.iter().map(|x| &x[..]).collect::>(); - match verify_proof::<_, V, _, _, _>( - verifier_params, - vk, - strategy, - &[instance_slice.as_slice()], - &mut transcript, - ) { - Ok(_p) => true, - Err(_e) => false, - } -} - -/// Verifies a native proof using SHPLONK proving method. Uses Poseidon for Fiat-Shamir. -/// -pub fn verify_snark_shplonk( - verifier_params: &ParamsKZG, - snark: Snark, - vk: &VerifyingKey, -) -> bool -where - ConcreteCircuit: CircuitExt, -{ - verify_snark::>(verifier_params, snark, vk) -} - -/// Verifies a native proof using GWC proving method. Uses Poseidon for Fiat-Shamir. -/// -pub fn verify_snark_gwc( - verifier_params: &ParamsKZG, - snark: Snark, - vk: &VerifyingKey, -) -> bool -where - ConcreteCircuit: CircuitExt, -{ - verify_snark::>(verifier_params, snark, vk) -} \ No newline at end of file diff --git a/snark-verifier-sdk/src/lib.rs b/snark-verifier-sdk/src/lib.rs index 40401a4c..aca538a9 100644 --- a/snark-verifier-sdk/src/lib.rs +++ b/snark-verifier-sdk/src/lib.rs @@ -29,6 +29,8 @@ use std::{ pub mod evm; #[cfg(feature = "loader_halo2")] pub mod halo2; +#[cfg(test)] +mod tests; pub const LIMBS: usize = 3; pub const BITS: usize = 88; diff --git a/snark-verifier-sdk/src/param.rs b/snark-verifier-sdk/src/param.rs deleted file mode 100644 index de3d0194..00000000 --- a/snark-verifier-sdk/src/param.rs +++ /dev/null @@ -1,10 +0,0 @@ -/// Number of limbs for non-native field decomposition -pub const LIMBS: usize = 3; -/// Number of bits for each limb. -pub const BITS: usize = 88; - -// Poseidon parameters -pub(crate) const T: usize = 5; -pub(crate) const RATE: usize = 4; -pub(crate) const R_F: usize = 8; -pub(crate) const R_P: usize = 60; \ No newline at end of file diff --git a/snark-verifier-sdk/src/snark.rs b/snark-verifier-sdk/src/snark.rs deleted file mode 100644 index fdb5c351..00000000 --- a/snark-verifier-sdk/src/snark.rs +++ /dev/null @@ -1,68 +0,0 @@ -use halo2_base::halo2_proofs; -use halo2_proofs::{ - circuit::Value, - halo2curves::bn256::{Fr, G1Affine}, -}; -use itertools::Itertools; -use serde::{Deserialize, Serialize}; -use snark_verifier::PlonkProtocol; - -mod mock; - -pub use mock::gen_dummy_snark; - -/// A Snark struct is all one may need to generate witnesses for an aggregation circuit. -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Snark { - pub protocol: PlonkProtocol, - pub instances: Vec>, - pub proof: Vec, -} - -impl Snark { - pub fn new(protocol: PlonkProtocol, instances: Vec>, proof: Vec) -> Self { - Self { protocol, instances, proof } - } -} - -impl From for SnarkWitness { - fn from(snark: Snark) -> Self { - Self { - protocol: snark.protocol, - instances: snark - .instances - .into_iter() - .map(|instances| instances.into_iter().map(Value::known).collect_vec()) - .collect(), - proof: Value::known(snark.proof), - } - } -} - -/// A SnarkWitness struct is a snark converted to witness. -#[derive(Clone, Debug)] -pub struct SnarkWitness { - pub protocol: PlonkProtocol, - pub instances: Vec>>, - pub proof: Value>, -} - -impl SnarkWitness { - /// Initialize an empty SnarkWitness with a same struct as self. - pub fn without_witnesses(&self) -> Self { - SnarkWitness { - protocol: self.protocol.clone(), - instances: self - .instances - .iter() - .map(|instances| vec![Value::unknown(); instances.len()]) - .collect(), - proof: Value::unknown(), - } - } - - /// Expose the proof of the witness. - pub fn proof(&self) -> Value<&[u8]> { - self.proof.as_ref().map(Vec::as_slice) - } -} \ No newline at end of file diff --git a/snark-verifier-sdk/src/snarks.rs b/snark-verifier-sdk/src/snarks.rs deleted file mode 100644 index 0ccfeb02..00000000 --- a/snark-verifier-sdk/src/snarks.rs +++ /dev/null @@ -1,68 +0,0 @@ -use halo2_base::halo2_proofs; -use halo2_proofs::{ - circuit::Value, - halo2curves::bn256::{Fr, G1Affine}, -}; -use itertools::Itertools; -use serde::{Deserialize, Serialize}; -use snark_verifier::Protocol; - -mod mock; - -pub use mock::gen_dummy_snark; - -/// A Snark struct is all one may need to generate witnesses for an aggregation circuit. -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct Snark { - pub protocol: Protocol, - pub instances: Vec>, - pub proof: Vec, -} - -impl Snark { - pub fn new(protocol: Protocol, instances: Vec>, proof: Vec) -> Self { - Self { protocol, instances, proof } - } -} - -impl From for SnarkWitness { - fn from(snark: Snark) -> Self { - Self { - protocol: snark.protocol, - instances: snark - .instances - .into_iter() - .map(|instances| instances.into_iter().map(Value::known).collect_vec()) - .collect(), - proof: Value::known(snark.proof), - } - } -} - -/// A SnarkWitness struct is a snark converted to witness. -#[derive(Clone, Debug)] -pub struct SnarkWitness { - pub protocol: Protocol, - pub instances: Vec>>, - pub proof: Value>, -} - -impl SnarkWitness { - /// Initialize an empty SnarkWitness with a same struct as self. - pub fn without_witnesses(&self) -> Self { - SnarkWitness { - protocol: self.protocol.clone(), - instances: self - .instances - .iter() - .map(|instances| vec![Value::unknown(); instances.len()]) - .collect(), - proof: Value::unknown(), - } - } - - /// Expose the proof of the witness. - pub fn proof(&self) -> Value<&[u8]> { - self.proof.as_ref().map(Vec::as_slice) - } -} \ No newline at end of file diff --git a/snark-verifier-sdk/src/tests/evm_verifier.rs b/snark-verifier-sdk/src/tests/evm_verifier.rs index 047bb8bc..e2e41dc7 100644 --- a/snark-verifier-sdk/src/tests/evm_verifier.rs +++ b/snark-verifier-sdk/src/tests/evm_verifier.rs @@ -1,15 +1,14 @@ use super::TestCircuit1; use crate::{ - evm_api::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier}, - halo2_api::gen_pk, - CircuitExt, + evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier}, + gen_pk, CircuitExt, }; use ark_std::test_rng; use halo2_base::halo2_proofs; use halo2_proofs::halo2curves::bn256::Bn256; use snark_verifier::{ loader::halo2::halo2_ecc::halo2_base::utils::fs::gen_srs, - pcs::kzg::{Bdfg21, Kzg}, + pcs::kzg::{Bdfg21, KzgAs}, }; #[test] @@ -21,7 +20,7 @@ fn test_evm_verification() { let circuit = TestCircuit1::rand(&mut rng); let pk = gen_pk(¶ms, &circuit, None); - let deployment_code = gen_evm_verifier::>( + let deployment_code = gen_evm_verifier::>( ¶ms, pk.get_vk(), circuit.num_instance(), @@ -31,4 +30,4 @@ fn test_evm_verification() { let instances = circuit.instances(); let proof = gen_evm_proof_shplonk(¶ms, &pk, circuit.clone(), instances.clone(), &mut rng); evm_verify(deployment_code.clone(), circuit.instances(), proof) -} \ No newline at end of file +} diff --git a/snark-verifier-sdk/src/tests/mod.rs b/snark-verifier-sdk/src/tests/mod.rs index 090ff9c4..e7d588df 100644 --- a/snark-verifier-sdk/src/tests/mod.rs +++ b/snark-verifier-sdk/src/tests/mod.rs @@ -11,7 +11,7 @@ mod evm_verifier; mod single_layer_aggregation; mod test_circuit_1; mod test_circuit_2; -mod two_layer_aggregation; +// mod two_layer_aggregation; #[derive(Clone, Copy)] pub struct StandardPlonkConfig { @@ -55,4 +55,4 @@ impl StandardPlonkConfig { StandardPlonkConfig { a, b, c, q_a, q_b, q_c, q_ab, constant, instance } } -} \ No newline at end of file +} diff --git a/snark-verifier-sdk/src/tests/single_layer_aggregation.rs b/snark-verifier-sdk/src/tests/single_layer_aggregation.rs index ead5a77b..36e39dc8 100644 --- a/snark-verifier-sdk/src/tests/single_layer_aggregation.rs +++ b/snark-verifier-sdk/src/tests/single_layer_aggregation.rs @@ -1,16 +1,16 @@ use super::{TestCircuit1, TestCircuit2}; use crate::{ - aggregation::aggregation_circuit::AggregationCircuit, - evm_api::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier}, - halo2_api::{gen_pk, gen_snark_shplonk}, - CircuitExt, + evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier}, + gen_pk, + halo2::{gen_snark_shplonk, aggregation::{AggregationCircuit, AggregationConfigParams, VerifierUniversality}}, + CircuitExt, SHPLONK, }; use ark_std::test_rng; -use halo2_base::halo2_proofs; +use halo2_base::{halo2_proofs, gates::circuit::CircuitBuilderStage}; use halo2_proofs::{halo2curves::bn256::Bn256, poly::commitment::Params}; use snark_verifier::{ loader::halo2::halo2_ecc::halo2_base::utils::fs::gen_srs, - pcs::kzg::{Bdfg21, Kzg}, + pcs::kzg::{Bdfg21, KzgAs}, }; use std::path::Path; @@ -66,9 +66,21 @@ fn test_shplonk_then_sphplonk_with_evm_verification() { // aggregation circuit let snarks = vec![snarks_1, snarks_2, snarks_3]; - let agg_circuit = AggregationCircuit::new(¶ms_outer, snarks, &mut rng); + // let agg_circuit = AggregationCircuit::new(¶ms_outer, snarks, &mut rng); + + let mut agg_circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + AggregationConfigParams { degree: k, lookup_bits:20, ..Default::default() }, + ¶ms_outer, + snarks, + VerifierUniversality::PreprocessedAsWitness, + ); + let _agg_config = agg_circuit.calculate_params(Some(10)); + let pk_outer = gen_pk(¶ms_outer, &agg_circuit, Some(Path::new("data/outer.pkey"))); - println!("finished outer pk generation"); + let _break_points = agg_circuit.break_points(); + + println!("finished outer pk generation"); let instances = agg_circuit.instances(); let proof = gen_evm_proof_shplonk( ¶ms_outer, @@ -79,7 +91,7 @@ fn test_shplonk_then_sphplonk_with_evm_verification() { ); println!("finished aggregation generation"); - let deployment_code = gen_evm_verifier::>( + let deployment_code = gen_evm_verifier::>( ¶ms_outer, pk_outer.get_vk(), agg_circuit.num_instance(), @@ -88,4 +100,4 @@ fn test_shplonk_then_sphplonk_with_evm_verification() { println!("finished bytecode generation"); evm_verify(deployment_code, instances, proof) -} \ No newline at end of file +} diff --git a/snark-verifier-sdk/src/tests/test_circuit_1.rs b/snark-verifier-sdk/src/tests/test_circuit_1.rs index 36d55680..7b9de8d3 100644 --- a/snark-verifier-sdk/src/tests/test_circuit_1.rs +++ b/snark-verifier-sdk/src/tests/test_circuit_1.rs @@ -31,6 +31,7 @@ impl CircuitExt for TestCircuit1 { impl Circuit for TestCircuit1 { type Config = StandardPlonkConfig; type FloorPlanner = SimpleFloorPlanner; + type Params = (); fn without_witnesses(&self) -> Self { Self::default() @@ -70,4 +71,4 @@ impl Circuit for TestCircuit1 { }, ) } -} \ No newline at end of file +} diff --git a/snark-verifier-sdk/src/tests/test_circuit_2.rs b/snark-verifier-sdk/src/tests/test_circuit_2.rs index 4fb23dad..36b9d952 100644 --- a/snark-verifier-sdk/src/tests/test_circuit_2.rs +++ b/snark-verifier-sdk/src/tests/test_circuit_2.rs @@ -31,6 +31,7 @@ impl CircuitExt for TestCircuit2 { impl Circuit for TestCircuit2 { type Config = StandardPlonkConfig; type FloorPlanner = SimpleFloorPlanner; + type Params = (); fn without_witnesses(&self) -> Self { Self::default() @@ -65,4 +66,4 @@ impl Circuit for TestCircuit2 { }, ) } -} \ No newline at end of file +} diff --git a/snark-verifier-sdk/src/types.rs b/snark-verifier-sdk/src/types.rs deleted file mode 100644 index e0220499..00000000 --- a/snark-verifier-sdk/src/types.rs +++ /dev/null @@ -1,52 +0,0 @@ -//! This module concretize generic types with Bn256 curve and BDFG KZG scheme. - -use super::{BITS, LIMBS}; -use halo2_base::halo2_proofs::halo2curves::bn256::{Bn256, Fr, G1Affine}; -use lazy_static::lazy_static; -use snark_verifier::{ - loader::halo2::{halo2_ecc::ecc::BaseFieldEccChip as EccChip, Halo2Loader as Loader}, - pcs::kzg::{ - Bdfg21, Kzg, KzgAs as KzgAccumulationScheme, KzgSuccinctVerifyingKey, LimbsEncoding, - }, - verifier, PoseidonSpec, -}; - -use crate::param::{RATE, R_F, R_P, T}; - -lazy_static! { - pub static ref POSEIDON_SPEC: PoseidonSpec = PoseidonSpec::new(R_F, R_P); -} - -/// Transcript instantiated with Poseidon -pub type PoseidonTranscript = - snark_verifier::system::halo2::transcript::halo2::PoseidonTranscript< - G1Affine, - L, - S, - T, - RATE, - R_F, - R_P, - >; - -/// Plonk configured with AS. -/// AS is either `Kzg` or `Kzg` -pub type PlonkVerifier = verifier::plonk::PlonkVerifier>; - -/// KZG instantiated with BDFG21 -pub type KzgBDFG = Kzg; - -/// Accumulator scheme build from KZG over BDFG21 scheme -pub type KzgAs = KzgAccumulationScheme; - -/// SHPlonk -pub type Shplonk = Plonk; - -/// KZG succinct verifying key. -pub type Svk = KzgSuccinctVerifyingKey; - -/// Non-native arithmetic chip -pub type BaseFieldEccChip = EccChip; - -/// Halo2 loader -pub type Halo2Loader<'a> = Loader<'a, G1Affine, BaseFieldEccChip>; \ No newline at end of file