Skip to content

Commit

Permalink
Remove usage of anyhow and thiserror crates (#397)
Browse files Browse the repository at this point in the history
* Remove usage of anyhow and thiserror crates

Fixes #343

* Centralize errors in a single file

This has the added effect of being able to entirely drop
usage of anyhow, even in tests, as well as removing a lot of
map_err calls. Additionally, the Display implementation for Error
is now captured by a feature flag for "std".

* Address review comments

- Remove conditional compilation flag in lib.rs
- Section off errors with comments
- Export the error module directly in the prelude

* Update CHANGELOG
  • Loading branch information
jules authored Feb 12, 2021
1 parent b2c6979 commit 8e251f6
Show file tree
Hide file tree
Showing 26 changed files with 191 additions and 227 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Removed
- Deprecated `anyhow` and `thiserror` [#343](https://github.com/dusk-network/plonk/issues/343)
### Changed
- Updated the native errors to all originate from the same enum

## [0.5.1] - 02-02-21
### Changed
Expand Down
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ 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}
Expand All @@ -44,6 +42,8 @@ tempdir = "0.3"
rustdoc-args = [ "--html-in-header", "katex-header.html" ]

[features]
default = ["std"]
std = []
nightly = []
trace = []
trace-print = ["trace"]
Expand Down
94 changes: 42 additions & 52 deletions src/circuit_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@

use crate::commitment_scheme::kzg10::PublicParameters;
use crate::constraint_system::StandardComposer;
use crate::error::Error;
use crate::proof_system::{Proof, ProverKey, VerifierKey};
use anyhow::Result;
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 @@ -62,24 +61,24 @@ impl PublicInput {
}

/// Generate a [`PublicInput`] structure from it's byte representation.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, CircuitErrors> {
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() < Self::serialized_size() {
return Err(CircuitErrors::InvalidPublicInputBytes.into());
return Err(Error::InvalidPublicInputBytes);
} else {
let mut array_bytes = [0u8; 32];
array_bytes.copy_from_slice(&bytes[1..Self::serialized_size()]);
match bytes[0] {
BLS_SCALAR => BlsScalar::from_bytes(&array_bytes)
.map(|s| Self::BlsScalar(s, 0))
.map_err(|_| CircuitErrors::InvalidPublicInputBytes),
.map_err(|_| Error::InvalidPublicInputBytes),

JUBJUB_SCALAR => JubJubScalar::from_bytes(&array_bytes)
.map(|s| Self::JubJubScalar(s, 0))
.map_err(|_| CircuitErrors::InvalidPublicInputBytes),
.map_err(|_| Error::InvalidPublicInputBytes),

JUBJUB_AFFINE => JubJubAffine::from_bytes(&array_bytes)
.map(|s| Self::AffinePoint(s, 0, 0))
.map_err(|_| CircuitErrors::InvalidPublicInputBytes),
.map_err(|_| Error::InvalidPublicInputBytes),

_ => unreachable!(),
}
Expand All @@ -103,10 +102,13 @@ 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<(), Error>;
/// 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), Error> {
use crate::proof_system::{Prover, Verifier};
// Setup PublicParams
let (ck, _) = pub_params.trim(self.get_trim_size())?;
Expand Down Expand Up @@ -136,7 +138,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 +155,7 @@ where
}
};
});
Ok(pi)
pi
}

/// Returns the size at which we trim the `PublicParameters`
Expand All @@ -171,7 +173,7 @@ where
pub_params: &PublicParameters,
prover_key: &ProverKey,
transcript_initialisation: &'static [u8],
) -> Result<Proof> {
) -> Result<Proof, Error> {
use crate::proof_system::Prover;
let (ck, _) = pub_params.trim(self.get_trim_size())?;
// New Prover instance
Expand All @@ -191,40 +193,23 @@ where
transcript_initialisation: &'static [u8],
proof: &Proof,
pub_inputs: &[PublicInput],
) -> Result<()> {
) -> Result<(), Error> {
use crate::proof_system::Verifier;
let (_, vk) = pub_params.trim(self.get_trim_size())?;
// 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))
}
}

