Skip to content

Commit

Permalink
Remove usage of anyhow and thiserror crates
Browse files Browse the repository at this point in the history
Fixes #343
  • Loading branch information
jules committed Feb 11, 2021
1 parent b2c6979 commit cf650b6
Show file tree
Hide file tree
Showing 20 changed files with 223 additions and 154 deletions.
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ dusk-jubjub = "0.8"
itertools = "0.9.0"
rand_chacha = "0.2"
rayon = "1.3.0"
anyhow = "1.0.32"
thiserror = "1.0"
serde = "1.0"
# Dusk related deps for WASMI serde
canonical = {version = "0.5", optional = true}

[dev-dependencies]
anyhow = "1.0.32"
tempdir = "0.3"

[package.metadata.docs.rs]
Expand Down
61 changes: 40 additions & 21 deletions src/circuit_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@

//! Tools & traits for PLONK circuits

use crate::commitment_scheme::kzg10::PublicParameters;
use crate::commitment_scheme::kzg10::{errors::KZG10Errors, PublicParameters};
use crate::constraint_system::cs_errors::PreProcessingErrors;
use crate::constraint_system::StandardComposer;
use crate::proof_system::{Proof, ProverKey, VerifierKey};
use anyhow::Result;
use crate::proof_system::{proof_system_errors::ProofErrors, Proof, ProverKey, VerifierKey};
use dusk_bls12_381::BlsScalar;
use dusk_bytes::Serializable;
use dusk_jubjub::{JubJubAffine, JubJubScalar};
use thiserror::Error;

const BLS_SCALAR: u8 = 1;
const JUBJUB_SCALAR: u8 = 2;
Expand Down Expand Up @@ -103,22 +102,31 @@ where
Self: Sized,
{
/// Gadget implementation used to fill the composer.
fn gadget(&mut self, composer: &mut StandardComposer) -> Result<()>;
fn gadget(&mut self, composer: &mut StandardComposer) -> Result<(), CircuitErrors>;
/// Compiles the circuit by using a function that returns a `Result`
/// with the `ProverKey`, `VerifierKey` and the circuit size.
fn compile(&mut self, pub_params: &PublicParameters) -> Result<(ProverKey, VerifierKey)> {
fn compile(
&mut self,
pub_params: &PublicParameters,
) -> Result<(ProverKey, VerifierKey), CircuitErrors> {
use crate::proof_system::{Prover, Verifier};
// Setup PublicParams
let (ck, _) = pub_params.trim(self.get_trim_size())?;
let (ck, _) = pub_params
.trim(self.get_trim_size())
.map_err(|e| CircuitErrors::CouldNotTrimPubParams(e))?;
// Generate & save `ProverKey` with some random values.
let mut prover = Prover::new(b"CircuitCompilation");
self.gadget(prover.mut_cs())?;
prover.preprocess(&ck)?;
prover
.preprocess(&ck)
.map_err(|e| CircuitErrors::CouldNotPreProcessCircuit(e))?;

// Generate & save `VerifierKey` with some random values.
let mut verifier = Verifier::new(b"CircuitCompilation");
self.gadget(verifier.mut_cs())?;
verifier.preprocess(&ck)?;
verifier
.preprocess(&ck)
.map_err(|e| CircuitErrors::CouldNotPreProcessCircuit(e))?;
Ok((
prover
.prover_key
Expand All @@ -136,7 +144,7 @@ where
fn get_pi_positions(&self) -> &Vec<PublicInput>;

/// Build PI vector for Proof verifications.
fn build_pi(&self, pub_inputs: &[PublicInput]) -> Result<Vec<BlsScalar>> {
fn build_pi(&self, pub_inputs: &[PublicInput]) -> Vec<BlsScalar> {
let mut pi = vec![BlsScalar::zero(); self.get_trim_size()];
pub_inputs
.iter()
Expand All @@ -153,7 +161,7 @@ where
}
};
});
Ok(pi)
pi
}

/// Returns the size at which we trim the `PublicParameters`
Expand All @@ -171,16 +179,18 @@ where
pub_params: &PublicParameters,
prover_key: &ProverKey,
transcript_initialisation: &'static [u8],
) -> Result<Proof> {
) -> Result<Proof, CircuitErrors> {
use crate::proof_system::Prover;
let (ck, _) = pub_params.trim(self.get_trim_size())?;
let (ck, _) = pub_params
.trim(self.get_trim_size())
.map_err(|e| CircuitErrors::CouldNotTrimPubParams(e))?;
// New Prover instance
let mut prover = Prover::new(transcript_initialisation);
// Fill witnesses for Prover
self.gadget(prover.mut_cs())?;
// Add ProverKey to Prover
prover.prover_key = Some(prover_key.clone());
prover.prove(&ck)
prover.prove(&ck).map_err(|e| CircuitErrors::ProverError(e))
}

/// Verifies a proof using the provided `CircuitInputs` & `VerifierKey` instances.
Expand All @@ -191,32 +201,41 @@ where
transcript_initialisation: &'static [u8],
proof: &Proof,
pub_inputs: &[PublicInput],
) -> Result<()> {
) -> Result<(), CircuitErrors> {
use crate::proof_system::Verifier;
let (_, vk) = pub_params.trim(self.get_trim_size())?;
let (_, vk) = pub_params
.trim(self.get_trim_size())
.map_err(|e| CircuitErrors::CouldNotTrimPubParams(e))?;
// New Verifier instance
let mut verifier = Verifier::new(transcript_initialisation);
// Fill witnesses for Verifier
self.gadget(verifier.mut_cs())?;
verifier.verifier_key = Some(*verifier_key);
verifier.verify(proof, &vk, &self.build_pi(pub_inputs)?)
verifier
.verify(proof, &vk, &self.build_pi(pub_inputs))
.map_err(|e| CircuitErrors::ProofVerificationFailed(e))
}
}

