Skip to content

Commit

Permalink
Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Pratyush committed Dec 28, 2023
1 parent a781861 commit c17337f
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 41 deletions.
4 changes: 0 additions & 4 deletions benches/merkle_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,10 @@ mod bytes_mt_benches {
use ark_crypto_primitives::to_uncompressed_bytes;
use ark_ff::BigInteger256;
use ark_serialize::CanonicalSerialize;
use ark_std::cfg_iter;
use ark_std::{test_rng, UniformRand};
use criterion::Criterion;
use std::borrow::Borrow;

#[cfg(feature = "parallel")]
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};

use crate::NUM_LEAVES;

type LeafH = sha2::Sha256;
Expand Down
4 changes: 2 additions & 2 deletions src/crh/bowe_hopwood/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use ark_ec::{
twisted_edwards::Projective as TEProjective, twisted_edwards::TECurveConfig, AdditiveGroup,
CurveGroup,
};
use ark_ff::{biginteger::BigInteger, fields::PrimeField};
use ark_ff::fields::PrimeField;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::borrow::Borrow;
use ark_std::cfg_chunks;
Expand Down Expand Up @@ -82,7 +82,7 @@ impl<P: TECurveConfig, W: pedersen::Window> CRHScheme for CRH<P, W> {
let mut c = 0;
let mut range = F::BigInt::from(2_u64);
while range < upper_limit {
range.muln(4);
range <<= 4;
c += 1;
}

Expand Down
6 changes: 3 additions & 3 deletions src/crh/injective_map/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{CryptoError, Error};
use crate::Error;
use ark_std::rand::Rng;
use ark_std::{fmt::Debug, hash::Hash, marker::PhantomData};

Expand All @@ -16,15 +16,15 @@ pub mod constraints;
pub trait InjectiveMap<C: CurveGroup> {
type Output: Clone + Eq + Hash + Default + Debug + CanonicalSerialize + CanonicalDeserialize;

fn injective_map(ge: &C::Affine) -> Result<Self::Output, CryptoError>;
fn injective_map(ge: &C::Affine) -> Result<Self::Output, Error>;
}

pub struct TECompressor;

impl<P: TECurveConfig> InjectiveMap<TEProjective<P>> for TECompressor {
type Output = <P as CurveConfig>::BaseField;

fn injective_map(ge: &TEAffine<P>) -> Result<Self::Output, CryptoError> {
fn injective_map(ge: &TEAffine<P>) -> Result<Self::Output, Error> {
debug_assert!(ge.is_in_correct_subgroup_assuming_on_curve());
Ok(ge.x)
}
Expand Down
27 changes: 17 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,22 +43,29 @@ pub mod snark;
#[cfg(feature = "sponge")]
pub mod sponge;

pub type Error = Box<dyn ark_std::error::Error + Send>;

#[derive(Debug)]
pub enum CryptoError {
pub enum Error {
IncorrectInputLength(usize),
NotPrimeOrder,
GenericError(Box<dyn ark_std::error::Error + Send>),
SerializationError(ark_serialize::SerializationError),
}

impl core::fmt::Display for CryptoError {
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let msg = match self {
CryptoError::IncorrectInputLength(len) => format!("input length is wrong: {}", len),
CryptoError::NotPrimeOrder => "element is not prime order".to_owned(),
};
write!(f, "{}", msg)
match self {
Self::IncorrectInputLength(len) => write!(f, "incorrect input length: {len}"),
Self::NotPrimeOrder => write!(f, "element is not prime order"),
Self::GenericError(e) => write!(f, "{e}"),
Self::SerializationError(e) => write!(f, "{e}"),
}
}
}

impl ark_std::error::Error for CryptoError {}
impl ark_std::error::Error for Error {}

impl From<ark_serialize::SerializationError> for Error {
fn from(e: ark_serialize::SerializationError) -> Self {
Self::SerializationError(e)
}
}
41 changes: 23 additions & 18 deletions src/merkle_tree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ impl<T: CanonicalSerialize> DigestConverter<T, [u8]> for ByteDigestConverter<T>
/// * `LeafHash`: Convert leaf to leaf digest
/// * `TwoToOneHash`: Compress two inner digests to one inner digest
pub trait Config {
type Leaf: ?Sized; // merkle tree does not store the leaf
// leaf layer
type Leaf: ?Sized + Send; // merkle tree does not store the leaf
// leaf layer
type LeafDigest: Clone
+ Eq
+ core::fmt::Debug
Expand Down Expand Up @@ -234,32 +234,37 @@ impl<P: Config> MerkleTree<P> {
height: usize,
) -> Result<Self, crate::Error> {
// use empty leaf digest
let leaves_digest = vec![P::LeafDigest::default(); 1 << (height - 1)];
Self::new_with_leaf_digest(leaf_hash_param, two_to_one_hash_param, leaves_digest)
let leaf_digests = vec![P::LeafDigest::default(); 1 << (height - 1)];
Self::new_with_leaf_digest(leaf_hash_param, two_to_one_hash_param, &leaf_digests)
}

/// Returns a new merkle tree. `leaves.len()` should be power of two.
pub fn new<L: Borrow<P::Leaf>>(
pub fn new<L, T>(
leaf_hash_param: &LeafParam<P>,
two_to_one_hash_param: &TwoToOneParam<P>,
leaves: impl IntoIterator<Item = L>,
) -> Result<Self, crate::Error> {
leaves: T,
) -> Result<Self, crate::Error>
where
L: Borrow<P::Leaf> + Send,
T: IntoIterator<Item = L>,
T::IntoIter: Send,
{
#[cfg(feature = "parallel")]
let leaves = leaves.into_iter().par_bridge();

let leaves_digest: Vec<_> = cfg_into_iter!(leaves)
let leaf_digests: Vec<_> = cfg_into_iter!(leaves)
.map(|leaf| P::LeafHash::evaluate(leaf_hash_param, leaf))
.collect()?;
.collect::<Result<Vec<_>, _>>()?;

Self::new_with_leaf_digest(leaf_hash_param, two_to_one_hash_param, leaves_digest)
Self::new_with_leaf_digest(leaf_hash_param, two_to_one_hash_param, &leaf_digests)
}

pub fn new_with_leaf_digest(
leaf_hash_param: &LeafParam<P>,
two_to_one_hash_param: &TwoToOneParam<P>,
leaves_digest: Vec<P::LeafDigest>,
leaf_digests: &[P::LeafDigest],
) -> Result<Self, crate::Error> {
let leaf_nodes_size = leaves_digest.len();
let leaf_nodes_size = leaf_digests.len();
assert!(
leaf_nodes_size.is_power_of_two() && leaf_nodes_size > 1,
"`leaves.len() should be power of two and greater than one"
Expand Down Expand Up @@ -305,14 +310,14 @@ impl<P: Config> MerkleTree<P> {
*n = P::TwoToOneHash::evaluate(
two_to_one_hash_param,
P::LeafInnerDigestConverter::convert(
leaves_digest[left_leaf_index].clone(),
leaf_digests[left_leaf_index].clone(),
)?,
P::LeafInnerDigestConverter::convert(
leaves_digest[right_leaf_index].clone(),
leaf_digests[right_leaf_index].clone(),
)?,
)?;
Ok::<(), crate::Error>(())
});
})?;
}

// compute the hash values for nodes in every other layer in the tree
Expand Down Expand Up @@ -343,11 +348,11 @@ impl<P: Config> MerkleTree<P> {
nodes_at_prev_level[left_leaf_index].clone(),
nodes_at_prev_level[right_leaf_index].clone(),
)?;
Ok::<(), crate::Error>(())
});
Ok::<_, crate::Error>(())
})?;
}
Ok(MerkleTree {
leaf_nodes: leaves_digest,
leaf_nodes: leaf_digests.to_vec(),
non_leaf_nodes,
height: tree_height,
leaf_hash_param: leaf_hash_param.clone(),
Expand Down
4 changes: 2 additions & 2 deletions src/prf/blake2s/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use blake2::{Blake2s256 as B2s, Blake2sMac};
use digest::Digest;

use super::PRF;
use crate::CryptoError;
use crate::Error;

#[cfg(feature = "r1cs")]
pub mod constraints;
Expand All @@ -16,7 +16,7 @@ impl PRF for Blake2s {
type Output = [u8; 32];
type Seed = [u8; 32];

fn evaluate(seed: &Self::Seed, input: &Self::Input) -> Result<Self::Output, CryptoError> {
fn evaluate(seed: &Self::Seed, input: &Self::Input) -> Result<Self::Output, Error> {
let eval_time = start_timer!(|| "Blake2s::Eval");
let mut h = B2s::new();
h.update(seed.as_ref());
Expand Down
4 changes: 2 additions & 2 deletions src/prf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use core::{fmt::Debug, hash::Hash};

use crate::CryptoError;
use crate::Error;

#[cfg(feature = "r1cs")]
pub mod constraints;
Expand All @@ -17,5 +17,5 @@ pub trait PRF {
type Output: CanonicalSerialize + Eq + Clone + Debug + Default + Hash;
type Seed: CanonicalDeserialize + CanonicalSerialize + Clone + Default + Debug;

fn evaluate(seed: &Self::Seed, input: &Self::Input) -> Result<Self::Output, CryptoError>;
fn evaluate(seed: &Self::Seed, input: &Self::Input) -> Result<Self::Output, Error>;
}

0 comments on commit c17337f

Please sign in to comment.