/// 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,
}

#[cfg(test)]
mod tests {
use super::*;
use crate::constraint_system::StandardComposer;
use crate::proof_system::{ProverKey, VerifierKey};
use anyhow::Result;

// Implements a circuit that checks:
// 1) a + b = c where C is a PI
Expand All @@ -248,10 +233,8 @@ mod tests {
}

impl<'a> Circuit<'a> for TestCircuit<'a> {
fn gadget(&mut self, composer: &mut StandardComposer) -> Result<()> {
let inputs = self
.inputs
.ok_or_else(|| CircuitErrors::CircuitInputsNotFound)?;
fn gadget(&mut self, composer: &mut StandardComposer) -> Result<(), Error> {
let inputs = self.inputs.ok_or_else(|| Error::CircuitInputsNotFound)?;
let pi = self.get_mut_pi_positions();
let a = composer.add_input(inputs[0]);
let b = composer.add_input(inputs[1]);
Expand Down Expand Up @@ -307,23 +290,25 @@ mod tests {
}

#[test]
fn test_full() -> Result<()> {
fn test_full() {
use std::fs::{self, File};
use std::io::Write;
use tempdir::TempDir;

let tmp = TempDir::new("plonk-keys-test-full")?.into_path();
let tmp = TempDir::new("plonk-keys-test-full").unwrap().into_path();
let pp_path = tmp.clone().join("pp_testcirc");
let pk_path = tmp.clone().join("pk_testcirc");
let vk_path = tmp.clone().join("vk_testcirc");

// Generate CRS
let pp_p = PublicParameters::setup(1 << 10, &mut rand::thread_rng())?;
File::create(&pp_path).and_then(|mut f| f.write(pp_p.to_raw_bytes().as_slice()))?;
let pp_p = PublicParameters::setup(1 << 10, &mut rand::thread_rng()).unwrap();
File::create(&pp_path)
.and_then(|mut f| f.write(pp_p.to_raw_bytes().as_slice()))
.unwrap();

// Read PublicParameters
let pp = fs::read(pp_path)?;
let pp = unsafe { PublicParameters::from_slice_unchecked(pp.as_slice())? };
let pp = fs::read(pp_path).unwrap();
let pp = unsafe { PublicParameters::from_slice_unchecked(pp.as_slice()).unwrap() };

// Generate circuit compilation params
let inputs = [
Expand All @@ -338,19 +323,23 @@ mod tests {
circuit.inputs = Some(&inputs);

// Compile the circuit
let (pk_p, vk_p) = circuit.compile(&pp)?;
let (pk_p, vk_p) = circuit.compile(&pp).unwrap();

// Write the keys
File::create(&pk_path).and_then(|mut f| f.write(pk_p.to_bytes().as_slice()))?;
File::create(&vk_path).and_then(|mut f| f.write(vk_p.to_bytes().as_slice()))?;
File::create(&pk_path)
.and_then(|mut f| f.write(pk_p.to_bytes().as_slice()))
.unwrap();
File::create(&vk_path)
.and_then(|mut f| f.write(vk_p.to_bytes().as_slice()))
.unwrap();

// Read ProverKey
let pk = fs::read(pk_path)?;
let pk = ProverKey::from_bytes(pk.as_slice())?;
let pk = fs::read(pk_path).unwrap();
let pk = ProverKey::from_bytes(pk.as_slice()).unwrap();

// Read VerifierKey
let vk = fs::read(vk_path)?;
let vk = VerifierKey::from_bytes(vk.as_slice())?;
let vk = fs::read(vk_path).unwrap();
let vk = VerifierKey::from_bytes(vk.as_slice()).unwrap();

assert_eq!(pk, pk_p);
assert_eq!(vk, vk_p);
Expand All @@ -371,7 +360,8 @@ mod tests {
let mut circuit = TestCircuit::default();
circuit.inputs = Some(&inputs2);
circuit.gen_proof(&pp, &pk, label)
}?;
}
.unwrap();

// Verifier POV
let mut circuit = TestCircuit::default();
Expand All @@ -381,8 +371,8 @@ mod tests {
PublicInput::BlsScalar(BlsScalar::from(100u64), 0),
];

circuit.verify_proof(&pp, &vk, label, &proof, &public_inputs2)?;

Ok(())
circuit
.verify_proof(&pp, &vk, label, &proof, &public_inputs2)
.unwrap();
}
}
36 changes: 0 additions & 36 deletions src/commitment_scheme/kzg10/errors.rs

This file was deleted.

15 changes: 7 additions & 8 deletions src/commitment_scheme/kzg10/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
//! Key module contains the utilities and data structures
//! 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 super::{AggregateProof, Commitment, Proof};
use crate::{error::Error, fft::Polynomial, transcript::TranscriptProtocol, util};
use dusk_bls12_381::{
multiscalar_mul::msm_variable_base, BlsScalar, G1Affine, G1Projective, G2Affine, G2Prepared,
};
Expand Down Expand Up @@ -127,12 +126,12 @@ impl CommitKey {
}
// Check that the truncated degree is not zero
if truncated_degree == 0 {
return Err(KZG10Errors::TruncatedDegreeIsZero.into());
return Err(Error::TruncatedDegreeIsZero);
}

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

let truncated_powers = Self {
Expand Down Expand Up @@ -339,7 +338,7 @@ impl OpeningKey {
.final_exponentiation();

if pairing != dusk_bls12_381::Gt::identity() {
return Err(KZG10Errors::PairingCheckFailure.into());
return Err(Error::PairingCheckFailure);
};
Ok(())
}
Expand All @@ -353,10 +352,10 @@ 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> {
if poly_degree == 0 {
return Err(KZG10Errors::PolynomialDegreeIsZero.into());
return Err(Error::PolynomialDegreeIsZero);
}
if poly_degree > max_degree {
return Err(KZG10Errors::PolynomialDegreeTooLarge.into());
return Err(Error::PolynomialDegreeTooLarge);
}
Ok(())
}
Expand Down
1 change: 0 additions & 1 deletion src/commitment_scheme/kzg10/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
// Copyright (c) DUSK NETWORK. All rights reserved.

//! Implementation of the KZG10 polynomial commitment scheme.
pub mod errors;
pub mod key;
pub mod srs;

Expand Down
12 changes: 4 additions & 8 deletions src/commitment_scheme/kzg10/srs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,8 @@
// Copyright (c) DUSK NETWORK. All rights reserved.

//! The Public Parameters can also be referred to as the Structured Reference String (SRS).
use super::{
errors::KZG10Errors,
key::{CommitKey, OpeningKey},
};
use crate::util;
use anyhow::{anyhow, Error, Result};
use super::key::{CommitKey, OpeningKey};
use crate::{error::Error, util};
use dusk_bls12_381::{G1Affine, G1Projective, G2Affine};
use rand_core::{CryptoRng, RngCore};

Expand Down Expand Up @@ -41,7 +37,7 @@ impl PublicParameters {
) -> Result<PublicParameters, Error> {
// Cannot commit to constants
if max_degree < 1 {
return Err(KZG10Errors::DegreeIsZero.into());
return Err(Error::DegreeIsZero);
}

// Generate the secret scalar beta
Expand Down Expand Up @@ -89,7 +85,7 @@ impl PublicParameters {
/// points security
pub unsafe fn from_slice_unchecked(bytes: &[u8]) -> Result<Self, Error> {
if bytes.len() < OpeningKey::serialized_size() + 1 {
return Err(anyhow!("Not enough bytes provided!"));
return Err(Error::NotEnoughBytes);
}

let opening_key = &bytes[..OpeningKey::serialized_size()];
Expand Down
Loading

0 comments on commit 8e251f6

Please sign in to comment.