Skip to content

Commit

Permalink
refactor: replace anyhow to EigenError (#59)
Browse files Browse the repository at this point in the history
* refactor: replace anyhow to EigenError

---------

Co-authored-by: ibmp33 <2285673866@qq.com>
  • Loading branch information
eigmax and ibmp33 authored May 20, 2023
1 parent 049ac94 commit c1e7715
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 87 deletions.
1 change: 0 additions & 1 deletion plonky/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ crate-type = ["cdylib", "rlib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.34"
bellman_vk_codegen = { git = "https://github.com/0xEigenLabs/solidity_plonk_verifier.git", version = "0.2.0" }
#bellman_vk_codegen = { path = "../../solidity_plonk_verifier/bellman_vk_codegen", version = "0.2.0" }
recursive_aggregation_circuit = { package = "recursive_aggregation_circuit", git = "https://github.com/0xEigenLabs/recursive_aggregation_circuit.git", version = "1.0.0"}
Expand Down
15 changes: 8 additions & 7 deletions plonky/src/aggregation.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![cfg(not(target_arch = "wasm32"))]
// refers to https://github.com/matter-labs/recursive_aggregation_circuit/blob/master/src/circuit/mod.rs
#![allow(clippy::needless_range_loop)]
use crate::errors::Result;
use crate::{bellman_ce, utils};
use bellman_ce::{
kate_commitment::{Crs, CrsForMonomialForm},
Expand Down Expand Up @@ -162,7 +163,7 @@ impl AggregatedProof {
}

impl Serialize for AggregatedProof {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
let mut seq = serializer.serialize_seq(Some(5))?;
let (input, serialized_proof) = serialize_new_proof(&self.proof);
seq.serialize_element(&input)?;
Expand Down Expand Up @@ -259,7 +260,7 @@ pub fn prove(
big_crs: Crs<Bn256, CrsForMonomialForm>,
old_proofs: Vec<OldProof<Bn256, PlonkCsWidth4WithNextStepParams>>,
old_vk: OldVerificationKey<Bn256, PlonkCsWidth4WithNextStepParams>,
) -> Result<AggregatedProof, SynthesisError> {
) -> Result<AggregatedProof> {
let num_proofs_to_check = old_proofs.len();
assert!(num_proofs_to_check > 0);
assert!(num_proofs_to_check < 256);
Expand Down Expand Up @@ -373,7 +374,7 @@ pub fn prove(
fn verify_subproof_limbs(
proof: &AggregatedProof,
vk: &VerificationKey<Bn256, RecursiveAggregationCircuitBn256>,
) -> Result<bool, SynthesisError> {
) -> Result<bool> {
let mut rns_params = RnsParameters::<Bn256, <Bn256 as Engine>::Fq>::new_for_field(68, 110, 4);

//keep the behavior same as recursive_aggregation_circuit
Expand Down Expand Up @@ -413,7 +414,7 @@ fn verify_subproof_limbs(
pub fn verify(
vk: VerificationKey<Bn256, RecursiveAggregationCircuitBn256>,
aggregated_proof: AggregatedProof,
) -> Result<bool, SynthesisError> {
) -> Result<bool> {
let mut inputs = Vec::new();
for chunk in aggregated_proof
.individual_vk_inputs
Expand Down Expand Up @@ -442,7 +443,7 @@ pub fn export_vk(
num_proofs_to_check: usize,
num_inputs: usize,
big_crs: &Crs<Bn256, CrsForMonomialForm>,
) -> Result<VerificationKey<Bn256, RecursiveAggregationCircuitBn256>, anyhow::Error> {
) -> Result<VerificationKey<Bn256, RecursiveAggregationCircuitBn256>> {
let (recursive_circuit_vk, _recursive_circuit_setup) = create_recursive_circuit_vk_and_setup(
num_proofs_to_check,
num_inputs,
Expand All @@ -456,7 +457,7 @@ pub fn export_vk(
pub fn get_aggregated_input(
old_proofs: Vec<OldProof<Bn256, PlonkCsWidth4WithNextStepParams>>,
old_vk: OldVerificationKey<Bn256, PlonkCsWidth4WithNextStepParams>,
) -> Result<bn256::Fr, anyhow::Error> {
) -> Result<bn256::Fr> {
let num_proofs_to_check = old_proofs.len();
assert!(num_proofs_to_check > 0);
assert!(num_proofs_to_check < 256);
Expand Down Expand Up @@ -489,7 +490,7 @@ pub fn get_aggregated_input(

pub fn get_vk_tree_root_hash(
old_vk: OldVerificationKey<Bn256, PlonkCsWidth4WithNextStepParams>,
) -> Result<bn256::Fr, anyhow::Error> {
) -> Result<bn256::Fr> {
let (_, (vks_tree, _)) = create_vks_tree(&vec![old_vk], VK_TREE_DEPTH)?;
Ok(vks_tree.get_commitment())
}
19 changes: 12 additions & 7 deletions plonky/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::bellman_ce::pairing::bn256::Bn256;
use crate::errors::{EigenError, Result};
use crate::witness::{flat_array, WitnessCalculator};
use crate::{circom_circuit::CircomCircuit, plonk, reader};
use num_bigint::BigInt;
Expand All @@ -9,7 +10,6 @@ use std::str::FromStr;
#[cfg(not(feature = "wasm"))]
use crate::{aggregation, verifier};

use anyhow::Result;
use std::path::Path;

// generate a monomial_form SRS, and save it to a file
Expand Down Expand Up @@ -152,7 +152,9 @@ pub fn verify(vk_file: &String, proof_bin: &String, transcript: &String) -> Resu
let vk = reader::load_verification_key::<Bn256>(vk_file);
let proof = reader::load_proof::<Bn256>(proof_bin);
let ok = plonk::verify(&vk, &proof, transcript)?;
anyhow::ensure!(ok, "Proof is invalid");
if !ok {
return Err(EigenError::from("Proof is invalid".to_string()));
}
Result::Ok(())
}

Expand Down Expand Up @@ -212,7 +214,9 @@ pub fn aggregation_verify(proof: &String, vk: &String) -> Result<()> {
let vk = reader::load_aggregation_verification_key(vk);
let proof = reader::load_aggregated_proof(proof);
let correct = aggregation::verify(vk, proof)?;
anyhow::ensure!(correct, "Proof is invalid");
if !correct {
return Err(EigenError::from("Proof is invalid".to_string()));
}
Result::Ok(())
}

Expand All @@ -229,10 +233,11 @@ pub fn aggregation_check(

let expected = aggregation::get_aggregated_input(old_proofs, old_vk)?;

anyhow::ensure!(
expected == new_proof.proof.inputs[0],
"Aggregation hash input mismatch",
);
if expected != new_proof.proof.inputs[0] {
return Err(EigenError::from(
"Aggregation hash input mismatch".to_string(),
));
}
Result::Ok(())
}

Expand Down
3 changes: 3 additions & 0 deletions plonky/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ pub enum EigenError {
#[error("parse bigint error")]
ParseBigIntError(#[from] num_bigint::ParseBigIntError),

#[error("Synthesis circuit error")]
SynthesisError(#[from] crate::bellman_ce::SynthesisError),

#[error("Unknown error, `{0}`")]
Unknown(String),
}
Expand Down
2 changes: 1 addition & 1 deletion plonky/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub mod transpile;
pub mod utils;
pub mod verifier;

use bellman_ce::pairing::ff;
pub use bellman_ce::pairing::ff;
pub use ff::*;
pub use franklin_crypto::bellman as bellman_ce;

Expand Down
101 changes: 59 additions & 42 deletions plonky/src/plonk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ use crate::bellman_ce::{
is_satisfied_using_one_shot_check, make_verification_key, prove, prove_by_steps, setup,
},
worker::Worker,
Circuit, ScalarEngine, SynthesisError,
Circuit, ScalarEngine,
};
use crate::circom_circuit::CircomCircuit;
use crate::errors::{EigenError, Result};
use crate::transpile::{transpile_with_gates_count, ConstraintStat, TranspilerWrapper};

type E = Bn256;
Expand All @@ -27,11 +28,16 @@ const SETUP_MIN_POW2: u32 = 10;
const SETUP_MAX_POW2: u32 = 26;

// generate a monomial_form SRS
pub fn gen_key_monomial_form(power: u32) -> Result<Crs<E, CrsForMonomialForm>, anyhow::Error> {
anyhow::ensure!(
(SETUP_MIN_POW2..=SETUP_MAX_POW2).contains(&power),
"setup power of two is not in the correct range"
);
pub fn gen_key_monomial_form(power: u32) -> Result<Crs<E, CrsForMonomialForm>> {
if (!SETUP_MIN_POW2..=SETUP_MAX_POW2).contains(&power) {
return Err(EigenError::OutOfRangeError {
expected: format!(
"setup power of two is not in the correct range {:?}..={:?}",
SETUP_MIN_POW2, SETUP_MAX_POW2
),
found: power.to_string(),
});
}

// run a small setup to estimate time
if power > 15 {
Expand Down Expand Up @@ -72,7 +78,7 @@ pub struct AnalyseResult {
}

// analyse a circuit
pub fn analyse<E: Engine>(circuit: CircomCircuit<E>) -> Result<AnalyseResult, anyhow::Error> {
pub fn analyse<E: Engine>(circuit: CircomCircuit<E>) -> Result<AnalyseResult> {
let mut transpiler = TranspilerWrapper::<E, PlonkCsWidth4WithNextStepParams>::new();
let mut result = AnalyseResult {
num_inputs: circuit.r1cs.num_inputs,
Expand Down Expand Up @@ -101,7 +107,7 @@ impl SetupForProver {
circuit: C,
key_monomial_form: Crs<E, CrsForMonomialForm>,
key_lagrange_form: Option<Crs<E, CrsForLagrangeForm>>,
) -> Result<Self, anyhow::Error> {
) -> Result<Self> {
let (gates_count, hints) = transpile_with_gates_count(circuit.clone())?;
log::info!(
"transpile done, gates_count {} hints size {}",
Expand All @@ -116,10 +122,15 @@ impl SetupForProver {
size
);
let setup_power_of_two = std::cmp::max(size, SETUP_MIN_POW2);
anyhow::ensure!(
(SETUP_MIN_POW2..=SETUP_MAX_POW2).contains(&setup_power_of_two),
"setup power of two is not in the correct range"
);
if (!SETUP_MIN_POW2..=SETUP_MAX_POW2).contains(&setup_power_of_two) {
return Err(EigenError::OutOfRangeError {
expected: format!(
"setup power of two is not in the correct range {:?}..={:?}",
SETUP_MIN_POW2, SETUP_MAX_POW2
),
found: setup_power_of_two.to_string(),
});
}

Ok(SetupForProver {
setup_polynomials,
Expand All @@ -132,60 +143,66 @@ impl SetupForProver {
// generate a verification key for a circuit
pub fn make_verification_key(
&self,
) -> Result<VerificationKey<E, PlonkCsWidth4WithNextStepParams>, SynthesisError> {
make_verification_key(&self.setup_polynomials, &self.key_monomial_form)
) -> Result<VerificationKey<E, PlonkCsWidth4WithNextStepParams>> {
return Ok(make_verification_key(
&self.setup_polynomials,
&self.key_monomial_form,
)?);
}

// quickly valiate whether a witness is satisfied
pub fn validate_witness<C: Circuit<E> + Clone>(
&self,
circuit: C,
) -> Result<(), SynthesisError> {
is_satisfied_using_one_shot_check(circuit, &self.hints)
pub fn validate_witness<C: Circuit<E> + Clone>(&self, circuit: C) -> Result<()> {
return Ok(is_satisfied_using_one_shot_check(circuit, &self.hints)?);
}

// generate a plonk proof for a circuit, with witness loaded
pub fn prove<C: Circuit<E> + Clone>(
&self,
circuit: C,
transcript: &str,
) -> Result<Proof<E, PlonkCsWidth4WithNextStepParams>, SynthesisError> {
) -> Result<Proof<E, PlonkCsWidth4WithNextStepParams>> {
is_satisfied_using_one_shot_check(circuit.clone(), &self.hints).expect("must satisfy");
match &self.key_lagrange_form {
Some(key_lagrange_form) => match transcript {
// NOTE: prove is not enabled in GPU bellman
"keccak" => prove::<_, _, RollingKeccakTranscript<<E as ScalarEngine>::Fr>>(
"keccak" => Ok(prove::<
_,
_,
RollingKeccakTranscript<<E as ScalarEngine>::Fr>,
>(
circuit,
&self.hints,
&self.setup_polynomials,
&self.key_monomial_form,
key_lagrange_form,
),
)?),
_ => {
unimplemented!();
}
},
None => match transcript {
"keccak" => {
prove_by_steps::<_, _, RollingKeccakTranscript<<E as ScalarEngine>::Fr>>(
circuit,
&self.hints,
&self.setup_polynomials,
None,
&self.key_monomial_form,
None,
)
}
"keccak" => Ok(prove_by_steps::<
_,
_,
RollingKeccakTranscript<<E as ScalarEngine>::Fr>,
>(
circuit,
&self.hints,
&self.setup_polynomials,
None,
&self.key_monomial_form,
None,
)?),
"rescue" => {
let (bn256_param, rns_param) = get_default_rescue_transcript_params();
prove_by_steps::<_, _, RescueTranscriptForRNS<E>>(
Ok(prove_by_steps::<_, _, RescueTranscriptForRNS<E>>(
circuit,
&self.hints,
&self.setup_polynomials,
None,
&self.key_monomial_form,
Some((&bn256_param, &rns_param)),
)
)?)
}
_ => {
unimplemented!("invalid transcript. use 'keccak' or 'rescue'");
Expand All @@ -209,20 +226,20 @@ pub fn verify(
vk: &VerificationKey<E, PlonkCsWidth4WithNextStepParams>,
proof: &Proof<E, PlonkCsWidth4WithNextStepParams>,
transcript: &str,
) -> Result<bool, SynthesisError> {
) -> Result<bool> {
match transcript {
"keccak" => crate::bellman_ce::plonk::better_cs::verifier::verify::<
"keccak" => Ok(crate::bellman_ce::plonk::better_cs::verifier::verify::<
_,
_,
RollingKeccakTranscript<<E as ScalarEngine>::Fr>,
>(proof, vk, None),
>(proof, vk, None)?),
"rescue" => {
let (bn256_param, rns_param) = get_default_rescue_transcript_params();
crate::bellman_ce::plonk::better_cs::verifier::verify::<_, _, RescueTranscriptForRNS<E>>(
proof,
vk,
Some((&bn256_param, &rns_param)),
)
Ok(crate::bellman_ce::plonk::better_cs::verifier::verify::<
_,
_,
RescueTranscriptForRNS<E>,
>(proof, vk, Some((&bn256_param, &rns_param)))?)
}
_ => {
unimplemented!("invalid transcript. use 'keccak' or 'rescue'");
Expand Down
Loading

0 comments on commit c1e7715

Please sign in to comment.