/// Represents an error in the PublicParameters creation and or modification.
#[derive(Error, Debug)]
pub enum CircuitErrors {
/// This error occurs when the circuit is not provided with all of the
/// required inputs.
#[error("missing inputs for the circuit")]
CircuitInputsNotFound,
/// This error occurs when we want to verify a Proof but the pi_constructor
/// attribute is uninitialized.
#[error("PI constructor attribute is uninitialized")]
UninitializedPIGenerator,
/// PublicInput serialization error
#[error("Invalid PublicInput bytes")]
InvalidPublicInputBytes,
/// This error occurs when we can not trim the public parameters.
CouldNotTrimPubParams(KZG10Errors),
/// This error occurs when preprocessing of a circuit fails.
CouldNotPreProcessCircuit(PreProcessingErrors),
/// This error occurs when proof verification fails.
ProofVerificationFailed(ProofErrors),
/// This error occurs when anything related to proof creation fails.
/// It is a generic error, as the underlying error should explain the issue.
ProverError(ProofErrors),
}

#[cfg(test)]
Expand Down
10 changes: 1 addition & 9 deletions src/commitment_scheme/kzg10/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,23 @@

//! Errors related to KZG10

use thiserror::Error;

/// Represents an error in the PublicParameters creation and or modification.
#[derive(Error, Debug)]
#[derive(core::fmt::Debug)]
pub enum KZG10Errors {
/// This error occurs when the user tries to create PublicParameters
/// and supplies the max degree as zero.
#[error("cannot create PublicParameters with max degree as 0")]
DegreeIsZero,
/// This error occurs when the user tries to trim PublicParameters
/// to a degree that is larger than the maximum degree.
#[error("cannot trim more than the maximum degree")]
TruncatedDegreeTooLarge,
/// This error occurs when the user tries to trim PublicParameters
/// down to a degree that is zero.
#[error("cannot trim PublicParameters to a maximum size of zero")]
TruncatedDegreeIsZero,
/// This error occurs when the user tries to commit to a polynomial whose degree is larger than
/// the supported degree for that proving key.
#[error("proving key is not large enough to commit to said polynomial")]
PolynomialDegreeTooLarge,
/// This error occurs when the user tries to commit to a polynomial whose degree is zero.
#[error("cannot commit to polynomial of zero degree")]
PolynomialDegreeIsZero,
/// This error occurs when the pairing check fails at being equal to the Identity point.
#[error("pairing check failed")]
PairingCheckFailure,
}
33 changes: 17 additions & 16 deletions src/commitment_scheme/kzg10/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
//! that support the generation and usage of Commit and
//! Opening keys.
use super::{errors::KZG10Errors, AggregateProof, Commitment, Proof};
use crate::{fft::Polynomial, transcript::TranscriptProtocol, util};
use anyhow::{Error, Result};
use crate::{
fft::Polynomial, serialisation::SerialisationErrors, transcript::TranscriptProtocol, util,
};
use dusk_bls12_381::{
multiscalar_mul::msm_variable_base, BlsScalar, G1Affine, G1Projective, G2Affine, G2Prepared,
};
Expand Down Expand Up @@ -96,7 +97,7 @@ impl CommitKey {
}

