Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assorted changes to fix warnings & remove dead code #2

Merged
merged 6 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 10 additions & 14 deletions benches/rsa.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,29 @@
use ff::{Field, PrimeFieldBits};
use criterion::{criterion_group, criterion_main, Criterion};
use ff::PrimeFieldBits;
use halo2_proofs::{
circuit::{floor_planner::V1, Layouter, SimpleFloorPlanner, Value},
circuit::{floor_planner::V1, Layouter, Value},
plonk::{
create_proof, keygen_pk, keygen_vk, verify_proof, Advice, Circuit, Column,
ConstraintSystem, Error, Instance, SecondPhase,
create_proof, keygen_pk, keygen_vk, Advice, Circuit, Column, ConstraintSystem, Error,
SecondPhase,
},
poly::{
commitment::ParamsProver,
kzg::{
commitment::{KZGCommitmentScheme, ParamsKZG},
multiopen::ProverGWC,
},
VerificationStrategy,
},
transcript::{
Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer,
},
transcript::{Blake2bWrite, Challenge255, TranscriptWriterBuffer},
};
use halo2_rsa::{
rsa::{Config, PKCSV15Witness},
witness_gen::signature::sign,
};
use halo2curves::bn256::{Bn256, Fr};

use halo2_rsa::rsa::{Config, PKCSV15Witness};
use halo2_rsa::witness_gen::signature::sign;
use num_bigint::BigUint;
use rand_core::OsRng;

use std::convert::TryInto;

use criterion::{criterion_group, criterion_main, Criterion};

#[derive(Clone, Default)]
struct RsaCircuit<F: PrimeFieldBits, const TABLE_BITS: usize> {
witness: PKCSV15Witness<F>,
Expand Down
234 changes: 8 additions & 226 deletions src/check_carry_to_zero.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
use crate::{
mul_cfgs::{MulAddConfig, MulConfig},
poly_eval::{self, LoadedPoly},
};
use ff::{Field, PrimeField, PrimeFieldBits};

use ff::PrimeFieldBits;
use halo2_proofs::{
circuit::{AssignedCell, Layouter, Value},
plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector, VirtualCells},
circuit::{Layouter, Value},
plonk::{Advice, Column, ConstraintSystem, Error, Expression, Selector},
poly::Rotation,
};

use crate::poly_eval::{self, LoadedPoly};

#[derive(Clone)]
pub(crate) struct Config<const BASE: u8, const N: usize, const K: usize, F: PrimeFieldBits> {
poly: poly_eval::Config<K, F>,
Expand Down Expand Up @@ -132,11 +129,11 @@ impl<const BASE: u8, const N: usize, const K: usize, F: PrimeFieldBits> Config<B
)?;
shifted_carries.push(shifted_carry);

for i in 1..N {
for (i, &f_i) in f.iter().enumerate().take(N).skip(1) {
self.selector.enable(&mut region, i)?;
self.carry_shift_selector.enable(&mut region, i)?;

carry = (carry + f[i]) * base_inv;
carry = (carry + f_i) * base_inv;
carry_cell = region.assign_advice(|| "carry", self.carry, i, || carry)?;

let shifted_carry = region.assign_advice(
Expand All @@ -157,226 +154,11 @@ impl<const BASE: u8, const N: usize, const K: usize, F: PrimeFieldBits> Config<B
for shifted_carry in shifted_carries.iter() {
self.poly.range_check.copy_check(
layouter.namespace(|| "range check shifted_carry"),
&shifted_carry,
shifted_carry,
70,
)?;
}

Ok(f_loaded)
}
}

#[cfg(test)]
mod tests {
use halo2_proofs::{
circuit::floor_planner::V1,
plonk::{
create_proof, keygen_pk, keygen_vk, verify_proof, Challenge, Circuit, FirstPhase,
SecondPhase, VerifyingKey,
},
poly::commitment::{CommitmentScheme, Verifier},
transcript::EncodedChallenge,
};
use halo2curves::{bn256::Bn256, pairing::Engine};

use super::*;

use crate::poly_eval;
use ff::{FromUniformBytes, PrimeFieldBits, WithSmallOrderMulGroup};
use halo2_proofs::{
dev::{metadata, FailureLocation, MockProver, VerifyFailure},
poly::{commitment::ParamsProver, VerificationStrategy},
transcript::{
Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer,
},
};
use rand_core::OsRng;

#[derive(Clone, Debug, Default)]
struct MyCircuit<F: PrimeField> {
f: [Value<F>; 4],
}

impl<F: PrimeFieldBits> Circuit<F> for MyCircuit<F> {
type Config = (super::Config<10, 4, 10, F>, Challenge);

type FloorPlanner = V1;

fn without_witnesses(&self) -> Self {
Self::default()
}

fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
let f = meta.advice_column();
let eval = meta.advice_column_in(SecondPhase);
let x = meta.challenge_usable_after(FirstPhase);
let range_check = meta.advice_column();
let table = meta.lookup_table_column();

let poly = poly_eval::Config::configure(meta, f, eval, x, range_check, table);
let carry = meta.advice_column();

meta.enable_equality(f);
meta.enable_equality(carry);

(super::Config::configure(meta, poly, carry), x)
}

fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<F>,
) -> Result<(), Error> {
let x = config.1;
let config = config.0;

let mut witness_poly = |poly: Vec<Value<F>>,
column: Column<Advice>|
-> Result<Vec<AssignedCell<F, F>>, Error> {
layouter.assign_region(
|| "",
|mut region| {
let mut coeffs = vec![];
for (i, coeff) in poly.iter().enumerate() {
let coeff = region.assign_advice(|| "", column, i, || *coeff)?;
coeffs.push(coeff);
}
Ok(coeffs)
},
)
};

let x = layouter.get_challenge(x);
// check carry to zero on f
config.synthesize(layouter.namespace(|| "f"), &self.f, x)?;

Ok(())
}
}

