diff --git a/halo2_gadgets/Cargo.toml b/halo2_gadgets/Cargo.toml index 14e562ff81..13026f4353 100644 --- a/halo2_gadgets/Cargo.toml +++ b/halo2_gadgets/Cargo.toml @@ -53,6 +53,7 @@ test-dev-graph = [ "plotters", "plotters/bitmap_backend", "plotters/bitmap_encoder", + "plotters/ttf", ] circuit-params = ["halo2_proofs/circuit-params"] test-dependencies = ["proptest"] diff --git a/halo2_gadgets/benches/sha256.rs b/halo2_gadgets/benches/sha256.rs index 4afceacd82..6a7e9b0bd9 100644 --- a/halo2_gadgets/benches/sha256.rs +++ b/halo2_gadgets/benches/sha256.rs @@ -8,7 +8,7 @@ use halo2curves::pasta::{pallas, EqAffine}; use rand::rngs::OsRng; use std::{ - fs::File, + fs::{create_dir_all, File}, io::{prelude::*, BufReader}, path::Path, }; @@ -88,6 +88,9 @@ fn bench(name: &str, k: u32, c: &mut Criterion) { } } + // Create parent directory for assets + create_dir_all("./benches/sha256_assets").expect("Failed to create sha256_assets directory"); + // Initialize the polynomial commitment parameters let params_path = Path::new("./benches/sha256_assets/sha256_params"); if File::open(params_path).is_err() { @@ -134,7 +137,7 @@ fn bench(name: &str, k: u32, c: &mut Criterion) { ¶ms, &pk, &[circuit], - &[], + &[&[]], OsRng, &mut transcript, ) @@ -159,7 +162,7 @@ fn bench(name: &str, k: u32, c: &mut Criterion) { ¶ms, pk.get_vk(), strategy, - &[], + &[&[]], &mut transcript, ) .unwrap(); diff --git a/halo2_gadgets/src/ecc/chip/constants.rs b/halo2_gadgets/src/ecc/chip/constants.rs index 82ed952ceb..90a989b9af 100644 --- a/halo2_gadgets/src/ecc/chip/constants.rs +++ b/halo2_gadgets/src/ecc/chip/constants.rs @@ -48,8 +48,8 @@ fn compute_window_table(base: C, num_windows: usize) -> Vec<[C; (0..H) .map(|k| { // scalar = (k+2)*(8^w) - let scalar = C::Scalar::from(k as u64 + 2) - * C::Scalar::from(H as u64).pow([w as u64, 0, 0, 0]); + let scalar = + C::Scalar::from(k as u64 + 2) * C::Scalar::from(H as u64).pow([w as u64]); (base * scalar).to_affine() }) .collect::>() @@ -62,14 +62,14 @@ fn compute_window_table(base: C, num_windows: usize) -> Vec<[C; // For the last window, we compute [k * (2^3)^w - sum]B, where sum is defined // as sum = \sum_{j = 0}^{`num_windows - 2`} 2^{3j+1} let sum = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, j| { - acc + C::Scalar::from(2).pow([FIXED_BASE_WINDOW_SIZE as u64 * j as u64 + 1, 0, 0, 0]) + acc + C::Scalar::from(2).pow([FIXED_BASE_WINDOW_SIZE as u64 * j as u64 + 1]) }); window_table.push( (0..H) .map(|k| { // scalar = k * (2^3)^w - sum, where w = `num_windows - 1` let scalar = C::Scalar::from(k as u64) - * C::Scalar::from(H as u64).pow([(num_windows - 1) as u64, 0, 0, 0]) + * C::Scalar::from(H as u64).pow([(num_windows - 1) as u64]) - sum; (base * scalar).to_affine() }) @@ -197,7 +197,7 @@ pub fn test_lagrange_coeffs(base: C, num_windows: usize) { // Compute the actual x-coordinate of the multiple [(k+2)*(8^w)]B. let point = base * C::Scalar::from(bits as u64 + 2) - * C::Scalar::from(H as u64).pow([idx as u64, 0, 0, 0]); + * C::Scalar::from(H as u64).pow([idx as u64]); let x = *point.to_affine().coordinates().unwrap().x(); // Check that the interpolated x-coordinate matches the actual one. @@ -214,10 +214,10 @@ pub fn test_lagrange_coeffs(base: C, num_windows: usize) { // Compute the actual x-coordinate of the multiple [k * (8^84) - offset]B, // where offset = \sum_{j = 0}^{83} 2^{3j+1} let offset = (0..(num_windows - 1)).fold(C::Scalar::ZERO, |acc, w| { - acc + C::Scalar::from(2).pow([FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0]) + acc + C::Scalar::from(2).pow([FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1]) }); let scalar = C::Scalar::from(bits as u64) - * C::Scalar::from(H as u64).pow([(num_windows - 1) as u64, 0, 0, 0]) + * C::Scalar::from(H as u64).pow([(num_windows - 1) as u64]) - offset; let point = base * scalar; let x = *point.to_affine().coordinates().unwrap().x(); diff --git a/halo2_gadgets/src/ecc/chip/mul_fixed.rs b/halo2_gadgets/src/ecc/chip/mul_fixed.rs index b22f2b66e7..ce478fdb86 100644 --- a/halo2_gadgets/src/ecc/chip/mul_fixed.rs +++ b/halo2_gadgets/src/ecc/chip/mul_fixed.rs @@ -372,7 +372,7 @@ impl> Config { base: &F, ) -> Result { // `scalar = [(k_w + 2) ⋅ 8^w] - let scalar = k.map(|k| (k + *TWO_SCALAR) * (*H_SCALAR).pow([w as u64, 0, 0, 0])); + let scalar = k.map(|k| (k + *TWO_SCALAR) * (*H_SCALAR).pow([w as u64])); self.process_window::<_, NUM_WINDOWS>(region, offset, w, k_usize, scalar, base) } @@ -389,12 +389,12 @@ impl> Config { // offset_acc = \sum_{j = 0}^{NUM_WINDOWS - 2} 2^{FIXED_BASE_WINDOW_SIZE*j + 1} let offset_acc = (0..(NUM_WINDOWS - 1)).fold(pallas::Scalar::zero(), |acc, w| { - acc + (*TWO_SCALAR).pow([FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1, 0, 0, 0]) + acc + (*TWO_SCALAR).pow([FIXED_BASE_WINDOW_SIZE as u64 * w as u64 + 1]) }); // `scalar = [k * 8^(NUM_WINDOWS - 1) - offset_acc]`. let scalar = scalar.windows_field()[scalar.windows_field().len() - 1] - .map(|k| k * (*H_SCALAR).pow([(NUM_WINDOWS - 1) as u64, 0, 0, 0]) - offset_acc); + .map(|k| k * (*H_SCALAR).pow([(NUM_WINDOWS - 1) as u64]) - offset_acc); self.process_window::<_, NUM_WINDOWS>( region, diff --git a/halo2_proofs/Cargo.toml b/halo2_proofs/Cargo.toml index 35ecbf4dab..8ced31c0f0 100644 --- a/halo2_proofs/Cargo.toml +++ b/halo2_proofs/Cargo.toml @@ -84,6 +84,7 @@ test-dev-graph = [ "dev-graph", "plotters/bitmap_backend", "plotters/bitmap_encoder", + "plotters/ttf", ] gadget-traces = ["backtrace"] thread-safe-region = [] diff --git a/halo2_proofs/src/arithmetic.rs b/halo2_proofs/src/arithmetic.rs index 984b102b45..f8694e069a 100644 --- a/halo2_proofs/src/arithmetic.rs +++ b/halo2_proofs/src/arithmetic.rs @@ -51,7 +51,7 @@ fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut let mut tmp = u64::from_le_bytes(v); tmp >>= skip_bits - (skip_bytes * 8); - tmp = tmp % (1 << c); + tmp %= 1 << c; tmp as usize } @@ -110,7 +110,7 @@ fn multiexp_serial(coeffs: &[C::Scalar], bases: &[C], acc: &mut let mut running_sum = C::Curve::identity(); for exp in buckets.into_iter().rev() { running_sum = exp.add(running_sum); - *acc = *acc + &running_sum; + *acc += &running_sum; } } } diff --git a/halo2_proofs/src/circuit.rs b/halo2_proofs/src/circuit.rs index 1d5fceb797..3fab93997c 100644 --- a/halo2_proofs/src/circuit.rs +++ b/halo2_proofs/src/circuit.rs @@ -1,6 +1,6 @@ //! Traits and structs for implementing circuit components. -use std::{convert::TryInto, fmt, marker::PhantomData}; +use std::{fmt, marker::PhantomData}; use ff::Field; diff --git a/halo2_proofs/src/circuit/layouter.rs b/halo2_proofs/src/circuit/layouter.rs index 2adc5dacbe..f939c3fca5 100644 --- a/halo2_proofs/src/circuit/layouter.rs +++ b/halo2_proofs/src/circuit/layouter.rs @@ -8,7 +8,7 @@ use ff::Field; pub use super::table_layouter::TableLayouter; use super::{Cell, RegionIndex, Value}; -use crate::plonk::{Advice, Any, Assigned, Column, Error, Fixed, Instance, Selector, TableColumn}; +use crate::plonk::{Advice, Any, Assigned, Column, Error, Fixed, Instance, Selector}; /// Intermediate trait requirements for [`RegionLayouter`] when thread-safe regions are enabled. #[cfg(feature = "thread-safe-region")] diff --git a/halo2_proofs/src/dev.rs b/halo2_proofs/src/dev.rs index ab6c79a795..6f0e63a6fe 100644 --- a/halo2_proofs/src/dev.rs +++ b/halo2_proofs/src/dev.rs @@ -1,19 +1,14 @@ //! Tools for developing circuits. -use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; -use std::fmt; use std::iter; use std::ops::{Add, Mul, Neg, Range}; -use std::time::{Duration, Instant}; use blake2b_simd::blake2b; use ff::Field; use ff::FromUniformBytes; -use group::Group; -use crate::circuit::layouter::SyncDeps; use crate::multicore::{ IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, ParallelIterator, ParallelSliceMut, @@ -24,11 +19,9 @@ use crate::{ plonk::{ permutation, sealed::{self, SealedPhase}, - Advice, Any, Assigned, Assignment, Challenge, Circuit, Column, ColumnType, - ConstraintSystem, Error, Expression, FirstPhase, Fixed, FloorPlanner, Instance, Phase, - Selector, VirtualCell, + Advice, Any, Assigned, Assignment, Challenge, Circuit, Column, ConstraintSystem, Error, + Expression, FirstPhase, Fixed, FloorPlanner, Instance, Phase, Selector, }, - poly::Rotation, }; pub mod metadata; diff --git a/halo2_proofs/src/dev/failure.rs b/halo2_proofs/src/dev/failure.rs index 95951edfb3..38b5b0ea61 100644 --- a/halo2_proofs/src/dev/failure.rs +++ b/halo2_proofs/src/dev/failure.rs @@ -14,7 +14,6 @@ use crate::dev::metadata::Constraint; use crate::{ dev::{Instance, Value}, plonk::{Any, Column, ConstraintSystem, Expression, Gate}, - poly::Rotation, }; mod emitter; diff --git a/halo2_proofs/src/dev/gates.rs b/halo2_proofs/src/dev/gates.rs index fd4c039623..352415bcd9 100644 --- a/halo2_proofs/src/dev/gates.rs +++ b/halo2_proofs/src/dev/gates.rs @@ -7,10 +7,7 @@ use ff::PrimeField; use crate::{ dev::util, - plonk::{ - sealed::{self, SealedPhase}, - Circuit, ConstraintSystem, FirstPhase, - }, + plonk::{sealed::SealedPhase, Circuit, ConstraintSystem, FirstPhase}, }; #[derive(Debug)] diff --git a/halo2_proofs/src/helpers.rs b/halo2_proofs/src/helpers.rs index 41fc2e8d1e..b3f47a2059 100644 --- a/halo2_proofs/src/helpers.rs +++ b/halo2_proofs/src/helpers.rs @@ -1,6 +1,6 @@ use crate::poly::Polynomial; use ff::PrimeField; -use halo2curves::{pairing::Engine, serde::SerdeObject, CurveAffine}; +use halo2curves::{serde::SerdeObject, CurveAffine}; use std::io; /// This enum specifies how various types are serialized and deserialized. diff --git a/halo2_proofs/src/lib.rs b/halo2_proofs/src/lib.rs index 52676ddb19..acc26aff15 100644 --- a/halo2_proofs/src/lib.rs +++ b/halo2_proofs/src/lib.rs @@ -1,29 +1,12 @@ //! # halo2_proofs #![cfg_attr(docsrs, feature(doc_cfg))] -// Build without warnings on stable 1.51 and later. -#![allow(unknown_lints)] -// Disable old lint warnings until our MSRV is at least 1.51. -#![allow(renamed_and_removed_lints)] -// Use the old lint name to build without warnings until our MSRV is at least 1.51. -#![allow(clippy::unknown_clippy_lints)] // The actual lints we want to disable. -#![allow( - clippy::op_ref, - clippy::assign_op_pattern, - clippy::too_many_arguments, - clippy::suspicious_arithmetic_impl, - clippy::many_single_char_names, - clippy::same_item_push, - clippy::upper_case_acronyms -)] -#![deny(broken_intra_doc_links)] +#![allow(clippy::op_ref, clippy::many_single_char_names)] +#![deny(rustdoc::broken_intra_doc_links)] #![deny(missing_debug_implementations)] #![deny(missing_docs)] #![deny(unsafe_code)] -// Remove this once we update pasta_curves -#![allow(unused_imports)] -#![allow(clippy::derive_partial_eq_without_eq)] pub mod arithmetic; pub mod circuit; diff --git a/halo2_proofs/src/plonk.rs b/halo2_proofs/src/plonk.rs index 5b22acfc74..f3ca4b6f83 100644 --- a/halo2_proofs/src/plonk.rs +++ b/halo2_proofs/src/plonk.rs @@ -14,8 +14,8 @@ use crate::helpers::{ SerdePrimeField, }; use crate::poly::{ - commitment::Params, Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, - PinnedEvaluationDomain, Polynomial, + Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, PinnedEvaluationDomain, + Polynomial, }; use crate::transcript::{ChallengeScalar, EncodedChallenge, Transcript}; use crate::SerdeFormat; diff --git a/halo2_proofs/src/plonk/assigned.rs b/halo2_proofs/src/plonk/assigned.rs index 919ddcdfb5..07de325678 100644 --- a/halo2_proofs/src/plonk/assigned.rs +++ b/halo2_proofs/src/plonk/assigned.rs @@ -446,7 +446,6 @@ mod tests { mod proptests { use std::{ cmp, - convert::TryFrom, ops::{Add, Mul, Neg, Sub}, }; diff --git a/halo2_proofs/src/plonk/circuit.rs b/halo2_proofs/src/plonk/circuit.rs index 86a47d65fc..a5736f28ca 100644 --- a/halo2_proofs/src/plonk/circuit.rs +++ b/halo2_proofs/src/plonk/circuit.rs @@ -9,9 +9,8 @@ use core::cmp::max; use core::ops::{Add, Mul}; use ff::Field; use sealed::SealedPhase; -use std::cmp::Ordering; use std::collections::HashMap; -use std::fmt::{Debug, Formatter}; +use std::fmt::Debug; use std::{ convert::TryFrom, ops::{Neg, Sub}, @@ -873,6 +872,7 @@ impl Expression { /// Evaluate the polynomial using the provided closures to perform the /// operations. + #[allow(clippy::too_many_arguments)] pub fn evaluate( &self, constant: &impl Fn(F) -> T, @@ -982,6 +982,7 @@ impl Expression { /// Evaluate the polynomial lazily using the provided closures to perform the /// operations. + #[allow(clippy::too_many_arguments)] pub fn evaluate_lazy( &self, constant: &impl Fn(F) -> T, diff --git a/halo2_proofs/src/plonk/error.rs b/halo2_proofs/src/plonk/error.rs index 27ed3e049b..d4a7e11c14 100644 --- a/halo2_proofs/src/plonk/error.rs +++ b/halo2_proofs/src/plonk/error.rs @@ -1,4 +1,3 @@ -use std::cmp; use std::error; use std::fmt; use std::io; diff --git a/halo2_proofs/src/plonk/evaluation.rs b/halo2_proofs/src/plonk/evaluation.rs index d1cb398a29..431c487c7e 100644 --- a/halo2_proofs/src/plonk/evaluation.rs +++ b/halo2_proofs/src/plonk/evaluation.rs @@ -1,30 +1,11 @@ use crate::multicore; -use crate::plonk::lookup::prover::Committed; -use crate::plonk::permutation::Argument; -use crate::plonk::{lookup, permutation, AdviceQuery, Any, FixedQuery, InstanceQuery, ProvingKey}; +use crate::plonk::{lookup, permutation, Any, ProvingKey}; use crate::poly::Basis; use crate::{ - arithmetic::{eval_polynomial, parallelize, CurveAffine}, - poly::{ - commitment::Params, Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, - Polynomial, ProverQuery, Rotation, - }, - transcript::{EncodedChallenge, TranscriptWrite}, -}; -use group::prime::PrimeCurve; -use group::{ - ff::{BatchInvert, Field, PrimeField, WithSmallOrderMulGroup}, - Curve, -}; -use std::any::TypeId; -use std::convert::TryInto; -use std::num::ParseIntError; -use std::slice; -use std::{ - collections::BTreeMap, - iter, - ops::{Index, Mul, MulAssign}, + arithmetic::{parallelize, CurveAffine}, + poly::{Coeff, ExtendedLagrangeCoeff, Polynomial, Rotation}, }; +use group::ff::{Field, PrimeField, WithSmallOrderMulGroup}; use super::{shuffle, ConstraintSystem, Expression}; @@ -68,6 +49,7 @@ impl Default for ValueSource { impl ValueSource { /// Get the value for this source + #[allow(clippy::too_many_arguments)] pub fn get( &self, rotations: &[usize], @@ -128,6 +110,7 @@ pub enum Calculation { impl Calculation { /// Get the resulting value of this calculation + #[allow(clippy::too_many_arguments)] pub fn evaluate( &self, rotations: &[usize], @@ -312,6 +295,7 @@ impl Evaluator { } /// Evaluate h poly + #[allow(clippy::too_many_arguments)] pub(in crate::plonk) fn evaluate_h( &self, pk: &ProvingKey, @@ -796,6 +780,7 @@ impl GraphEvaluator { } } + #[allow(clippy::too_many_arguments)] pub fn evaluate( &self, data: &mut EvaluationData, diff --git a/halo2_proofs/src/plonk/keygen.rs b/halo2_proofs/src/plonk/keygen.rs index bfffd68dc4..bd48b7c96a 100644 --- a/halo2_proofs/src/plonk/keygen.rs +++ b/halo2_proofs/src/plonk/keygen.rs @@ -11,15 +11,14 @@ use super::{ Selector, }, evaluation::Evaluator, - permutation, Assigned, Challenge, Error, Expression, LagrangeCoeff, Polynomial, ProvingKey, - VerifyingKey, + permutation, Assigned, Challenge, Error, LagrangeCoeff, Polynomial, ProvingKey, VerifyingKey, }; use crate::{ arithmetic::{parallelize, CurveAffine}, - circuit::{layouter::SyncDeps, Value}, + circuit::Value, poly::{ batch_invert_assigned, - commitment::{Blind, Params, MSM}, + commitment::{Blind, Params}, EvaluationDomain, }, }; diff --git a/halo2_proofs/src/plonk/lookup/prover.rs b/halo2_proofs/src/plonk/lookup/prover.rs index 6a5f883a03..028b298853 100644 --- a/halo2_proofs/src/plonk/lookup/prover.rs +++ b/halo2_proofs/src/plonk/lookup/prover.rs @@ -8,8 +8,7 @@ use crate::{ arithmetic::{eval_polynomial, parallelize, CurveAffine}, poly::{ commitment::{Blind, Params}, - Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, ProverQuery, - Rotation, + Coeff, EvaluationDomain, LagrangeCoeff, Polynomial, ProverQuery, Rotation, }, transcript::{EncodedChallenge, TranscriptWrite}, }; @@ -19,7 +18,6 @@ use group::{ Curve, }; use rand_core::RngCore; -use std::{any::TypeId, convert::TryInto, num::ParseIntError, ops::Index}; use std::{ collections::BTreeMap, iter, @@ -62,6 +60,7 @@ impl> Argument { /// - constructs Permuted struct using permuted_input_value = A', and /// permuted_table_expression = S'. /// The Permuted struct is used to update the Lookup, and is then returned. + #[allow(clippy::too_many_arguments)] pub(in crate::plonk) fn commit_permuted< 'a, 'params: 'a, diff --git a/halo2_proofs/src/plonk/lookup/verifier.rs b/halo2_proofs/src/plonk/lookup/verifier.rs index 1dc111f2cc..bbc86c8e9d 100644 --- a/halo2_proofs/src/plonk/lookup/verifier.rs +++ b/halo2_proofs/src/plonk/lookup/verifier.rs @@ -90,6 +90,7 @@ impl Committed { } impl Evaluated { + #[allow(clippy::too_many_arguments)] pub(in crate::plonk) fn expressions<'a>( &'a self, l_0: C::Scalar, @@ -141,7 +142,7 @@ impl Evaluated { std::iter::empty() .chain( - // l_0(X) * (1 - z'(X)) = 0 + // l_0(X) * (1 - z(X)) = 0 Some(l_0 * &(C::Scalar::ONE - &self.product_eval)), ) .chain( diff --git a/halo2_proofs/src/plonk/permutation.rs b/halo2_proofs/src/plonk/permutation.rs index 0e92ccc705..3c54f51943 100644 --- a/halo2_proofs/src/plonk/permutation.rs +++ b/halo2_proofs/src/plonk/permutation.rs @@ -10,7 +10,6 @@ use crate::{ poly::{Coeff, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial}, SerdeFormat, }; -use ff::PrimeField; pub(crate) mod keygen; pub(crate) mod prover; diff --git a/halo2_proofs/src/plonk/permutation/keygen.rs b/halo2_proofs/src/plonk/permutation/keygen.rs index 843e2a9fab..d164a827cc 100644 --- a/halo2_proofs/src/plonk/permutation/keygen.rs +++ b/halo2_proofs/src/plonk/permutation/keygen.rs @@ -1,22 +1,20 @@ -use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; - use ff::{Field, PrimeField}; use group::Curve; use super::{Argument, ProvingKey, VerifyingKey}; use crate::{ arithmetic::{parallelize, CurveAffine}, - multicore::{ - IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, - IntoParallelRefMutIterator, ParallelIterator, - }, + multicore::{IndexedParallelIterator, ParallelIterator}, plonk::{Any, Column, Error}, poly::{ - commitment::{Blind, CommitmentScheme, Params}, + commitment::{Blind, Params}, EvaluationDomain, }, }; +#[cfg(feature = "thread-safe-region")] +use std::collections::{BTreeSet, HashMap}; + #[cfg(not(feature = "thread-safe-region"))] /// Struct that accumulates all the necessary data in order to construct the permutation argument. #[derive(Clone, Debug, PartialEq, Eq)] @@ -138,6 +136,8 @@ impl Assembly { pub fn mapping( &self, ) -> impl Iterator + '_> { + use crate::multicore::IntoParallelRefIterator; + self.mapping.iter().map(|c| c.par_iter().copied()) } @@ -246,6 +246,8 @@ impl Assembly { /// Builds the ordered mapping of the cycles. /// This will only get executed once. pub fn build_ordered_mapping(&mut self) { + use crate::multicore::IntoParallelRefMutIterator; + // will only get called once if self.ordered_cycles.is_empty() && !self.cycles.is_empty() { self.ordered_cycles = self @@ -316,6 +318,8 @@ impl Assembly { pub fn mapping( &self, ) -> impl Iterator + '_> { + use crate::multicore::IntoParallelIterator; + (0..self.num_cols).map(move |i| { (0..self.col_len) .into_par_iter() diff --git a/halo2_proofs/src/plonk/permutation/prover.rs b/halo2_proofs/src/plonk/permutation/prover.rs index f31c6ed19c..d6b108554d 100644 --- a/halo2_proofs/src/plonk/permutation/prover.rs +++ b/halo2_proofs/src/plonk/permutation/prover.rs @@ -12,7 +12,6 @@ use crate::{ arithmetic::{eval_polynomial, parallelize, CurveAffine}, plonk::{self, Error}, poly::{ - self, commitment::{Blind, Params}, Coeff, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, ProverQuery, Rotation, }, @@ -43,6 +42,7 @@ pub(crate) struct Evaluated { } impl Argument { + #[allow(clippy::too_many_arguments)] pub(in crate::plonk) fn commit< 'params, C: CurveAffine, diff --git a/halo2_proofs/src/plonk/permutation/verifier.rs b/halo2_proofs/src/plonk/permutation/verifier.rs index 88fed41a18..a4637422ae 100644 --- a/halo2_proofs/src/plonk/permutation/verifier.rs +++ b/halo2_proofs/src/plonk/permutation/verifier.rs @@ -99,6 +99,7 @@ impl Committed { } impl Evaluated { + #[allow(clippy::too_many_arguments)] pub(in crate::plonk) fn expressions<'a>( &'a self, vk: &'a plonk::VerifyingKey, diff --git a/halo2_proofs/src/plonk/prover.rs b/halo2_proofs/src/plonk/prover.rs index d02e187dfc..e64f3bfd8c 100644 --- a/halo2_proofs/src/plonk/prover.rs +++ b/halo2_proofs/src/plonk/prover.rs @@ -1,32 +1,27 @@ -use ff::{Field, FromUniformBytes, PrimeField, WithSmallOrderMulGroup}; +use ff::{Field, FromUniformBytes, WithSmallOrderMulGroup}; use group::Curve; -use halo2curves::CurveExt; use rand_core::RngCore; use std::collections::BTreeSet; -use std::env::var; use std::ops::RangeTo; -use std::sync::atomic::AtomicUsize; -use std::time::Instant; -use std::{collections::HashMap, iter, mem, sync::atomic::Ordering}; +use std::{collections::HashMap, iter}; use super::{ circuit::{ - sealed::{self, SealedPhase}, - Advice, Any, Assignment, Challenge, Circuit, Column, ConstraintSystem, FirstPhase, Fixed, - FloorPlanner, Instance, Selector, + sealed::{self}, + Advice, Any, Assignment, Challenge, Circuit, Column, ConstraintSystem, Fixed, FloorPlanner, + Instance, Selector, }, lookup, permutation, shuffle, vanishing, ChallengeBeta, ChallengeGamma, ChallengeTheta, - ChallengeX, ChallengeY, Error, Expression, ProvingKey, + ChallengeX, ChallengeY, Error, ProvingKey, }; -use crate::circuit::layouter::SyncDeps; + use crate::{ arithmetic::{eval_polynomial, CurveAffine}, circuit::Value, plonk::Assigned, poly::{ - self, commitment::{Blind, CommitmentScheme, Params, Prover}, - Basis, Coeff, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, ProverQuery, + Basis, Coeff, LagrangeCoeff, Polynomial, ProverQuery, }, }; use crate::{ @@ -58,6 +53,10 @@ pub fn create_proof< where Scheme::Scalar: WithSmallOrderMulGroup<3> + FromUniformBytes<64>, { + if circuits.len() != instances.len() { + return Err(Error::InvalidInstances); + } + for instance in instances.iter() { if instance.len() != pk.vk.cs.num_instance_columns { return Err(Error::InvalidInstances); @@ -552,7 +551,7 @@ where let vanishing = vanishing.construct(params, domain, h_poly, &mut rng, transcript)?; let x: ChallengeX<_> = transcript.squeeze_challenge_scalar(); - let xn = x.pow([params.n(), 0, 0, 0]); + let xn = x.pow([params.n()]); if P::QUERY_INSTANCE { // Compute and hash instance evals for each circuit instance @@ -698,3 +697,69 @@ where .create_proof(rng, transcript, instances) .map_err(|_| Error::ConstraintSystemFailure) } + +#[test] +fn test_create_proof() { + use crate::{ + circuit::SimpleFloorPlanner, + plonk::{keygen_pk, keygen_vk}, + poly::kzg::{ + commitment::{KZGCommitmentScheme, ParamsKZG}, + multiopen::ProverSHPLONK, + }, + transcript::{Blake2bWrite, Challenge255, TranscriptWriterBuffer}, + }; + use halo2curves::bn256::Bn256; + use rand_core::OsRng; + + #[derive(Clone, Copy)] + struct MyCircuit; + + impl Circuit for MyCircuit { + type Config = (); + type FloorPlanner = SimpleFloorPlanner; + #[cfg(feature = "circuit-params")] + type Params = (); + + fn without_witnesses(&self) -> Self { + *self + } + + fn configure(_meta: &mut ConstraintSystem) -> Self::Config {} + + fn synthesize( + &self, + _config: Self::Config, + _layouter: impl crate::circuit::Layouter, + ) -> Result<(), Error> { + Ok(()) + } + } + + let params: ParamsKZG = ParamsKZG::setup(3, OsRng); + let vk = keygen_vk(¶ms, &MyCircuit).expect("keygen_vk should not fail"); + let pk = keygen_pk(¶ms, vk, &MyCircuit).expect("keygen_pk should not fail"); + let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); + + // Create proof with wrong number of instances + let proof = create_proof::, ProverSHPLONK<_>, _, _, _, _>( + ¶ms, + &pk, + &[MyCircuit, MyCircuit], + &[], + OsRng, + &mut transcript, + ); + assert!(matches!(proof.unwrap_err(), Error::InvalidInstances)); + + // Create proof with correct number of instances + create_proof::, ProverSHPLONK<_>, _, _, _, _>( + ¶ms, + &pk, + &[MyCircuit, MyCircuit], + &[&[], &[]], + OsRng, + &mut transcript, + ) + .expect("proof generation should not fail"); +} diff --git a/halo2_proofs/src/plonk/shuffle/prover.rs b/halo2_proofs/src/plonk/shuffle/prover.rs index ef3a459f22..fd30436a47 100644 --- a/halo2_proofs/src/plonk/shuffle/prover.rs +++ b/halo2_proofs/src/plonk/shuffle/prover.rs @@ -1,6 +1,5 @@ use super::super::{ - circuit::Expression, ChallengeBeta, ChallengeGamma, ChallengeTheta, ChallengeX, Error, - ProvingKey, + circuit::Expression, ChallengeGamma, ChallengeTheta, ChallengeX, Error, ProvingKey, }; use super::Argument; use crate::plonk::evaluation::evaluate; @@ -8,20 +7,14 @@ use crate::{ arithmetic::{eval_polynomial, parallelize, CurveAffine}, poly::{ commitment::{Blind, Params}, - Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, ProverQuery, - Rotation, + Coeff, EvaluationDomain, LagrangeCoeff, Polynomial, ProverQuery, Rotation, }, transcript::{EncodedChallenge, TranscriptWrite}, }; use ff::WithSmallOrderMulGroup; -use group::{ - ff::{BatchInvert, Field}, - Curve, -}; +use group::{ff::BatchInvert, Curve}; use rand_core::RngCore; -use std::{any::TypeId, convert::TryInto, num::ParseIntError, ops::Index}; use std::{ - collections::BTreeMap, iter, ops::{Mul, MulAssign}, }; @@ -47,6 +40,7 @@ impl> Argument { /// [S_0, S_1, ..., S_{m-1}], this method /// - constructs A_compressed = \theta^{m-1} A_0 + theta^{m-2} A_1 + ... + \theta A_{m-2} + A_{m-1} /// and S_compressed = \theta^{m-1} S_0 + theta^{m-2} S_1 + ... + \theta S_{m-2} + S_{m-1}, + #[allow(clippy::too_many_arguments)] fn compress<'a, 'params: 'a, C, P: Params<'params, C>>( &self, pk: &ProvingKey, @@ -99,6 +93,7 @@ impl> Argument { /// constructs the grand product polynomial over the shuffle. /// The grand product polynomial is used to populate the Product struct. /// The Product struct is added to the Shuffle and finally returned by the method. + #[allow(clippy::too_many_arguments)] pub(in crate::plonk) fn commit_product< 'a, 'params: 'a, diff --git a/halo2_proofs/src/plonk/shuffle/verifier.rs b/halo2_proofs/src/plonk/shuffle/verifier.rs index b02febb694..379cc5c8a1 100644 --- a/halo2_proofs/src/plonk/shuffle/verifier.rs +++ b/halo2_proofs/src/plonk/shuffle/verifier.rs @@ -52,6 +52,7 @@ impl Committed { } impl Evaluated { + #[allow(clippy::too_many_arguments)] pub(in crate::plonk) fn expressions<'a>( &'a self, l_0: C::Scalar, diff --git a/halo2_proofs/src/plonk/vanishing/prover.rs b/halo2_proofs/src/plonk/vanishing/prover.rs index 453cb8dc49..6220385ee6 100644 --- a/halo2_proofs/src/plonk/vanishing/prover.rs +++ b/halo2_proofs/src/plonk/vanishing/prover.rs @@ -1,6 +1,6 @@ use std::iter; -use ff::{Field, PrimeField}; +use ff::Field; use group::Curve; use rand_chacha::ChaCha20Rng; use rand_core::{RngCore, SeedableRng}; @@ -9,12 +9,11 @@ use super::Argument; use crate::{ arithmetic::{eval_polynomial, CurveAffine}, multicore::{ - current_num_threads, IndexedParallelIterator, IntoParallelIterator, - IntoParallelRefMutIterator, ParallelIterator, ParallelSliceMut, + current_num_threads, IndexedParallelIterator, IntoParallelRefMutIterator, ParallelIterator, + ParallelSliceMut, }, - plonk::{ChallengeX, ChallengeY, Error}, + plonk::{ChallengeX, Error}, poly::{ - self, commitment::{Blind, ParamsProver}, Coeff, EvaluationDomain, ExtendedLagrangeCoeff, Polynomial, ProverQuery, }, diff --git a/halo2_proofs/src/plonk/verifier.rs b/halo2_proofs/src/plonk/verifier.rs index 1e431be41b..76675bcdfa 100644 --- a/halo2_proofs/src/plonk/verifier.rs +++ b/halo2_proofs/src/plonk/verifier.rs @@ -1,28 +1,25 @@ use ff::{Field, FromUniformBytes, WithSmallOrderMulGroup}; use group::Curve; -use rand_core::RngCore; use std::iter; use super::{ vanishing, ChallengeBeta, ChallengeGamma, ChallengeTheta, ChallengeX, ChallengeY, Error, VerifyingKey, }; -use crate::arithmetic::{compute_inner_product, CurveAffine}; +use crate::arithmetic::compute_inner_product; use crate::poly::commitment::{CommitmentScheme, Verifier}; use crate::poly::VerificationStrategy; use crate::poly::{ - commitment::{Blind, Params, MSM}, - Guard, VerifierQuery, + commitment::{Blind, Params}, + VerifierQuery, }; -use crate::transcript::{read_n_points, read_n_scalars, EncodedChallenge, TranscriptRead}; +use crate::transcript::{read_n_scalars, EncodedChallenge, TranscriptRead}; #[cfg(feature = "batch")] mod batch; #[cfg(feature = "batch")] pub use batch::BatchVerifier; -use crate::poly::commitment::ParamsVerifier; - /// Returns a boolean indicating whether or not the proof is valid pub fn verify_proof< 'params, @@ -188,7 +185,7 @@ where }) .collect::, _>>()? } else { - let xn = x.pow([params.n(), 0, 0, 0]); + let xn = x.pow([params.n()]); let (min_rotation, max_rotation) = vk.cs .instance_queries @@ -267,7 +264,7 @@ where // commitments open to the correct values. let vanishing = { // x^n - let xn = x.pow([params.n(), 0, 0, 0]); + let xn = x.pow([params.n()]); let blinding_factors = vk.cs.blinding_factors(); let l_evals = vk diff --git a/halo2_proofs/src/plonk/verifier/batch.rs b/halo2_proofs/src/plonk/verifier/batch.rs index db3800371b..ba3e2419e6 100644 --- a/halo2_proofs/src/plonk/verifier/batch.rs +++ b/halo2_proofs/src/plonk/verifier/batch.rs @@ -1,9 +1,7 @@ -use std::{io, marker::PhantomData}; - use ff::FromUniformBytes; use group::ff::Field; use halo2curves::CurveAffine; -use rand_core::{OsRng, RngCore}; +use rand_core::OsRng; use super::{verify_proof, VerificationStrategy}; use crate::{ diff --git a/halo2_proofs/src/poly.rs b/halo2_proofs/src/poly.rs index 7d9c2c4cfd..02779d0e79 100644 --- a/halo2_proofs/src/poly.rs +++ b/halo2_proofs/src/poly.rs @@ -7,7 +7,6 @@ use crate::helpers::SerdePrimeField; use crate::plonk::Assigned; use crate::SerdeFormat; -use ff::PrimeField; use group::ff::{BatchInvert, Field}; use std::fmt::Debug; use std::io; @@ -304,7 +303,7 @@ impl<'a, F: Field, B: Basis> Sub for &'a Polynomial { /// Describes the relative rotation of a vector. Negative numbers represent /// reverse (leftmost) rotations and positive numbers represent forward (rightmost) /// rotations. Zero represents no rotation. -#[derive(Copy, Clone, Debug, PartialEq)] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct Rotation(pub i32); impl Rotation { diff --git a/halo2_proofs/src/poly/commitment.rs b/halo2_proofs/src/poly/commitment.rs index 3a0b68f62a..590767e68e 100644 --- a/halo2_proofs/src/poly/commitment.rs +++ b/halo2_proofs/src/poly/commitment.rs @@ -6,12 +6,11 @@ use super::{ use crate::poly::Error; use crate::transcript::{EncodedChallenge, TranscriptRead, TranscriptWrite}; use ff::Field; -use group::{Curve, Group}; -use halo2curves::{CurveAffine, CurveExt}; +use halo2curves::CurveAffine; use rand_core::RngCore; use std::{ fmt::Debug, - io::{self, Read, Write}, + io::{self}, ops::{Add, AddAssign, Mul, MulAssign}, }; diff --git a/halo2_proofs/src/poly/domain.rs b/halo2_proofs/src/poly/domain.rs index 5fefe82df2..4b448821d9 100644 --- a/halo2_proofs/src/poly/domain.rs +++ b/halo2_proofs/src/poly/domain.rs @@ -8,10 +8,7 @@ use crate::{ use super::{Coeff, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, Rotation}; use ff::WithSmallOrderMulGroup; -use group::{ - ff::{BatchInvert, Field, PrimeField}, - Group, -}; +use group::ff::{BatchInvert, Field}; use std::marker::PhantomData; @@ -54,6 +51,9 @@ impl> EvaluationDomain { extended_k += 1; } + // ensure extended_k <= S + assert!(extended_k <= F::S); + let mut extended_omega = F::ROOT_OF_UNITY; // Get extended_omega, the 2^{extended_k}'th root of unity @@ -537,7 +537,7 @@ fn test_l_i() { let mut l = vec![]; let mut points = vec![]; for i in 0..8 { - points.push(domain.omega.pow([i, 0, 0, 0])); + points.push(domain.omega.pow([i])); } for i in 0..8 { let mut l_i = vec![Scalar::zero(); 8]; @@ -547,7 +547,7 @@ fn test_l_i() { } let x = Scalar::random(OsRng); - let xn = x.pow([8, 0, 0, 0]); + let xn = x.pow([8]); let evaluations = domain.l_i_range(x, xn, -7..=7); for i in 0..8 { diff --git a/halo2_proofs/src/poly/evaluator.rs b/halo2_proofs/src/poly/evaluator.rs deleted file mode 100644 index 5d20221255..0000000000 --- a/halo2_proofs/src/poly/evaluator.rs +++ /dev/null @@ -1,699 +0,0 @@ -use std::{ - cmp, - collections::{HashMap, HashSet}, - fmt, - hash::{Hash, Hasher}, - marker::PhantomData, - ops::{Add, Mul, MulAssign, Neg, Sub}, - sync::Arc, -}; - -use group::ff::Field; -use halo2curves::Field; - -use super::{ - Basis, Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff, Polynomial, Rotation, -}; -use crate::{arithmetic::parallelize, multicore}; - -/// Returns `(chunk_size, num_chunks)` suitable for processing the given polynomial length -/// in the current parallelization environment. -fn get_chunk_params(poly_len: usize) -> (usize, usize) { - // Check the level of parallelization we have available. - let num_threads = multicore::current_num_threads(); - // We scale the number of chunks by a constant factor, to ensure that if not all - // threads are available, we can achieve more uniform throughput and don't end up - // waiting on a couple of threads to process the last chunks. - let num_chunks = num_threads * 4; - // Calculate the ideal chunk size for the desired throughput. We use ceiling - // division to ensure the minimum chunk size is 1. - // chunk_size = ceil(poly_len / num_chunks) - let chunk_size = (poly_len + num_chunks - 1) / num_chunks; - // Now re-calculate num_chunks from the actual chunk size. - // num_chunks = ceil(poly_len / chunk_size) - let num_chunks = (poly_len + chunk_size - 1) / chunk_size; - - (chunk_size, num_chunks) -} - -/// A reference to a polynomial registered with an [`Evaluator`]. -#[derive(Clone, Copy)] -pub(crate) struct AstLeaf { - index: usize, - rotation: Rotation, - _evaluator: PhantomData<(E, B)>, -} - -impl fmt::Debug for AstLeaf { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("AstLeaf") - .field("index", &self.index) - .field("rotation", &self.rotation) - .finish() - } -} - -impl PartialEq for AstLeaf { - fn eq(&self, rhs: &Self) -> bool { - // We compare rotations by offset, which doesn't account for equivalent rotations. - self.index.eq(&rhs.index) && self.rotation.0.eq(&rhs.rotation.0) - } -} - -impl Eq for AstLeaf {} - -impl Hash for AstLeaf { - fn hash(&self, state: &mut H) { - self.index.hash(state); - self.rotation.0.hash(state); - } -} - -impl AstLeaf { - /// Produces a new `AstLeaf` node corresponding to the underlying polynomial at a - /// _new_ rotation. Existing rotations applied to this leaf node are ignored and the - /// returned polynomial is not rotated _relative_ to the previous structure. - pub(crate) fn with_rotation(&self, rotation: Rotation) -> Self { - AstLeaf { - index: self.index, - rotation, - _evaluator: PhantomData::default(), - } - } -} - -/// An evaluation context for polynomial operations. -/// -/// This context enables us to de-duplicate queries of circuit columns (and the rotations -/// they might require), by storing a list of all the underlying polynomials involved in -/// any query (which are almost certainly column polynomials). We use the context like so: -/// -/// - We register each underlying polynomial with the evaluator, which returns a reference -/// to it as a [`AstLeaf`]. -/// - The references are then used to build up a [`Ast`] that represents the overall -/// operations to be applied to the polynomials. -/// - Finally, we call [`Evaluator::evaluate`] passing in the [`Ast`]. -pub(crate) struct Evaluator { - polys: Vec>, - _context: E, -} - -/// Constructs a new `Evaluator`. -/// -/// The `context` parameter is used to provide type safety for evaluators. It ensures that -/// an evaluator will only be used to evaluate [`Ast`]s containing [`AstLeaf`]s obtained -/// from itself. It should be set to the empty closure `|| {}`, because anonymous closures -/// all have unique types. -pub(crate) fn new_evaluator(context: E) -> Evaluator { - Evaluator { - polys: vec![], - _context: context, - } -} - -impl Evaluator { - /// Registers the given polynomial for use in this evaluation context. - /// - /// This API treats each registered polynomial as unique, even if the same polynomial - /// is added multiple times. - pub(crate) fn register_poly(&mut self, poly: Polynomial) -> AstLeaf { - let index = self.polys.len(); - self.polys.push(poly); - - AstLeaf { - index, - rotation: Rotation::cur(), - _evaluator: PhantomData::default(), - } - } - - /// Evaluates the given polynomial operation against this context. - pub(crate) fn evaluate( - &self, - ast: &Ast, - domain: &EvaluationDomain, - ) -> Polynomial - where - E: Copy + Send + Sync, - F: Field, - B: BasisOps, - { - // Traverse `ast` to collect the used leaves. - fn collect_rotations( - ast: &Ast, - ) -> HashSet> { - match ast { - Ast::Poly(leaf) => vec![*leaf].into_iter().collect(), - Ast::Add(a, b) | Ast::Mul(AstMul(a, b)) => { - let lhs = collect_rotations(a); - let rhs = collect_rotations(b); - lhs.union(&rhs).cloned().collect() - } - Ast::Scale(a, _) => collect_rotations(a), - Ast::DistributePowers(terms, _) => terms - .iter() - .flat_map(|term| collect_rotations(term).into_iter()) - .collect(), - Ast::LinearTerm(_) | Ast::ConstantTerm(_) => HashSet::default(), - } - } - let leaves = collect_rotations(ast); - - // Produce the rotated polynomials. - let rotated: HashMap<_, _> = leaves - .iter() - .cloned() - .map(|leaf| { - ( - leaf, - B::rotate(domain, &self.polys[leaf.index], leaf.rotation), - ) - }) - .collect(); - - // We're working in a single basis, so all polynomials are the same length. - let poly_len = self.polys.first().unwrap().len(); - let (chunk_size, num_chunks) = get_chunk_params(poly_len); - - // Split each rotated polynomial into chunks. - let chunks: Vec> = (0..num_chunks) - .map(|i| { - rotated - .iter() - .map(|(leaf, poly)| { - ( - *leaf, - poly.chunks(chunk_size) - .nth(i) - .expect("num_chunks was calculated correctly"), - ) - }) - .collect() - }) - .collect(); - - struct AstContext<'a, E, F: Field, B: Basis> { - domain: &'a EvaluationDomain, - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - leaves: &'a HashMap, &'a [F]>, - } - - fn recurse( - ast: &Ast, - ctx: &AstContext<'_, E, F, B>, - ) -> Vec { - match ast { - Ast::Poly(leaf) => ctx.leaves.get(leaf).expect("We prepared this").to_vec(), - Ast::Add(a, b) => { - let mut lhs = recurse(a, ctx); - let rhs = recurse(b, ctx); - for (lhs, rhs) in lhs.iter_mut().zip(rhs.iter()) { - *lhs += *rhs; - } - lhs - } - Ast::Mul(AstMul(a, b)) => { - let mut lhs = recurse(a, ctx); - let rhs = recurse(b, ctx); - for (lhs, rhs) in lhs.iter_mut().zip(rhs.iter()) { - *lhs *= *rhs; - } - lhs - } - Ast::Scale(a, scalar) => { - let mut lhs = recurse(a, ctx); - for lhs in lhs.iter_mut() { - *lhs *= scalar; - } - lhs - } - Ast::DistributePowers(terms, base) => terms.iter().fold( - B::constant_term(ctx.poly_len, ctx.chunk_size, ctx.chunk_index, F::ZERO), - |mut acc, term| { - let term = recurse(term, ctx); - for (acc, term) in acc.iter_mut().zip(term) { - *acc *= base; - *acc += term; - } - acc - }, - ), - Ast::LinearTerm(scalar) => B::linear_term( - ctx.domain, - ctx.poly_len, - ctx.chunk_size, - ctx.chunk_index, - *scalar, - ), - Ast::ConstantTerm(scalar) => { - B::constant_term(ctx.poly_len, ctx.chunk_size, ctx.chunk_index, *scalar) - } - } - } - - // Apply `ast` to each chunk in parallel, writing the result into an output - // polynomial. - let mut result = B::empty_poly(domain); - multicore::scope(|scope| { - for (chunk_index, (out, leaves)) in - result.chunks_mut(chunk_size).zip(chunks.iter()).enumerate() - { - scope.spawn(move |_| { - let ctx = AstContext { - domain, - poly_len, - chunk_size, - chunk_index, - leaves, - }; - out.copy_from_slice(&recurse(ast, &ctx)); - }); - } - }); - result - } -} - -/// Struct representing the [`Ast::Mul`] case. -/// -/// This struct exists to make the internals of this case private so that we don't -/// accidentally construct this case directly, because it can only be implemented for the -/// [`ExtendedLagrangeCoeff`] basis. -#[derive(Clone)] -pub(crate) struct AstMul(Arc>, Arc>); - -impl fmt::Debug for AstMul { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("AstMul") - .field(&self.0) - .field(&self.1) - .finish() - } -} - -/// A polynomial operation backed by an [`Evaluator`]. -#[derive(Clone)] -pub(crate) enum Ast { - Poly(AstLeaf), - Add(Arc>, Arc>), - Mul(AstMul), - Scale(Arc>, F), - /// Represents a linear combination of a vector of nodes and the powers of a - /// field element, where the nodes are ordered from highest to lowest degree - /// terms. - DistributePowers(Arc>>, F), - /// The degree-1 term of a polynomial. - /// - /// The field element is the coefficient of the term in the standard basis, not the - /// coefficient basis. - LinearTerm(F), - /// The degree-0 term of a polynomial. - /// - /// The field element is the same in both the standard and evaluation bases. - ConstantTerm(F), -} - -impl Ast { - pub fn distribute_powers>(i: I, base: F) -> Self { - Ast::DistributePowers(Arc::new(i.into_iter().collect()), base) - } -} - -impl fmt::Debug for Ast { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Poly(leaf) => f.debug_tuple("Poly").field(leaf).finish(), - Self::Add(lhs, rhs) => f.debug_tuple("Add").field(lhs).field(rhs).finish(), - Self::Mul(x) => f.debug_tuple("Mul").field(x).finish(), - Self::Scale(base, scalar) => f.debug_tuple("Scale").field(base).field(scalar).finish(), - Self::DistributePowers(terms, base) => f - .debug_tuple("DistributePowers") - .field(terms) - .field(base) - .finish(), - Self::LinearTerm(x) => f.debug_tuple("LinearTerm").field(x).finish(), - Self::ConstantTerm(x) => f.debug_tuple("ConstantTerm").field(x).finish(), - } - } -} - -impl From> for Ast { - fn from(leaf: AstLeaf) -> Self { - Ast::Poly(leaf) - } -} - -impl Ast { - pub(crate) fn one() -> Self { - Self::ConstantTerm(F::ONE) - } -} - -impl Neg for Ast { - type Output = Ast; - - fn neg(self) -> Self::Output { - Ast::Scale(Arc::new(self), -F::ONE) - } -} - -impl Neg for &Ast { - type Output = Ast; - - fn neg(self) -> Self::Output { - -(self.clone()) - } -} - -impl Add for Ast { - type Output = Ast; - - fn add(self, other: Self) -> Self::Output { - Ast::Add(Arc::new(self), Arc::new(other)) - } -} - -impl<'a, E: Clone, F: Field, B: Basis> Add<&'a Ast> for &'a Ast { - type Output = Ast; - - fn add(self, other: &'a Ast) -> Self::Output { - self.clone() + other.clone() - } -} - -impl Add> for Ast { - type Output = Ast; - - fn add(self, other: AstLeaf) -> Self::Output { - Ast::Add(Arc::new(self), Arc::new(other.into())) - } -} - -impl Sub for Ast { - type Output = Ast; - - fn sub(self, other: Self) -> Self::Output { - self + (-other) - } -} - -impl<'a, E: Clone, F: Field, B: Basis> Sub<&'a Ast> for &'a Ast { - type Output = Ast; - - fn sub(self, other: &'a Ast) -> Self::Output { - self + &(-other) - } -} - -impl Sub> for Ast { - type Output = Ast; - - fn sub(self, other: AstLeaf) -> Self::Output { - self + (-Ast::from(other)) - } -} - -impl Mul for Ast { - type Output = Ast; - - fn mul(self, other: Self) -> Self::Output { - Ast::Mul(AstMul(Arc::new(self), Arc::new(other))) - } -} - -impl<'a, E: Clone, F: Field> Mul<&'a Ast> for &'a Ast { - type Output = Ast; - - fn mul(self, other: &'a Ast) -> Self::Output { - self.clone() * other.clone() - } -} - -impl Mul> for Ast { - type Output = Ast; - - fn mul(self, other: AstLeaf) -> Self::Output { - Ast::Mul(AstMul(Arc::new(self), Arc::new(other.into()))) - } -} - -impl Mul for Ast { - type Output = Ast; - - fn mul(self, other: Self) -> Self::Output { - Ast::Mul(AstMul(Arc::new(self), Arc::new(other))) - } -} - -impl<'a, E: Clone, F: Field> Mul<&'a Ast> - for &'a Ast -{ - type Output = Ast; - - fn mul(self, other: &'a Ast) -> Self::Output { - self.clone() * other.clone() - } -} - -impl Mul> for Ast { - type Output = Ast; - - fn mul(self, other: AstLeaf) -> Self::Output { - Ast::Mul(AstMul(Arc::new(self), Arc::new(other.into()))) - } -} - -impl Mul for Ast { - type Output = Ast; - - fn mul(self, other: F) -> Self::Output { - Ast::Scale(Arc::new(self), other) - } -} - -impl Mul for &Ast { - type Output = Ast; - - fn mul(self, other: F) -> Self::Output { - Ast::Scale(Arc::new(self.clone()), other) - } -} - -impl MulAssign for Ast { - fn mul_assign(&mut self, rhs: Self) { - *self = self.clone().mul(rhs) - } -} - -/// Operations which can be performed over a given basis. -pub(crate) trait BasisOps: Basis { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial; - fn constant_term( - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec; - fn linear_term( - domain: &EvaluationDomain, - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec; - fn rotate( - domain: &EvaluationDomain, - poly: &Polynomial, - rotation: Rotation, - ) -> Polynomial; -} - -impl BasisOps for Coeff { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial { - domain.empty_coeff() - } - - fn constant_term( - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec { - let mut chunk = vec![F::ZERO; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]; - if chunk_index == 0 { - chunk[0] = scalar; - } - chunk - } - - fn linear_term( - _: &EvaluationDomain, - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec { - let mut chunk = vec![F::ZERO; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)]; - // If the chunk size is 1 (e.g. if we have a small k and many threads), then the - // linear coefficient is the second chunk. Otherwise, the chunk size is greater - // than one, and the linear coefficient is the second element of the first chunk. - // Note that we check against the original chunk size, not the potentially-short - // actual size of the current chunk, because we want to know whether the size of - // the previous chunk was 1. - if chunk_size == 1 && chunk_index == 1 { - chunk[0] = scalar; - } else if chunk_index == 0 { - chunk[1] = scalar; - } - chunk - } - - fn rotate( - _: &EvaluationDomain, - _: &Polynomial, - _: Rotation, - ) -> Polynomial { - panic!("Can't rotate polynomials in the standard basis") - } -} - -impl BasisOps for LagrangeCoeff { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial { - domain.empty_lagrange() - } - - fn constant_term( - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec { - vec![scalar; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)] - } - - fn linear_term( - domain: &EvaluationDomain, - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec { - // Take every power of omega within the chunk, and multiply by scalar. - let omega = domain.get_omega(); - let start = chunk_size * chunk_index; - (0..cmp::min(chunk_size, poly_len - start)) - .scan(omega.pow_vartime(&[start as u64]) * scalar, |acc, _| { - let ret = *acc; - *acc *= omega; - Some(ret) - }) - .collect() - } - - fn rotate( - _: &EvaluationDomain, - poly: &Polynomial, - rotation: Rotation, - ) -> Polynomial { - poly.rotate(rotation) - } -} - -impl BasisOps for ExtendedLagrangeCoeff { - fn empty_poly(domain: &EvaluationDomain) -> Polynomial { - domain.empty_extended() - } - - fn constant_term( - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec { - vec![scalar; cmp::min(chunk_size, poly_len - chunk_size * chunk_index)] - } - - fn linear_term( - domain: &EvaluationDomain, - poly_len: usize, - chunk_size: usize, - chunk_index: usize, - scalar: F, - ) -> Vec { - // Take every power of the extended omega within the chunk, and multiply by scalar. - let omega = domain.get_extended_omega(); - let start = chunk_size * chunk_index; - (0..cmp::min(chunk_size, poly_len - start)) - .scan( - omega.pow_vartime(&[start as u64]) * F::ZETA * scalar, - |acc, _| { - let ret = *acc; - *acc *= omega; - Some(ret) - }, - ) - .collect() - } - - fn rotate( - domain: &EvaluationDomain, - poly: &Polynomial, - rotation: Rotation, - ) -> Polynomial { - domain.rotate_extended(poly, rotation) - } -} - -#[cfg(test)] -mod tests { - use std::iter; - - use halo2curves::pasta::pallas; - - use super::{get_chunk_params, new_evaluator, Ast, BasisOps, Evaluator}; - use crate::{ - multicore, - poly::{Coeff, EvaluationDomain, ExtendedLagrangeCoeff, LagrangeCoeff}, - }; - - #[test] - fn short_chunk_regression_test() { - // Pick the smallest polynomial length that is guaranteed to produce a short chunk - // on this machine. - let k = match (1..16) - .map(|k| (k, get_chunk_params(1 << k))) - .find(|(k, (chunk_size, num_chunks))| (1 << k) < chunk_size * num_chunks) - .map(|(k, _)| k) - { - Some(k) => k, - None => { - // We are on a machine with a power-of-two number of threads, and cannot - // trigger the bug. - eprintln!( - "can't find a polynomial length for short_chunk_regression_test; skipping" - ); - return; - } - }; - eprintln!("Testing short-chunk regression with k = {}", k); - - fn test_case( - k: u32, - mut evaluator: Evaluator, - ) { - // Instantiate the evaluator with a trivial polynomial. - let domain = EvaluationDomain::new(1, k); - evaluator.register_poly(B::empty_poly(&domain)); - - // With the bug present, these will panic. - let _ = evaluator.evaluate(&Ast::ConstantTerm(pallas::Base::zero()), &domain); - let _ = evaluator.evaluate(&Ast::LinearTerm(pallas::Base::zero()), &domain); - } - - test_case(k, new_evaluator::<_, _, Coeff>(|| {})); - test_case(k, new_evaluator::<_, _, LagrangeCoeff>(|| {})); - test_case(k, new_evaluator::<_, _, ExtendedLagrangeCoeff>(|| {})); - } -} diff --git a/halo2_proofs/src/poly/ipa/commitment.rs b/halo2_proofs/src/poly/ipa/commitment.rs index f9b4ad059b..7be053c49c 100644 --- a/halo2_proofs/src/poly/ipa/commitment.rs +++ b/halo2_proofs/src/poly/ipa/commitment.rs @@ -3,18 +3,14 @@ //! //! [halo]: https://eprint.iacr.org/2019/1021 -use crate::arithmetic::{ - best_fft, best_multiexp, g_to_lagrange, parallelize, CurveAffine, CurveExt, -}; +use crate::arithmetic::{best_multiexp, g_to_lagrange, parallelize, CurveAffine, CurveExt}; use crate::helpers::CurveRead; -use crate::poly::commitment::{Blind, CommitmentScheme, Params, ParamsProver, ParamsVerifier, MSM}; +use crate::poly::commitment::{Blind, CommitmentScheme, Params, ParamsProver, ParamsVerifier}; use crate::poly::ipa::msm::MSMIPA; use crate::poly::{Coeff, LagrangeCoeff, Polynomial}; -use ff::{Field, PrimeField}; -use group::{prime::PrimeCurveAffine, Curve, Group}; +use group::{Curve, Group}; use std::marker::PhantomData; -use std::ops::{Add, AddAssign, Mul, MulAssign}; mod prover; mod verifier; @@ -233,21 +229,13 @@ impl<'params, C: CurveAffine> ParamsProver<'params, C> for ParamsIPA { #[cfg(test)] mod test { - - use crate::arithmetic::{best_fft, best_multiexp, parallelize, CurveAffine, CurveExt}; - use crate::helpers::CurveRead; use crate::poly::commitment::ParamsProver; - use crate::poly::commitment::{Blind, CommitmentScheme, Params, MSM}; + use crate::poly::commitment::{Blind, Params, MSM}; use crate::poly::ipa::commitment::{create_proof, verify_proof, ParamsIPA}; use crate::poly::ipa::msm::MSMIPA; - use crate::poly::{Coeff, LagrangeCoeff, Polynomial}; - - use ff::{Field, PrimeField}; - use group::{prime::PrimeCurveAffine, Curve, Group}; - use std::marker::PhantomData; - use std::ops::{Add, AddAssign, Mul, MulAssign}; - use std::io; + use ff::Field; + use group::Curve; #[test] fn test_commit_lagrange_epaffine() { diff --git a/halo2_proofs/src/poly/ipa/commitment/prover.rs b/halo2_proofs/src/poly/ipa/commitment/prover.rs index d176987c96..344dbc0e65 100644 --- a/halo2_proofs/src/poly/ipa/commitment/prover.rs +++ b/halo2_proofs/src/poly/ipa/commitment/prover.rs @@ -1,7 +1,7 @@ use ff::Field; use rand_core::RngCore; -use super::{Params, ParamsIPA}; +use super::ParamsIPA; use crate::arithmetic::{ best_multiexp, compute_inner_product, eval_polynomial, parallelize, CurveAffine, }; @@ -11,7 +11,7 @@ use crate::poly::{commitment::Blind, Coeff, Polynomial}; use crate::transcript::{EncodedChallenge, TranscriptWrite}; use group::Curve; -use std::io::{self, Write}; +use std::io::{self}; /// Create a polynomial commitment opening proof for the polynomial defined /// by the coefficients `px`, the blinding factor `blind` used for the @@ -51,7 +51,7 @@ pub fn create_proof< // Evaluate the random polynomial at x_3 let s_at_x3 = eval_polynomial(&s_poly[..], x_3); // Subtract constant coefficient to get a random polynomial with a root at x_3 - s_poly[0] = s_poly[0] - &s_at_x3; + s_poly[0] -= &s_at_x3; // And sample a random blind let s_poly_blind = Blind(C::Scalar::random(&mut rng)); @@ -72,7 +72,7 @@ pub fn create_proof< // zero. let mut p_prime_poly = s_poly * xi + p_poly; let v = eval_polynomial(&p_prime_poly, x_3); - p_prime_poly[0] = p_prime_poly[0] - &v; + p_prime_poly[0] -= &v; let p_prime_blind = s_poly_blind * Blind(xi) + p_blind; // This accumulates the synthetic blinding factor `f` starting diff --git a/halo2_proofs/src/poly/ipa/commitment/verifier.rs b/halo2_proofs/src/poly/ipa/commitment/verifier.rs index 0b60842899..cf258625d5 100644 --- a/halo2_proofs/src/poly/ipa/commitment/verifier.rs +++ b/halo2_proofs/src/poly/ipa/commitment/verifier.rs @@ -1,18 +1,9 @@ -use std::io::Read; - -use group::{ - ff::{BatchInvert, Field}, - Curve, -}; +use group::ff::{BatchInvert, Field}; use super::ParamsIPA; -use crate::poly::ipa::commitment::{IPACommitmentScheme, ParamsVerifierIPA}; -use crate::{ - arithmetic::{best_multiexp, CurveAffine}, - poly::ipa::strategy::GuardIPA, -}; +use crate::{arithmetic::CurveAffine, poly::ipa::strategy::GuardIPA}; use crate::{ - poly::{commitment::MSM, ipa::msm::MSMIPA, strategy::Guard, Error}, + poly::{commitment::MSM, ipa::msm::MSMIPA, Error}, transcript::{EncodedChallenge, TranscriptRead}, }; @@ -75,6 +66,9 @@ pub fn verify_proof<'params, C: CurveAffine, E: EncodedChallenge, T: Transcri // P' + \sum([u_j^{-1}] L_j) + \sum([u_j] R_j) // + [-c] G'_0 + [-cbz] U + [-f] W // = 0 + // + // Note that the guard returned from this function does not include + // the [-c]G'_0 term. let c = transcript.read_scalar().map_err(|_| Error::SamplingError)?; let neg_c = -c; diff --git a/halo2_proofs/src/poly/ipa/msm.rs b/halo2_proofs/src/poly/ipa/msm.rs index 3316e25337..a615ddce49 100644 --- a/halo2_proofs/src/poly/ipa/msm.rs +++ b/halo2_proofs/src/poly/ipa/msm.rs @@ -1,9 +1,5 @@ -use super::commitment::{IPACommitmentScheme, ParamsIPA}; -use crate::arithmetic::{best_multiexp, parallelize, CurveAffine}; -use crate::poly::{ - commitment::{CommitmentScheme, Params, MSM}, - ipa::commitment::ParamsVerifierIPA, -}; +use crate::arithmetic::{best_multiexp, CurveAffine}; +use crate::poly::{commitment::MSM, ipa::commitment::ParamsVerifierIPA}; use ff::Field; use group::Group; use std::collections::BTreeMap; @@ -222,13 +218,10 @@ impl<'a, C: CurveAffine> MSMIPA<'a, C> { #[cfg(test)] mod tests { - use super::ParamsIPA; - use crate::poly::commitment::ParamsProver; use crate::poly::{ - commitment::{Params, MSM}, - ipa::msm::MSMIPA, + commitment::{ParamsProver, MSM}, + ipa::{commitment::ParamsIPA, msm::MSMIPA}, }; - use group::Curve; use halo2curves::{ pasta::{Ep, EpAffine, Fp, Fq}, CurveAffine, diff --git a/halo2_proofs/src/poly/ipa/multiopen.rs b/halo2_proofs/src/poly/ipa/multiopen.rs index fd6aa78544..b78acb5934 100644 --- a/halo2_proofs/src/poly/ipa/multiopen.rs +++ b/halo2_proofs/src/poly/ipa/multiopen.rs @@ -4,7 +4,7 @@ //! [halo]: https://eprint.iacr.org/2019/1021 use super::*; -use crate::{arithmetic::CurveAffine, poly::query::Query, transcript::ChallengeScalar}; +use crate::{poly::query::Query, transcript::ChallengeScalar}; use ff::Field; use std::collections::{BTreeMap, BTreeSet}; diff --git a/halo2_proofs/src/poly/ipa/multiopen/prover.rs b/halo2_proofs/src/poly/ipa/multiopen/prover.rs index 6d65e7ae64..8998f38723 100644 --- a/halo2_proofs/src/poly/ipa/multiopen/prover.rs +++ b/halo2_proofs/src/poly/ipa/multiopen/prover.rs @@ -1,9 +1,7 @@ -use super::{ - construct_intermediate_sets, ChallengeX1, ChallengeX2, ChallengeX3, ChallengeX4, Query, -}; +use super::{construct_intermediate_sets, ChallengeX1, ChallengeX2, ChallengeX3, ChallengeX4}; use crate::arithmetic::{eval_polynomial, kate_division, CurveAffine}; use crate::poly::commitment::ParamsProver; -use crate::poly::commitment::{Blind, Params, Prover}; +use crate::poly::commitment::{Blind, Prover}; use crate::poly::ipa::commitment::{self, IPACommitmentScheme, ParamsIPA}; use crate::poly::query::ProverQuery; use crate::poly::{Coeff, Polynomial}; diff --git a/halo2_proofs/src/poly/ipa/multiopen/verifier.rs b/halo2_proofs/src/poly/ipa/multiopen/verifier.rs index 391f89e15b..d559e33384 100644 --- a/halo2_proofs/src/poly/ipa/multiopen/verifier.rs +++ b/halo2_proofs/src/poly/ipa/multiopen/verifier.rs @@ -1,20 +1,14 @@ use std::fmt::Debug; -use std::io::Read; -use std::marker::PhantomData; use ff::Field; -use rand_core::RngCore; -use super::{ - construct_intermediate_sets, ChallengeX1, ChallengeX2, ChallengeX3, ChallengeX4, Query, -}; +use super::{construct_intermediate_sets, ChallengeX1, ChallengeX2, ChallengeX3, ChallengeX4}; use crate::arithmetic::{eval_polynomial, lagrange_interpolate, CurveAffine}; use crate::poly::commitment::{Params, Verifier, MSM}; use crate::poly::ipa::commitment::{IPACommitmentScheme, ParamsIPA, ParamsVerifierIPA}; use crate::poly::ipa::msm::MSMIPA; use crate::poly::ipa::strategy::GuardIPA; use crate::poly::query::{CommitmentReference, VerifierQuery}; -use crate::poly::strategy::VerificationStrategy; use crate::poly::Error; use crate::transcript::{EncodedChallenge, TranscriptRead}; @@ -57,7 +51,9 @@ impl<'params, C: CurveAffine> Verifier<'params, IPACommitmentScheme> // Compress the commitments and expected evaluations at x together. // using the challenge x_1 - let mut q_commitments: Vec<_> = vec![self.params.empty_msm(); point_sets.len()]; + let mut q_commitments: Vec<_> = vec![ + (self.params.empty_msm(), C::Scalar::ONE); // (accumulator, next x_1 power). + point_sets.len()]; // A vec of vecs of evals. The outer vec corresponds to the point set, // while the inner vec corresponds to the points in a particular set. @@ -65,28 +61,32 @@ impl<'params, C: CurveAffine> Verifier<'params, IPACommitmentScheme> for point_set in point_sets.iter() { q_eval_sets.push(vec![C::Scalar::ZERO; point_set.len()]); } + { let mut accumulate = |set_idx: usize, new_commitment: CommitmentReference>, evals: Vec| { - q_commitments[set_idx].scale(*x_1); + let (q_commitment, x_1_power) = &mut q_commitments[set_idx]; match new_commitment { CommitmentReference::Commitment(c) => { - q_commitments[set_idx].append_term(C::Scalar::ONE, (*c).into()); + q_commitment.append_term(*x_1_power, (*c).into()); } CommitmentReference::MSM(msm) => { - q_commitments[set_idx].add_msm(msm); + let mut msm = msm.clone(); + msm.scale(*x_1_power); + q_commitment.add_msm(&msm); } } for (eval, set_eval) in evals.iter().zip(q_eval_sets[set_idx].iter_mut()) { - *set_eval *= &(*x_1); - *set_eval += eval; + *set_eval += (*eval) * (*x_1_power); } + *x_1_power *= *x_1; }; // Each commitment corresponds to evaluations at a set of points. // For each set, we collapse each commitment's evals pointwise. - for commitment_data in commitment_map.into_iter() { + // Run in order of increasing x_1 powers. + for commitment_data in commitment_map.into_iter().rev() { accumulate( commitment_data.set_index, // set_idx, commitment_data.commitment, // commitment, @@ -135,7 +135,7 @@ impl<'params, C: CurveAffine> Verifier<'params, IPACommitmentScheme> msm.append_term(C::Scalar::ONE, q_prime_commitment.into()); let (msm, v) = q_commitments.into_iter().zip(u.iter()).fold( (msm, msm_eval), - |(mut msm, msm_eval), (q_commitment, q_eval)| { + |(mut msm, msm_eval), ((q_commitment, _), q_eval)| { msm.scale(*x_4); msm.add_msm(&q_commitment); (msm, msm_eval * &(*x_4) + q_eval) diff --git a/halo2_proofs/src/poly/ipa/strategy.rs b/halo2_proofs/src/poly/ipa/strategy.rs index c8d385f90c..d2d1b3d364 100644 --- a/halo2_proofs/src/poly/ipa/strategy.rs +++ b/halo2_proofs/src/poly/ipa/strategy.rs @@ -1,10 +1,6 @@ -use std::marker::PhantomData; - -use super::commitment::{IPACommitmentScheme, ParamsIPA, ParamsVerifierIPA}; +use super::commitment::{IPACommitmentScheme, ParamsIPA}; use super::msm::MSMIPA; use super::multiopen::VerifierIPA; -use crate::poly::commitment::CommitmentScheme; -use crate::transcript::TranscriptRead; use crate::{ arithmetic::best_multiexp, plonk::Error, @@ -12,12 +8,11 @@ use crate::{ commitment::MSM, strategy::{Guard, VerificationStrategy}, }, - transcript::EncodedChallenge, }; use ff::Field; use group::Curve; use halo2curves::CurveAffine; -use rand_core::{OsRng, RngCore}; +use rand_core::OsRng; /// Wrapper for verification accumulator #[derive(Debug, Clone)] diff --git a/halo2_proofs/src/poly/kzg/commitment.rs b/halo2_proofs/src/poly/kzg/commitment.rs index d918a05065..70050e824b 100644 --- a/halo2_proofs/src/poly/kzg/commitment.rs +++ b/halo2_proofs/src/poly/kzg/commitment.rs @@ -1,8 +1,6 @@ -use crate::arithmetic::{ - best_fft, best_multiexp, g_to_lagrange, parallelize, CurveAffine, CurveExt, -}; +use crate::arithmetic::{best_multiexp, g_to_lagrange, parallelize}; use crate::helpers::SerdeCurveAffine; -use crate::poly::commitment::{Blind, CommitmentScheme, Params, ParamsProver, ParamsVerifier, MSM}; +use crate::poly::commitment::{Blind, CommitmentScheme, Params, ParamsProver, ParamsVerifier}; use crate::poly::{Coeff, LagrangeCoeff, Polynomial}; use crate::SerdeFormat; @@ -12,7 +10,6 @@ use halo2curves::pairing::Engine; use rand_core::{OsRng, RngCore}; use std::fmt::Debug; use std::marker::PhantomData; -use std::ops::{Add, AddAssign, Mul, MulAssign}; use std::io; @@ -371,21 +368,10 @@ where #[cfg(test)] mod test { - use crate::arithmetic::{best_fft, best_multiexp, parallelize, CurveAffine, CurveExt}; use crate::poly::commitment::ParamsProver; - use crate::poly::commitment::{Blind, CommitmentScheme, Params, MSM}; - use crate::poly::kzg::commitment::{ParamsKZG, ParamsVerifierKZG}; - use crate::poly::kzg::msm::MSMKZG; - use crate::poly::kzg::multiopen::ProverSHPLONK; - use crate::poly::{Coeff, LagrangeCoeff, Polynomial}; - - use ff::{Field, PrimeField}; - use group::{prime::PrimeCurveAffine, Curve, Group}; - use halo2curves::bn256::G1Affine; - use std::marker::PhantomData; - use std::ops::{Add, AddAssign, Mul, MulAssign}; - - use std::io; + use crate::poly::commitment::{Blind, Params}; + use crate::poly::kzg::commitment::ParamsKZG; + use ff::Field; #[test] fn test_commit_lagrange() { @@ -416,13 +402,8 @@ mod test { fn test_parameter_serialisation_roundtrip() { const K: u32 = 4; - use ff::Field; - use rand_core::OsRng; - - use super::super::commitment::{Blind, Params}; - use crate::arithmetic::eval_polynomial; - use crate::halo2curves::bn256::{Bn256, Fr}; - use crate::poly::EvaluationDomain; + use super::super::commitment::Params; + use crate::halo2curves::bn256::Bn256; let params0 = ParamsKZG::::new(K); let mut data = vec![]; diff --git a/halo2_proofs/src/poly/kzg/msm.rs b/halo2_proofs/src/poly/kzg/msm.rs index 667a5c3614..77758d1b97 100644 --- a/halo2_proofs/src/poly/kzg/msm.rs +++ b/halo2_proofs/src/poly/kzg/msm.rs @@ -1,8 +1,8 @@ use std::fmt::Debug; -use super::commitment::{KZGCommitmentScheme, ParamsKZG}; +use super::commitment::ParamsKZG; use crate::{ - arithmetic::{best_multiexp, parallelize, CurveAffine}, + arithmetic::{best_multiexp, parallelize}, poly::commitment::MSM, }; use group::{Curve, Group}; @@ -92,8 +92,6 @@ impl PreMSM { } pub(crate) fn normalize(self) -> MSMKZG { - use group::prime::PrimeCurveAffine; - let (scalars, bases) = self .projectives_msms .into_iter() diff --git a/halo2_proofs/src/poly/kzg/multiopen/gwc.rs b/halo2_proofs/src/poly/kzg/multiopen/gwc.rs index 8e7d742fc0..3fd28dd00a 100644 --- a/halo2_proofs/src/poly/kzg/multiopen/gwc.rs +++ b/halo2_proofs/src/poly/kzg/multiopen/gwc.rs @@ -4,20 +4,9 @@ mod verifier; pub use prover::ProverGWC; pub use verifier::VerifierGWC; -use crate::{ - arithmetic::{eval_polynomial, CurveAffine}, - poly::{ - commitment::{Params, ParamsVerifier}, - query::Query, - Coeff, Polynomial, - }, - transcript::ChallengeScalar, -}; +use crate::{poly::query::Query, transcript::ChallengeScalar}; use ff::Field; -use std::{ - collections::{BTreeMap, BTreeSet}, - marker::PhantomData, -}; +use std::marker::PhantomData; #[derive(Clone, Copy, Debug)] struct U {} diff --git a/halo2_proofs/src/poly/kzg/multiopen/gwc/prover.rs b/halo2_proofs/src/poly/kzg/multiopen/gwc/prover.rs index 12e3d1f8fd..8add3eef38 100644 --- a/halo2_proofs/src/poly/kzg/multiopen/gwc/prover.rs +++ b/halo2_proofs/src/poly/kzg/multiopen/gwc/prover.rs @@ -1,23 +1,19 @@ use super::{construct_intermediate_sets, ChallengeV, Query}; -use crate::arithmetic::{eval_polynomial, kate_division, powers, CurveAffine}; +use crate::arithmetic::{kate_division, powers}; use crate::helpers::SerdeCurveAffine; use crate::poly::commitment::ParamsProver; use crate::poly::commitment::Prover; use crate::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG}; use crate::poly::query::ProverQuery; -use crate::poly::Rotation; -use crate::poly::{ - commitment::{Blind, Params}, - Coeff, Polynomial, -}; +use crate::poly::{commitment::Blind, Polynomial}; use crate::transcript::{EncodedChallenge, TranscriptWrite}; -use ff::{Field, PrimeField}; +use ff::PrimeField; use group::Curve; use halo2curves::pairing::Engine; use rand_core::RngCore; use std::fmt::Debug; -use std::io::{self, Write}; +use std::io; use std::marker::PhantomData; /// Concrete KZG prover with GWC variant diff --git a/halo2_proofs/src/poly/kzg/multiopen/gwc/verifier.rs b/halo2_proofs/src/poly/kzg/multiopen/gwc/verifier.rs index ead5670b44..776c8408bc 100644 --- a/halo2_proofs/src/poly/kzg/multiopen/gwc/verifier.rs +++ b/halo2_proofs/src/poly/kzg/multiopen/gwc/verifier.rs @@ -1,28 +1,20 @@ use std::fmt::Debug; -use std::io::Read; -use std::marker::PhantomData; use super::{construct_intermediate_sets, ChallengeU, ChallengeV}; -use crate::arithmetic::{eval_polynomial, lagrange_interpolate, powers, CurveAffine}; +use crate::arithmetic::powers; use crate::helpers::SerdeCurveAffine; use crate::poly::commitment::Verifier; use crate::poly::commitment::MSM; use crate::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG}; use crate::poly::kzg::msm::{DualMSM, MSMKZG}; -use crate::poly::kzg::strategy::{AccumulatorStrategy, GuardKZG, SingleStrategy}; +use crate::poly::kzg::strategy::GuardKZG; use crate::poly::query::Query; use crate::poly::query::{CommitmentReference, VerifierQuery}; -use crate::poly::strategy::VerificationStrategy; -use crate::poly::{ - commitment::{Params, ParamsVerifier}, - Error, -}; +use crate::poly::Error; use crate::transcript::{EncodedChallenge, TranscriptRead}; use ff::{Field, PrimeField}; -use group::Group; -use halo2curves::pairing::{Engine, MillerLoopResult, MultiMillerLoop}; -use rand_core::OsRng; +use halo2curves::pairing::{Engine, MultiMillerLoop}; #[derive(Debug)] /// Concrete KZG verifier with GWC variant diff --git a/halo2_proofs/src/poly/kzg/multiopen/shplonk.rs b/halo2_proofs/src/poly/kzg/multiopen/shplonk.rs index eb0222bd19..eb88aa92fc 100644 --- a/halo2_proofs/src/poly/kzg/multiopen/shplonk.rs +++ b/halo2_proofs/src/poly/kzg/multiopen/shplonk.rs @@ -2,18 +2,10 @@ mod prover; mod verifier; use crate::multicore::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}; -use crate::{ - arithmetic::{eval_polynomial, lagrange_interpolate, CurveAffine}, - poly::{query::Query, Coeff, Polynomial}, - transcript::ChallengeScalar, -}; +use crate::{poly::query::Query, transcript::ChallengeScalar}; use ff::Field; pub use prover::ProverSHPLONK; -use std::{ - collections::{btree_map::Entry, BTreeMap, BTreeSet, HashMap, HashSet}, - marker::PhantomData, - sync::Arc, -}; +use std::collections::BTreeSet; pub use verifier::VerifierSHPLONK; #[derive(Clone, Copy, Debug)] @@ -148,18 +140,10 @@ where #[cfg(test)] mod proptests { - use proptest::{ - collection::vec, - prelude::*, - sample::{select, subsequence}, - strategy::Strategy, - }; - use super::{construct_intermediate_sets, Commitment, IntermediateSets}; - use crate::poly::Rotation; - use ff::{Field, FromUniformBytes}; + use ff::FromUniformBytes; use halo2curves::pasta::Fp; - use std::collections::BTreeMap; + use proptest::{collection::vec, prelude::*, sample::select}; use std::convert::TryFrom; #[derive(Debug, Clone)] diff --git a/halo2_proofs/src/poly/kzg/multiopen/shplonk/prover.rs b/halo2_proofs/src/poly/kzg/multiopen/shplonk/prover.rs index ebde585d5e..2bb5fcff4d 100644 --- a/halo2_proofs/src/poly/kzg/multiopen/shplonk/prover.rs +++ b/halo2_proofs/src/poly/kzg/multiopen/shplonk/prover.rs @@ -1,5 +1,5 @@ use super::{ - construct_intermediate_sets, ChallengeU, ChallengeV, ChallengeY, Commitment, Query, RotationSet, + construct_intermediate_sets, ChallengeU, ChallengeV, ChallengeY, Commitment, RotationSet, }; use crate::arithmetic::{ eval_polynomial, evaluate_vanishing_polynomial, kate_division, lagrange_interpolate, @@ -9,8 +9,7 @@ use crate::helpers::SerdeCurveAffine; use crate::poly::commitment::{Blind, ParamsProver, Prover}; use crate::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG}; use crate::poly::query::{PolynomialPointer, ProverQuery}; -use crate::poly::Rotation; -use crate::poly::{commitment::Params, Coeff, Polynomial}; +use crate::poly::{Coeff, Polynomial}; use crate::transcript::{EncodedChallenge, TranscriptWrite}; use crate::multicore::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}; @@ -19,7 +18,7 @@ use group::Curve; use halo2curves::pairing::Engine; use rand_core::RngCore; use std::fmt::Debug; -use std::io::{self, Write}; +use std::io; use std::marker::PhantomData; use std::ops::MulAssign; diff --git a/halo2_proofs/src/poly/kzg/multiopen/shplonk/verifier.rs b/halo2_proofs/src/poly/kzg/multiopen/shplonk/verifier.rs index d1d1660e9c..53930f88dd 100644 --- a/halo2_proofs/src/poly/kzg/multiopen/shplonk/verifier.rs +++ b/halo2_proofs/src/poly/kzg/multiopen/shplonk/verifier.rs @@ -1,10 +1,9 @@ use std::fmt::Debug; -use std::io::Read; use super::ChallengeY; use super::{construct_intermediate_sets, ChallengeU, ChallengeV}; use crate::arithmetic::{ - eval_polynomial, evaluate_vanishing_polynomial, lagrange_interpolate, powers, CurveAffine, + eval_polynomial, evaluate_vanishing_polynomial, lagrange_interpolate, powers, }; use crate::helpers::SerdeCurveAffine; use crate::poly::commitment::Verifier; @@ -12,19 +11,12 @@ use crate::poly::commitment::MSM; use crate::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG}; use crate::poly::kzg::msm::DualMSM; use crate::poly::kzg::msm::{PreMSM, MSMKZG}; -use crate::poly::kzg::strategy::{AccumulatorStrategy, GuardKZG, SingleStrategy}; -use crate::poly::query::Query; +use crate::poly::kzg::strategy::GuardKZG; use crate::poly::query::{CommitmentReference, VerifierQuery}; -use crate::poly::strategy::VerificationStrategy; -use crate::poly::{ - commitment::{Params, ParamsVerifier}, - Error, -}; +use crate::poly::Error; use crate::transcript::{EncodedChallenge, TranscriptRead}; use ff::{Field, PrimeField}; -use group::Group; -use halo2curves::pairing::{Engine, MillerLoopResult, MultiMillerLoop}; -use rand_core::OsRng; +use halo2curves::pairing::{Engine, MultiMillerLoop}; use std::ops::MulAssign; /// Concrete KZG multiopen verifier with SHPLONK variant diff --git a/halo2_proofs/src/poly/kzg/strategy.rs b/halo2_proofs/src/poly/kzg/strategy.rs index 15cdba2069..14b6565b80 100644 --- a/halo2_proofs/src/poly/kzg/strategy.rs +++ b/halo2_proofs/src/poly/kzg/strategy.rs @@ -1,27 +1,19 @@ -use std::{fmt::Debug, marker::PhantomData}; - use super::{ commitment::{KZGCommitmentScheme, ParamsKZG}, - msm::{DualMSM, MSMKZG}, - multiopen::VerifierGWC, + msm::DualMSM, }; use crate::{ helpers::SerdeCurveAffine, plonk::Error, poly::{ - commitment::{Verifier, MSM}, - ipa::msm::MSMIPA, + commitment::Verifier, strategy::{Guard, VerificationStrategy}, }, - transcript::{EncodedChallenge, TranscriptRead}, }; use ff::{Field, PrimeField}; -use group::Group; -use halo2curves::{ - pairing::{Engine, MillerLoopResult, MultiMillerLoop}, - CurveAffine, -}; +use halo2curves::pairing::{Engine, MultiMillerLoop}; use rand_core::OsRng; +use std::fmt::Debug; /// Wrapper for linear verification accumulator #[derive(Debug, Clone)] diff --git a/halo2_proofs/src/poly/multiopen_test.rs b/halo2_proofs/src/poly/multiopen_test.rs index d57243f712..47c6731167 100644 --- a/halo2_proofs/src/poly/multiopen_test.rs +++ b/halo2_proofs/src/poly/multiopen_test.rs @@ -2,33 +2,28 @@ mod test { use crate::arithmetic::eval_polynomial; use crate::plonk::Error; + use crate::poly::commitment::Blind; use crate::poly::commitment::ParamsProver; - use crate::poly::commitment::{Blind, ParamsVerifier, MSM}; - use crate::poly::query::PolynomialPointer; use crate::poly::{ commitment::{CommitmentScheme, Params, Prover, Verifier}, query::{ProverQuery, VerifierQuery}, strategy::VerificationStrategy, EvaluationDomain, }; - use crate::poly::{Coeff, Polynomial}; use crate::transcript::{ - self, Blake2bRead, Blake2bWrite, Challenge255, EncodedChallenge, Keccak256Read, - Keccak256Write, TranscriptRead, TranscriptReadBuffer, TranscriptWrite, - TranscriptWriterBuffer, + Blake2bRead, Blake2bWrite, Challenge255, EncodedChallenge, Keccak256Read, Keccak256Write, + TranscriptReadBuffer, TranscriptWriterBuffer, }; - use ff::{Field, PrimeField, WithSmallOrderMulGroup}; - use group::{Curve, Group}; - use halo2curves::CurveAffine; - use rand_core::{OsRng, RngCore}; - use std::io::{Read, Write}; + use ff::WithSmallOrderMulGroup; + use group::Curve; + use rand_core::OsRng; #[test] fn test_roundtrip_ipa() { use crate::poly::ipa::commitment::{IPACommitmentScheme, ParamsIPA}; use crate::poly::ipa::multiopen::{ProverIPA, VerifierIPA}; use crate::poly::ipa::strategy::AccumulatorStrategy; - use halo2curves::pasta::{Ep, EqAffine, Fp}; + use halo2curves::pasta::EqAffine; const K: u32 = 4; @@ -65,7 +60,7 @@ mod test { use crate::poly::ipa::commitment::{IPACommitmentScheme, ParamsIPA}; use crate::poly::ipa::multiopen::{ProverIPA, VerifierIPA}; use crate::poly::ipa::strategy::AccumulatorStrategy; - use halo2curves::pasta::{Ep, EqAffine, Fp}; + use halo2curves::pasta::EqAffine; const K: u32 = 4; @@ -102,8 +97,7 @@ mod test { use crate::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG}; use crate::poly::kzg::multiopen::{ProverGWC, VerifierGWC}; use crate::poly::kzg::strategy::AccumulatorStrategy; - use halo2curves::bn256::{Bn256, G1Affine}; - use halo2curves::pairing::Engine; + use halo2curves::bn256::Bn256; const K: u32 = 4; @@ -134,8 +128,7 @@ mod test { use crate::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG}; use crate::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; use crate::poly::kzg::strategy::AccumulatorStrategy; - use halo2curves::bn256::{Bn256, G1Affine}; - use halo2curves::pairing::Engine; + use halo2curves::bn256::Bn256; const K: u32 = 4; diff --git a/halo2_proofs/src/poly/query.rs b/halo2_proofs/src/poly/query.rs index c596e6a71c..b9894edd38 100644 --- a/halo2_proofs/src/poly/query.rs +++ b/halo2_proofs/src/poly/query.rs @@ -1,11 +1,10 @@ -use std::{fmt::Debug, ops::Deref}; +use std::fmt::Debug; -use super::commitment::{Blind, CommitmentScheme, Params, MSM}; +use super::commitment::{Blind, MSM}; use crate::{ arithmetic::eval_polynomial, - poly::{commitment, Coeff, Polynomial}, + poly::{Coeff, Polynomial}, }; -use ff::Field; use halo2curves::CurveAffine; pub trait Query: Sized + Clone + Send + Sync { @@ -100,6 +99,7 @@ impl<'com, C: CurveAffine, M: MSM> Clone for VerifierQuery<'com, C, M> { } } +#[allow(clippy::upper_case_acronyms)] #[derive(Clone, Debug)] pub enum CommitmentReference<'r, C: CurveAffine, M: MSM> { Commitment(&'r C), diff --git a/halo2_proofs/src/poly/strategy.rs b/halo2_proofs/src/poly/strategy.rs index 36480d372f..850f95e6c9 100644 --- a/halo2_proofs/src/poly/strategy.rs +++ b/halo2_proofs/src/poly/strategy.rs @@ -1,11 +1,5 @@ -use halo2curves::CurveAffine; -use rand_core::RngCore; - -use super::commitment::{CommitmentScheme, Verifier, MSM}; -use crate::{ - plonk::Error, - transcript::{EncodedChallenge, TranscriptRead}, -}; +use super::commitment::{CommitmentScheme, Verifier}; +use crate::plonk::Error; /// Guards is unfinished verification result. Implement this to construct various /// verification strategies such as aggregation and recursion.