/// Deserialises a bytes slice to a Commitment Key
pub fn from_bytes(bytes: &[u8]) -> Result<CommitKey, Error> {
pub fn from_bytes(bytes: &[u8]) -> Result<CommitKey, SerialisationErrors> {
use crate::serialisation::{read_g1_affine, read_u64};

let (num_points, rest) = read_u64(&bytes)?;
Expand All @@ -121,18 +122,18 @@ impl CommitKey {
/// Truncates the commit key to a lower max degree.
/// Returns an error if the truncated degree is zero or if the truncated degree
/// is larger than the max degree of the commit key.
pub fn truncate(&self, mut truncated_degree: usize) -> Result<CommitKey, Error> {
pub fn truncate(&self, mut truncated_degree: usize) -> Result<CommitKey, KZG10Errors> {
if truncated_degree == 1 {
truncated_degree += 1;
}
// Check that the truncated degree is not zero
if truncated_degree == 0 {
return Err(KZG10Errors::TruncatedDegreeIsZero.into());
return Err(KZG10Errors::TruncatedDegreeIsZero);
}

// Check that max degree is less than truncated degree
if truncated_degree > self.max_degree() {
return Err(KZG10Errors::TruncatedDegreeTooLarge.into());
return Err(KZG10Errors::TruncatedDegreeTooLarge);
}

let truncated_powers = Self {
Expand All @@ -142,14 +143,14 @@ impl CommitKey {
Ok(truncated_powers)
}

fn check_commit_degree_is_within_bounds(&self, poly_degree: usize) -> Result<(), Error> {
fn check_commit_degree_is_within_bounds(&self, poly_degree: usize) -> Result<(), KZG10Errors> {
check_degree_is_within_bounds(self.max_degree(), poly_degree)
}

/// Commits to a polynomial returning the corresponding `Commitment`.
///
/// Returns an error if the polynomial's degree is more than the max degree of the commit key.
pub fn commit(&self, polynomial: &Polynomial) -> Result<Commitment, Error> {
pub fn commit(&self, polynomial: &Polynomial) -> Result<Commitment, KZG10Errors> {
// Check whether we can safely commit to this polynomial
self.check_commit_degree_is_within_bounds(polynomial.degree())?;

Expand Down Expand Up @@ -199,7 +200,7 @@ impl CommitKey {
polynomial: &Polynomial,
value: &BlsScalar,
point: &BlsScalar,
) -> Result<Proof, Error> {
) -> Result<Proof, KZG10Errors> {
let witness_poly = self.compute_single_witness(polynomial, point);
Ok(Proof {
commitment_to_witness: self.commit(&witness_poly)?,
Expand All @@ -217,7 +218,7 @@ impl CommitKey {
evaluations: Vec<BlsScalar>,
point: &BlsScalar,
transcript: &mut Transcript,
) -> Result<AggregateProof, Error> {
) -> Result<AggregateProof, KZG10Errors> {
// Commit to polynomials
let mut polynomial_commitments = Vec::with_capacity(polynomials.len());
for poly in polynomials.iter() {
Expand Down Expand Up @@ -274,7 +275,7 @@ impl OpeningKey {
}

/// Deserialises a byte slice into an Opening Key
pub fn from_bytes(bytes: &[u8]) -> Result<OpeningKey, Error> {
pub fn from_bytes(bytes: &[u8]) -> Result<OpeningKey, SerialisationErrors> {
use crate::serialisation::{read_g1_affine, read_g2_affine};

let (g, rest) = read_g1_affine(&bytes)?;
Expand Down Expand Up @@ -308,7 +309,7 @@ impl OpeningKey {
points: &[BlsScalar],
proofs: &[Proof],
transcript: &mut Transcript,
) -> Result<(), Error> {
) -> Result<(), KZG10Errors> {
let mut total_c = G1Projective::identity();
let mut total_w = G1Projective::identity();

Expand Down Expand Up @@ -339,7 +340,7 @@ impl OpeningKey {
.final_exponentiation();

if pairing != dusk_bls12_381::Gt::identity() {
return Err(KZG10Errors::PairingCheckFailure.into());
return Err(KZG10Errors::PairingCheckFailure);
};
Ok(())
}
Expand All @@ -351,12 +352,12 @@ impl OpeningKey {
///
///
/// Returns an error if any of the above conditions are true.
fn check_degree_is_within_bounds(max_degree: usize, poly_degree: usize) -> Result<(), Error> {
fn check_degree_is_within_bounds(max_degree: usize, poly_degree: usize) -> Result<(), KZG10Errors> {
if poly_degree == 0 {
return Err(KZG10Errors::PolynomialDegreeIsZero.into());
return Err(KZG10Errors::PolynomialDegreeIsZero);
}
if poly_degree > max_degree {
return Err(KZG10Errors::PolynomialDegreeTooLarge.into());
return Err(KZG10Errors::PolynomialDegreeTooLarge);
}
Ok(())
}
Expand Down
15 changes: 7 additions & 8 deletions src/commitment_scheme/kzg10/srs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ use super::{
errors::KZG10Errors,
key::{CommitKey, OpeningKey},
};
use crate::util;
use anyhow::{anyhow, Error, Result};
use crate::{serialisation::SerialisationErrors, util};
use dusk_bls12_381::{G1Affine, G1Projective, G2Affine};
use rand_core::{CryptoRng, RngCore};

Expand Down Expand Up @@ -38,10 +37,10 @@ impl PublicParameters {
pub fn setup<R: RngCore + CryptoRng>(
max_degree: usize,
mut rng: &mut R,
) -> Result<PublicParameters, Error> {
) -> Result<PublicParameters, KZG10Errors> {
// Cannot commit to constants
if max_degree < 1 {
return Err(KZG10Errors::DegreeIsZero.into());
return Err(KZG10Errors::DegreeIsZero);
}

// Generate the secret scalar beta
Expand Down Expand Up @@ -87,9 +86,9 @@ impl PublicParameters {
///
/// The bytes source is expected to be trusted and no check will be performed reggarding the
/// points security
pub unsafe fn from_slice_unchecked(bytes: &[u8]) -> Result<Self, Error> {
pub unsafe fn from_slice_unchecked(bytes: &[u8]) -> Result<Self, SerialisationErrors> {
if bytes.len() < OpeningKey::serialized_size() + 1 {
return Err(anyhow!("Not enough bytes provided!"));
return Err(SerialisationErrors::NotEnoughBytes);
}

let opening_key = &bytes[..OpeningKey::serialized_size()];
Expand All @@ -112,7 +111,7 @@ impl PublicParameters {
}

/// Deserialise a slice of bytes into a Public Parameter struct
pub fn from_bytes(bytes: &[u8]) -> Result<PublicParameters, Error> {
pub fn from_bytes(bytes: &[u8]) -> Result<PublicParameters, SerialisationErrors> {
let opening_key_bytes = &bytes[0..OpeningKey::serialized_size()];
let commit_key_bytes = &bytes[OpeningKey::serialized_size()..];

Expand All @@ -130,7 +129,7 @@ impl PublicParameters {
/// Trim truncates the prover key to allow the prover to commit to polynomials up to the
/// and including the truncated degree.
/// Returns an error if the truncated degree is larger than the public parameters configured degree.
pub fn trim(&self, truncated_degree: usize) -> Result<(CommitKey, OpeningKey), Error> {
pub fn trim(&self, truncated_degree: usize) -> Result<(CommitKey, OpeningKey), KZG10Errors> {
let truncated_prover_key = self.commit_key.truncate(truncated_degree)?;
let opening_key = self.opening_key.clone();
Ok((truncated_prover_key, opening_key))
Expand Down
15 changes: 11 additions & 4 deletions src/constraint_system/cs_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,20 @@

//! Errors related to the Constraint system

use thiserror::Error;
use crate::commitment_scheme::kzg10::errors::KZG10Errors;
use crate::fft::fft_errors::FFTErrors;

/// Represents an error on the Circuit preprocessing stage.
#[derive(Error, Debug)]
pub enum PreProcessingError {
#[derive(core::fmt::Debug)]
pub enum PreProcessingErrors {
/// This error occurs when an error triggers during the preprocessing
/// stage.
#[error("the length of the wires it's not the same")]
MismatchedPolyLen,
/// This error occurs when no evaluation domain can be constructed.
CouldNotConstructEvaluationDomain(FFTErrors),
/// This error occurs when a poly can not be committed to.
CouldNotCommitToPoly(KZG10Errors),
/// This error occurs when the Prover structure already contains a
/// preprocessed circuit inside, but you call preprocess again.
CircuitAlreadyPreprocessed,
}
1 change: 0 additions & 1 deletion src/constraint_system/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use super::StandardComposer;
use crate::commitment_scheme::kzg10::PublicParameters;
use crate::proof_system::{Prover, Verifier};
use anyhow::{Error, Result};
use dusk_bls12_381::BlsScalar;

/// Adds dummy constraints using arithmetic gates
Expand Down
Loading

0 comments on commit cf650b6

Please sign in to comment.