diff --git a/evm/src/cross_table_lookup.rs b/evm/src/cross_table_lookup.rs index 28dae98c..15e186aa 100644 --- a/evm/src/cross_table_lookup.rs +++ b/evm/src/cross_table_lookup.rs @@ -8,7 +8,6 @@ use plonky2::field::packed::PackedField; use plonky2::field::polynomial::PolynomialValues; use plonky2::field::types::Field; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; use plonky2::plonk::circuit_builder::CircuitBuilder; @@ -328,10 +327,7 @@ impl<'a, F: RichField + Extendable, const D: usize> cross_table_lookups: &'a [CrossTableLookup], ctl_challenges: &'a GrandProductChallengeSet, num_permutation_zs: &[usize; NUM_TABLES], - ) -> [Vec; NUM_TABLES] - where - [(); C::HCO::WIDTH]:, - { + ) -> [Vec; NUM_TABLES] { let mut ctl_zs = proofs .iter() .zip(num_permutation_zs) diff --git a/evm/src/fixed_recursive_verifier.rs b/evm/src/fixed_recursive_verifier.rs index 2e6f01aa..483aaf54 100644 --- a/evm/src/fixed_recursive_verifier.rs +++ b/evm/src/fixed_recursive_verifier.rs @@ -3,12 +3,11 @@ use std::collections::BTreeMap; use std::ops::Range; use hashbrown::HashMap; -use itertools::Itertools; +use itertools::{zip_eq, Itertools}; use plonky2::field::extension::Extendable; use plonky2::fri::FriParams; use plonky2::gates::noop::NoopGate; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::challenger::RecursiveChallenger; use plonky2::iop::target::{BoolTarget, Target}; use plonky2::iop::witness::{PartialWitness, WitnessWrite}; @@ -16,7 +15,7 @@ use plonky2::plonk::circuit_builder::CircuitBuilder; use plonky2::plonk::circuit_data::{ CircuitConfig, CircuitData, CommonCircuitData, VerifierCircuitTarget, }; -use plonky2::plonk::config::{AlgebraicHasher, GenericConfig, Hasher}; +use plonky2::plonk::config::{AlgebraicHasher, GenericConfig}; use plonky2::plonk::proof::{ProofWithPublicInputs, ProofWithPublicInputsTarget}; use plonky2::recursion::cyclic_recursion::check_cyclic_proof_verifier_data; use plonky2::recursion::dummy_circuit::cyclic_base_proof; @@ -56,7 +55,7 @@ pub struct AllRecursiveCircuits where F: RichField + Extendable, C: GenericConfig, - [(); C::HCO::WIDTH]:, + C::Hasher: AlgebraicHasher, { /// The EVM root circuit, which aggregates the (shrunk) per-table recursive proofs. pub root: RootCircuitData, @@ -265,15 +264,12 @@ impl AllRecursiveCircuits where F: RichField + Extendable, C: GenericConfig + 'static, - C::Hasher: AlgebraicHasher, - [(); C::Hasher::HASH_SIZE]:, + C::Hasher: AlgebraicHasher, [(); CpuStark::::COLUMNS]:, [(); KeccakStark::::COLUMNS]:, [(); KeccakSpongeStark::::COLUMNS]:, [(); LogicStark::::COLUMNS]:, [(); MemoryStark::::COLUMNS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { pub fn to_bytes( &self, @@ -401,14 +397,14 @@ where let recursive_proofs = core::array::from_fn(|i| builder.add_virtual_proof_with_pis(inner_common_data[i])); let pis: [_; NUM_TABLES] = core::array::from_fn(|i| { - PublicInputs::::from_vec( + PublicInputs::>::AlgebraicPermutation>::from_vec( &recursive_proofs[i].public_inputs, stark_config, ) }); let index_verifier_data = core::array::from_fn(|_i| builder.add_virtual_target()); - let mut challenger = RecursiveChallenger::::new(&mut builder); + let mut challenger = RecursiveChallenger::::new(&mut builder); for pi in &pis { for h in &pi.trace_cap { challenger.observe_elements(h); @@ -434,16 +430,16 @@ where } let state = challenger.compact(&mut builder); - for k in 0..C::HCO::WIDTH { - builder.connect(state[k], pis[0].challenger_state_before[k]); + for (&before, &s) in zip_eq(state.as_ref(), pis[0].challenger_state_before.as_ref()) { + builder.connect(before, s); } // Check that the challenger state is consistent between proofs. for i in 1..NUM_TABLES { - for k in 0..C::HCO::WIDTH { - builder.connect( - pis[i].challenger_state_before[k], - pis[i - 1].challenger_state_after[k], - ); + for (&before, &after) in zip_eq( + pis[i].challenger_state_before.as_ref(), + pis[i - 1].challenger_state_after.as_ref(), + ) { + builder.connect(before, after); } } @@ -701,7 +697,7 @@ pub struct RecursiveCircuitsForTable where F: RichField + Extendable, C: GenericConfig, - [(); C::HCO::WIDTH]:, + C::Hasher: AlgebraicHasher, { /// A map from `log_2(height)` to a chain of shrinking recursion circuits starting at that /// height. @@ -712,10 +708,7 @@ impl RecursiveCircuitsForTable where F: RichField + Extendable, C: GenericConfig, - C::Hasher: AlgebraicHasher, - [(); C::Hasher::HASH_SIZE]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { pub fn to_buffer( &self, @@ -800,7 +793,7 @@ struct RecursiveCircuitsForTableSize where F: RichField + Extendable, C: GenericConfig, - [(); C::HCO::WIDTH]:, + C::Hasher: AlgebraicHasher, { initial_wrapper: StarkWrapperCircuit, shrinking_wrappers: Vec>, @@ -810,10 +803,7 @@ impl RecursiveCircuitsForTableSize where F: RichField + Extendable, C: GenericConfig, - C::Hasher: AlgebraicHasher, - [(); C::Hasher::HASH_SIZE]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { pub fn to_buffer( &self, diff --git a/evm/src/get_challenges.rs b/evm/src/get_challenges.rs index 6bccb48d..d5816e64 100644 --- a/evm/src/get_challenges.rs +++ b/evm/src/get_challenges.rs @@ -1,7 +1,6 @@ use plonky2::field::extension::Extendable; use plonky2::fri::proof::{FriProof, FriProofTarget}; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::challenger::{Challenger, RecursiveChallenger}; use plonky2::plonk::circuit_builder::CircuitBuilder; use plonky2::plonk::config::{AlgebraicHasher, GenericConfig}; @@ -14,21 +13,14 @@ use crate::permutation::{ }; use crate::proof::*; -impl, C: GenericConfig, const D: usize> AllProof -where - [(); C::HCO::WIDTH]:, -{ +impl, C: GenericConfig, const D: usize> AllProof { /// Computes all Fiat-Shamir challenges used in the STARK proof. pub(crate) fn get_challenges( &self, all_stark: &AllStark, config: &StarkConfig, - ) -> AllProofChallenges - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { - let mut challenger = Challenger::::new(); + ) -> AllProofChallenges { + let mut challenger = Challenger::::new(); for proof in &self.stark_proofs { challenger.observe_cap(&proof.proof.trace_cap); @@ -61,12 +53,8 @@ where &self, all_stark: &AllStark, config: &StarkConfig, - ) -> AllChallengerState - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { - let mut challenger = Challenger::::new(); + ) -> AllChallengerState { + let mut challenger = Challenger::::new(); for proof in &self.stark_proofs { challenger.observe_cap(&proof.proof.trace_cap); @@ -106,15 +94,11 @@ where /// Computes all Fiat-Shamir challenges used in the STARK proof. pub(crate) fn get_challenges( &self, - challenger: &mut Challenger, + challenger: &mut Challenger, stark_use_permutation: bool, stark_permutation_batch_size: usize, config: &StarkConfig, - ) -> StarkProofChallenges - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> StarkProofChallenges { let degree_bits = self.recover_degree_bits(config); let StarkProof { @@ -169,15 +153,13 @@ impl StarkProofTarget { pub(crate) fn get_challenges, C: GenericConfig>( &self, builder: &mut CircuitBuilder, - challenger: &mut RecursiveChallenger, + challenger: &mut RecursiveChallenger, stark_use_permutation: bool, stark_permutation_batch_size: usize, config: &StarkConfig, ) -> StarkProofChallengesTarget where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let StarkProofTarget { permutation_ctl_zs_cap, diff --git a/evm/src/permutation.rs b/evm/src/permutation.rs index 72078c93..35d6ee61 100644 --- a/evm/src/permutation.rs +++ b/evm/src/permutation.rs @@ -9,7 +9,6 @@ use plonky2::field::packed::PackedField; use plonky2::field::polynomial::PolynomialValues; use plonky2::field::types::Field; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::challenger::{Challenger, RecursiveChallenger}; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; @@ -201,38 +200,29 @@ fn poly_product_elementwise( product } -fn get_grand_product_challenge>( - challenger: &mut Challenger, -) -> GrandProductChallenge -where - [(); HC::WIDTH]:, -{ +fn get_grand_product_challenge>( + challenger: &mut Challenger, +) -> GrandProductChallenge { let beta = challenger.get_challenge(); let gamma = challenger.get_challenge(); GrandProductChallenge { beta, gamma } } -pub(crate) fn get_grand_product_challenge_set>( - challenger: &mut Challenger, +pub(crate) fn get_grand_product_challenge_set>( + challenger: &mut Challenger, num_challenges: usize, -) -> GrandProductChallengeSet -where - [(); HC::WIDTH]:, -{ +) -> GrandProductChallengeSet { let challenges = (0..num_challenges) .map(|_| get_grand_product_challenge(challenger)) .collect(); GrandProductChallengeSet { challenges } } -pub(crate) fn get_n_grand_product_challenge_sets>( - challenger: &mut Challenger, +pub(crate) fn get_n_grand_product_challenge_sets>( + challenger: &mut Challenger, num_challenges: usize, num_sets: usize, -) -> Vec> -where - [(); HC::WIDTH]:, -{ +) -> Vec> { (0..num_sets) .map(|_| get_grand_product_challenge_set(challenger, num_challenges)) .collect() @@ -240,16 +230,12 @@ where fn get_grand_product_challenge_target< F: RichField + Extendable, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, const D: usize, >( builder: &mut CircuitBuilder, - challenger: &mut RecursiveChallenger, -) -> GrandProductChallenge -where - [(); HC::WIDTH]:, -{ + challenger: &mut RecursiveChallenger, +) -> GrandProductChallenge { let beta = challenger.get_challenge(builder); let gamma = challenger.get_challenge(builder); GrandProductChallenge { beta, gamma } @@ -257,17 +243,13 @@ where pub(crate) fn get_grand_product_challenge_set_target< F: RichField + Extendable, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, const D: usize, >( builder: &mut CircuitBuilder, - challenger: &mut RecursiveChallenger, + challenger: &mut RecursiveChallenger, num_challenges: usize, -) -> GrandProductChallengeSet -where - [(); HC::WIDTH]:, -{ +) -> GrandProductChallengeSet { let challenges = (0..num_challenges) .map(|_| get_grand_product_challenge_target(builder, challenger)) .collect(); @@ -276,18 +258,14 @@ where pub(crate) fn get_n_grand_product_challenge_sets_target< F: RichField + Extendable, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, const D: usize, >( builder: &mut CircuitBuilder, - challenger: &mut RecursiveChallenger, + challenger: &mut RecursiveChallenger, num_challenges: usize, num_sets: usize, -) -> Vec> -where - [(); HC::WIDTH]:, -{ +) -> Vec> { (0..num_sets) .map(|_| get_grand_product_challenge_set_target(builder, challenger, num_challenges)) .collect() diff --git a/evm/src/proof.rs b/evm/src/proof.rs index 0fefcc0c..33133efc 100644 --- a/evm/src/proof.rs +++ b/evm/src/proof.rs @@ -7,11 +7,10 @@ use plonky2::fri::structure::{ FriOpeningBatch, FriOpeningBatchTarget, FriOpenings, FriOpeningsTarget, }; use plonky2::hash::hash_types::{MerkleCapTarget, RichField}; -use plonky2::hash::hashing::HashConfig; use plonky2::hash::merkle_tree::MerkleCap; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; -use plonky2::plonk::config::GenericConfig; +use plonky2::plonk::config::{GenericConfig, Hasher}; use plonky2::util::serialization::{Buffer, IoResult, Read, Write}; use plonky2_maybe_rayon::*; use serde::{Deserialize, Serialize}; @@ -22,19 +21,13 @@ use crate::permutation::GrandProductChallengeSet; /// A STARK proof for each table, plus some metadata used to create recursive wrapper proofs. #[derive(Debug, Clone)] -pub struct AllProof, C: GenericConfig, const D: usize> -where - [(); C::HCO::WIDTH]:, -{ +pub struct AllProof, C: GenericConfig, const D: usize> { pub stark_proofs: [StarkProofWithMetadata; NUM_TABLES], pub(crate) ctl_challenges: GrandProductChallengeSet, pub public_values: PublicValues, } -impl, C: GenericConfig, const D: usize> AllProof -where - [(); C::HCO::WIDTH]:, -{ +impl, C: GenericConfig, const D: usize> AllProof { pub fn degree_bits(&self, config: &StarkConfig) -> [usize; NUM_TABLES] { core::array::from_fn(|i| self.stark_proofs[i].proof.recover_degree_bits(config)) } @@ -46,13 +39,10 @@ pub(crate) struct AllProofChallenges, const D: usiz } #[allow(unused)] // TODO: should be used soon -pub(crate) struct AllChallengerState, HC: HashConfig, const D: usize> -where - [(); HC::WIDTH]:, -{ +pub(crate) struct AllChallengerState, H: Hasher, const D: usize> { /// Sponge state of the challenger before starting each proof, /// along with the final state after all proofs are done. This final state isn't strictly needed. - pub states: [[F; HC::WIDTH]; NUM_TABLES + 1], + pub states: [H::Permutation; NUM_TABLES + 1], pub ctl_challenges: GrandProductChallengeSet, } @@ -109,15 +99,15 @@ pub struct BlockMetadataTarget { #[derive(Debug, Clone)] pub struct StarkProof, C: GenericConfig, const D: usize> { /// Merkle cap of LDEs of trace values. - pub trace_cap: MerkleCap, + pub trace_cap: MerkleCap, /// Merkle cap of LDEs of permutation Z values. - pub permutation_ctl_zs_cap: MerkleCap, + pub permutation_ctl_zs_cap: MerkleCap, /// Merkle cap of LDEs of trace values. - pub quotient_polys_cap: MerkleCap, + pub quotient_polys_cap: MerkleCap, /// Purported values of each polynomial at the challenge point. pub openings: StarkOpeningSet, /// A batch FRI argument for all openings. - pub opening_proof: FriProof, + pub opening_proof: FriProof, } /// A `StarkProof` along with some metadata about the initial Fiat-Shamir state, which is used when @@ -127,9 +117,8 @@ pub struct StarkProofWithMetadata where F: RichField + Extendable, C: GenericConfig, - [(); C::HCO::WIDTH]:, { - pub(crate) init_challenger_state: [F; C::HCO::WIDTH], + pub(crate) init_challenger_state: >::Permutation, pub(crate) proof: StarkProof, } diff --git a/evm/src/prover.rs b/evm/src/prover.rs index 63e44b3b..9f087c69 100644 --- a/evm/src/prover.rs +++ b/evm/src/prover.rs @@ -11,9 +11,8 @@ use plonky2::field::types::Field; use plonky2::field::zero_poly_coset::ZeroPolyOnCoset; use plonky2::fri::oracle::PolynomialBatch; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::challenger::Challenger; -use plonky2::plonk::config::{GenericConfig, Hasher}; +use plonky2::plonk::config::GenericConfig; use plonky2::timed; use plonky2::util::timing::TimingTree; use plonky2::util::transpose; @@ -56,9 +55,6 @@ where [(); KeccakSpongeStark::::COLUMNS]:, [(); LogicStark::::COLUMNS]:, [(); MemoryStark::::COLUMNS]:, - [(); C::Hasher::HASH_SIZE]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let (proof, _outputs) = prove_with_outputs(all_stark, config, inputs, timing)?; Ok(proof) @@ -75,14 +71,11 @@ pub fn prove_with_outputs( where F: RichField + Extendable, C: GenericConfig, - [(); C::Hasher::HASH_SIZE]:, [(); CpuStark::::COLUMNS]:, [(); KeccakStark::::COLUMNS]:, [(); KeccakSpongeStark::::COLUMNS]:, [(); LogicStark::::COLUMNS]:, [(); MemoryStark::::COLUMNS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { timed!(timing, "build kernel", Lazy::force(&KERNEL)); let (traces, public_values, outputs) = timed!( @@ -110,9 +103,6 @@ where [(); KeccakSpongeStark::::COLUMNS]:, [(); LogicStark::::COLUMNS]:, [(); MemoryStark::::COLUMNS]:, - [(); C::Hasher::HASH_SIZE]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let rate_bits = config.fri_config.rate_bits; let cap_height = config.fri_config.cap_height; @@ -146,7 +136,7 @@ where .iter() .map(|c| c.merkle_tree.cap.clone()) .collect::>(); - let mut challenger = Challenger::::new(); + let mut challenger = Challenger::::new(); for cap in &trace_caps { challenger.observe_cap(cap); } @@ -189,20 +179,17 @@ fn prove_with_commitments( trace_poly_values: [Vec>; NUM_TABLES], trace_commitments: Vec>, ctl_data_per_table: [CtlData; NUM_TABLES], - challenger: &mut Challenger, + challenger: &mut Challenger, timing: &mut TimingTree, ) -> Result<[StarkProofWithMetadata; NUM_TABLES]> where F: RichField + Extendable, C: GenericConfig, - [(); C::Hasher::HASH_SIZE]:, [(); CpuStark::::COLUMNS]:, [(); KeccakStark::::COLUMNS]:, [(); KeccakSpongeStark::::COLUMNS]:, [(); LogicStark::::COLUMNS]:, [(); MemoryStark::::COLUMNS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let cpu_proof = timed!( timing, @@ -285,7 +272,7 @@ pub(crate) fn prove_single_table( trace_poly_values: &[PolynomialValues], trace_commitment: &PolynomialBatch, ctl_data: &CtlData, - challenger: &mut Challenger, + challenger: &mut Challenger, timing: &mut TimingTree, ) -> Result> where @@ -293,8 +280,6 @@ where C: GenericConfig, S: Stark, [(); S::COLUMNS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let degree = trace_poly_values[0].len(); let degree_bits = log2_strict(degree); diff --git a/evm/src/recursive_verifier.rs b/evm/src/recursive_verifier.rs index 9da9281a..477d36c2 100644 --- a/evm/src/recursive_verifier.rs +++ b/evm/src/recursive_verifier.rs @@ -1,7 +1,6 @@ use std::fmt::Debug; use anyhow::{ensure, Result}; -use itertools::Itertools; use plonky2::field::extension::Extendable; use plonky2::field::types::Field; use plonky2::fri::witness_util::set_fri_proof_target; @@ -9,14 +8,14 @@ use plonky2::gates::exponentiation::ExponentiationGate; use plonky2::gates::gate::GateRef; use plonky2::gates::noop::NoopGate; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; +use plonky2::hash::hashing::PlonkyPermutation; use plonky2::iop::challenger::{Challenger, RecursiveChallenger}; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; use plonky2::iop::witness::{PartialWitness, Witness, WitnessWrite}; use plonky2::plonk::circuit_builder::CircuitBuilder; use plonky2::plonk::circuit_data::{CircuitConfig, CircuitData, VerifierCircuitData}; -use plonky2::plonk::config::{AlgebraicHasher, GenericConfig}; +use plonky2::plonk::config::{AlgebraicHasher, GenericConfig, Hasher}; use plonky2::plonk::proof::{ProofWithPublicInputs, ProofWithPublicInputsTarget}; use plonky2::util::reducing::ReducingFactorTarget; use plonky2::util::serialization::{ @@ -52,35 +51,25 @@ pub struct RecursiveAllProof< pub recursive_proofs: [ProofWithPublicInputs; NUM_TABLES], } -pub(crate) struct PublicInputs -where - [(); HC::WIDTH]:, +pub(crate) struct PublicInputs> { pub(crate) trace_cap: Vec>, pub(crate) ctl_zs_last: Vec, pub(crate) ctl_challenges: GrandProductChallengeSet, - pub(crate) challenger_state_before: [T; HC::WIDTH], - pub(crate) challenger_state_after: [T; HC::WIDTH], + pub(crate) challenger_state_before: P, + pub(crate) challenger_state_after: P, } -/// Similar to the unstable `Iterator::next_chunk`. Could be replaced with that when it's stable. -fn next_chunk(iter: &mut impl Iterator) -> [T; N] { - (0..N) - .flat_map(|_| iter.next()) - .collect_vec() - .try_into() - .expect("Not enough elements") -} - -impl PublicInputs -where - [(); HC::WIDTH]:, -{ +impl> PublicInputs { pub(crate) fn from_vec(v: &[T], config: &StarkConfig) -> Self { - let mut iter = v.iter().copied(); - let trace_cap = (0..config.fri_config.num_cap_elements()) - .map(|_| next_chunk::<_, 4>(&mut iter).to_vec()) - .collect(); + // TODO: Document magic number 4; probably comes from + // Ethereum 256 bits = 4 * Goldilocks 64 bits + let nelts = config.fri_config.num_cap_elements(); + let mut trace_cap = Vec::with_capacity(nelts); + for i in 0..nelts { + trace_cap.push(v[4 * i..4 * (i + 1)].to_vec()); + } + let mut iter = v.iter().copied().skip(4 * nelts); let ctl_challenges = GrandProductChallengeSet { challenges: (0..config.num_challenges) .map(|_| GrandProductChallenge { @@ -89,8 +78,8 @@ where }) .collect(), }; - let challenger_state_before = next_chunk(&mut iter); - let challenger_state_after = next_chunk(&mut iter); + let challenger_state_before = P::new(&mut iter); + let challenger_state_after = P::new(&mut iter); let ctl_zs_last: Vec<_> = iter.collect(); Self { @@ -112,19 +101,15 @@ impl, C: GenericConfig, const D: usize> verifier_data: &[VerifierCircuitData; NUM_TABLES], cross_table_lookups: Vec>, inner_config: &StarkConfig, - ) -> Result<()> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> Result<()> { let pis: [_; NUM_TABLES] = core::array::from_fn(|i| { - PublicInputs::::from_vec( + PublicInputs::>::Permutation>::from_vec( &self.recursive_proofs[i].public_inputs, inner_config, ) }); - let mut challenger = Challenger::::new(); + let mut challenger = Challenger::::new(); for pi in &pis { for h in &pi.trace_cap { challenger.observe_elements(h); @@ -165,12 +150,13 @@ pub(crate) struct StarkWrapperCircuit where F: RichField + Extendable, C: GenericConfig, - [(); C::HCO::WIDTH]:, + C::Hasher: AlgebraicHasher, { pub(crate) circuit: CircuitData, pub(crate) stark_proof_target: StarkProofTarget, pub(crate) ctl_challenges_target: GrandProductChallengeSet, - pub(crate) init_challenger_state_target: [Target; C::HCO::WIDTH], + pub(crate) init_challenger_state_target: + >::AlgebraicPermutation, pub(crate) zero_target: Target, } @@ -178,9 +164,7 @@ impl StarkWrapperCircuit where F: RichField + Extendable, C: GenericConfig, - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { pub fn to_buffer( &self, @@ -189,7 +173,7 @@ where generator_serializer: &dyn WitnessGeneratorSerializer, ) -> IoResult<()> { buffer.write_circuit_data(&self.circuit, gate_serializer, generator_serializer)?; - buffer.write_target_vec(&self.init_challenger_state_target)?; + buffer.write_target_vec(self.init_challenger_state_target.as_ref())?; buffer.write_target(self.zero_target)?; self.stark_proof_target.to_buffer(buffer)?; self.ctl_challenges_target.to_buffer(buffer)?; @@ -202,7 +186,9 @@ where generator_serializer: &dyn WitnessGeneratorSerializer, ) -> IoResult { let circuit = buffer.read_circuit_data(gate_serializer, generator_serializer)?; - let init_challenger_state_target = buffer.read_target_vec()?; + let target_vec = buffer.read_target_vec()?; + let init_challenger_state_target = + >::AlgebraicPermutation::new(target_vec.into_iter()); let zero_target = buffer.read_target()?; let stark_proof_target = StarkProofTarget::from_buffer(buffer)?; let ctl_challenges_target = GrandProductChallengeSet::from_buffer(buffer)?; @@ -210,7 +196,7 @@ where circuit, stark_proof_target, ctl_challenges_target, - init_challenger_state_target: init_challenger_state_target.try_into().unwrap(), + init_challenger_state_target, zero_target, }) } @@ -240,8 +226,8 @@ where } inputs.set_target_arr( - self.init_challenger_state_target, - proof_with_metadata.init_challenger_state, + self.init_challenger_state_target.as_ref(), + proof_with_metadata.init_challenger_state.as_ref(), ); self.circuit.prove(inputs) @@ -263,9 +249,7 @@ impl PlonkWrapperCircuit where F: RichField + Extendable, C: GenericConfig, - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { pub(crate) fn prove( &self, @@ -294,9 +278,7 @@ pub(crate) fn recursive_stark_circuit< ) -> StarkWrapperCircuit where [(); S::COLUMNS]:, - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let mut builder = CircuitBuilder::::new(circuit_config.clone()); let zero_target = builder.zero(); @@ -333,9 +315,12 @@ where num_permutation_zs, ); - let init_challenger_state_target = core::array::from_fn(|_| builder.add_virtual_public_input()); + let init_challenger_state_target = + >::AlgebraicPermutation::new(std::iter::from_fn(|| { + Some(builder.add_virtual_public_input()) + })); let mut challenger = - RecursiveChallenger::::from_state(init_challenger_state_target); + RecursiveChallenger::::from_state(init_challenger_state_target); let challenges = proof_target.get_challenges::( &mut builder, &mut challenger, @@ -344,7 +329,7 @@ where inner_config, ); let challenger_state = challenger.compact(&mut builder); - builder.register_public_inputs(&challenger_state); + builder.register_public_inputs(challenger_state.as_ref()); builder.register_public_inputs(&proof_target.openings.ctl_zs_last); @@ -399,9 +384,8 @@ fn verify_stark_proof_with_challenges_circuit< ctl_vars: &[CtlCheckVarsTarget], inner_config: &StarkConfig, ) where - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, [(); S::COLUMNS]:, - [(); C::HCO::WIDTH]:, { let zero = builder.zero(); let one = builder.one_extension(); @@ -620,7 +604,7 @@ pub(crate) fn set_stark_proof_target, W, const D: zero: Target, ) where F: RichField + Extendable, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, W: Witness, { witness.set_cap_target(&proof_target.trace_cap, &proof.trace_cap); @@ -674,16 +658,16 @@ pub(crate) fn set_trie_roots_target( W: Witness, { witness.set_target_arr( - trie_roots_target.state_root, - h256_limbs(trie_roots.state_root), + &trie_roots_target.state_root, + &h256_limbs(trie_roots.state_root), ); witness.set_target_arr( - trie_roots_target.transactions_root, - h256_limbs(trie_roots.transactions_root), + &trie_roots_target.transactions_root, + &h256_limbs(trie_roots.transactions_root), ); witness.set_target_arr( - trie_roots_target.receipts_root, - h256_limbs(trie_roots.receipts_root), + &trie_roots_target.receipts_root, + &h256_limbs(trie_roots.receipts_root), ); } @@ -696,8 +680,8 @@ pub(crate) fn set_block_metadata_target( W: Witness, { witness.set_target_arr( - block_metadata_target.block_beneficiary, - h160_limbs(block_metadata.block_beneficiary), + &block_metadata_target.block_beneficiary, + &h160_limbs(block_metadata.block_beneficiary), ); witness.set_target( block_metadata_target.block_timestamp, diff --git a/evm/src/stark_testing.rs b/evm/src/stark_testing.rs index c8d5fed5..e005d2ea 100644 --- a/evm/src/stark_testing.rs +++ b/evm/src/stark_testing.rs @@ -3,11 +3,11 @@ use plonky2::field::extension::{Extendable, FieldExtension}; use plonky2::field::polynomial::{PolynomialCoeffs, PolynomialValues}; use plonky2::field::types::{Field, Sample}; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; +use plonky2::hash::hashing::PlonkyPermutation; use plonky2::iop::witness::{PartialWitness, WitnessWrite}; use plonky2::plonk::circuit_builder::CircuitBuilder; use plonky2::plonk::circuit_data::CircuitConfig; -use plonky2::plonk::config::GenericConfig; +use plonky2::plonk::config::{GenericConfig, Hasher}; use plonky2::util::transpose; use plonky2_util::{log2_ceil, log2_strict}; @@ -87,8 +87,8 @@ pub fn test_stark_circuit_constraints< ) -> Result<()> where [(); S::COLUMNS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + [(); >::Permutation::WIDTH]:, + [(); >::Permutation::WIDTH]:, { // Compute native constraint evaluation on random values. let vars = StarkEvaluationVars { diff --git a/evm/src/verifier.rs b/evm/src/verifier.rs index eb91cfe9..807ca203 100644 --- a/evm/src/verifier.rs +++ b/evm/src/verifier.rs @@ -5,7 +5,6 @@ use plonky2::field::extension::{Extendable, FieldExtension}; use plonky2::field::types::Field; use plonky2::fri::verifier::verify_fri_proof; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::plonk::config::GenericConfig; use plonky2::plonk::plonk_common::reduce_with_powers; @@ -37,8 +36,6 @@ where [(); KeccakSpongeStark::::COLUMNS]:, [(); LogicStark::::COLUMNS]:, [(); MemoryStark::::COLUMNS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let AllProofChallenges { stark_challenges, @@ -120,7 +117,6 @@ pub(crate) fn verify_stark_proof_with_challenges< ) -> Result<()> where [(); S::COLUMNS]:, - [(); C::HCO::WIDTH]:, { log::debug!("Checking proof: {}", type_name::()); validate_proof_shape(stark, proof, config, ctl_vars.len())?; diff --git a/plonky2/benches/hashing.rs b/plonky2/benches/hashing.rs index ef433112..cf64b764 100644 --- a/plonky2/benches/hashing.rs +++ b/plonky2/benches/hashing.rs @@ -6,16 +6,14 @@ use plonky2::field::types::Sample; use plonky2::hash::hash_types::{BytesHash, RichField}; use plonky2::hash::keccak::KeccakHash; use plonky2::hash::poseidon::{Poseidon, SPONGE_WIDTH}; -use plonky2::plonk::config::{Hasher, KeccakHashConfig}; +use plonky2::plonk::config::Hasher; use tynm::type_name; pub(crate) fn bench_keccak(c: &mut Criterion) { c.bench_function("keccak256", |b| { b.iter_batched( || (BytesHash::<32>::rand(), BytesHash::<32>::rand()), - |(left, right)| { - as Hasher>::two_to_one(left, right) - }, + |(left, right)| as Hasher>::two_to_one(left, right), BatchSize::SmallInput, ) }); diff --git a/plonky2/benches/merkle.rs b/plonky2/benches/merkle.rs index 11d73b8c..f9bae127 100644 --- a/plonky2/benches/merkle.rs +++ b/plonky2/benches/merkle.rs @@ -1,23 +1,17 @@ -#![feature(generic_const_exprs)] - mod allocator; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use plonky2::field::goldilocks_field::GoldilocksField; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::hash::keccak::KeccakHash; use plonky2::hash::merkle_tree::MerkleTree; use plonky2::hash::poseidon::PoseidonHash; -use plonky2::plonk::config::{Hasher, KeccakHashConfig, PoseidonHashConfig}; +use plonky2::plonk::config::Hasher; use tynm::type_name; const ELEMS_PER_LEAF: usize = 135; -pub(crate) fn bench_merkle_tree>(c: &mut Criterion) -where - [(); HC::WIDTH]:, -{ +pub(crate) fn bench_merkle_tree>(c: &mut Criterion) { let mut group = c.benchmark_group(&format!( "merkle-tree<{}, {}>", type_name::(), @@ -29,14 +23,14 @@ where let size = 1 << size_log; group.bench_with_input(BenchmarkId::from_parameter(size), &size, |b, _| { let leaves = vec![F::rand_vec(ELEMS_PER_LEAF); size]; - b.iter(|| MerkleTree::::new(leaves.clone(), 0)); + b.iter(|| MerkleTree::::new(leaves.clone(), 0)); }); } } fn criterion_benchmark(c: &mut Criterion) { - bench_merkle_tree::(c); - bench_merkle_tree::>(c); + bench_merkle_tree::(c); + bench_merkle_tree::>(c); } criterion_group!(benches, criterion_benchmark); diff --git a/plonky2/examples/bench_recursion.rs b/plonky2/examples/bench_recursion.rs index ccee9f74..f2a3f2cb 100644 --- a/plonky2/examples/bench_recursion.rs +++ b/plonky2/examples/bench_recursion.rs @@ -3,8 +3,6 @@ // put it in `src/bin/`, but then we wouldn't have access to // `[dev-dependencies]`. -#![feature(generic_const_exprs)] -#![allow(incomplete_features)] #![allow(clippy::upper_case_acronyms)] use core::num::ParseIntError; @@ -15,7 +13,6 @@ use anyhow::{anyhow, Context as _, Result}; use log::{info, Level, LevelFilter}; use plonky2::gates::noop::NoopGate; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::witness::{PartialWitness, WitnessWrite}; use plonky2::plonk::circuit_builder::CircuitBuilder; use plonky2::plonk::circuit_data::{CircuitConfig, CommonCircuitData, VerifierOnlyCircuitData}; @@ -68,11 +65,7 @@ struct Options { fn dummy_proof, C: GenericConfig, const D: usize>( config: &CircuitConfig, log2_size: usize, -) -> Result> -where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, -{ +) -> Result> { // 'size' is in degree, but we want number of noop gates. A non-zero amount of padding will be added and size will be rounded to the next power of two. To hit our target size, we go just under the previous power of two and hope padding is less than half the proof. let num_dummy_gates = match log2_size { 0 => return Err(anyhow!("size must be at least 1")), @@ -109,11 +102,7 @@ fn recursive_proof< min_degree_bits: Option, ) -> Result> where - InnerC::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - [(); InnerC::HCO::WIDTH]:, - [(); InnerC::HCI::WIDTH]:, + InnerC::Hasher: AlgebraicHasher, { let (inner_proof, inner_vd, inner_cd) = inner; let mut builder = CircuitBuilder::::new(config.clone()); @@ -155,11 +144,7 @@ fn test_serialization, C: GenericConfig, proof: &ProofWithPublicInputs, vd: &VerifierOnlyCircuitData, cd: &CommonCircuitData, -) -> Result<()> -where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, -{ +) -> Result<()> { let proof_bytes = proof.to_bytes(); info!("Proof length: {} bytes", proof_bytes.len()); let proof_from_bytes = ProofWithPublicInputs::from_bytes(proof_bytes, cd)?; @@ -252,8 +237,7 @@ fn main() -> Result<()> { builder.try_init()?; // Initialize randomness source - let mut rng = OsRng; - let rng_seed = options.seed.unwrap_or_else(|| rng.next_u64()); + let rng_seed = options.seed.unwrap_or_else(|| OsRng.next_u64()); info!("Using random seed {rng_seed:16x}"); let _rng = ChaCha8Rng::seed_from_u64(rng_seed); // TODO: Use `rng` to create deterministic runs diff --git a/plonky2/examples/square_root.rs b/plonky2/examples/square_root.rs index 6ac9eddd..019d2c14 100644 --- a/plonky2/examples/square_root.rs +++ b/plonky2/examples/square_root.rs @@ -76,7 +76,7 @@ impl WitnessGeneratorSerializer for CustomGeneratorS where F: RichField + Extendable, C: GenericConfig + 'static, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { impl_generator_serializer! { CustomGeneratorSerializer, diff --git a/plonky2/src/fri/challenges.rs b/plonky2/src/fri/challenges.rs index 984b7093..be73a8c2 100644 --- a/plonky2/src/fri/challenges.rs +++ b/plonky2/src/fri/challenges.rs @@ -5,21 +5,16 @@ use crate::fri::structure::{FriOpenings, FriOpeningsTarget}; use crate::fri::FriConfig; use crate::gadgets::polynomial::PolynomialCoeffsExtTarget; use crate::hash::hash_types::{MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleCap; use crate::iop::challenger::{Challenger, RecursiveChallenger}; use crate::iop::target::Target; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::config::{AlgebraicHasher, GenericConfig, Hasher}; -impl> Challenger -where - [(); HCO::WIDTH]:, -{ +impl> Challenger { pub fn observe_openings(&mut self, openings: &FriOpenings) where F: RichField + Extendable, - [(); HCO::WIDTH]:, { for v in &openings.batches { self.observe_extension_elements(&v.values); @@ -28,7 +23,7 @@ where pub fn fri_challenges, const D: usize>( &mut self, - commit_phase_merkle_caps: &[MerkleCap], + commit_phase_merkle_caps: &[MerkleCap], final_poly: &PolynomialCoeffs, pow_witness: F, degree_bits: usize, @@ -36,8 +31,6 @@ where ) -> FriChallenges where F: RichField + Extendable, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let num_fri_queries = config.num_query_rounds; let lde_size = 1 << (degree_bits + config.rate_bits); @@ -48,7 +41,7 @@ where let fri_betas = commit_phase_merkle_caps .iter() .map(|cap| { - self.observe_cap::(cap); + self.observe_cap::(cap); self.get_extension_challenge::() }) .collect(); @@ -71,15 +64,10 @@ where } } -impl, HCO: HashConfig, H: AlgebraicHasher, const D: usize> - RecursiveChallenger -where - [(); HCO::WIDTH]:, +impl, H: AlgebraicHasher, const D: usize> + RecursiveChallenger { - pub fn observe_openings(&mut self, openings: &FriOpeningsTarget) - where - [(); HCO::WIDTH]:, - { + pub fn observe_openings(&mut self, openings: &FriOpeningsTarget) { for v in &openings.batches { self.observe_extension_elements(&v.values); } diff --git a/plonky2/src/fri/oracle.rs b/plonky2/src/fri/oracle.rs index bb0421fe..dca3202a 100644 --- a/plonky2/src/fri/oracle.rs +++ b/plonky2/src/fri/oracle.rs @@ -14,7 +14,6 @@ use crate::fri::prover::fri_proof; use crate::fri::structure::{FriBatchInfo, FriInstanceInfo}; use crate::fri::FriParams; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleTree; use crate::iop::challenger::Challenger; use crate::plonk::config::GenericConfig; @@ -31,7 +30,7 @@ pub const SALT_SIZE: usize = 4; pub struct PolynomialBatch, C: GenericConfig, const D: usize> { pub polynomials: Vec>, - pub merkle_tree: MerkleTree, + pub merkle_tree: MerkleTree, pub degree_log: usize, pub rate_bits: usize, pub blinding: bool, @@ -48,10 +47,7 @@ impl, C: GenericConfig, const D: usize> cap_height: usize, timing: &mut TimingTree, fft_root_table: Option<&FftRootTable>, - ) -> Self - where - [(); C::HCO::WIDTH]:, - { + ) -> Self { let coeffs = timed!( timing, "IFFT", @@ -76,10 +72,7 @@ impl, C: GenericConfig, const D: usize> cap_height: usize, timing: &mut TimingTree, fft_root_table: Option<&FftRootTable>, - ) -> Self - where - [(); C::HCO::WIDTH]:, - { + ) -> Self { let degree = polynomials[0].len(); let lde_values = timed!( timing, @@ -169,14 +162,10 @@ impl, C: GenericConfig, const D: usize> pub fn prove_openings( instance: &FriInstanceInfo, oracles: &[&Self], - challenger: &mut Challenger, + challenger: &mut Challenger, fri_params: &FriParams, timing: &mut TimingTree, - ) -> FriProof - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> FriProof { assert!(D > 1, "Not implemented for D=1."); let alpha = challenger.get_extension_challenge::(); let mut alpha = ReducingFactor::new(alpha); diff --git a/plonky2/src/fri/proof.rs b/plonky2/src/fri/proof.rs index 326001fd..641d0a59 100644 --- a/plonky2/src/fri/proof.rs +++ b/plonky2/src/fri/proof.rs @@ -10,7 +10,6 @@ use crate::field::polynomial::PolynomialCoeffs; use crate::fri::FriParams; use crate::gadgets::polynomial::PolynomialCoeffsExtTarget; use crate::hash::hash_types::{MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_proofs::{MerkleProof, MerkleProofTarget}; use crate::hash::merkle_tree::MerkleCap; use crate::hash::path_compression::{compress_merkle_proofs, decompress_merkle_proofs}; @@ -23,14 +22,9 @@ use crate::plonk::proof::{FriInferredElements, ProofChallenges}; /// Evaluations and Merkle proof produced by the prover in a FRI query step. #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] #[serde(bound = "")] -pub struct FriQueryStep< - F: RichField + Extendable, - HC: HashConfig, - H: Hasher, - const D: usize, -> { +pub struct FriQueryStep, H: Hasher, const D: usize> { pub evals: Vec, - pub merkle_proof: MerkleProof, + pub merkle_proof: MerkleProof, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -43,11 +37,11 @@ pub struct FriQueryStepTarget { /// before they are combined into a composition polynomial. #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] #[serde(bound = "")] -pub struct FriInitialTreeProof> { - pub evals_proofs: Vec<(Vec, MerkleProof)>, +pub struct FriInitialTreeProof> { + pub evals_proofs: Vec<(Vec, MerkleProof)>, } -impl> FriInitialTreeProof { +impl> FriInitialTreeProof { pub(crate) fn unsalted_eval(&self, oracle_index: usize, poly_index: usize, salted: bool) -> F { self.unsalted_evals(oracle_index, salted)[poly_index] } @@ -82,14 +76,9 @@ impl FriInitialTreeProofTarget { /// Proof for a FRI query round. #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] #[serde(bound = "")] -pub struct FriQueryRound< - F: RichField + Extendable, - HC: HashConfig, - H: Hasher, - const D: usize, -> { - pub initial_trees_proof: FriInitialTreeProof, - pub steps: Vec>, +pub struct FriQueryRound, H: Hasher, const D: usize> { + pub initial_trees_proof: FriInitialTreeProof, + pub steps: Vec>, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -101,28 +90,22 @@ pub struct FriQueryRoundTarget { /// Compressed proof of the FRI query rounds. #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] #[serde(bound = "")] -pub struct CompressedFriQueryRounds< - F: RichField + Extendable, - HC: HashConfig, - H: Hasher, - const D: usize, -> { +pub struct CompressedFriQueryRounds, H: Hasher, const D: usize> { /// Query indices. pub indices: Vec, /// Map from initial indices `i` to the `FriInitialProof` for the `i`th leaf. - pub initial_trees_proofs: HashMap>, + pub initial_trees_proofs: HashMap>, /// For each FRI query step, a map from indices `i` to the `FriQueryStep` for the `i`th leaf. - pub steps: Vec>>, + pub steps: Vec>>, } #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] #[serde(bound = "")] -pub struct FriProof, HC: HashConfig, H: Hasher, const D: usize> -{ +pub struct FriProof, H: Hasher, const D: usize> { /// A Merkle cap for each reduced polynomial in the commit phase. - pub commit_phase_merkle_caps: Vec>, + pub commit_phase_merkle_caps: Vec>, /// Query rounds proofs - pub query_round_proofs: Vec>, + pub query_round_proofs: Vec>, /// The final polynomial in coefficient form. pub final_poly: PolynomialCoeffs, /// Witness showing that the prover did PoW. @@ -139,31 +122,20 @@ pub struct FriProofTarget { #[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)] #[serde(bound = "")] -pub struct CompressedFriProof< - F: RichField + Extendable, - HC: HashConfig, - H: Hasher, - const D: usize, -> { +pub struct CompressedFriProof, H: Hasher, const D: usize> { /// A Merkle cap for each reduced polynomial in the commit phase. - pub commit_phase_merkle_caps: Vec>, + pub commit_phase_merkle_caps: Vec>, /// Compressed query rounds proof. - pub query_round_proofs: CompressedFriQueryRounds, + pub query_round_proofs: CompressedFriQueryRounds, /// The final polynomial in coefficient form. pub final_poly: PolynomialCoeffs, /// Witness showing that the prover did PoW. pub pow_witness: F, } -impl, HCO: HashConfig, H: Hasher, const D: usize> - FriProof -{ +impl, H: Hasher, const D: usize> FriProof { /// Compress all the Merkle paths in the FRI proof and remove duplicate indices. - pub fn compress( - self, - indices: &[usize], - params: &FriParams, - ) -> CompressedFriProof { + pub fn compress(self, indices: &[usize], params: &FriParams) -> CompressedFriProof { let FriProof { commit_phase_merkle_caps, query_round_proofs, @@ -263,19 +235,14 @@ impl, HCO: HashConfig, H: Hasher, const D: } } -impl, HCO: HashConfig, H: Hasher, const D: usize> - CompressedFriProof -{ +impl, H: Hasher, const D: usize> CompressedFriProof { /// Decompress all the Merkle paths in the FRI proof and reinsert duplicate indices. pub(crate) fn decompress( self, challenges: &ProofChallenges, fri_inferred_elements: FriInferredElements, params: &FriParams, - ) -> FriProof - where - [(); HCO::WIDTH]:, - { + ) -> FriProof { let CompressedFriProof { commit_phase_merkle_caps, query_round_proofs, diff --git a/plonky2/src/fri/prover.rs b/plonky2/src/fri/prover.rs index b7ed8af5..75747f62 100644 --- a/plonky2/src/fri/prover.rs +++ b/plonky2/src/fri/prover.rs @@ -7,10 +7,10 @@ use crate::field::polynomial::{PolynomialCoeffs, PolynomialValues}; use crate::fri::proof::{FriInitialTreeProof, FriProof, FriQueryRound, FriQueryStep}; use crate::fri::{FriConfig, FriParams}; use crate::hash::hash_types::RichField; -use crate::hash::hashing::{HashConfig, PlonkyPermutation}; +use crate::hash::hashing::PlonkyPermutation; use crate::hash::merkle_tree::MerkleTree; use crate::iop::challenger::Challenger; -use crate::plonk::config::{GenericConfig, Hasher}; +use crate::plonk::config::GenericConfig; use crate::plonk::plonk_common::reduce_with_powers; use crate::timed; use crate::util::reverse_index_bits_in_place; @@ -18,19 +18,15 @@ use crate::util::timing::TimingTree; /// Builds a FRI proof. pub fn fri_proof, C: GenericConfig, const D: usize>( - initial_merkle_trees: &[&MerkleTree], + initial_merkle_trees: &[&MerkleTree], // Coefficients of the polynomial on which the LDT is performed. Only the first `1/rate` coefficients are non-zero. lde_polynomial_coeffs: PolynomialCoeffs, // Evaluation of the polynomial on the large domain. lde_polynomial_values: PolynomialValues, - challenger: &mut Challenger, + challenger: &mut Challenger, fri_params: &FriParams, timing: &mut TimingTree, -) -> FriProof -where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, -{ +) -> FriProof { let n = lde_polynomial_values.len(); assert_eq!(lde_polynomial_coeffs.len(), n); @@ -66,19 +62,16 @@ where } type FriCommitedTrees = ( - Vec>::HCO, >::Hasher>>, + Vec>::Hasher>>, PolynomialCoeffs<>::Extension>, ); fn fri_committed_trees, C: GenericConfig, const D: usize>( mut coeffs: PolynomialCoeffs, mut values: PolynomialValues, - challenger: &mut Challenger, + challenger: &mut Challenger, fri_params: &FriParams, -) -> FriCommitedTrees -where - [(); C::HCO::WIDTH]:, -{ +) -> FriCommitedTrees { let mut trees = Vec::new(); let mut shift = F::MULTIPLICATIVE_GROUP_GENERATOR; @@ -91,8 +84,7 @@ where .par_chunks(arity) .map(|chunk: &[F::Extension]| flatten(chunk)) .collect(); - let tree = - MerkleTree::::new(chunked_values, fri_params.config.cap_height); + let tree = MerkleTree::::new(chunked_values, fri_params.config.cap_height); challenger.observe_cap(&tree.cap); trees.push(tree); @@ -121,13 +113,9 @@ where /// Performs the proof-of-work (a.k.a. grinding) step of the FRI protocol. Returns the PoW witness. fn fri_proof_of_work, C: GenericConfig, const D: usize>( - challenger: &mut Challenger, + challenger: &mut Challenger, config: &FriConfig, -) -> F -where - [(); C::HCI::WIDTH]:, - [(); C::HCO::WIDTH]:, -{ +) -> F { let min_leading_zeros = config.proof_of_work_bits + (64 - F::order().bits()) as u32; // The easiest implementation would be repeatedly clone our Challenger. With each clone, we'd @@ -138,8 +126,8 @@ where // since it stores vectors, which means allocations. We'd like a more compact state to clone. // // We know that a duplex will be performed right after we send the PoW witness, so we can ignore - // any output_buffer, which will be invalidated. We also know input_buffer.len() < HCO::WIDTH, - // an invariant of Challenger. + // any output_buffer, which will be invalidated. We also know + // input_buffer.len() < H::Permutation::WIDTH, an invariant of Challenger. // // We separate the duplex operation into two steps, one which can be performed now, and the // other which depends on the PoW witness candidate. The first step is the overwrite our sponge @@ -148,20 +136,15 @@ where // obtaining our duplex's post-state which contains the PoW response. let mut duplex_intermediate_state = challenger.sponge_state; let witness_input_pos = challenger.input_buffer.len(); - for (i, input) in challenger.input_buffer.iter().enumerate() { - duplex_intermediate_state[i] = *input; - } + duplex_intermediate_state.set_from_iter(challenger.input_buffer.clone().into_iter(), 0); let pow_witness = (0..=F::NEG_ONE.to_canonical_u64()) .into_par_iter() .find_any(|&candidate| { let mut duplex_state = duplex_intermediate_state; - duplex_state[witness_input_pos] = F::from_canonical_u64(candidate); - duplex_state = - <>::Hasher as Hasher>::Permutation::permute( - duplex_state, - ); - let pow_response = duplex_state[C::HCO::RATE - 1]; + duplex_state.set_elt(F::from_canonical_u64(candidate), witness_input_pos); + duplex_state.permute(); + let pow_response = duplex_state.squeeze().iter().last().unwrap(); let leading_zeros = pow_response.to_canonical_u64().leading_zeros(); leading_zeros >= min_leading_zeros }) @@ -181,15 +164,12 @@ fn fri_prover_query_rounds< C: GenericConfig, const D: usize, >( - initial_merkle_trees: &[&MerkleTree], - trees: &[MerkleTree], - challenger: &mut Challenger, + initial_merkle_trees: &[&MerkleTree], + trees: &[MerkleTree], + challenger: &mut Challenger, n: usize, fri_params: &FriParams, -) -> Vec> -where - [(); C::HCO::WIDTH]:, -{ +) -> Vec> { challenger .get_n_challenges(fri_params.config.num_query_rounds) .into_par_iter() @@ -205,14 +185,11 @@ fn fri_prover_query_round< C: GenericConfig, const D: usize, >( - initial_merkle_trees: &[&MerkleTree], - trees: &[MerkleTree], + initial_merkle_trees: &[&MerkleTree], + trees: &[MerkleTree], mut x_index: usize, fri_params: &FriParams, -) -> FriQueryRound -where - [(); C::HCO::WIDTH]:, -{ +) -> FriQueryRound { let mut query_steps = Vec::new(); let initial_proof = initial_merkle_trees .iter() diff --git a/plonky2/src/fri/recursive_verifier.rs b/plonky2/src/fri/recursive_verifier.rs index d456b2a4..8e9329d5 100644 --- a/plonky2/src/fri/recursive_verifier.rs +++ b/plonky2/src/fri/recursive_verifier.rs @@ -14,7 +14,6 @@ use crate::gates::coset_interpolation::CosetInterpolationGate; use crate::gates::gate::Gate; use crate::gates::random_access::RandomAccessGate; use crate::hash::hash_types::{MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::iop::ext_target::{flatten_target, ExtensionTarget}; use crate::iop::target::{BoolTarget, Target}; use crate::plonk::circuit_builder::CircuitBuilder; @@ -108,8 +107,7 @@ impl, const D: usize> CircuitBuilder { proof: &FriProofTarget, params: &FriParams, ) where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, + C::Hasher: AlgebraicHasher, { if let Some(max_arity_bits) = params.max_arity_bits() { self.check_recursion_config(max_arity_bits); @@ -177,15 +175,13 @@ impl, const D: usize> CircuitBuilder { } } - fn fri_verify_initial_proof>( + fn fri_verify_initial_proof>( &mut self, x_index_bits: &[BoolTarget], proof: &FriInitialTreeProofTarget, initial_merkle_caps: &[MerkleCapTarget], cap_index: Target, - ) where - [(); HC::WIDTH]:, - { + ) { for (i, ((evals, merkle_proof), cap)) in proof .evals_proofs .iter() @@ -195,7 +191,7 @@ impl, const D: usize> CircuitBuilder { with_context!( self, &format!("verify {i}'th initial Merkle proof"), - self.verify_merkle_proof_to_cap_with_cap_index::( + self.verify_merkle_proof_to_cap_with_cap_index::( evals.clone(), x_index_bits, cap_index, @@ -262,8 +258,7 @@ impl, const D: usize> CircuitBuilder { round_proof: &FriQueryRoundTarget, params: &FriParams, ) where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, + C::Hasher: AlgebraicHasher, { let n_log = log2_strict(n); @@ -277,7 +272,7 @@ impl, const D: usize> CircuitBuilder { with_context!( self, "check FRI initial proof", - self.fri_verify_initial_proof::( + self.fri_verify_initial_proof::( &x_index_bits, &round_proof.initial_trees_proof, initial_merkle_caps, @@ -337,7 +332,7 @@ impl, const D: usize> CircuitBuilder { with_context!( self, "verify FRI round Merkle proof.", - self.verify_merkle_proof_to_cap_with_cap_index::( + self.verify_merkle_proof_to_cap_with_cap_index::( flatten_target(evals), &coset_index_bits, cap_index, diff --git a/plonky2/src/fri/validate_shape.rs b/plonky2/src/fri/validate_shape.rs index 6a4e7cc5..526da8f7 100644 --- a/plonky2/src/fri/validate_shape.rs +++ b/plonky2/src/fri/validate_shape.rs @@ -9,7 +9,7 @@ use crate::plonk::config::GenericConfig; use crate::plonk::plonk_common::salt_size; pub(crate) fn validate_fri_proof_shape( - proof: &FriProof, + proof: &FriProof, instance: &FriInstanceInfo, params: &FriParams, ) -> anyhow::Result<()> diff --git a/plonky2/src/fri/verifier.rs b/plonky2/src/fri/verifier.rs index 2e30214e..f860ba30 100644 --- a/plonky2/src/fri/verifier.rs +++ b/plonky2/src/fri/verifier.rs @@ -10,7 +10,6 @@ use crate::fri::structure::{FriBatchInfo, FriInstanceInfo, FriOpenings}; use crate::fri::validate_shape::validate_fri_proof_shape; use crate::fri::{FriConfig, FriParams}; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_proofs::verify_merkle_proof_to_cap; use crate::hash::merkle_tree::MerkleCap; use crate::plonk::config::{GenericConfig, Hasher}; @@ -59,17 +58,18 @@ pub(crate) fn fri_verify_proof_of_work, const D: us Ok(()) } -pub fn verify_fri_proof, C: GenericConfig, const D: usize>( +pub fn verify_fri_proof< + F: RichField + Extendable, + C: GenericConfig, + const D: usize, +>( instance: &FriInstanceInfo, openings: &FriOpenings, challenges: &FriChallenges, - initial_merkle_caps: &[MerkleCap], - proof: &FriProof, + initial_merkle_caps: &[MerkleCap], + proof: &FriProof, params: &FriParams, -) -> Result<()> -where - [(); C::HCO::WIDTH]:, -{ +) -> Result<()> { validate_fri_proof_shape::(proof, instance, params)?; // Size of the LDE domain. @@ -107,16 +107,13 @@ where Ok(()) } -fn fri_verify_initial_proof>( +fn fri_verify_initial_proof>( x_index: usize, - proof: &FriInitialTreeProof, - initial_merkle_caps: &[MerkleCap], -) -> Result<()> -where - [(); HC::WIDTH]:, -{ + proof: &FriInitialTreeProof, + initial_merkle_caps: &[MerkleCap], +) -> Result<()> { for ((evals, merkle_proof), cap) in proof.evals_proofs.iter().zip(initial_merkle_caps) { - verify_merkle_proof_to_cap::(evals.clone(), x_index, cap, merkle_proof)?; + verify_merkle_proof_to_cap::(evals.clone(), x_index, cap, merkle_proof)?; } Ok(()) @@ -128,7 +125,7 @@ pub(crate) fn fri_combine_initial< const D: usize, >( instance: &FriInstanceInfo, - proof: &FriInitialTreeProof, + proof: &FriInitialTreeProof, alpha: F::Extension, subgroup_x: F, precomputed_reduced_evals: &PrecomputedReducedOpenings, @@ -171,17 +168,14 @@ fn fri_verifier_query_round< instance: &FriInstanceInfo, challenges: &FriChallenges, precomputed_reduced_evals: &PrecomputedReducedOpenings, - initial_merkle_caps: &[MerkleCap], - proof: &FriProof, + initial_merkle_caps: &[MerkleCap], + proof: &FriProof, mut x_index: usize, n: usize, - round_proof: &FriQueryRound, + round_proof: &FriQueryRound, params: &FriParams, -) -> Result<()> -where - [(); C::HCO::WIDTH]:, -{ - fri_verify_initial_proof::( +) -> Result<()> { + fri_verify_initial_proof::( x_index, &round_proof.initial_trees_proof, initial_merkle_caps, @@ -222,7 +216,7 @@ where challenges.fri_betas[i], ); - verify_merkle_proof_to_cap::( + verify_merkle_proof_to_cap::( flatten(evals), coset_index, &proof.commit_phase_merkle_caps[i], diff --git a/plonky2/src/fri/witness_util.rs b/plonky2/src/fri/witness_util.rs index 67ab8f24..ce47e7cb 100644 --- a/plonky2/src/fri/witness_util.rs +++ b/plonky2/src/fri/witness_util.rs @@ -3,20 +3,18 @@ use itertools::Itertools; use crate::field::extension::Extendable; use crate::fri::proof::{FriProof, FriProofTarget}; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; use crate::iop::witness::WitnessWrite; use crate::plonk::config::AlgebraicHasher; /// Set the targets in a `FriProofTarget` to their corresponding values in a `FriProof`. -pub fn set_fri_proof_target( +pub fn set_fri_proof_target( witness: &mut W, fri_proof_target: &FriProofTarget, - fri_proof: &FriProof, + fri_proof: &FriProof, ) where F: RichField + Extendable, W: WitnessWrite + ?Sized, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, { witness.set_target(fri_proof_target.pow_witness, fri_proof.pow_witness); diff --git a/plonky2/src/gadgets/hash.rs b/plonky2/src/gadgets/hash.rs index 5386f3f5..90f9c625 100644 --- a/plonky2/src/gadgets/hash.rs +++ b/plonky2/src/gadgets/hash.rs @@ -1,27 +1,26 @@ use crate::field::extension::Extendable; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; -use crate::iop::target::{BoolTarget, Target}; +use crate::iop::target::BoolTarget; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::config::AlgebraicHasher; impl, const D: usize> CircuitBuilder { - pub fn permute>( + pub fn permute>( &mut self, - inputs: [Target; HC::WIDTH], - ) -> [Target; HC::WIDTH] { + inputs: H::AlgebraicPermutation, + ) -> H::AlgebraicPermutation { // We don't want to swap any inputs, so set that wire to 0. let _false = self._false(); - self.permute_swapped::(inputs, _false) + self.permute_swapped::(inputs, _false) } /// Conditionally swap two chunks of the inputs (useful in verifying Merkle proofs), then apply /// a cryptographic permutation. - pub(crate) fn permute_swapped>( + pub(crate) fn permute_swapped>( &mut self, - inputs: [Target; HC::WIDTH], + inputs: H::AlgebraicPermutation, swap: BoolTarget, - ) -> [Target; HC::WIDTH] { + ) -> H::AlgebraicPermutation { H::permute_swapped(inputs, swap, self) } } diff --git a/plonky2/src/gates/gate_testing.rs b/plonky2/src/gates/gate_testing.rs index 2fa982bb..9a1f0f49 100644 --- a/plonky2/src/gates/gate_testing.rs +++ b/plonky2/src/gates/gate_testing.rs @@ -8,7 +8,6 @@ use crate::field::polynomial::{PolynomialCoeffs, PolynomialValues}; use crate::field::types::{Field, Sample}; use crate::gates::gate::Gate; use crate::hash::hash_types::{HashOut, RichField}; -use crate::hash::hashing::HashConfig; use crate::iop::witness::{PartialWitness, WitnessWrite}; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::circuit_data::CircuitConfig; @@ -94,11 +93,7 @@ pub fn test_eval_fns< const D: usize, >( gate: G, -) -> Result<()> -where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, -{ +) -> Result<()> { // Test that `eval_unfiltered` and `eval_unfiltered_base` are coherent. let wires_base = F::rand_vec(gate.num_wires()); let constants_base = F::rand_vec(gate.num_constants()); diff --git a/plonky2/src/hash/hash_types.rs b/plonky2/src/hash/hash_types.rs index c16092a8..edd473c5 100644 --- a/plonky2/src/hash/hash_types.rs +++ b/plonky2/src/hash/hash_types.rs @@ -14,35 +14,37 @@ pub trait RichField: PrimeField64 + Poseidon {} impl RichField for GoldilocksField {} +pub const NUM_HASH_OUT_ELTS: usize = 4; + /// Represents a ~256 bit hash output. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(bound = "")] pub struct HashOut { - pub elements: [F; 4], + pub elements: [F; NUM_HASH_OUT_ELTS], } impl HashOut { pub const ZERO: Self = Self { - elements: [F::ZERO; 4], + elements: [F::ZERO; NUM_HASH_OUT_ELTS], }; // TODO: Switch to a TryFrom impl. pub fn from_vec(elements: Vec) -> Self { - debug_assert!(elements.len() == 4); + debug_assert!(elements.len() == NUM_HASH_OUT_ELTS); Self { elements: elements.try_into().unwrap(), } } pub fn from_partial(elements_in: &[F]) -> Self { - let mut elements = [F::ZERO; 4]; + let mut elements = [F::ZERO; NUM_HASH_OUT_ELTS]; elements[0..elements_in.len()].copy_from_slice(elements_in); Self { elements } } } -impl From<[F; 4]> for HashOut { - fn from(elements: [F; 4]) -> Self { +impl From<[F; NUM_HASH_OUT_ELTS]> for HashOut { + fn from(elements: [F; NUM_HASH_OUT_ELTS]) -> Self { Self { elements } } } @@ -51,7 +53,7 @@ impl TryFrom<&[F]> for HashOut { type Error = anyhow::Error; fn try_from(elements: &[F]) -> Result { - ensure!(elements.len() == 4); + ensure!(elements.len() == NUM_HASH_OUT_ELTS); Ok(Self { elements: elements.try_into().unwrap(), }) @@ -90,7 +92,7 @@ impl GenericHashOut for HashOut { HashOut { elements: bytes .chunks(8) - .take(4) + .take(NUM_HASH_OUT_ELTS) .map(|x| F::from_canonical_u64(u64::from_le_bytes(x.try_into().unwrap()))) .collect::>() .try_into() @@ -112,27 +114,27 @@ impl Default for HashOut { /// Represents a ~256 bit hash output. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct HashOutTarget { - pub elements: [Target; 4], + pub elements: [Target; NUM_HASH_OUT_ELTS], } impl HashOutTarget { // TODO: Switch to a TryFrom impl. pub fn from_vec(elements: Vec) -> Self { - debug_assert!(elements.len() == 4); + debug_assert!(elements.len() == NUM_HASH_OUT_ELTS); Self { elements: elements.try_into().unwrap(), } } pub fn from_partial(elements_in: &[Target], zero: Target) -> Self { - let mut elements = [zero; 4]; + let mut elements = [zero; NUM_HASH_OUT_ELTS]; elements[0..elements_in.len()].copy_from_slice(elements_in); Self { elements } } } -impl From<[Target; 4]> for HashOutTarget { - fn from(elements: [Target; 4]) -> Self { +impl From<[Target; NUM_HASH_OUT_ELTS]> for HashOutTarget { + fn from(elements: [Target; NUM_HASH_OUT_ELTS]) -> Self { Self { elements } } } @@ -141,7 +143,7 @@ impl TryFrom<&[Target]> for HashOutTarget { type Error = anyhow::Error; fn try_from(elements: &[Target]) -> Result { - ensure!(elements.len() == 4); + ensure!(elements.len() == NUM_HASH_OUT_ELTS); Ok(Self { elements: elements.try_into().unwrap(), }) diff --git a/plonky2/src/hash/hashing.rs b/plonky2/src/hash/hashing.rs index d8576d3c..28d3b89f 100644 --- a/plonky2/src/hash/hashing.rs +++ b/plonky2/src/hash/hashing.rs @@ -2,137 +2,145 @@ use alloc::vec::Vec; use core::fmt::Debug; +use std::iter::repeat; use crate::field::extension::Extendable; -use crate::hash::hash_types::{HashOut, HashOutTarget, RichField}; +use crate::field::types::Field; +use crate::hash::hash_types::{HashOut, HashOutTarget, RichField, NUM_HASH_OUT_ELTS}; use crate::iop::target::Target; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::config::AlgebraicHasher; -pub trait HashConfig: Clone + Debug + Eq + PartialEq { - const RATE: usize; - const WIDTH: usize; -} - impl, const D: usize> CircuitBuilder { - pub fn hash_or_noop>( - &mut self, - inputs: Vec, - ) -> HashOutTarget - where - [(); HC::WIDTH]:, - { + pub fn hash_or_noop>(&mut self, inputs: Vec) -> HashOutTarget { let zero = self.zero(); - if inputs.len() <= 4 { + if inputs.len() <= NUM_HASH_OUT_ELTS { HashOutTarget::from_partial(&inputs, zero) } else { - self.hash_n_to_hash_no_pad::(inputs) + self.hash_n_to_hash_no_pad::(inputs) } } - pub fn hash_n_to_hash_no_pad>( + pub fn hash_n_to_hash_no_pad>( &mut self, inputs: Vec, - ) -> HashOutTarget - where - [(); HC::WIDTH]:, - { - HashOutTarget::from_vec(self.hash_n_to_m_no_pad::(inputs, 4)) + ) -> HashOutTarget { + HashOutTarget::from_vec(self.hash_n_to_m_no_pad::(inputs, NUM_HASH_OUT_ELTS)) } - pub fn hash_n_to_m_no_pad>( + pub fn hash_n_to_m_no_pad>( &mut self, inputs: Vec, num_outputs: usize, - ) -> Vec - where - [(); HC::WIDTH]:, - { + ) -> Vec { let zero = self.zero(); - - let mut state = [zero; HC::WIDTH]; + let mut state = H::AlgebraicPermutation::new(std::iter::repeat(zero)); // Absorb all input chunks. - for input_chunk in inputs.chunks(HC::RATE) { + for input_chunk in inputs.chunks(H::AlgebraicPermutation::RATE) { // Overwrite the first r elements with the inputs. This differs from a standard sponge, // where we would xor or add in the inputs. This is a well-known variant, though, // sometimes called "overwrite mode". - state[..input_chunk.len()].copy_from_slice(input_chunk); - state = self.permute::(state); + state.set_from_slice(input_chunk, 0); + state = self.permute::(state); } // Squeeze until we have the desired number of outputs. let mut outputs = Vec::with_capacity(num_outputs); loop { - for i in 0..HC::RATE { - outputs.push(state[i]); + for &s in state.squeeze() { + outputs.push(s); if outputs.len() == num_outputs { return outputs; } } - state = self.permute::(state); + state = self.permute::(state); } } } -/// A one-way compression function which takes two ~256 bit inputs and returns a ~256 bit output. -pub fn compress>( - x: HashOut, - y: HashOut, -) -> HashOut -where - [(); HC::WIDTH]:, +/// Permutation that can be used in the sponge construction for an algebraic hash. +pub trait PlonkyPermutation: + AsRef<[T]> + Copy + Debug + Default + Eq + Sync + Send { - let mut perm_inputs = [F::ZERO; HC::WIDTH]; - perm_inputs[..4].copy_from_slice(&x.elements); - perm_inputs[4..8].copy_from_slice(&y.elements); - HashOut { - elements: P::permute(perm_inputs)[..4].try_into().unwrap(), - } + const RATE: usize; + const WIDTH: usize; + + /// Initialises internal state with values from `iter` until + /// `iter` is exhausted or `Self::WIDTH` values have been + /// received; remaining state (if any) initialised with + /// `T::default()`. To initialise remaining elements with a + /// different value, instead of your original `iter` pass + /// `iter.chain(std::iter::repeat(F::from_canonical_u64(12345)))` + /// or similar. + fn new>(iter: I) -> Self; + + /// Set idx-th state element to be `elt`. Panics if `idx >= WIDTH`. + fn set_elt(&mut self, elt: T, idx: usize); + + /// Set state element `i` to be `elts[i] for i = + /// start_idx..start_idx + n` where `n = min(elts.len(), + /// WIDTH-start_idx)`. Panics if `start_idx > WIDTH`. + fn set_from_iter>(&mut self, elts: I, start_idx: usize); + + /// Same semantics as for `set_from_iter` but probably faster than + /// just calling `set_from_iter(elts.iter())`. + fn set_from_slice(&mut self, elts: &[T], start_idx: usize); + + /// Apply permutation to internal state + fn permute(&mut self); + + /// Return a slice of `RATE` elements + fn squeeze(&self) -> &[T]; } -/// Permutation that can be used in the sponge construction for an algebraic hash. -pub trait PlonkyPermutation { - fn permute(input: [F; HC::WIDTH]) -> [F; HC::WIDTH] - where - [(); HC::WIDTH]:; +/// A one-way compression function which takes two ~256 bit inputs and returns a ~256 bit output. +pub fn compress>(x: HashOut, y: HashOut) -> HashOut { + // TODO: With some refactoring, this function could be implemented as + // hash_n_to_m_no_pad(chain(x.elements, y.elements), NUM_HASH_OUT_ELTS). + + debug_assert_eq!(x.elements.len(), NUM_HASH_OUT_ELTS); + debug_assert_eq!(y.elements.len(), NUM_HASH_OUT_ELTS); + debug_assert!(P::RATE >= NUM_HASH_OUT_ELTS); + + let mut perm = P::new(repeat(F::ZERO)); + perm.set_from_slice(&x.elements, 0); + perm.set_from_slice(&y.elements, NUM_HASH_OUT_ELTS); + + perm.permute(); + + HashOut { + elements: perm.squeeze()[..NUM_HASH_OUT_ELTS].try_into().unwrap(), + } } /// Hash a message without any padding step. Note that this can enable length-extension attacks. /// However, it is still collision-resistant in cases where the input has a fixed length. -pub fn hash_n_to_m_no_pad>( +pub fn hash_n_to_m_no_pad>( inputs: &[F], num_outputs: usize, -) -> Vec -where - [(); HC::WIDTH]:, -{ - let mut state = [F::ZERO; HC::WIDTH]; +) -> Vec { + let mut perm = P::new(repeat(F::ZERO)); // Absorb all input chunks. - for input_chunk in inputs.chunks(HC::RATE) { - state[..input_chunk.len()].copy_from_slice(input_chunk); - state = P::permute(state); + for input_chunk in inputs.chunks(P::RATE) { + perm.set_from_slice(input_chunk, 0); + perm.permute(); } // Squeeze until we have the desired number of outputs. let mut outputs = Vec::new(); loop { - for &item in state.iter().take(HC::RATE) { + for &item in perm.squeeze() { outputs.push(item); if outputs.len() == num_outputs { return outputs; } } - state = P::permute(state); + perm.permute(); } } -pub fn hash_n_to_hash_no_pad>( - inputs: &[F], -) -> HashOut -where - [(); HC::WIDTH]:, -{ - HashOut::from_vec(hash_n_to_m_no_pad::(inputs, 4)) +pub fn hash_n_to_hash_no_pad>(inputs: &[F]) -> HashOut { + HashOut::from_vec(hash_n_to_m_no_pad::(inputs, NUM_HASH_OUT_ELTS)) } diff --git a/plonky2/src/hash/keccak.rs b/plonky2/src/hash/keccak.rs index 7fc83188..15196560 100644 --- a/plonky2/src/hash/keccak.rs +++ b/plonky2/src/hash/keccak.rs @@ -8,7 +8,7 @@ use keccak_hash::keccak; use crate::hash::hash_types::{BytesHash, RichField}; use crate::hash::hashing::PlonkyPermutation; -use crate::plonk::config::{Hasher, KeccakHashConfig}; +use crate::plonk::config::Hasher; use crate::util::serialization::Write; pub const SPONGE_RATE: usize = 8; @@ -18,21 +18,59 @@ pub const SPONGE_WIDTH: usize = SPONGE_RATE + SPONGE_CAPACITY; /// Keccak-256 pseudo-permutation (not necessarily one-to-one) used in the challenger. /// A state `input: [F; 12]` is sent to the field representation of `H(input) || H(H(input)) || H(H(H(input)))` /// where `H` is the Keccak-256 hash. -pub struct KeccakPermutation; -impl PlonkyPermutation for KeccakPermutation { - fn permute(input: [F; SPONGE_WIDTH]) -> [F; SPONGE_WIDTH] - where - [(); SPONGE_WIDTH]:, - { - let mut state = vec![0u8; SPONGE_WIDTH * size_of::()]; +#[derive(Copy, Clone, Default, Debug, PartialEq)] +pub struct KeccakPermutation { + state: [F; SPONGE_WIDTH], +} + +impl Eq for KeccakPermutation {} + +impl AsRef<[F]> for KeccakPermutation { + fn as_ref(&self) -> &[F] { + &self.state + } +} + +// TODO: Several implementations here are copied from +// PoseidonPermutation; they should be refactored. +impl PlonkyPermutation for KeccakPermutation { + const RATE: usize = SPONGE_RATE; + const WIDTH: usize = SPONGE_WIDTH; + + fn new>(elts: I) -> Self { + let mut perm = Self { + state: [F::default(); SPONGE_WIDTH], + }; + perm.set_from_iter(elts, 0); + perm + } + + fn set_elt(&mut self, elt: F, idx: usize) { + self.state[idx] = elt; + } + + fn set_from_slice(&mut self, elts: &[F], start_idx: usize) { + let begin = start_idx; + let end = start_idx + elts.len(); + self.state[begin..end].copy_from_slice(elts); + } + + fn set_from_iter>(&mut self, elts: I, start_idx: usize) { + for (s, e) in self.state[start_idx..].iter_mut().zip(elts) { + *s = e; + } + } + + fn permute(&mut self) { + let mut state_bytes = vec![0u8; SPONGE_WIDTH * size_of::()]; for i in 0..SPONGE_WIDTH { - state[i * size_of::()..(i + 1) * size_of::()] - .copy_from_slice(&input[i].to_canonical_u64().to_le_bytes()); + state_bytes[i * size_of::()..(i + 1) * size_of::()] + .copy_from_slice(&self.state[i].to_canonical_u64().to_le_bytes()); } let hash_onion = iter::repeat_with(|| { - let output = keccak(state.clone()).to_fixed_bytes(); - state = output.to_vec(); + let output = keccak(state_bytes.clone()).to_fixed_bytes(); + state_bytes = output.to_vec(); output }); @@ -49,21 +87,25 @@ impl PlonkyPermutation for KeccakPermutation .filter(|&word| word < F::ORDER) .map(F::from_canonical_u64); - hash_onion_elems + self.state = hash_onion_elems .take(SPONGE_WIDTH) .collect_vec() .try_into() - .unwrap() + .unwrap(); + } + + fn squeeze(&self) -> &[F] { + &self.state[..Self::RATE] } } /// Keccak-256 hash function. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct KeccakHash; -impl Hasher for KeccakHash { +impl Hasher for KeccakHash { const HASH_SIZE: usize = N; type Hash = BytesHash; - type Permutation = KeccakPermutation; + type Permutation = KeccakPermutation; fn hash_no_pad(input: &[F]) -> Self::Hash { let mut buffer = Vec::new(); diff --git a/plonky2/src/hash/merkle_proofs.rs b/plonky2/src/hash/merkle_proofs.rs index 240e6cd2..14eb3a1c 100644 --- a/plonky2/src/hash/merkle_proofs.rs +++ b/plonky2/src/hash/merkle_proofs.rs @@ -6,8 +6,8 @@ use itertools::Itertools; use serde::{Deserialize, Serialize}; use crate::field::extension::Extendable; -use crate::hash::hash_types::{HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; +use crate::hash::hash_types::{HashOutTarget, MerkleCapTarget, RichField, NUM_HASH_OUT_ELTS}; +use crate::hash::hashing::PlonkyPermutation; use crate::hash::merkle_tree::MerkleCap; use crate::iop::target::{BoolTarget, Target}; use crate::plonk::circuit_builder::CircuitBuilder; @@ -16,12 +16,12 @@ use crate::plonk::config::{AlgebraicHasher, Hasher}; #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] #[serde(bound = "")] -pub struct MerkleProof> { +pub struct MerkleProof> { /// The Merkle digest of each sibling subtree, staying from the bottommost layer. pub siblings: Vec, } -impl> MerkleProof { +impl> MerkleProof { pub fn len(&self) -> usize { self.siblings.len() } @@ -39,30 +39,24 @@ pub struct MerkleProofTarget { /// Verifies that the given leaf data is present at the given index in the Merkle tree with the /// given root. -pub fn verify_merkle_proof>( +pub fn verify_merkle_proof>( leaf_data: Vec, leaf_index: usize, merkle_root: H::Hash, - proof: &MerkleProof, -) -> Result<()> -where - [(); HC::WIDTH]:, -{ + proof: &MerkleProof, +) -> Result<()> { let merkle_cap = MerkleCap(vec![merkle_root]); verify_merkle_proof_to_cap(leaf_data, leaf_index, &merkle_cap, proof) } /// Verifies that the given leaf data is present at the given index in the Merkle tree with the /// given cap. -pub fn verify_merkle_proof_to_cap>( +pub fn verify_merkle_proof_to_cap>( leaf_data: Vec, leaf_index: usize, - merkle_cap: &MerkleCap, - proof: &MerkleProof, -) -> Result<()> -where - [(); HC::WIDTH]:, -{ + merkle_cap: &MerkleCap, + proof: &MerkleProof, +) -> Result<()> { let mut index = leaf_index; let mut current_digest = H::hash_or_noop(&leaf_data); for &sibling_digest in proof.siblings.iter() { @@ -85,32 +79,28 @@ where impl, const D: usize> CircuitBuilder { /// Verifies that the given leaf data is present at the given index in the Merkle tree with the /// given root. The index is given by its little-endian bits. - pub fn verify_merkle_proof>( + pub fn verify_merkle_proof>( &mut self, leaf_data: Vec, leaf_index_bits: &[BoolTarget], merkle_root: HashOutTarget, proof: &MerkleProofTarget, - ) where - [(); HC::WIDTH]:, - { + ) { let merkle_cap = MerkleCapTarget(vec![merkle_root]); - self.verify_merkle_proof_to_cap::(leaf_data, leaf_index_bits, &merkle_cap, proof); + self.verify_merkle_proof_to_cap::(leaf_data, leaf_index_bits, &merkle_cap, proof); } /// Verifies that the given leaf data is present at the given index in the Merkle tree with the /// given cap. The index is given by its little-endian bits. - pub fn verify_merkle_proof_to_cap>( + pub fn verify_merkle_proof_to_cap>( &mut self, leaf_data: Vec, leaf_index_bits: &[BoolTarget], merkle_cap: &MerkleCapTarget, proof: &MerkleProofTarget, - ) where - [(); HC::WIDTH]:, - { + ) { let cap_index = self.le_sum(leaf_index_bits[proof.siblings.len()..].iter().copied()); - self.verify_merkle_proof_to_cap_with_cap_index::( + self.verify_merkle_proof_to_cap_with_cap_index::( leaf_data, leaf_index_bits, cap_index, @@ -121,34 +111,38 @@ impl, const D: usize> CircuitBuilder { /// Same as `verify_merkle_proof_to_cap`, except with the final "cap index" as separate parameter, /// rather than being contained in `leaf_index_bits`. - pub(crate) fn verify_merkle_proof_to_cap_with_cap_index< - HC: HashConfig, - H: AlgebraicHasher, - >( + pub(crate) fn verify_merkle_proof_to_cap_with_cap_index>( &mut self, leaf_data: Vec, leaf_index_bits: &[BoolTarget], cap_index: Target, merkle_cap: &MerkleCapTarget, proof: &MerkleProofTarget, - ) where - [(); HC::WIDTH]:, - { + ) { + debug_assert!(H::AlgebraicPermutation::RATE >= NUM_HASH_OUT_ELTS); + let zero = self.zero(); - let mut state: HashOutTarget = self.hash_or_noop::(leaf_data); + let mut state: HashOutTarget = self.hash_or_noop::(leaf_data); + debug_assert_eq!(state.elements.len(), NUM_HASH_OUT_ELTS); for (&bit, &sibling) in leaf_index_bits.iter().zip(&proof.siblings) { - let mut perm_inputs = [zero; HC::WIDTH]; - perm_inputs[..4].copy_from_slice(&state.elements); - perm_inputs[4..8].copy_from_slice(&sibling.elements); - let perm_outs = self.permute_swapped::(perm_inputs, bit); - let hash_outs = perm_outs[0..4].try_into().unwrap(); + debug_assert_eq!(sibling.elements.len(), NUM_HASH_OUT_ELTS); + + let mut perm_inputs = H::AlgebraicPermutation::default(); + perm_inputs.set_from_slice(&state.elements, 0); + perm_inputs.set_from_slice(&sibling.elements, NUM_HASH_OUT_ELTS); + // Ensure the rest of the state, if any, is zero: + perm_inputs.set_from_iter(std::iter::repeat(zero), 2 * NUM_HASH_OUT_ELTS); + let perm_outs = self.permute_swapped::(perm_inputs, bit); + let hash_outs = perm_outs.squeeze()[0..NUM_HASH_OUT_ELTS] + .try_into() + .unwrap(); state = HashOutTarget { elements: hash_outs, }; } - for i in 0..4 { + for i in 0..NUM_HASH_OUT_ELTS { let result = self.random_access( cap_index, merkle_cap.0.iter().map(|h| h.elements[i]).collect(), @@ -158,7 +152,7 @@ impl, const D: usize> CircuitBuilder { } pub fn connect_hashes(&mut self, x: HashOutTarget, y: HashOutTarget) { - for i in 0..4 { + for i in 0..NUM_HASH_OUT_ELTS { self.connect(x.elements[i], y.elements[i]); } } @@ -207,10 +201,7 @@ mod tests { let n = 1 << log_n; let cap_height = 1; let leaves = random_data::(n, 7); - let tree = - MerkleTree::>::HCO, >::Hasher>::new( - leaves, cap_height, - ); + let tree = MerkleTree::>::Hasher>::new(leaves, cap_height); let i: usize = OsRng.gen_range(0..n); let proof = tree.prove(i); @@ -232,7 +223,7 @@ mod tests { pw.set_target(data[j], tree.leaves[i][j]); } - builder.verify_merkle_proof_to_cap::<>::HCI, >::InnerHasher>( + builder.verify_merkle_proof_to_cap::<>::InnerHasher>( data, &i_bits, &cap_t, &proof_t, ); diff --git a/plonky2/src/hash/merkle_tree.rs b/plonky2/src/hash/merkle_tree.rs index 67fe7968..b3b0e0cb 100644 --- a/plonky2/src/hash/merkle_tree.rs +++ b/plonky2/src/hash/merkle_tree.rs @@ -6,7 +6,6 @@ use plonky2_maybe_rayon::*; use serde::{Deserialize, Serialize}; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_proofs::MerkleProof; use crate::plonk::config::{GenericHashOut, Hasher}; use crate::util::log2_strict; @@ -16,9 +15,9 @@ use crate::util::log2_strict; #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)] #[serde(bound = "")] // TODO: Change H to GenericHashOut, since this only cares about the hash, not the hasher. -pub struct MerkleCap>(pub Vec); +pub struct MerkleCap>(pub Vec); -impl> MerkleCap { +impl> MerkleCap { pub fn len(&self) -> usize { self.0.len() } @@ -37,7 +36,7 @@ impl> MerkleCap { } #[derive(Clone, Debug, Eq, PartialEq)] -pub struct MerkleTree> { +pub struct MerkleTree> { /// The data in the leaves of the Merkle tree. pub leaves: Vec>, @@ -52,7 +51,7 @@ pub struct MerkleTree> { pub digests: Vec, /// The Merkle cap. - pub cap: MerkleCap, + pub cap: MerkleCap, } fn capacity_up_to_mut(v: &mut Vec, len: usize) -> &mut [MaybeUninit] { @@ -67,13 +66,10 @@ fn capacity_up_to_mut(v: &mut Vec, len: usize) -> &mut [MaybeUninit] { } } -fn fill_subtree>( +fn fill_subtree>( digests_buf: &mut [MaybeUninit], leaves: &[Vec], -) -> H::Hash -where - [(); HC::WIDTH]:, -{ +) -> H::Hash { assert_eq!(leaves.len(), digests_buf.len() / 2 + 1); if digests_buf.is_empty() { H::hash_or_noop(&leaves[0]) @@ -89,8 +85,8 @@ where let (left_leaves, right_leaves) = leaves.split_at(leaves.len() / 2); let (left_digest, right_digest) = plonky2_maybe_rayon::join( - || fill_subtree::(left_digests_buf, left_leaves), - || fill_subtree::(right_digests_buf, right_leaves), + || fill_subtree::(left_digests_buf, left_leaves), + || fill_subtree::(right_digests_buf, right_leaves), ); left_digest_mem.write(left_digest); @@ -99,14 +95,12 @@ where } } -fn fill_digests_buf>( +fn fill_digests_buf>( digests_buf: &mut [MaybeUninit], cap_buf: &mut [MaybeUninit], leaves: &[Vec], cap_height: usize, -) where - [(); HC::WIDTH]:, -{ +) { // Special case of a tree that's all cap. The usual case will panic because we'll try to split // an empty slice into chunks of `0`. (We would not need this if there was a way to split into // `blah` chunks as opposed to chunks _of_ `blah`.) @@ -132,15 +126,12 @@ fn fill_digests_buf>( // We have `1 << cap_height` sub-trees, one for each entry in `cap`. They are totally // independent, so we schedule one task for each. `digests_buf` and `leaves` are split // into `1 << cap_height` slices, one for each sub-tree. - subtree_cap.write(fill_subtree::(subtree_digests, subtree_leaves)); + subtree_cap.write(fill_subtree::(subtree_digests, subtree_leaves)); }, ); } -impl> MerkleTree -where - [(); HC::WIDTH]:, -{ +impl> MerkleTree { pub fn new(leaves: Vec>, cap_height: usize) -> Self { let log2_leaves_len = log2_strict(leaves.len()); assert!( @@ -158,7 +149,7 @@ where let digests_buf = capacity_up_to_mut(&mut digests, num_digests); let cap_buf = capacity_up_to_mut(&mut cap, len_cap); - fill_digests_buf::(digests_buf, cap_buf, &leaves[..], cap_height); + fill_digests_buf::(digests_buf, cap_buf, &leaves[..], cap_height); unsafe { // SAFETY: `fill_digests_buf` and `cap` initialized the spare capacity up to @@ -179,7 +170,7 @@ where } /// Create a Merkle proof from a leaf index. - pub fn prove(&self, leaf_index: usize) -> MerkleProof { + pub fn prove(&self, leaf_index: usize) -> MerkleProof { let cap_height = log2_strict(self.cap.len()); let num_layers = log2_strict(self.leaves.len()) - cap_height; debug_assert_eq!(leaf_index >> (cap_height + num_layers), 0); @@ -229,14 +220,15 @@ mod tests { (0..n).map(|_| F::rand_vec(k)).collect() } - fn verify_all_leaves, C: GenericConfig, const D: usize>( + fn verify_all_leaves< + F: RichField + Extendable, + C: GenericConfig, + const D: usize, + >( leaves: Vec>, cap_height: usize, - ) -> Result<()> - where - [(); C::HCO::WIDTH]:, - { - let tree = MerkleTree::::new(leaves.clone(), cap_height); + ) -> Result<()> { + let tree = MerkleTree::::new(leaves.clone(), cap_height); for (i, leaf) in leaves.into_iter().enumerate() { let proof = tree.prove(i); verify_merkle_proof_to_cap(leaf, i, &tree.cap, &proof)?; @@ -255,9 +247,7 @@ mod tests { let cap_height = log_n + 1; // Should panic if `cap_height > len_n`. let leaves = random_data::(1 << log_n, 7); - let _ = MerkleTree::>::HCO, >::Hasher>::new( - leaves, cap_height, - ); + let _ = MerkleTree::>::Hasher>::new(leaves, cap_height); } #[test] diff --git a/plonky2/src/hash/path_compression.rs b/plonky2/src/hash/path_compression.rs index 853ffc85..d4f7d5eb 100644 --- a/plonky2/src/hash/path_compression.rs +++ b/plonky2/src/hash/path_compression.rs @@ -5,16 +5,15 @@ use hashbrown::HashMap; use num::Integer; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_proofs::MerkleProof; use crate::plonk::config::Hasher; /// Compress multiple Merkle proofs on the same tree by removing redundancy in the Merkle paths. -pub(crate) fn compress_merkle_proofs>( +pub(crate) fn compress_merkle_proofs>( cap_height: usize, indices: &[usize], - proofs: &[MerkleProof], -) -> Vec> { + proofs: &[MerkleProof], +) -> Vec> { assert!(!proofs.is_empty()); let height = cap_height + proofs[0].siblings.len(); let num_leaves = 1 << height; @@ -54,16 +53,13 @@ pub(crate) fn compress_merkle_proofs>( +pub(crate) fn decompress_merkle_proofs>( leaves_data: &[Vec], leaves_indices: &[usize], - compressed_proofs: &[MerkleProof], + compressed_proofs: &[MerkleProof], height: usize, cap_height: usize, -) -> Vec> -where - [(); HC::WIDTH]:, -{ +) -> Vec> { let num_leaves = 1 << height; let compressed_proofs = compressed_proofs.to_vec(); let mut decompressed_proofs = Vec::with_capacity(compressed_proofs.len()); @@ -134,11 +130,7 @@ mod tests { let h = 10; let cap_height = 3; let vs = (0..1 << h).map(|_| vec![F::rand()]).collect::>(); - let mt = - MerkleTree::>::HCO, >::Hasher>::new( - vs.clone(), - cap_height, - ); + let mt = MerkleTree::>::Hasher>::new(vs.clone(), cap_height); let mut rng = OsRng; let k = rng.gen_range(1..=1 << h); diff --git a/plonky2/src/hash/poseidon.rs b/plonky2/src/hash/poseidon.rs index 468b3d4d..a89deda7 100644 --- a/plonky2/src/hash/poseidon.rs +++ b/plonky2/src/hash/poseidon.rs @@ -3,6 +3,7 @@ use alloc::vec; use alloc::vec::Vec; +use std::fmt::Debug; use unroll::unroll_for_loops; @@ -16,7 +17,7 @@ use crate::hash::hashing::{compress, hash_n_to_hash_no_pad, PlonkyPermutation}; use crate::iop::ext_target::ExtensionTarget; use crate::iop::target::{BoolTarget, Target}; use crate::plonk::circuit_builder::CircuitBuilder; -use crate::plonk::config::{AlgebraicHasher, Hasher, PoseidonHashConfig}; +use crate::plonk::config::{AlgebraicHasher, Hasher}; pub const SPONGE_RATE: usize = 8; pub const SPONGE_CAPACITY: usize = 4; @@ -632,36 +633,99 @@ pub trait Poseidon: PrimeField64 { } } -pub struct PoseidonPermutation; -impl PlonkyPermutation for PoseidonPermutation { - fn permute(input: [F; SPONGE_WIDTH]) -> [F; SPONGE_WIDTH] { - F::poseidon(input) +#[derive(Copy, Clone, Default, Debug, PartialEq)] +pub struct PoseidonPermutation { + state: [T; SPONGE_WIDTH], +} + +impl Eq for PoseidonPermutation {} + +impl AsRef<[T]> for PoseidonPermutation { + fn as_ref(&self) -> &[T] { + &self.state + } +} + +trait Permuter: Sized { + fn permute(input: [Self; SPONGE_WIDTH]) -> [Self; SPONGE_WIDTH]; +} + +impl Permuter for F { + fn permute(input: [Self; SPONGE_WIDTH]) -> [Self; SPONGE_WIDTH] { + ::poseidon(input) + } +} + +impl Permuter for Target { + fn permute(_input: [Self; SPONGE_WIDTH]) -> [Self; SPONGE_WIDTH] { + panic!("Call `permute_swapped()` instead of `permute()`"); + } +} + +impl PlonkyPermutation + for PoseidonPermutation +{ + const RATE: usize = SPONGE_RATE; + const WIDTH: usize = SPONGE_WIDTH; + + fn new>(elts: I) -> Self { + let mut perm = Self { + state: [T::default(); SPONGE_WIDTH], + }; + perm.set_from_iter(elts, 0); + perm + } + + fn set_elt(&mut self, elt: T, idx: usize) { + self.state[idx] = elt; + } + + fn set_from_slice(&mut self, elts: &[T], start_idx: usize) { + let begin = start_idx; + let end = start_idx + elts.len(); + self.state[begin..end].copy_from_slice(elts); + } + + fn set_from_iter>(&mut self, elts: I, start_idx: usize) { + for (s, e) in self.state[start_idx..].iter_mut().zip(elts) { + *s = e; + } + } + + fn permute(&mut self) { + self.state = T::permute(self.state); + } + + fn squeeze(&self) -> &[T] { + &self.state[..Self::RATE] } } /// Poseidon hash function. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct PoseidonHash; -impl Hasher for PoseidonHash { +impl Hasher for PoseidonHash { const HASH_SIZE: usize = 4 * 8; type Hash = HashOut; - type Permutation = PoseidonPermutation; + type Permutation = PoseidonPermutation; fn hash_no_pad(input: &[F]) -> Self::Hash { - hash_n_to_hash_no_pad::(input) + hash_n_to_hash_no_pad::(input) } fn two_to_one(left: Self::Hash, right: Self::Hash) -> Self::Hash { - compress::(left, right) + compress::(left, right) } } -impl AlgebraicHasher for PoseidonHash { +impl AlgebraicHasher for PoseidonHash { + type AlgebraicPermutation = PoseidonPermutation; + fn permute_swapped( - inputs: [Target; SPONGE_WIDTH], + inputs: Self::AlgebraicPermutation, swap: BoolTarget, builder: &mut CircuitBuilder, - ) -> [Target; SPONGE_WIDTH] + ) -> Self::AlgebraicPermutation where F: RichField + Extendable, { @@ -673,6 +737,7 @@ impl AlgebraicHasher for PoseidonHash { builder.connect(swap.target, swap_wire); // Route input wires. + let inputs = inputs.as_ref(); for i in 0..SPONGE_WIDTH { let in_wire = PoseidonGate::::wire_input(i); let in_wire = Target::wire(gate, in_wire); @@ -680,11 +745,9 @@ impl AlgebraicHasher for PoseidonHash { } // Collect output wires. - (0..SPONGE_WIDTH) - .map(|i| Target::wire(gate, PoseidonGate::::wire_output(i))) - .collect::>() - .try_into() - .unwrap() + Self::AlgebraicPermutation::new( + (0..SPONGE_WIDTH).map(|i| Target::wire(gate, PoseidonGate::::wire_output(i))), + ) } } diff --git a/plonky2/src/iop/challenger.rs b/plonky2/src/iop/challenger.rs index 6a39b351..06636d8a 100644 --- a/plonky2/src/iop/challenger.rs +++ b/plonky2/src/iop/challenger.rs @@ -4,7 +4,7 @@ use core::marker::PhantomData; use crate::field::extension::{Extendable, FieldExtension}; use crate::hash::hash_types::{HashOut, HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::{HashConfig, PlonkyPermutation}; +use crate::hash::hashing::PlonkyPermutation; use crate::hash::merkle_tree::MerkleCap; use crate::iop::ext_target::ExtensionTarget; use crate::iop::target::Target; @@ -13,14 +13,10 @@ use crate::plonk::config::{AlgebraicHasher, GenericHashOut, Hasher}; /// Observes prover messages, and generates challenges by hashing the transcript, a la Fiat-Shamir. #[derive(Clone)] -pub struct Challenger> -where - [(); HC::WIDTH]:, -{ - pub(crate) sponge_state: [F; HC::WIDTH], +pub struct Challenger> { + pub(crate) sponge_state: H::Permutation, pub(crate) input_buffer: Vec, output_buffer: Vec, - _phantom: PhantomData, } /// Observes prover messages, and generates verifier challenges based on the transcript. @@ -31,16 +27,12 @@ where /// design, but it can be viewed as a duplex sponge whose inputs are sometimes zero (when we perform /// multiple squeezes) and whose outputs are sometimes ignored (when we perform multiple /// absorptions). Thus the security properties of a duplex sponge still apply to our design. -impl> Challenger -where - [(); HC::WIDTH]:, -{ - pub fn new() -> Challenger { +impl> Challenger { + pub fn new() -> Challenger { Challenger { - sponge_state: [F::ZERO; HC::WIDTH], - input_buffer: Vec::with_capacity(HC::RATE), - output_buffer: Vec::with_capacity(HC::RATE), - _phantom: Default::default(), + sponge_state: H::Permutation::new(std::iter::repeat(F::ZERO)), + input_buffer: Vec::with_capacity(H::Permutation::RATE), + output_buffer: Vec::with_capacity(H::Permutation::RATE), } } @@ -50,7 +42,7 @@ where self.input_buffer.push(element); - if self.input_buffer.len() == HC::RATE { + if self.input_buffer.len() == H::Permutation::RATE { self.duplexing(); } } @@ -71,23 +63,19 @@ where pub fn observe_extension_elements(&mut self, elements: &[F::Extension]) where F: RichField + Extendable, - [(); HC::WIDTH]:, { for element in elements { self.observe_extension_element(element); } } - pub fn observe_hash>(&mut self, hash: OH::Hash) { + pub fn observe_hash>(&mut self, hash: OH::Hash) { self.observe_elements(&hash.to_vec()) } - pub fn observe_cap>( - &mut self, - cap: &MerkleCap, - ) { + pub fn observe_cap>(&mut self, cap: &MerkleCap) { for &hash in &cap.0 { - self.observe_hash::(hash); + self.observe_hash::(hash); } } @@ -139,24 +127,23 @@ where /// Absorb any buffered inputs. After calling this, the input buffer will be empty, and the /// output buffer will be full. fn duplexing(&mut self) { - assert!(self.input_buffer.len() <= HC::RATE); + assert!(self.input_buffer.len() <= H::Permutation::RATE); // Overwrite the first r elements with the inputs. This differs from a standard sponge, // where we would xor or add in the inputs. This is a well-known variant, though, // sometimes called "overwrite mode". - for (i, input) in self.input_buffer.drain(..).enumerate() { - self.sponge_state[i] = input; - } + self.sponge_state + .set_from_iter(self.input_buffer.drain(..), 0); // Apply the permutation. - self.sponge_state = H::Permutation::permute(self.sponge_state); + self.sponge_state.permute(); self.output_buffer.clear(); self.output_buffer - .extend_from_slice(&self.sponge_state[0..HC::RATE]); + .extend_from_slice(self.sponge_state.squeeze()); } - pub fn compact(&mut self) -> [F; HC::WIDTH] { + pub fn compact(&mut self) -> H::Permutation { if !self.input_buffer.is_empty() { self.duplexing(); } @@ -165,48 +152,37 @@ where } } -impl> Default for Challenger -where - [(); HC::WIDTH]:, -{ +impl> Default for Challenger { fn default() -> Self { Self::new() } } /// A recursive version of `Challenger`. The main difference is that `RecursiveChallenger`'s input -/// buffer can grow beyond `HC::RATE`. This is so that `observe_element` etc do not need access +/// buffer can grow beyond `H::Permutation::RATE`. This is so that `observe_element` etc do not need access /// to the `CircuitBuilder`. -pub struct RecursiveChallenger< - F: RichField + Extendable, - HC: HashConfig, - H: AlgebraicHasher, - const D: usize, -> where - [(); HC::WIDTH]:, +pub struct RecursiveChallenger, H: AlgebraicHasher, const D: usize> { - sponge_state: [Target; HC::WIDTH], + sponge_state: H::AlgebraicPermutation, input_buffer: Vec, output_buffer: Vec, __: PhantomData<(F, H)>, } -impl, HC: HashConfig, H: AlgebraicHasher, const D: usize> - RecursiveChallenger -where - [(); HC::WIDTH]:, +impl, H: AlgebraicHasher, const D: usize> + RecursiveChallenger { pub fn new(builder: &mut CircuitBuilder) -> Self { let zero = builder.zero(); Self { - sponge_state: [zero; HC::WIDTH], + sponge_state: H::AlgebraicPermutation::new(std::iter::repeat(zero)), input_buffer: Vec::new(), output_buffer: Vec::new(), __: PhantomData, } } - pub fn from_state(sponge_state: [Target; HC::WIDTH]) -> Self { + pub fn from_state(sponge_state: H::AlgebraicPermutation) -> Self { Self { sponge_state, input_buffer: vec![], @@ -253,8 +229,8 @@ where if self.output_buffer.is_empty() { // Evaluate the permutation to produce `r` new outputs. - self.sponge_state = builder.permute::(self.sponge_state); - self.output_buffer = self.sponge_state[0..HC::RATE].to_vec(); + self.sponge_state = builder.permute::(self.sponge_state); + self.output_buffer = self.sponge_state.squeeze().to_vec(); } self.output_buffer @@ -295,24 +271,20 @@ where return; } - for input_chunk in self.input_buffer.chunks(HC::RATE) { + for input_chunk in self.input_buffer.chunks(H::AlgebraicPermutation::RATE) { // Overwrite the first r elements with the inputs. This differs from a standard sponge, // where we would xor or add in the inputs. This is a well-known variant, though, // sometimes called "overwrite mode". - for (i, &input) in input_chunk.iter().enumerate() { - self.sponge_state[i] = input; - } - - // Apply the permutation. - self.sponge_state = builder.permute::(self.sponge_state); + self.sponge_state.set_from_slice(input_chunk, 0); + self.sponge_state = builder.permute::(self.sponge_state); } - self.output_buffer = self.sponge_state[0..HC::RATE].to_vec(); + self.output_buffer = self.sponge_state.squeeze().to_vec(); self.input_buffer.clear(); } - pub fn compact(&mut self, builder: &mut CircuitBuilder) -> [Target; HC::WIDTH] { + pub fn compact(&mut self, builder: &mut CircuitBuilder) -> H::AlgebraicPermutation { self.absorb_buffered_inputs(builder); self.output_buffer.clear(); self.sponge_state @@ -335,11 +307,7 @@ mod tests { const D: usize = 2; type C = PoseidonGoldilocksConfig; type F = >::F; - let mut challenger = Challenger::< - F, - >::HCI, - >::InnerHasher, - >::new(); + let mut challenger = Challenger::>::InnerHasher>::new(); let mut challenges = Vec::new(); for i in 1..10 { @@ -373,11 +341,7 @@ mod tests { .map(|&n| F::rand_vec(n)) .collect(); - let mut challenger = Challenger::< - F, - >::HCI, - >::InnerHasher, - >::new(); + let mut challenger = Challenger::>::InnerHasher>::new(); let mut outputs_per_round: Vec> = Vec::new(); for (r, inputs) in inputs_per_round.iter().enumerate() { challenger.observe_elements(inputs); @@ -386,12 +350,8 @@ mod tests { let config = CircuitConfig::standard_recursion_config(); let mut builder = CircuitBuilder::::new(config); - let mut recursive_challenger = RecursiveChallenger::< - F, - >::HCI, - >::InnerHasher, - D, - >::new(&mut builder); + let mut recursive_challenger = + RecursiveChallenger::>::InnerHasher, D>::new(&mut builder); let mut recursive_outputs_per_round: Vec> = Vec::new(); for (r, inputs) in inputs_per_round.iter().enumerate() { recursive_challenger.observe_elements(&builder.constants(inputs)); diff --git a/plonky2/src/iop/witness.rs b/plonky2/src/iop/witness.rs index 21531d71..6ad690d0 100644 --- a/plonky2/src/iop/witness.rs +++ b/plonky2/src/iop/witness.rs @@ -2,14 +2,13 @@ use alloc::vec; use alloc::vec::Vec; use hashbrown::HashMap; -use itertools::Itertools; +use itertools::{zip_eq, Itertools}; use crate::field::extension::{Extendable, FieldExtension}; use crate::field::types::Field; use crate::fri::structure::{FriOpenings, FriOpeningsTarget}; use crate::fri::witness_util::set_fri_proof_target; use crate::hash::hash_types::{HashOut, HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleCap; use crate::iop::ext_target::ExtensionTarget; use crate::iop::target::{BoolTarget, Target}; @@ -28,10 +27,10 @@ pub trait WitnessWrite { .for_each(|(&t, x)| self.set_target(t, x)); } - fn set_cap_target>( + fn set_cap_target>( &mut self, ct: &MerkleCapTarget, - value: &MerkleCap, + value: &MerkleCap, ) where F: RichField, { @@ -44,13 +43,11 @@ pub trait WitnessWrite { where F: RichField + Extendable, { - self.set_target_arr(et.0, value.to_basefield_array()); + self.set_target_arr(&et.0, &value.to_basefield_array()); } - fn set_target_arr(&mut self, targets: [Target; N], values: [F; N]) { - (0..N).for_each(|i| { - self.set_target(targets[i], values[i]); - }); + fn set_target_arr(&mut self, targets: &[Target], values: &[F]) { + zip_eq(targets, values).for_each(|(&target, &value)| self.set_target(target, value)); } fn set_extension_targets( @@ -78,7 +75,7 @@ pub trait WitnessWrite { proof_with_pis: &ProofWithPublicInputs, ) where F: RichField + Extendable, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { let ProofWithPublicInputs { proof, @@ -104,7 +101,7 @@ pub trait WitnessWrite { proof: &Proof, ) where F: RichField + Extendable, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { self.set_cap_target(&proof_target.wires_cap, &proof.wires_cap); self.set_cap_target( @@ -143,7 +140,7 @@ pub trait WitnessWrite { vd: &VerifierOnlyCircuitData, ) where F: RichField + Extendable, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { self.set_cap_target(&vdt.constants_sigmas_cap, &vd.constants_sigmas_cap); self.set_hash_target(vdt.circuit_digest, vd.circuit_digest); @@ -225,14 +222,10 @@ pub trait Witness: WitnessWrite { } } - fn get_merkle_cap_target>( - &self, - cap_target: MerkleCapTarget, - ) -> MerkleCap + fn get_merkle_cap_target>(&self, cap_target: MerkleCapTarget) -> MerkleCap where F: RichField, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, { let cap = cap_target .0 diff --git a/plonky2/src/lib.rs b/plonky2/src/lib.rs index 4b7ebbbc..b955fea7 100644 --- a/plonky2/src/lib.rs +++ b/plonky2/src/lib.rs @@ -1,8 +1,6 @@ #![allow(clippy::too_many_arguments)] #![allow(clippy::needless_range_loop)] #![allow(clippy::upper_case_acronyms)] -#![allow(incomplete_features)] -#![feature(generic_const_exprs)] #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; diff --git a/plonky2/src/plonk/circuit_builder.rs b/plonky2/src/plonk/circuit_builder.rs index 851e23a8..84b2a0ed 100644 --- a/plonky2/src/plonk/circuit_builder.rs +++ b/plonky2/src/plonk/circuit_builder.rs @@ -27,7 +27,6 @@ use crate::gates::noop::NoopGate; use crate::gates::public_input::PublicInputGate; use crate::gates::selectors::selector_polynomials; use crate::hash::hash_types::{HashOut, HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_proofs::MerkleProofTarget; use crate::hash::merkle_tree::MerkleCap; use crate::iop::ext_target::ExtensionTarget; @@ -435,9 +434,9 @@ impl, const D: usize> CircuitBuilder { } } - pub fn constant_merkle_cap>>( + pub fn constant_merkle_cap>>( &mut self, - cap: &MerkleCap, + cap: &MerkleCap, ) -> MerkleCapTarget { MerkleCapTarget(cap.0.iter().map(|h| self.constant_hash(*h)).collect()) } @@ -447,7 +446,7 @@ impl, const D: usize> CircuitBuilder { verifier_data: &VerifierOnlyCircuitData, ) -> VerifierCircuitTarget where - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { VerifierCircuitTarget { constants_sigmas_cap: self.constant_merkle_cap(&verifier_data.constants_sigmas_cap), @@ -738,11 +737,7 @@ impl, const D: usize> CircuitBuilder { } /// Builds a "full circuit", with both prover and verifier data. - pub fn build>(mut self) -> CircuitData - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + pub fn build>(mut self) -> CircuitData { let mut timing = TimingTree::new("preprocess", Level::Trace); #[cfg(feature = "std")] let start = Instant::now(); @@ -753,7 +748,7 @@ impl, const D: usize> CircuitBuilder { // those hash wires match the claimed public inputs. let num_public_inputs = self.public_inputs.len(); let public_inputs_hash = - self.hash_n_to_hash_no_pad::(self.public_inputs.clone()); + self.hash_n_to_hash_no_pad::(self.public_inputs.clone()); let pi_gate = self.add_gate(PublicInputGate, vec![]); for (&hash_part, wire) in public_inputs_hash .elements @@ -946,22 +941,14 @@ impl, const D: usize> CircuitBuilder { } /// Builds a "prover circuit", with data needed to generate proofs but not verify them. - pub fn build_prover>(self) -> ProverCircuitData - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + pub fn build_prover>(self) -> ProverCircuitData { // TODO: Can skip parts of this. let circuit_data = self.build::(); circuit_data.prover_data() } /// Builds a "verifier circuit", with data needed to verify proofs but not generate them. - pub fn build_verifier>(self) -> VerifierCircuitData - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + pub fn build_verifier>(self) -> VerifierCircuitData { // TODO: Can skip parts of this. let circuit_data = self.build::(); circuit_data.verifier_data() diff --git a/plonky2/src/plonk/circuit_data.rs b/plonky2/src/plonk/circuit_data.rs index 8ecf646e..46bfd40c 100644 --- a/plonky2/src/plonk/circuit_data.rs +++ b/plonky2/src/plonk/circuit_data.rs @@ -19,7 +19,6 @@ use crate::fri::{FriConfig, FriParams}; use crate::gates::gate::GateRef; use crate::gates::selectors::SelectorsInfo; use crate::hash::hash_types::{HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleCap; use crate::iop::ext_target::ExtensionTarget; use crate::iop::generator::WitnessGeneratorRef; @@ -139,11 +138,7 @@ impl, C: GenericConfig, const D: usize> buffer.read_circuit_data(gate_serializer, generator_serializer) } - pub fn prove(&self, inputs: PartialWitness) -> Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + pub fn prove(&self, inputs: PartialWitness) -> Result> { prove::( &self.prover_only, &self.common, @@ -152,44 +147,28 @@ impl, C: GenericConfig, const D: usize> ) } - pub fn verify(&self, proof_with_pis: ProofWithPublicInputs) -> Result<()> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + pub fn verify(&self, proof_with_pis: ProofWithPublicInputs) -> Result<()> { verify::(proof_with_pis, &self.verifier_only, &self.common) } pub fn verify_compressed( &self, compressed_proof_with_pis: CompressedProofWithPublicInputs, - ) -> Result<()> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> Result<()> { compressed_proof_with_pis.verify(&self.verifier_only, &self.common) } pub fn compress( &self, proof: ProofWithPublicInputs, - ) -> Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> Result> { proof.compress(&self.verifier_only.circuit_digest, &self.common) } pub fn decompress( &self, proof: CompressedProofWithPublicInputs, - ) -> Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> Result> { proof.decompress(&self.verifier_only.circuit_digest, &self.common) } @@ -256,11 +235,7 @@ impl, C: GenericConfig, const D: usize> buffer.read_prover_circuit_data(gate_serializer, generator_serializer) } - pub fn prove(&self, inputs: PartialWitness) -> Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + pub fn prove(&self, inputs: PartialWitness) -> Result> { prove::( &self.prover_only, &self.common, @@ -298,22 +273,14 @@ impl, C: GenericConfig, const D: usize> buffer.read_verifier_circuit_data(gate_serializer) } - pub fn verify(&self, proof_with_pis: ProofWithPublicInputs) -> Result<()> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + pub fn verify(&self, proof_with_pis: ProofWithPublicInputs) -> Result<()> { verify::(proof_with_pis, &self.verifier_only, &self.common) } pub fn verify_compressed( &self, compressed_proof_with_pis: CompressedProofWithPublicInputs, - ) -> Result<()> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> Result<()> { compressed_proof_with_pis.verify(&self.verifier_only, &self.common) } } @@ -344,17 +311,17 @@ pub struct ProverOnlyCircuitData< pub fft_root_table: Option>, /// A digest of the "circuit" (i.e. the instance, minus public inputs), which can be used to /// seed Fiat-Shamir. - pub circuit_digest: <>::Hasher as Hasher>::Hash, + pub circuit_digest: <>::Hasher as Hasher>::Hash, } /// Circuit data required by the verifier, but not the prover. #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct VerifierOnlyCircuitData, const D: usize> { /// A commitment to each constant polynomial and each permutation polynomial. - pub constants_sigmas_cap: MerkleCap, + pub constants_sigmas_cap: MerkleCap, /// A digest of the "circuit" (i.e. the instance, minus public inputs), which can be used to /// seed Fiat-Shamir. - pub circuit_digest: <>::Hasher as Hasher>::Hash, + pub circuit_digest: <>::Hasher as Hasher>::Hash, } impl, const D: usize> VerifierOnlyCircuitData { diff --git a/plonky2/src/plonk/config.rs b/plonky2/src/plonk/config.rs index a5fe5bdc..04df1ba7 100644 --- a/plonky2/src/plonk/config.rs +++ b/plonky2/src/plonk/config.rs @@ -9,7 +9,7 @@ use crate::field::extension::quadratic::QuadraticExtension; use crate::field::extension::{Extendable, FieldExtension}; use crate::field::goldilocks_field::GoldilocksField; use crate::hash::hash_types::{HashOut, RichField}; -use crate::hash::hashing::{HashConfig, PlonkyPermutation}; +use crate::hash::hashing::PlonkyPermutation; use crate::hash::keccak::KeccakHash; use crate::hash::poseidon::PoseidonHash; use crate::iop::target::{BoolTarget, Target}; @@ -25,7 +25,7 @@ pub trait GenericHashOut: } /// Trait for hash functions. -pub trait Hasher: Sized + Clone + Debug + Eq + PartialEq { +pub trait Hasher: Sized + Copy + Debug + Eq + PartialEq { /// Size of `Hash` in bytes. const HASH_SIZE: usize; @@ -33,22 +33,17 @@ pub trait Hasher: Sized + Clone + Debug + Eq + Par type Hash: GenericHashOut; /// Permutation used in the sponge construction. - type Permutation: PlonkyPermutation; + type Permutation: PlonkyPermutation; /// Hash a message without any padding step. Note that this can enable length-extension attacks. /// However, it is still collision-resistant in cases where the input has a fixed length. - fn hash_no_pad(input: &[F]) -> Self::Hash - where - [(); HC::WIDTH]:; + fn hash_no_pad(input: &[F]) -> Self::Hash; /// Pad the message using the `pad10*1` rule, then hash it. - fn hash_pad(input: &[F]) -> Self::Hash - where - [(); HC::WIDTH]:, - { + fn hash_pad(input: &[F]) -> Self::Hash { let mut padded_input = input.to_vec(); padded_input.push(F::ONE); - while (padded_input.len() + 1) % HC::WIDTH != 0 { + while (padded_input.len() + 1) % Self::Permutation::WIDTH != 0 { padded_input.push(F::ZERO); } padded_input.push(F::ONE); @@ -57,10 +52,7 @@ pub trait Hasher: Sized + Clone + Debug + Eq + Par /// Hash the slice if necessary to reduce its length to ~256 bits. If it already fits, this is a /// no-op. - fn hash_or_noop(inputs: &[F]) -> Self::Hash - where - [(); HC::WIDTH]:, - { + fn hash_or_noop(inputs: &[F]) -> Self::Hash { if inputs.len() * 8 <= Self::HASH_SIZE { let mut inputs_bytes = vec![0u8; Self::HASH_SIZE]; for i in 0..inputs.len() { @@ -73,22 +65,21 @@ pub trait Hasher: Sized + Clone + Debug + Eq + Par } } - fn two_to_one(left: Self::Hash, right: Self::Hash) -> Self::Hash - where - [(); HC::WIDTH]:; + fn two_to_one(left: Self::Hash, right: Self::Hash) -> Self::Hash; } /// Trait for algebraic hash functions, built from a permutation using the sponge construction. -pub trait AlgebraicHasher: Hasher> { +pub trait AlgebraicHasher: Hasher> { + type AlgebraicPermutation: PlonkyPermutation; + /// Circuit to conditionally swap two chunks of the inputs (useful in verifying Merkle proofs), /// then apply the permutation. fn permute_swapped( - inputs: [Target; HC::WIDTH], + inputs: Self::AlgebraicPermutation, swap: BoolTarget, builder: &mut CircuitBuilder, - ) -> [Target; HC::WIDTH] + ) -> Self::AlgebraicPermutation where - [(); HC::WIDTH]:, F: RichField + Extendable; } @@ -100,48 +91,28 @@ pub trait GenericConfig: type F: RichField + Extendable; /// Field extension of degree D of the main field. type FE: FieldExtension; - /// Hash configuration for this GenericConfig's `Hasher`. - type HCO: HashConfig; - /// Hash configuration for this GenericConfig's `InnerHasher`. - type HCI: HashConfig; /// Hash function used for building Merkle trees. - type Hasher: Hasher; + type Hasher: Hasher; /// Algebraic hash function used for the challenger and hashing public inputs. - type InnerHasher: AlgebraicHasher; + type InnerHasher: AlgebraicHasher; } -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct PoseidonHashConfig; -impl HashConfig for PoseidonHashConfig { - const RATE: usize = 8; - const WIDTH: usize = 12; -} /// Configuration using Poseidon over the Goldilocks field. #[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize)] pub struct PoseidonGoldilocksConfig; impl GenericConfig<2> for PoseidonGoldilocksConfig { type F = GoldilocksField; type FE = QuadraticExtension; - type HCO = PoseidonHashConfig; - type HCI = PoseidonHashConfig; type Hasher = PoseidonHash; type InnerHasher = PoseidonHash; } -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct KeccakHashConfig; -impl HashConfig for KeccakHashConfig { - const RATE: usize = 8; - const WIDTH: usize = 12; -} /// Configuration using truncated Keccak over the Goldilocks field. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct KeccakGoldilocksConfig; impl GenericConfig<2> for KeccakGoldilocksConfig { type F = GoldilocksField; type FE = QuadraticExtension; - type HCO = KeccakHashConfig; - type HCI = PoseidonHashConfig; type Hasher = KeccakHash<25>; type InnerHasher = PoseidonHash; } diff --git a/plonky2/src/plonk/get_challenges.rs b/plonky2/src/plonk/get_challenges.rs index 0e90b398..d5f028b4 100644 --- a/plonky2/src/plonk/get_challenges.rs +++ b/plonky2/src/plonk/get_challenges.rs @@ -9,7 +9,6 @@ use crate::fri::proof::{CompressedFriProof, FriChallenges, FriProof, FriProofTar use crate::fri::verifier::{compute_evaluation, fri_combine_initial, PrecomputedReducedOpenings}; use crate::gadgets::polynomial::PolynomialCoeffsExtTarget; use crate::hash::hash_types::{HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleCap; use crate::iop::challenger::{Challenger, RecursiveChallenger}; use crate::iop::target::Target; @@ -24,38 +23,34 @@ use crate::plonk::proof::{ use crate::util::reverse_bits; fn get_challenges, C: GenericConfig, const D: usize>( - public_inputs_hash: <>::InnerHasher as Hasher>::Hash, - wires_cap: &MerkleCap, - plonk_zs_partial_products_cap: &MerkleCap, - quotient_polys_cap: &MerkleCap, + public_inputs_hash: <>::InnerHasher as Hasher>::Hash, + wires_cap: &MerkleCap, + plonk_zs_partial_products_cap: &MerkleCap, + quotient_polys_cap: &MerkleCap, openings: &OpeningSet, - commit_phase_merkle_caps: &[MerkleCap], + commit_phase_merkle_caps: &[MerkleCap], final_poly: &PolynomialCoeffs, pow_witness: F, - circuit_digest: &<>::Hasher as Hasher>::Hash, + circuit_digest: &<>::Hasher as Hasher>::Hash, common_data: &CommonCircuitData, -) -> anyhow::Result> -where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, -{ +) -> anyhow::Result> { let config = &common_data.config; let num_challenges = config.num_challenges; - let mut challenger = Challenger::::new(); + let mut challenger = Challenger::::new(); // Observe the instance. - challenger.observe_hash::(*circuit_digest); - challenger.observe_hash::(public_inputs_hash); + challenger.observe_hash::(*circuit_digest); + challenger.observe_hash::(public_inputs_hash); - challenger.observe_cap::(wires_cap); + challenger.observe_cap::(wires_cap); let plonk_betas = challenger.get_n_challenges(num_challenges); let plonk_gammas = challenger.get_n_challenges(num_challenges); - challenger.observe_cap::(plonk_zs_partial_products_cap); + challenger.observe_cap::(plonk_zs_partial_products_cap); let plonk_alphas = challenger.get_n_challenges(num_challenges); - challenger.observe_cap::(quotient_polys_cap); + challenger.observe_cap::(quotient_polys_cap); let plonk_zeta = challenger.get_extension_challenge::(); challenger.observe_openings(&openings.to_fri_openings()); @@ -80,13 +75,9 @@ impl, C: GenericConfig, const D: usize> { pub(crate) fn fri_query_indices( &self, - circuit_digest: &<>::Hasher as Hasher>::Hash, + circuit_digest: &<>::Hasher as Hasher>::Hash, common_data: &CommonCircuitData, - ) -> anyhow::Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> anyhow::Result> { Ok(self .get_challenges(self.get_public_inputs_hash(), circuit_digest, common_data)? .fri_challenges @@ -96,14 +87,10 @@ impl, C: GenericConfig, const D: usize> /// Computes all Fiat-Shamir challenges used in the Plonk proof. pub fn get_challenges( &self, - public_inputs_hash: <>::InnerHasher as Hasher>::Hash, - circuit_digest: &<>::Hasher as Hasher>::Hash, + public_inputs_hash: <>::InnerHasher as Hasher>::Hash, + circuit_digest: &<>::Hasher as Hasher>::Hash, common_data: &CommonCircuitData, - ) -> anyhow::Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> anyhow::Result> { let Proof { wires_cap, plonk_zs_partial_products_cap, @@ -139,14 +126,10 @@ impl, C: GenericConfig, const D: usize> /// Computes all Fiat-Shamir challenges used in the Plonk proof. pub(crate) fn get_challenges( &self, - public_inputs_hash: <>::InnerHasher as Hasher>::Hash, - circuit_digest: &<>::Hasher as Hasher>::Hash, + public_inputs_hash: <>::InnerHasher as Hasher>::Hash, + circuit_digest: &<>::Hasher as Hasher>::Hash, common_data: &CommonCircuitData, - ) -> anyhow::Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> anyhow::Result> { let CompressedProof { wires_cap, plonk_zs_partial_products_cap, @@ -266,14 +249,12 @@ impl, const D: usize> CircuitBuilder { inner_common_data: &CommonCircuitData, ) -> ProofChallengesTarget where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let config = &inner_common_data.config; let num_challenges = config.num_challenges; - let mut challenger = RecursiveChallenger::::new(self); + let mut challenger = RecursiveChallenger::::new(self); // Observe the instance. challenger.observe_hash(&inner_circuit_digest); @@ -316,9 +297,7 @@ impl ProofWithPublicInputsTarget { inner_common_data: &CommonCircuitData, ) -> ProofChallengesTarget where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let ProofTarget { wires_cap, diff --git a/plonky2/src/plonk/proof.rs b/plonky2/src/plonk/proof.rs index 86203dd1..f0009150 100644 --- a/plonky2/src/plonk/proof.rs +++ b/plonky2/src/plonk/proof.rs @@ -15,7 +15,6 @@ use crate::fri::structure::{ }; use crate::fri::FriParams; use crate::hash::hash_types::{MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleCap; use crate::iop::ext_target::ExtensionTarget; use crate::iop::target::Target; @@ -30,15 +29,15 @@ use crate::util::serialization::{Buffer, Read}; #[serde(bound = "")] pub struct Proof, C: GenericConfig, const D: usize> { /// Merkle cap of LDEs of wire values. - pub wires_cap: MerkleCap, + pub wires_cap: MerkleCap, /// Merkle cap of LDEs of Z, in the context of Plonk's permutation argument. - pub plonk_zs_partial_products_cap: MerkleCap, + pub plonk_zs_partial_products_cap: MerkleCap, /// Merkle cap of LDEs of the quotient polynomial components. - pub quotient_polys_cap: MerkleCap, + pub quotient_polys_cap: MerkleCap, /// Purported values of each polynomial at the challenge point. pub openings: OpeningSet, /// A batch FRI argument for all openings. - pub opening_proof: FriProof, + pub opening_proof: FriProof, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -87,13 +86,9 @@ impl, C: GenericConfig, const D: usize> { pub fn compress( self, - circuit_digest: &<>::Hasher as Hasher>::Hash, + circuit_digest: &<>::Hasher as Hasher>::Hash, common_data: &CommonCircuitData, - ) -> anyhow::Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> anyhow::Result> { let indices = self.fri_query_indices(circuit_digest, common_data)?; let compressed_proof = self.proof.compress(&indices, &common_data.fri_params); Ok(CompressedProofWithPublicInputs { @@ -104,10 +99,7 @@ impl, C: GenericConfig, const D: usize> pub fn get_public_inputs_hash( &self, - ) -> <>::InnerHasher as Hasher>::Hash - where - [(); C::HCI::WIDTH]:, - { + ) -> <>::InnerHasher as Hasher>::Hash { C::InnerHasher::hash_no_pad(&self.public_inputs) } @@ -137,15 +129,15 @@ impl, C: GenericConfig, const D: usize> pub struct CompressedProof, C: GenericConfig, const D: usize> { /// Merkle cap of LDEs of wire values. - pub wires_cap: MerkleCap, + pub wires_cap: MerkleCap, /// Merkle cap of LDEs of Z, in the context of Plonk's permutation argument. - pub plonk_zs_partial_products_cap: MerkleCap, + pub plonk_zs_partial_products_cap: MerkleCap, /// Merkle cap of LDEs of the quotient polynomial components. - pub quotient_polys_cap: MerkleCap, + pub quotient_polys_cap: MerkleCap, /// Purported values of each polynomial at the challenge point. pub openings: OpeningSet, /// A compressed batch FRI argument for all openings. - pub opening_proof: CompressedFriProof, + pub opening_proof: CompressedFriProof, } impl, C: GenericConfig, const D: usize> @@ -157,10 +149,7 @@ impl, C: GenericConfig, const D: usize> challenges: &ProofChallenges, fri_inferred_elements: FriInferredElements, params: &FriParams, - ) -> Proof - where - [(); C::HCO::WIDTH]:, - { + ) -> Proof { let CompressedProof { wires_cap, plonk_zs_partial_products_cap, @@ -195,13 +184,9 @@ impl, C: GenericConfig, const D: usize> { pub fn decompress( self, - circuit_digest: &<>::Hasher as Hasher>::Hash, + circuit_digest: &<>::Hasher as Hasher>::Hash, common_data: &CommonCircuitData, - ) -> anyhow::Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> anyhow::Result> { let challenges = self.get_challenges(self.get_public_inputs_hash(), circuit_digest, common_data)?; let fri_inferred_elements = self.get_inferred_elements(&challenges, common_data); @@ -218,11 +203,7 @@ impl, C: GenericConfig, const D: usize> self, verifier_data: &VerifierOnlyCircuitData, common_data: &CommonCircuitData, - ) -> anyhow::Result<()> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> anyhow::Result<()> { ensure!( self.public_inputs.len() == common_data.num_public_inputs, "Number of public inputs doesn't match circuit data." @@ -248,10 +229,7 @@ impl, C: GenericConfig, const D: usize> pub(crate) fn get_public_inputs_hash( &self, - ) -> <>::InnerHasher as Hasher>::Hash - where - [(); C::HCI::WIDTH]:, - { + ) -> <>::InnerHasher as Hasher>::Hash { C::InnerHasher::hash_no_pad(&self.public_inputs) } diff --git a/plonky2/src/plonk/prover.rs b/plonky2/src/plonk/prover.rs index 29d9721f..86301bb9 100644 --- a/plonky2/src/plonk/prover.rs +++ b/plonky2/src/plonk/prover.rs @@ -11,7 +11,6 @@ use crate::field::types::Field; use crate::field::zero_poly_coset::ZeroPolyOnCoset; use crate::fri::oracle::PolynomialBatch; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; use crate::iop::challenger::Challenger; use crate::iop::generator::generate_partial_witness; use crate::iop::witness::{MatrixWitness, PartialWitness, Witness}; @@ -33,10 +32,8 @@ pub fn prove, C: GenericConfig, const D: timing: &mut TimingTree, ) -> Result> where - C::Hasher: Hasher, - C::InnerHasher: Hasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: Hasher, + C::InnerHasher: Hasher, { let config = &common_data.config; let num_challenges = config.num_challenges; @@ -81,13 +78,13 @@ where ) ); - let mut challenger = Challenger::::new(); + let mut challenger = Challenger::::new(); // Observe the instance. - challenger.observe_hash::(prover_data.circuit_digest); - challenger.observe_hash::(public_inputs_hash); + challenger.observe_hash::(prover_data.circuit_digest); + challenger.observe_hash::(public_inputs_hash); - challenger.observe_cap::(&wires_commitment.merkle_tree.cap); + challenger.observe_cap::(&wires_commitment.merkle_tree.cap); let betas = challenger.get_n_challenges(num_challenges); let gammas = challenger.get_n_challenges(num_challenges); @@ -121,8 +118,7 @@ where ) ); - challenger - .observe_cap::(&partial_products_and_zs_commitment.merkle_tree.cap); + challenger.observe_cap::(&partial_products_and_zs_commitment.merkle_tree.cap); let alphas = challenger.get_n_challenges(num_challenges); @@ -170,7 +166,7 @@ where ) ); - challenger.observe_cap::("ient_polys_commitment.merkle_tree.cap); + challenger.observe_cap::("ient_polys_commitment.merkle_tree.cap); let zeta = challenger.get_extension_challenge::(); // To avoid leaking witness data, we want to ensure that our opening locations, `zeta` and @@ -324,7 +320,7 @@ fn compute_quotient_polys< >( common_data: &CommonCircuitData, prover_data: &'a ProverOnlyCircuitData, - public_inputs_hash: &<>::InnerHasher as Hasher>::Hash, + public_inputs_hash: &<>::InnerHasher as Hasher>::Hash, wires_commitment: &'a PolynomialBatch, zs_partial_products_commitment: &'a PolynomialBatch, betas: &[F], diff --git a/plonky2/src/plonk/verifier.rs b/plonky2/src/plonk/verifier.rs index 4c4905df..ecb7e46c 100644 --- a/plonky2/src/plonk/verifier.rs +++ b/plonky2/src/plonk/verifier.rs @@ -4,7 +4,6 @@ use crate::field::extension::Extendable; use crate::field::types::Field; use crate::fri::verifier::verify_fri_proof; use crate::hash::hash_types::RichField; -use crate::hash::hashing::HashConfig; use crate::plonk::circuit_data::{CommonCircuitData, VerifierOnlyCircuitData}; use crate::plonk::config::{GenericConfig, Hasher}; use crate::plonk::plonk_common::reduce_with_powers; @@ -17,11 +16,7 @@ pub(crate) fn verify, C: GenericConfig, c proof_with_pis: ProofWithPublicInputs, verifier_data: &VerifierOnlyCircuitData, common_data: &CommonCircuitData, -) -> Result<()> -where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, -{ +) -> Result<()> { validate_proof_with_pis_shape(&proof_with_pis, common_data)?; let public_inputs_hash = proof_with_pis.get_public_inputs_hash(); @@ -46,14 +41,11 @@ pub(crate) fn verify_with_challenges< const D: usize, >( proof: Proof, - public_inputs_hash: <>::InnerHasher as Hasher>::Hash, + public_inputs_hash: <>::InnerHasher as Hasher>::Hash, challenges: ProofChallenges, verifier_data: &VerifierOnlyCircuitData, common_data: &CommonCircuitData, -) -> Result<()> -where - [(); C::HCO::WIDTH]:, -{ +) -> Result<()> { let local_constants = &proof.openings.constants; let local_wires = &proof.openings.wires; let vars = EvaluationVars { diff --git a/plonky2/src/recursion/conditional_recursive_verifier.rs b/plonky2/src/recursion/conditional_recursive_verifier.rs index 20eaf493..6331118b 100644 --- a/plonky2/src/recursion/conditional_recursive_verifier.rs +++ b/plonky2/src/recursion/conditional_recursive_verifier.rs @@ -8,7 +8,6 @@ use crate::fri::proof::{ }; use crate::gadgets::polynomial::PolynomialCoeffsExtTarget; use crate::hash::hash_types::{HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_proofs::MerkleProofTarget; use crate::iop::ext_target::ExtensionTarget; use crate::iop::target::{BoolTarget, Target}; @@ -30,9 +29,7 @@ impl, const D: usize> CircuitBuilder { inner_verifier_data1: &VerifierCircuitTarget, inner_common_data: &CommonCircuitData, ) where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let selected_proof = self.select_proof_with_pis(condition, proof_with_pis0, proof_with_pis1); @@ -61,9 +58,7 @@ impl, const D: usize> CircuitBuilder { inner_common_data: &CommonCircuitData, ) -> anyhow::Result<()> where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let (dummy_proof_with_pis_target, dummy_verifier_data_target) = self.dummy_proof_and_vk::(inner_common_data)?; diff --git a/plonky2/src/recursion/cyclic_recursion.rs b/plonky2/src/recursion/cyclic_recursion.rs index 7b584e4d..4c47787f 100644 --- a/plonky2/src/recursion/cyclic_recursion.rs +++ b/plonky2/src/recursion/cyclic_recursion.rs @@ -4,7 +4,6 @@ use anyhow::{ensure, Result}; use crate::field::extension::Extendable; use crate::hash::hash_types::{HashOut, HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleCap; use crate::iop::target::{BoolTarget, Target}; use crate::plonk::circuit_builder::CircuitBuilder; @@ -18,7 +17,7 @@ use crate::util::serialization::{Buffer, IoResult, Read, Write}; impl, const D: usize> VerifierOnlyCircuitData { fn from_slice(slice: &[C::F], common_data: &CommonCircuitData) -> Result where - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { // The structure of the public inputs is `[..., circuit_digest, constants_sigmas_cap]`. let cap_len = common_data.config.fri_config.num_cap_elements(); @@ -107,9 +106,7 @@ impl, const D: usize> CircuitBuilder { common_data: &CommonCircuitData, ) -> Result<()> where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let verifier_data = self .verifier_data_public_input @@ -161,9 +158,7 @@ impl, const D: usize> CircuitBuilder { common_data: &CommonCircuitData, ) -> Result<()> where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let (dummy_proof_with_pis_target, dummy_verifier_data_target) = self.dummy_proof_and_vk::(common_data)?; @@ -190,9 +185,7 @@ pub fn check_cyclic_proof_verifier_data< common_data: &CommonCircuitData, ) -> Result<()> where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let pis = VerifierOnlyCircuitData::::from_slice(&proof.public_inputs, common_data)?; ensure!(verifier_data.constants_sigmas_cap == pis.constants_sigmas_cap); @@ -209,14 +202,12 @@ mod tests { use crate::field::types::{Field, PrimeField64}; use crate::gates::noop::NoopGate; use crate::hash::hash_types::{HashOutTarget, RichField}; - use crate::hash::hashing::{hash_n_to_hash_no_pad, HashConfig}; + use crate::hash::hashing::hash_n_to_hash_no_pad; use crate::hash::poseidon::{PoseidonHash, PoseidonPermutation}; use crate::iop::witness::{PartialWitness, WitnessWrite}; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::circuit_data::{CircuitConfig, CommonCircuitData}; - use crate::plonk::config::{ - AlgebraicHasher, GenericConfig, PoseidonGoldilocksConfig, PoseidonHashConfig, - }; + use crate::plonk::config::{AlgebraicHasher, GenericConfig, PoseidonGoldilocksConfig}; use crate::recursion::cyclic_recursion::check_cyclic_proof_verifier_data; use crate::recursion::dummy_circuit::cyclic_base_proof; @@ -227,9 +218,7 @@ mod tests { const D: usize, >() -> CommonCircuitData where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let config = CircuitConfig::standard_recursion_config(); let builder = CircuitBuilder::::new(config); @@ -274,9 +263,8 @@ mod tests { let initial_hash_target = builder.add_virtual_hash(); builder.register_public_inputs(&initial_hash_target.elements); let current_hash_in = builder.add_virtual_hash(); - let current_hash_out = builder.hash_n_to_hash_no_pad::( - current_hash_in.elements.to_vec(), - ); + let current_hash_out = + builder.hash_n_to_hash_no_pad::(current_hash_in.elements.to_vec()); builder.register_public_inputs(¤t_hash_out.elements); let counter = builder.add_virtual_public_input(); @@ -377,8 +365,7 @@ mod tests { fn iterate_poseidon(initial_state: [F; 4], n: usize) -> [F; 4] { let mut current = initial_state; for _ in 0..n { - current = hash_n_to_hash_no_pad::(¤t) - .elements; + current = hash_n_to_hash_no_pad::>(¤t).elements; } current } diff --git a/plonky2/src/recursion/dummy_circuit.rs b/plonky2/src/recursion/dummy_circuit.rs index 79bfff15..daf9319a 100644 --- a/plonky2/src/recursion/dummy_circuit.rs +++ b/plonky2/src/recursion/dummy_circuit.rs @@ -10,7 +10,6 @@ use crate::fri::proof::{FriProof, FriProofTarget}; use crate::gadgets::polynomial::PolynomialCoeffsExtTarget; use crate::gates::noop::NoopGate; use crate::hash::hash_types::{HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_tree::MerkleCap; use crate::iop::generator::{GeneratedValues, SimpleGenerator}; use crate::iop::target::Target; @@ -39,9 +38,7 @@ pub fn cyclic_base_proof( where F: RichField + Extendable, C: GenericConfig, - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let pis_len = common_data.num_public_inputs; let cap_elements = common_data.config.fri_config.num_cap_elements(); @@ -76,8 +73,6 @@ pub(crate) fn dummy_proof< nonzero_public_inputs: HashMap, ) -> anyhow::Result> where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let mut pw = PartialWitness::new(); for i in 0..circuit.common.num_public_inputs { @@ -94,11 +89,7 @@ pub(crate) fn dummy_circuit< const D: usize, >( common_data: &CommonCircuitData, -) -> CircuitData -where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, -{ +) -> CircuitData { let config = common_data.config.clone(); assert!( !common_data.config.zero_knowledge, @@ -132,9 +123,7 @@ impl, const D: usize> CircuitBuilder { common_data: &CommonCircuitData, ) -> anyhow::Result<(ProofWithPublicInputsTarget, VerifierCircuitTarget)> where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let dummy_circuit = dummy_circuit::(common_data); let dummy_proof_with_pis = dummy_proof::(&dummy_circuit, HashMap::new())?; @@ -212,10 +201,9 @@ where let verifier_data = VerifierOnlyCircuitData { constants_sigmas_cap: MerkleCap(vec![]), - circuit_digest: - <>::Hasher as Hasher>::Hash::from_bytes( - &vec![0; <>::Hasher as Hasher>::HASH_SIZE], - ), + circuit_digest: <>::Hasher as Hasher>::Hash::from_bytes( + &vec![0; <>::Hasher as Hasher>::HASH_SIZE], + ), }; Self { @@ -231,7 +219,7 @@ impl DummyProofGenerator where F: RichField + Extendable, C: GenericConfig + 'static, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { pub fn deserialize_with_circuit_data( src: &mut Buffer, @@ -254,7 +242,7 @@ impl SimpleGenerator for DummyProofGenerator where F: RichField + Extendable, C: GenericConfig + 'static, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { fn id(&self) -> String { "DummyProofGenerator".to_string() diff --git a/plonky2/src/recursion/recursive_verifier.rs b/plonky2/src/recursion/recursive_verifier.rs index 240c8c1a..ec13dab3 100644 --- a/plonky2/src/recursion/recursive_verifier.rs +++ b/plonky2/src/recursion/recursive_verifier.rs @@ -1,6 +1,5 @@ use crate::field::extension::Extendable; use crate::hash::hash_types::{HashOutTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::plonk::circuit_builder::CircuitBuilder; use crate::plonk::circuit_data::{CommonCircuitData, VerifierCircuitTarget}; use crate::plonk::config::{AlgebraicHasher, GenericConfig}; @@ -21,16 +20,14 @@ impl, const D: usize> CircuitBuilder { inner_verifier_data: &VerifierCircuitTarget, inner_common_data: &CommonCircuitData, ) where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { assert_eq!( proof_with_pis.public_inputs.len(), inner_common_data.num_public_inputs ); - let public_inputs_hash = self - .hash_n_to_hash_no_pad::(proof_with_pis.public_inputs.clone()); + let public_inputs_hash = + self.hash_n_to_hash_no_pad::(proof_with_pis.public_inputs.clone()); let challenges = proof_with_pis.get_challenges::( self, public_inputs_hash, @@ -56,8 +53,7 @@ impl, const D: usize> CircuitBuilder { inner_verifier_data: &VerifierCircuitTarget, inner_common_data: &CommonCircuitData, ) where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, + C::Hasher: AlgebraicHasher, { let one = self.one_extension(); @@ -329,11 +325,7 @@ mod tests { fn dummy_proof, C: GenericConfig, const D: usize>( config: &CircuitConfig, num_dummy_gates: u64, - ) -> Result> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> Result> { let mut builder = CircuitBuilder::::new(config.clone()); for _ in 0..num_dummy_gates { builder.add_gate(NoopGate, vec![]); @@ -362,11 +354,7 @@ mod tests { print_timing: bool, ) -> Result> where - InnerC::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - [(); InnerC::HCO::WIDTH]:, - [(); InnerC::HCI::WIDTH]:, + InnerC::Hasher: AlgebraicHasher, { let mut builder = CircuitBuilder::::new(config.clone()); let mut pw = PartialWitness::new(); @@ -418,11 +406,7 @@ mod tests { proof: &ProofWithPublicInputs, vd: &VerifierOnlyCircuitData, cd: &CommonCircuitData, - ) -> Result<()> - where - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - { + ) -> Result<()> { let proof_bytes = proof.to_bytes(); info!("Proof length: {} bytes", proof_bytes.len()); let proof_from_bytes = ProofWithPublicInputs::from_bytes(proof_bytes, cd)?; diff --git a/plonky2/src/util/serialization/generator_serialization.rs b/plonky2/src/util/serialization/generator_serialization.rs index 5fab57e1..14f94acc 100644 --- a/plonky2/src/util/serialization/generator_serialization.rs +++ b/plonky2/src/util/serialization/generator_serialization.rs @@ -133,7 +133,7 @@ pub mod default { where F: RichField + Extendable, C: GenericConfig + 'static, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, { impl_generator_serializer! { DefaultGeneratorSerializer, diff --git a/plonky2/src/util/serialization/mod.rs b/plonky2/src/util/serialization/mod.rs index 5a92afb5..db86879d 100644 --- a/plonky2/src/util/serialization/mod.rs +++ b/plonky2/src/util/serialization/mod.rs @@ -32,7 +32,6 @@ use crate::gadgets::polynomial::PolynomialCoeffsExtTarget; use crate::gates::gate::GateRef; use crate::gates::selectors::SelectorsInfo; use crate::hash::hash_types::{HashOutTarget, MerkleCapTarget, RichField}; -use crate::hash::hashing::HashConfig; use crate::hash::merkle_proofs::{MerkleProof, MerkleProofTarget}; use crate::hash::merkle_tree::{MerkleCap, MerkleTree}; use crate::iop::ext_target::ExtensionTarget; @@ -235,11 +234,10 @@ pub trait Read { /// Reads a hash value from `self`. #[inline] - fn read_hash(&mut self) -> IoResult + fn read_hash(&mut self) -> IoResult where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { let mut buf = vec![0; H::HASH_SIZE]; self.read_exact(&mut buf)?; @@ -259,29 +257,27 @@ pub trait Read { /// Reads a vector of Hash from `self`. #[inline] - fn read_hash_vec(&mut self, length: usize) -> IoResult> + fn read_hash_vec(&mut self, length: usize) -> IoResult> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { (0..length) - .map(|_| self.read_hash::()) + .map(|_| self.read_hash::()) .collect::, _>>() } /// Reads a value of type [`MerkleCap`] from `self` with the given `cap_height`. #[inline] - fn read_merkle_cap(&mut self, cap_height: usize) -> IoResult> + fn read_merkle_cap(&mut self, cap_height: usize) -> IoResult> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { let cap_length = 1 << cap_height; Ok(MerkleCap( (0..cap_length) - .map(|_| self.read_hash::()) + .map(|_| self.read_hash::()) .collect::, _>>()?, )) } @@ -299,11 +295,10 @@ pub trait Read { /// Reads a value of type [`MerkleTree`] from `self`. #[inline] - fn read_merkle_tree(&mut self) -> IoResult> + fn read_merkle_tree(&mut self) -> IoResult> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { let leaves_len = self.read_usize()?; let mut leaves = Vec::with_capacity(leaves_len); @@ -313,9 +308,9 @@ pub trait Read { } let digests_len = self.read_usize()?; - let digests = self.read_hash_vec::(digests_len)?; + let digests = self.read_hash_vec::(digests_len)?; let cap_height = self.read_usize()?; - let cap = self.read_merkle_cap::(cap_height)?; + let cap = self.read_merkle_cap::(cap_height)?; Ok(MerkleTree { leaves, digests, @@ -379,16 +374,15 @@ pub trait Read { /// Reads a value of type [`MerkleProof`] from `self`. #[inline] - fn read_merkle_proof(&mut self) -> IoResult> + fn read_merkle_proof(&mut self) -> IoResult> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { let length = self.read_u8()?; Ok(MerkleProof { siblings: (0..length) - .map(|_| self.read_hash::()) + .map(|_| self.read_hash::()) .collect::>()?, }) } @@ -409,7 +403,7 @@ pub trait Read { fn read_fri_initial_proof( &mut self, common_data: &CommonCircuitData, - ) -> IoResult> + ) -> IoResult> where F: RichField + Extendable, C: GenericConfig, @@ -461,7 +455,7 @@ pub trait Read { &mut self, arity: usize, compressed: bool, - ) -> IoResult> + ) -> IoResult> where F: RichField + Extendable, C: GenericConfig, @@ -491,7 +485,7 @@ pub trait Read { fn read_fri_query_rounds( &mut self, common_data: &CommonCircuitData, - ) -> IoResult>> + ) -> IoResult>> where F: RichField + Extendable, C: GenericConfig, @@ -540,7 +534,7 @@ pub trait Read { fn read_fri_proof( &mut self, common_data: &CommonCircuitData, - ) -> IoResult> + ) -> IoResult> where F: RichField + Extendable, C: GenericConfig, @@ -829,8 +823,7 @@ pub trait Read { false => None, }; - let circuit_digest = - self.read_hash::>::HCO, >::Hasher>()?; + let circuit_digest = self.read_hash::>::Hasher>()?; Ok(ProverOnlyCircuitData { generators, @@ -871,8 +864,7 @@ pub trait Read { ) -> IoResult> { let height = self.read_usize()?; let constants_sigmas_cap = self.read_merkle_cap(height)?; - let circuit_digest = - self.read_hash::>::HCO, >::Hasher>()?; + let circuit_digest = self.read_hash::>::Hasher>()?; Ok(VerifierOnlyCircuitData { constants_sigmas_cap, circuit_digest, @@ -984,7 +976,7 @@ pub trait Read { fn read_compressed_fri_query_rounds( &mut self, common_data: &CommonCircuitData, - ) -> IoResult> + ) -> IoResult> where F: RichField + Extendable, C: GenericConfig, @@ -1032,7 +1024,7 @@ pub trait Read { fn read_compressed_fri_proof( &mut self, common_data: &CommonCircuitData, - ) -> IoResult> + ) -> IoResult> where F: RichField + Extendable, C: GenericConfig, @@ -1256,11 +1248,10 @@ pub trait Write { /// Writes a hash `h` to `self`. #[inline] - fn write_hash(&mut self, h: H::Hash) -> IoResult<()> + fn write_hash(&mut self, h: H::Hash) -> IoResult<()> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { self.write_all(&h.to_bytes()) } @@ -1277,15 +1268,14 @@ pub trait Write { /// Writes a vector of Hash `v` to `self.` #[inline] - fn write_hash_vec(&mut self, v: &[H::Hash]) -> IoResult<()> + fn write_hash_vec(&mut self, v: &[H::Hash]) -> IoResult<()> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { self.write_usize(v.len())?; for &elem in v.iter() { - self.write_hash::(elem)?; + self.write_hash::(elem)?; } Ok(()) @@ -1293,14 +1283,13 @@ pub trait Write { /// Writes `cap`, a value of type [`MerkleCap`], to `self`. #[inline] - fn write_merkle_cap(&mut self, cap: &MerkleCap) -> IoResult<()> + fn write_merkle_cap(&mut self, cap: &MerkleCap) -> IoResult<()> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { for &a in &cap.0 { - self.write_hash::(a)?; + self.write_hash::(a)?; } Ok(()) } @@ -1317,18 +1306,17 @@ pub trait Write { /// Writes `tree`, a value of type [`MerkleTree`], to `self`. #[inline] - fn write_merkle_tree(&mut self, tree: &MerkleTree) -> IoResult<()> + fn write_merkle_tree(&mut self, tree: &MerkleTree) -> IoResult<()> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { self.write_usize(tree.leaves.len())?; for i in 0..tree.leaves.len() { self.write_usize(tree.leaves[i].len())?; self.write_field_vec(&tree.leaves[i])?; } - self.write_hash_vec::(&tree.digests)?; + self.write_hash_vec::(&tree.digests)?; self.write_usize(tree.cap.height())?; self.write_merkle_cap(&tree.cap)?; @@ -1367,11 +1355,10 @@ pub trait Write { /// Writes a value `p` of type [`MerkleProof`] to `self.` #[inline] - fn write_merkle_proof(&mut self, p: &MerkleProof) -> IoResult<()> + fn write_merkle_proof(&mut self, p: &MerkleProof) -> IoResult<()> where F: RichField, - HC: HashConfig, - H: Hasher, + H: Hasher, { let length = p.siblings.len(); self.write_u8( @@ -1380,7 +1367,7 @@ pub trait Write { .expect("Merkle proof length must fit in u8."), )?; for &h in &p.siblings { - self.write_hash::(h)?; + self.write_hash::(h)?; } Ok(()) } @@ -1404,7 +1391,7 @@ pub trait Write { #[inline] fn write_fri_initial_proof( &mut self, - fitp: &FriInitialTreeProof, + fitp: &FriInitialTreeProof, ) -> IoResult<()> where F: RichField + Extendable, @@ -1435,7 +1422,7 @@ pub trait Write { #[inline] fn write_fri_query_step( &mut self, - fqs: &FriQueryStep, + fqs: &FriQueryStep, ) -> IoResult<()> where F: RichField + Extendable, @@ -1459,7 +1446,7 @@ pub trait Write { #[inline] fn write_fri_query_rounds( &mut self, - fqrs: &[FriQueryRound], + fqrs: &[FriQueryRound], ) -> IoResult<()> where F: RichField + Extendable, @@ -1495,7 +1482,7 @@ pub trait Write { #[inline] fn write_fri_proof( &mut self, - fp: &FriProof, + fp: &FriProof, ) -> IoResult<()> where F: RichField + Extendable, @@ -1771,9 +1758,7 @@ pub trait Write { None => self.write_bool(false)?, } - self.write_hash::>::HCO, >::Hasher>( - *circuit_digest, - )?; + self.write_hash::>::Hasher>(*circuit_digest)?; Ok(()) } @@ -1807,9 +1792,7 @@ pub trait Write { self.write_usize(constants_sigmas_cap.height())?; self.write_merkle_cap(constants_sigmas_cap)?; - self.write_hash::>::HCO, >::Hasher>( - *circuit_digest, - )?; + self.write_hash::>::Hasher>(*circuit_digest)?; Ok(()) } @@ -1903,7 +1886,7 @@ pub trait Write { #[inline] fn write_compressed_fri_query_rounds( &mut self, - cfqrs: &CompressedFriQueryRounds, + cfqrs: &CompressedFriQueryRounds, ) -> IoResult<()> where F: RichField + Extendable, @@ -1931,7 +1914,7 @@ pub trait Write { #[inline] fn write_compressed_fri_proof( &mut self, - fp: &CompressedFriProof, + fp: &CompressedFriProof, ) -> IoResult<()> where F: RichField + Extendable, diff --git a/starky/src/fibonacci_stark.rs b/starky/src/fibonacci_stark.rs index 86c5ace7..24108f00 100644 --- a/starky/src/fibonacci_stark.rs +++ b/starky/src/fibonacci_stark.rs @@ -127,7 +127,6 @@ mod tests { use plonky2::field::extension::Extendable; use plonky2::field::types::Field; use plonky2::hash::hash_types::RichField; - use plonky2::hash::hashing::HashConfig; use plonky2::iop::witness::PartialWitness; use plonky2::plonk::circuit_builder::CircuitBuilder; use plonky2::plonk::circuit_data::CircuitConfig; @@ -235,13 +234,9 @@ mod tests { print_gate_counts: bool, ) -> Result<()> where - InnerC::Hasher: AlgebraicHasher, + InnerC::Hasher: AlgebraicHasher, [(); S::COLUMNS]:, [(); S::PUBLIC_INPUTS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, - [(); InnerC::HCO::WIDTH]:, - [(); InnerC::HCI::WIDTH]:, { let circuit_config = CircuitConfig::standard_recursion_config(); let mut builder = CircuitBuilder::::new(circuit_config); diff --git a/starky/src/get_challenges.rs b/starky/src/get_challenges.rs index eaa91c12..b34b427d 100644 --- a/starky/src/get_challenges.rs +++ b/starky/src/get_challenges.rs @@ -5,7 +5,6 @@ use plonky2::field::polynomial::PolynomialCoeffs; use plonky2::fri::proof::{FriProof, FriProofTarget}; use plonky2::gadgets::polynomial::PolynomialCoeffsExtTarget; use plonky2::hash::hash_types::{MerkleCapTarget, RichField}; -use plonky2::hash::hashing::HashConfig; use plonky2::hash::merkle_tree::MerkleCap; use plonky2::iop::challenger::{Challenger, RecursiveChallenger}; use plonky2::iop::target::Target; @@ -21,11 +20,11 @@ use crate::stark::Stark; fn get_challenges( stark: &S, - trace_cap: &MerkleCap, - permutation_zs_cap: Option<&MerkleCap>, - quotient_polys_cap: &MerkleCap, + trace_cap: &MerkleCap, + permutation_zs_cap: Option<&MerkleCap>, + quotient_polys_cap: &MerkleCap, openings: &StarkOpeningSet, - commit_phase_merkle_caps: &[MerkleCap], + commit_phase_merkle_caps: &[MerkleCap], final_poly: &PolynomialCoeffs, pow_witness: F, config: &StarkConfig, @@ -35,12 +34,10 @@ where F: RichField + Extendable, C: GenericConfig, S: Stark, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let num_challenges = config.num_challenges; - let mut challenger = Challenger::::new(); + let mut challenger = Challenger::::new(); challenger.observe_cap(trace_cap); @@ -79,8 +76,6 @@ impl StarkProofWithPublicInputs where F: RichField + Extendable, C: GenericConfig, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { // TODO: Should be used later in compression? #![allow(dead_code)] @@ -150,13 +145,11 @@ pub(crate) fn get_challenges_target< config: &StarkConfig, ) -> StarkProofChallengesTarget where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let num_challenges = config.num_challenges; - let mut challenger = RecursiveChallenger::::new(builder); + let mut challenger = RecursiveChallenger::::new(builder); challenger.observe_cap(trace_cap); @@ -204,9 +197,7 @@ impl StarkProofWithPublicInputsTarget { config: &StarkConfig, ) -> StarkProofChallengesTarget where - C::Hasher: AlgebraicHasher, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, + C::Hasher: AlgebraicHasher, { let StarkProofTarget { trace_cap, diff --git a/starky/src/permutation.rs b/starky/src/permutation.rs index 1bf6386b..4f5d2921 100644 --- a/starky/src/permutation.rs +++ b/starky/src/permutation.rs @@ -10,7 +10,6 @@ use plonky2::field::packed::PackedField; use plonky2::field::polynomial::PolynomialValues; use plonky2::field::types::Field; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::challenger::{Challenger, RecursiveChallenger}; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::target::Target; @@ -150,38 +149,29 @@ fn poly_product_elementwise( product } -fn get_permutation_challenge>( - challenger: &mut Challenger, -) -> PermutationChallenge -where - [(); HC::WIDTH]:, -{ +fn get_permutation_challenge>( + challenger: &mut Challenger, +) -> PermutationChallenge { let beta = challenger.get_challenge(); let gamma = challenger.get_challenge(); PermutationChallenge { beta, gamma } } -fn get_permutation_challenge_set>( - challenger: &mut Challenger, +fn get_permutation_challenge_set>( + challenger: &mut Challenger, num_challenges: usize, -) -> PermutationChallengeSet -where - [(); HC::WIDTH]:, -{ +) -> PermutationChallengeSet { let challenges = (0..num_challenges) .map(|_| get_permutation_challenge(challenger)) .collect(); PermutationChallengeSet { challenges } } -pub(crate) fn get_n_permutation_challenge_sets>( - challenger: &mut Challenger, +pub(crate) fn get_n_permutation_challenge_sets>( + challenger: &mut Challenger, num_challenges: usize, num_sets: usize, -) -> Vec> -where - [(); HC::WIDTH]:, -{ +) -> Vec> { (0..num_sets) .map(|_| get_permutation_challenge_set(challenger, num_challenges)) .collect() @@ -189,16 +179,12 @@ where fn get_permutation_challenge_target< F: RichField + Extendable, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, const D: usize, >( builder: &mut CircuitBuilder, - challenger: &mut RecursiveChallenger, -) -> PermutationChallenge -where - [(); HC::WIDTH]:, -{ + challenger: &mut RecursiveChallenger, +) -> PermutationChallenge { let beta = challenger.get_challenge(builder); let gamma = challenger.get_challenge(builder); PermutationChallenge { beta, gamma } @@ -206,17 +192,13 @@ where fn get_permutation_challenge_set_target< F: RichField + Extendable, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, const D: usize, >( builder: &mut CircuitBuilder, - challenger: &mut RecursiveChallenger, + challenger: &mut RecursiveChallenger, num_challenges: usize, -) -> PermutationChallengeSet -where - [(); HC::WIDTH]:, -{ +) -> PermutationChallengeSet { let challenges = (0..num_challenges) .map(|_| get_permutation_challenge_target(builder, challenger)) .collect(); @@ -225,18 +207,14 @@ where pub(crate) fn get_n_permutation_challenge_sets_target< F: RichField + Extendable, - HC: HashConfig, - H: AlgebraicHasher, + H: AlgebraicHasher, const D: usize, >( builder: &mut CircuitBuilder, - challenger: &mut RecursiveChallenger, + challenger: &mut RecursiveChallenger, num_challenges: usize, num_sets: usize, -) -> Vec> -where - [(); HC::WIDTH]:, -{ +) -> Vec> { (0..num_sets) .map(|_| get_permutation_challenge_set_target(builder, challenger, num_challenges)) .collect() diff --git a/starky/src/proof.rs b/starky/src/proof.rs index b19d6ac8..6bd5f787 100644 --- a/starky/src/proof.rs +++ b/starky/src/proof.rs @@ -23,15 +23,15 @@ use crate::permutation::PermutationChallengeSet; #[derive(Debug, Clone)] pub struct StarkProof, C: GenericConfig, const D: usize> { /// Merkle cap of LDEs of trace values. - pub trace_cap: MerkleCap, + pub trace_cap: MerkleCap, /// Merkle cap of LDEs of permutation Z values. - pub permutation_zs_cap: Option>, + pub permutation_zs_cap: Option>, /// Merkle cap of LDEs of trace values. - pub quotient_polys_cap: MerkleCap, + pub quotient_polys_cap: MerkleCap, /// Purported values of each polynomial at the challenge point. pub openings: StarkOpeningSet, /// A batch FRI argument for all openings. - pub opening_proof: FriProof, + pub opening_proof: FriProof, } impl, C: GenericConfig, const D: usize> StarkProof { @@ -88,11 +88,11 @@ pub struct CompressedStarkProof< const D: usize, > { /// Merkle cap of LDEs of trace values. - pub trace_cap: MerkleCap, + pub trace_cap: MerkleCap, /// Purported values of each polynomial at the challenge point. pub openings: StarkOpeningSet, /// A batch FRI argument for all openings. - pub opening_proof: CompressedFriProof, + pub opening_proof: CompressedFriProof, } pub struct CompressedStarkProofWithPublicInputs< diff --git a/starky/src/prover.rs b/starky/src/prover.rs index 535cd76c..62a5987d 100644 --- a/starky/src/prover.rs +++ b/starky/src/prover.rs @@ -11,7 +11,6 @@ use plonky2::field::types::Field; use plonky2::field::zero_poly_coset::ZeroPolyOnCoset; use plonky2::fri::oracle::PolynomialBatch; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::challenger::Challenger; use plonky2::plonk::config::GenericConfig; use plonky2::timed; @@ -43,8 +42,6 @@ where S: Stark, [(); S::COLUMNS]:, [(); S::PUBLIC_INPUTS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { let degree = trace_poly_values[0].len(); let degree_bits = log2_strict(degree); diff --git a/starky/src/recursive_verifier.rs b/starky/src/recursive_verifier.rs index 8daeabb8..11d83479 100644 --- a/starky/src/recursive_verifier.rs +++ b/starky/src/recursive_verifier.rs @@ -7,7 +7,6 @@ use plonky2::field::extension::Extendable; use plonky2::field::types::Field; use plonky2::fri::witness_util::set_fri_proof_target; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::ext_target::ExtensionTarget; use plonky2::iop::witness::Witness; use plonky2::plonk::circuit_builder::CircuitBuilder; @@ -37,11 +36,9 @@ pub fn verify_stark_proof_circuit< proof_with_pis: StarkProofWithPublicInputsTarget, inner_config: &StarkConfig, ) where - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, [(); S::COLUMNS]:, [(); S::PUBLIC_INPUTS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { assert_eq!(proof_with_pis.public_inputs.len(), S::PUBLIC_INPUTS); let degree_bits = proof_with_pis.proof.recover_degree_bits(inner_config); @@ -75,10 +72,9 @@ fn verify_stark_proof_with_challenges_circuit< inner_config: &StarkConfig, degree_bits: usize, ) where - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, [(); S::COLUMNS]:, [(); S::PUBLIC_INPUTS]:, - [(); C::HCO::WIDTH]:, { check_permutation_options(&stark, &proof_with_pis, &challenges).unwrap(); let one = builder.one_extension(); @@ -269,7 +265,7 @@ pub fn set_stark_proof_with_pis_target, W, const D stark_proof_with_pis: &StarkProofWithPublicInputs, ) where F: RichField + Extendable, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, W: Witness, { let StarkProofWithPublicInputs { @@ -295,7 +291,7 @@ pub fn set_stark_proof_target, W, const D: usize>( proof: &StarkProof, ) where F: RichField + Extendable, - C::Hasher: AlgebraicHasher, + C::Hasher: AlgebraicHasher, W: Witness, { witness.set_cap_target(&proof_target.trace_cap, &proof.trace_cap); diff --git a/starky/src/stark_testing.rs b/starky/src/stark_testing.rs index 227a8574..8572547c 100644 --- a/starky/src/stark_testing.rs +++ b/starky/src/stark_testing.rs @@ -6,7 +6,6 @@ use plonky2::field::extension::{Extendable, FieldExtension}; use plonky2::field::polynomial::{PolynomialCoeffs, PolynomialValues}; use plonky2::field::types::{Field, Sample}; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::iop::witness::{PartialWitness, WitnessWrite}; use plonky2::plonk::circuit_builder::CircuitBuilder; use plonky2::plonk::circuit_data::CircuitConfig; @@ -90,8 +89,6 @@ pub fn test_stark_circuit_constraints< where [(); S::COLUMNS]:, [(); S::PUBLIC_INPUTS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { // Compute native constraint evaluation on random values. let vars = StarkEvaluationVars { diff --git a/starky/src/verifier.rs b/starky/src/verifier.rs index a6e0de54..7ed6d14a 100644 --- a/starky/src/verifier.rs +++ b/starky/src/verifier.rs @@ -7,7 +7,6 @@ use plonky2::field::extension::{Extendable, FieldExtension}; use plonky2::field::types::Field; use plonky2::fri::verifier::verify_fri_proof; use plonky2::hash::hash_types::RichField; -use plonky2::hash::hashing::HashConfig; use plonky2::plonk::config::GenericConfig; use plonky2::plonk::plonk_common::reduce_with_powers; @@ -32,8 +31,6 @@ pub fn verify_stark_proof< where [(); S::COLUMNS]:, [(); S::PUBLIC_INPUTS]:, - [(); C::HCO::WIDTH]:, - [(); C::HCI::WIDTH]:, { ensure!(proof_with_pis.public_inputs.len() == S::PUBLIC_INPUTS); let degree_bits = proof_with_pis.proof.recover_degree_bits(config); @@ -56,7 +53,6 @@ pub(crate) fn verify_stark_proof_with_challenges< where [(); S::COLUMNS]:, [(); S::PUBLIC_INPUTS]:, - [(); C::HCO::WIDTH]:, { validate_proof_shape(&stark, &proof_with_pis, config)?; check_permutation_options(&stark, &proof_with_pis, &challenges)?;