fn test_mock_prover<F: Ord + FromUniformBytes<64> + PrimeFieldBits>(
k: u32,
circuit: MyCircuit<F>,
expected: Result<(), Vec<(metadata::Constraint, FailureLocation)>>,
) {
let prover = MockProver::run(k, &circuit, vec![]).unwrap();
match (prover.verify(), expected) {
(Ok(_), Ok(_)) => {}
(Err(err), Err(expected)) => {
assert_eq!(
err.into_iter()
.map(|failure| match failure {
VerifyFailure::ConstraintNotSatisfied {
constraint,
location,
..
} => (constraint, location),
_ => panic!("MockProver::verify has result unmatching expected"),
})
.collect::<Vec<_>>(),
expected
)
}
(_, _) => panic!("MockProver::verify has result unmatching expected"),
};
}

fn test_prover(k: u32, circuit: MyCircuit<<Bn256 as Engine>::Scalar>, expected: bool) {
use halo2_proofs::poly::kzg::commitment::{KZGCommitmentScheme, ParamsKZG};
use halo2_proofs::poly::kzg::multiopen::{ProverGWC, VerifierGWC};
use halo2_proofs::poly::kzg::strategy::AccumulatorStrategy;

let params = ParamsKZG::<Bn256>::new(k);
let _rng = OsRng;

let vk = keygen_vk(&params, &circuit).unwrap();
let pk = keygen_pk(&params, vk, &circuit).unwrap();

let proof = {
let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]);

create_proof::<KZGCommitmentScheme<_>, ProverGWC<'_, _>, _, _, _, _>(
&params,
&pk,
&[circuit],
&[&[]],
OsRng,
&mut transcript,
)
.expect("proof generation should not fail");

transcript.finalize()
};

fn verify_proof_helper<
'a,
'params,
Scheme: CommitmentScheme,
V: Verifier<'params, Scheme>,
E: EncodedChallenge<Scheme::Curve>,
T: TranscriptReadBuffer<&'a [u8], Scheme::Curve, E>,
Strategy: VerificationStrategy<'params, Scheme, V, Output = Strategy>,
>(
params_verifier: &'params Scheme::ParamsVerifier,
vk: &VerifyingKey<Scheme::Curve>,
proof: &'a [u8],
) -> bool
where
Scheme::Scalar: Ord + WithSmallOrderMulGroup<3> + FromUniformBytes<64>,
{
let mut transcript = T::init(proof);

let strategy = Strategy::new(params_verifier);
verify_proof(params_verifier, vk, strategy, &[&[]], &mut transcript)
.unwrap()
.finalize()
}

let accepted = {
let verifier_params = params.verifier_params();

verify_proof_helper::<
_,
VerifierGWC<_>,
_,
Blake2bRead<_, _, Challenge255<_>>,
AccumulatorStrategy<_>,
>(verifier_params, pk.get_vk(), &proof[..])
};

assert_eq!(accepted, expected);
}

#[test]
fn fpmul_test() {
use halo2curves::bn256::Fr;

const K: u32 = 11;

fn array_value<const L: usize>(array: [i64; L]) -> [Value<Fr>; L] {
array
.iter()
.map(|&coeff| {
let fi = if coeff < 0 {
-Fr::from(-coeff as u64)
} else {
Fr::from(coeff as u64)
};

Value::known(fi)
})
.collect::<Vec<_>>()
.try_into()
.unwrap()
}

let circuit = MyCircuit::<Fr> {
f: array_value([-10, -9, -9, 1]),
};

{
test_mock_prover(K, circuit.clone(), Ok(()));
test_prover(K, circuit.clone(), true);
}
}
}
2 changes: 0 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,8 @@ FpMul:


*/
#![feature(int_roundings)]
mod check_carry_to_zero;
mod lookup_range_check;
mod mul_cfgs;
mod poly_eval;
pub mod rsa;
pub mod witness_gen;
Loading