arnaucube
arnaucube/ark-r1cs-stdPublic Self-hosted repository
crypto-primitives no-std (#96)


Marek Kotewicz marek.kotewicz@gmail.com
Thu, 20 Feb 2020 20:35:53 +0100
commit

d4896ade47e0a2acaa6fb9b063cfbd87072e456f

parent

02e6b32d7d8794e85ed8f34e02cc60cedb717ca0

37 files changed, 202 insertions(+), 153 deletions(-)

jump to
M Cargo.toml → Cargo.toml

@@ -4,6 +4,7 @@ members = [

"algebra", "algebra-benches", "bench-utils", + "cp-benches", "crypto-primitives", "dpc", "ff-fft",
A cp-benches/Cargo.toml

@@ -0,0 +1,58 @@

+[package] +name = "cp-benches" +version = "0.1.0" +authors = [ + "Sean Bowe", + "Alessandro Chiesa", + "Matthew Green", + "Ian Miers", + "Pratyush Mishra", + "Howard Wu" +] +description = "A library of cryptographic primitives that are used by Zexe" +homepage = "https://libzexe.org" +repository = "https://github.com/scipr/zexe" +documentation = "https://docs.rs/crypto-primitives/" +keywords = ["r1cs", "groth16", "gm17", "pedersen", "blake2s"] +categories = ["cryptography"] +include = ["Cargo.toml", "src", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +license = "MIT/Apache-2.0" +edition = "2018" + +################################# Dependencies ################################ + +[dev-dependencies] +algebra = { path = "../algebra", default-features = false } +blake2 = { version = "0.7", default-features = false } +criterion = "0.3.1" +crypto-primitives = { path = "../crypto-primitives" } +rand = { version = "0.7" } +rand_xorshift = { version = "0.2" } + +################################# Benchmarks ################################## + +[[bench]] +name = "pedersen_crh" +path = "benches/crypto_primitives/crh.rs" +harness = false + +[[bench]] +name = "pedersen_comm" +path = "benches/crypto_primitives/comm.rs" +harness = false + +[[bench]] +name = "blake2s_prf" +path = "benches/crypto_primitives/prf.rs" +harness = false + +[[bench]] +name = "schnorr_sig" +path = "benches/crypto_primitives/signature.rs" +harness = false + +[[bench]] +name = "gm17" +path = "benches/crypto_primitives/nizk.rs" +required-features = ["r1cs", "gm17"] +harness = false
M crypto-primitives/Cargo.toml → crypto-primitives/Cargo.toml

@@ -22,51 +22,24 @@

################################# Dependencies ################################ [dependencies] -algebra = { path = "../algebra" } -r1cs-core = { path = "../r1cs-core", optional = true } -r1cs-std = { path = "../r1cs-std", optional = true } -gm17 = { path = "../gm17", optional = true } -groth16 = { path = "../groth16", optional = true } +algebra = { path = "../algebra", default-features = false } bench-utils = { path = "../bench-utils" } - +blake2 = { version = "0.7", default-features = false } +derivative = { version = "1.0", features = ["use_core"] } digest = "0.7" -blake2 = "0.7" - -rand = { version = "0.7" } -derivative = "1" -rayon = "1" +ff-fft = { path = "../ff-fft", default-features = false } +gm17 = { path = "../gm17", optional = true, default-features = false } +groth16 = { path = "../groth16", optional = true, default-features = false } +r1cs-core = { path = "../r1cs-core", optional = true, default-features = false } +r1cs-std = { path = "../r1cs-std", optional = true, default-features = false } +rand = { version = "0.7", default-features = false } +rayon = { version = "1.0", optional = true } [features] -r1cs = [ "r1cs-core", "r1cs-std" ] +default = ["parallel"] +r1cs = ["r1cs-core", "r1cs-std"] +std = ["r1cs", "algebra/std", "r1cs-core/std", "r1cs-std/std", "gm17/std", "groth16/std", "ff-fft/std"] +parallel = ["std", "rayon"] [dev-dependencies] -criterion = "0.3.1" rand_xorshift = { version = "0.2" } - -################################# Benchmarks ################################## - -[[bench]] -name = "pedersen_crh" -path = "benches/crypto_primitives/crh.rs" -harness = false - -[[bench]] -name = "pedersen_comm" -path = "benches/crypto_primitives/comm.rs" -harness = false - -[[bench]] -name = "blake2s_prf" -path = "benches/crypto_primitives/prf.rs" -harness = false - -[[bench]] -name = "schnorr_sig" -path = "benches/crypto_primitives/signature.rs" -harness = false - -[[bench]] -name = "gm17" -path = "benches/crypto_primitives/nizk.rs" -required-features = ["r1cs", "gm17"] -harness = false
M crypto-primitives/src/commitment/blake2s/constraints.rs → crypto-primitives/src/commitment/blake2s/constraints.rs

@@ -8,7 +8,7 @@ };

use algebra::{Field, PrimeField}; use r1cs_std::prelude::*; -use std::borrow::Borrow; +use core::borrow::Borrow; #[derive(Clone)] pub struct Blake2sParametersGadget;

@@ -110,9 +110,6 @@ }

#[cfg(test)] mod test { - use algebra::fields::bls12_381::Fr; - use rand::{thread_rng, Rng}; - use crate::{ commitment::blake2s::{ constraints::{Blake2sCommitmentGadget, Blake2sRandomnessGadget},

@@ -120,8 +117,10 @@ Blake2sCommitment,

}, *, }; + use algebra::{fields::bls12_381::Fr, test_rng}; use r1cs_core::ConstraintSystem; use r1cs_std::{prelude::*, test_constraint_system::TestConstraintSystem}; + use rand::Rng; #[test] fn commitment_gadget_test() {

@@ -129,7 +128,7 @@ let mut cs = TestConstraintSystem::<Fr>::new();

let input = [1u8; 32]; - let rng = &mut thread_rng(); + let rng = &mut test_rng(); type TestCOMM = Blake2sCommitment; type TestCOMMGadget = Blake2sCommitmentGadget;
M crypto-primitives/src/commitment/constraints.rs → crypto-primitives/src/commitment/constraints.rs

@@ -1,8 +1,8 @@

use crate::CommitmentScheme; use algebra::Field; +use core::fmt::Debug; use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_std::prelude::*; -use std::fmt::Debug; pub trait CommitmentGadget<C: CommitmentScheme, ConstraintF: Field> { type OutputGadget: EqGadget<ConstraintF>
M crypto-primitives/src/commitment/injective_map/constraints.rs → crypto-primitives/src/commitment/injective_map/constraints.rs

@@ -16,7 +16,7 @@ use algebra::groups::Group;

use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_std::{groups::GroupGadget, uint8::UInt8}; -use std::marker::PhantomData; +use core::marker::PhantomData; pub struct PedersenCommitmentCompressorGadget<G, I, ConstraintF, GG, IG> where
M crypto-primitives/src/commitment/injective_map/mod.rs → crypto-primitives/src/commitment/injective_map/mod.rs

@@ -1,6 +1,6 @@

use crate::Error; +use core::marker::PhantomData; use rand::Rng; -use std::marker::PhantomData; use super::{ pedersen::{PedersenCommitment, PedersenParameters, PedersenRandomness, PedersenWindow},
M crypto-primitives/src/commitment/mod.rs → crypto-primitives/src/commitment/mod.rs

@@ -1,6 +1,6 @@

use algebra::UniformRand; +use core::{fmt::Debug, hash::Hash}; use rand::Rng; -use std::{fmt::Debug, hash::Hash}; use algebra::bytes::ToBytes;
M crypto-primitives/src/commitment/pedersen/constraints.rs → crypto-primitives/src/commitment/pedersen/constraints.rs

@@ -7,8 +7,8 @@ use r1cs_core::{ConstraintSystem, SynthesisError};

use crate::commitment::CommitmentGadget; use algebra::fields::{Field, PrimeField}; +use core::{borrow::Borrow, marker::PhantomData}; use r1cs_std::prelude::*; -use std::{borrow::Borrow, marker::PhantomData}; #[derive(Derivative)] #[derivative(Clone(bound = "G: Group, W: PedersenWindow, ConstraintF: Field"))]

@@ -171,12 +171,6 @@ }

#[cfg(test)] mod test { - use algebra::{ - fields::jubjub::{fq::Fq, fr::Fr}, - UniformRand, - }; - use rand::thread_rng; - use crate::{ commitment::{ pedersen::{

@@ -186,7 +180,11 @@ CommitmentGadget, CommitmentScheme,

}, crh::pedersen::PedersenWindow, }; - use algebra::curves::{jubjub::JubJubProjective as JubJub, ProjectiveCurve}; + use algebra::{ + curves::{jubjub::JubJubProjective as JubJub, ProjectiveCurve}, + fields::jubjub::{fq::Fq, fr::Fr}, + test_rng, UniformRand, + }; use r1cs_core::ConstraintSystem; use r1cs_std::{ groups::jubjub::JubJubGadget, prelude::*, test_constraint_system::TestConstraintSystem,

@@ -206,7 +204,7 @@ }

let input = [1u8; 4]; - let rng = &mut thread_rng(); + let rng = &mut test_rng(); type TestCOMM = PedersenCommitment<JubJub, Window>; type TestCOMMGadget = PedersenCommitmentGadget<JubJub, Fq, JubJubGadget>;
M crypto-primitives/src/commitment/pedersen/mod.rs → crypto-primitives/src/commitment/pedersen/mod.rs

@@ -1,14 +1,14 @@

-use crate::Error; +use crate::{Error, Vec}; use algebra::{ bytes::ToBytes, groups::Group, BitIterator, Field, FpParameters, PrimeField, ToConstraintField, UniformRand, }; +use core::marker::PhantomData; use rand::Rng; -use std::marker::PhantomData; use super::CommitmentScheme; -use std::io::{Result as IoResult, Write}; +use algebra::io::{Result as IoResult, Write}; pub use crate::crh::pedersen::PedersenWindow; use crate::crh::{
M crypto-primitives/src/crh/bowe_hopwood/constraints.rs → crypto-primitives/src/crh/bowe_hopwood/constraints.rs

@@ -1,5 +1,5 @@

use algebra::Field; -use std::hash::Hash; +use core::hash::Hash; use crate::crh::{ bowe_hopwood::{BoweHopwoodPedersenCRH, BoweHopwoodPedersenParameters, CHUNK_SIZE},

@@ -10,8 +10,8 @@ use algebra::groups::Group;

use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_std::{alloc::AllocGadget, groups::GroupGadget, uint8::UInt8}; +use core::{borrow::Borrow, marker::PhantomData}; use r1cs_std::bits::boolean::Boolean; -use std::{borrow::Borrow, marker::PhantomData}; #[derive(Derivative)] #[derivative(Clone(

@@ -125,20 +125,21 @@ }

#[cfg(test)] mod test { - use algebra::fields::sw6::fr::Fr; - use rand::{thread_rng, Rng}; - use crate::crh::{ bowe_hopwood::{constraints::BoweHopwoodPedersenCRHGadget, BoweHopwoodPedersenCRH}, pedersen::PedersenWindow, FixedLengthCRH, FixedLengthCRHGadget, }; - use algebra::{curves::edwards_sw6::EdwardsProjective as Edwards, ProjectiveCurve}; + use algebra::{ + curves::edwards_sw6::EdwardsProjective as Edwards, fields::sw6::fr::Fr, test_rng, + ProjectiveCurve, + }; use r1cs_core::ConstraintSystem; use r1cs_std::{ alloc::AllocGadget, groups::curves::twisted_edwards::edwards_sw6::EdwardsSWGadget, test_constraint_system::TestConstraintSystem, uint8::UInt8, }; + use rand::Rng; type TestCRH = BoweHopwoodPedersenCRH<Edwards, Window>; type TestCRHGadget = BoweHopwoodPedersenCRHGadget<Edwards, Fr, EdwardsSWGadget>;

@@ -168,7 +169,7 @@ }

#[test] fn crh_primitive_gadget_test() { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let mut cs = TestConstraintSystem::<Fr>::new(); let (input, input_bytes) = generate_input(&mut cs, rng);
M crypto-primitives/src/crh/bowe_hopwood/mod.rs → crypto-primitives/src/crh/bowe_hopwood/mod.rs

@@ -1,14 +1,16 @@

-use crate::Error; -use rand::Rng; -use rayon::prelude::*; -use std::{ +use crate::{Error, Vec}; +use core::{ fmt::{Debug, Formatter, Result as FmtResult}, marker::PhantomData, }; +use rand::Rng; +#[cfg(feature = "parallel")] +use rayon::prelude::*; use super::pedersen::{bytes_to_bits, PedersenCRH, PedersenWindow}; use crate::crh::FixedLengthCRH; use algebra::{biginteger::BigInteger, fields::PrimeField, groups::Group}; +use ff_fft::cfg_chunks; #[cfg(feature = "r1cs")] pub mod constraints;

@@ -126,12 +128,11 @@ // Compute sum of h_i^{sum of

// (1-2*c_{i,j,2})*(1+c_{i,j,0}+2*c_{i,j,1})*2^{4*(j-1)} for all j in segment} // for all i. Described in section 5.4.1.7 in the Zcash protocol // specification. - let result = padded_input - .par_chunks(W::WINDOW_SIZE * CHUNK_SIZE) + + let result = cfg_chunks!(padded_input, W::WINDOW_SIZE * CHUNK_SIZE) .zip(&parameters.generators) .map(|(segment_bits, segment_generators)| { - segment_bits - .par_chunks(CHUNK_SIZE) + cfg_chunks!(segment_bits, CHUNK_SIZE) .zip(segment_generators) .map(|(chunk_bits, generator)| { let mut encoded = generator.clone();

@@ -146,9 +147,10 @@ encoded = encoded.neg();

} encoded }) - .reduce(G::zero, |a, b| a + &b) + .sum::<G>() }) - .reduce(G::zero, |a, b| a + &b); + .sum::<G>(); + end_timer!(eval_time); Ok(result)

@@ -171,8 +173,7 @@ use crate::{

crh::{bowe_hopwood::BoweHopwoodPedersenCRH, pedersen::PedersenWindow}, FixedLengthCRH, }; - use algebra::curves::edwards_sw6::EdwardsProjective; - use rand::thread_rng; + use algebra::{curves::edwards_sw6::EdwardsProjective, test_rng}; #[test] fn test_simple_bh() {

@@ -183,7 +184,7 @@ const WINDOW_SIZE: usize = 90;

const NUM_WINDOWS: usize = 8; } - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let params = <BoweHopwoodPedersenCRH<EdwardsProjective, TestWindow> as FixedLengthCRH>::setup(rng) .unwrap();
M crypto-primitives/src/crh/constraints.rs → crypto-primitives/src/crh/constraints.rs

@@ -1,5 +1,5 @@

use algebra::Field; -use std::fmt::Debug; +use core::fmt::Debug; use crate::crh::FixedLengthCRH; use r1cs_core::{ConstraintSystem, SynthesisError};
M crypto-primitives/src/crh/injective_map/constraints.rs → crypto-primitives/src/crh/injective_map/constraints.rs

@@ -1,4 +1,4 @@

-use std::{fmt::Debug, marker::PhantomData}; +use core::{fmt::Debug, marker::PhantomData}; use crate::crh::{ injective_map::{InjectiveMap, PedersenCRHCompressor, TECompressor},
M crypto-primitives/src/crh/injective_map/mod.rs → crypto-primitives/src/crh/injective_map/mod.rs

@@ -1,7 +1,7 @@

use crate::{CryptoError, Error}; use algebra::bytes::ToBytes; +use core::{fmt::Debug, hash::Hash, marker::PhantomData}; use rand::Rng; -use std::{fmt::Debug, hash::Hash, marker::PhantomData}; use super::{ pedersen::{PedersenCRH, PedersenParameters, PedersenWindow},
M crypto-primitives/src/crh/mod.rs → crypto-primitives/src/crh/mod.rs

@@ -1,6 +1,6 @@

use algebra::bytes::ToBytes; +use core::hash::Hash; use rand::Rng; -use std::hash::Hash; pub mod bowe_hopwood; pub mod injective_map;
M crypto-primitives/src/crh/pedersen/constraints.rs → crypto-primitives/src/crh/pedersen/constraints.rs

@@ -6,7 +6,7 @@ use algebra::{Field, Group};

use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_std::prelude::*; -use std::{borrow::Borrow, marker::PhantomData}; +use core::{borrow::Borrow, marker::PhantomData}; #[derive(Derivative)] #[derivative(Clone(

@@ -114,19 +114,21 @@ }

#[cfg(test)] mod test { - use algebra::fields::bls12_381::fr::Fr; - use rand::{thread_rng, Rng}; - use crate::crh::{ pedersen::{constraints::PedersenCRHGadget, PedersenCRH, PedersenWindow}, FixedLengthCRH, FixedLengthCRHGadget, }; - use algebra::curves::{jubjub::JubJubProjective as JubJub, ProjectiveCurve}; + use algebra::{ + curves::{jubjub::JubJubProjective as JubJub, ProjectiveCurve}, + fields::bls12_381::fr::Fr, + test_rng, + }; use r1cs_core::ConstraintSystem; use r1cs_std::{ groups::curves::twisted_edwards::jubjub::JubJubGadget, prelude::*, test_constraint_system::TestConstraintSystem, }; + use rand::Rng; type TestCRH = PedersenCRH<JubJub, Window>; type TestCRHGadget = PedersenCRHGadget<JubJub, Fr, JubJubGadget>;

@@ -156,7 +158,7 @@ }

#[test] fn crh_primitive_gadget_test() { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let mut cs = TestConstraintSystem::<Fr>::new(); let (input, input_bytes) = generate_input(&mut cs, rng);
M crypto-primitives/src/crh/pedersen/mod.rs → crypto-primitives/src/crh/pedersen/mod.rs

@@ -1,13 +1,15 @@

-use crate::Error; -use rand::Rng; -use rayon::prelude::*; -use std::{ +use crate::{Error, Vec}; +use core::{ fmt::{Debug, Formatter, Result as FmtResult}, marker::PhantomData, }; +use rand::Rng; +#[cfg(feature = "parallel")] +use rayon::prelude::*; use crate::crh::FixedLengthCRH; use algebra::{groups::Group, Field, ToConstraintField}; +use ff_fft::cfg_chunks; #[cfg(feature = "r1cs")] pub mod constraints;

@@ -99,8 +101,8 @@ W::NUM_WINDOWS

); // Compute sum of h_i^{m_i} for all i. - let result = bytes_to_bits(input) - .par_chunks(W::WINDOW_SIZE) + let bits = bytes_to_bits(input); + let result = cfg_chunks!(bits, W::WINDOW_SIZE) .zip(&parameters.generators) .map(|(bits, generator_powers)| { let mut encoded = G::zero();

@@ -111,7 +113,8 @@ }

} encoded }) - .reduce(G::zero, |a, b| a + &b); + .sum::<G>(); + end_timer!(eval_time); Ok(result)
M crypto-primitives/src/lib.rs → crypto-primitives/src/lib.rs

@@ -1,8 +1,19 @@

+#![cfg_attr(not(feature = "std"), no_std)] + #[macro_use] extern crate bench_utils; #[macro_use] extern crate derivative; + +#[macro_use] +extern crate alloc; + +#[cfg(not(feature = "std"))] +pub(crate) use alloc::{borrow::ToOwned, boxed::Box, vec::Vec}; + +#[cfg(feature = "std")] +pub(crate) use std::{borrow::ToOwned, boxed::Box, vec::Vec}; pub mod commitment; pub mod crh;

@@ -27,16 +38,20 @@ merkle_tree::constraints::MerkleTreePathGadget, nizk::NIZKVerifierGadget, prf::PRFGadget,

signature::SigRandomizePkGadget, }; +#[cfg(feature = "std")] pub type Error = Box<dyn std::error::Error>; +#[cfg(not(feature = "std"))] +pub type Error = Box<dyn algebra::Error>; + #[derive(Debug)] pub enum CryptoError { IncorrectInputLength(usize), NotPrimeOrder, } -impl std::fmt::Display for CryptoError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for CryptoError { + 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(),

@@ -45,9 +60,13 @@ write!(f, "{}", msg)

} } +#[cfg(feature = "std")] impl std::error::Error for CryptoError { #[inline] fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } + +#[cfg(not(feature = "std"))] +impl algebra::Error for CryptoError {}
M crypto-primitives/src/merkle_tree/constraints.rs → crypto-primitives/src/merkle_tree/constraints.rs

@@ -7,7 +7,7 @@ crh::{FixedLengthCRH, FixedLengthCRHGadget},

merkle_tree::*, }; -use std::borrow::Borrow; +use core::borrow::Borrow; pub struct MerkleTreePathGadget<P, HGadget, ConstraintF> where

@@ -178,8 +178,6 @@ }

#[cfg(test)] mod test { - use std::rc::Rc; - use crate::{ crh::{ pedersen::{constraints::PedersenCRHGadget, PedersenCRH, PedersenWindow},

@@ -220,7 +218,7 @@

fn generate_merkle_tree(leaves: &[[u8; 30]], use_bad_root: bool) -> () { let mut rng = XorShiftRng::seed_from_u64(9174123u64); - let crh_parameters = Rc::new(H::setup(&mut rng).unwrap()); + let crh_parameters = H::setup(&mut rng).unwrap(); let tree = JubJubMerkleTree::new(crh_parameters.clone(), leaves).unwrap(); let root = tree.root(); let mut satisfied = true;
M crypto-primitives/src/merkle_tree/mod.rs → crypto-primitives/src/merkle_tree/mod.rs

@@ -1,6 +1,6 @@

-use crate::{crh::FixedLengthCRH, Error}; -use algebra::bytes::ToBytes; -use std::{fmt, rc::Rc}; +use crate::{crh::FixedLengthCRH, Error, Vec}; +use algebra::{bytes::ToBytes, io::Cursor}; +use core::fmt; #[cfg(feature = "r1cs")] pub mod constraints;

@@ -87,14 +87,14 @@ padding_tree: Vec<(

<P::H as FixedLengthCRH>::Output, <P::H as FixedLengthCRH>::Output, )>, - parameters: Rc<<P::H as FixedLengthCRH>::Parameters>, + parameters: <P::H as FixedLengthCRH>::Parameters, root: Option<<P::H as FixedLengthCRH>::Output>, } impl<P: MerkleTreeConfig> MerkleHashTree<P> { pub const HEIGHT: u8 = P::HEIGHT as u8; - pub fn blank(parameters: Rc<<P::H as FixedLengthCRH>::Parameters>) -> Self { + pub fn blank(parameters: <P::H as FixedLengthCRH>::Parameters) -> Self { MerkleHashTree { tree: Vec::new(), padding_tree: Vec::new(),

@@ -104,7 +104,7 @@ }

} pub fn new<L: ToBytes>( - parameters: Rc<<P::H as FixedLengthCRH>::Parameters>, + parameters: <P::H as FixedLengthCRH>::Parameters, leaves: &[L], ) -> Result<Self, Error> { let new_time = start_timer!(|| "MerkleTree::New");

@@ -243,8 +243,8 @@ IncorrectLeafIndex(usize),

IncorrectPathLength(usize), } -impl std::fmt::Display for MerkleTreeError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for MerkleTreeError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { let msg = match self { MerkleTreeError::IncorrectLeafIndex(index) => { format!("incorrect leaf index: {}", index)

@@ -255,6 +255,7 @@ write!(f, "{}", msg)

} } +#[cfg(feature = "std")] impl std::error::Error for MerkleTreeError { #[inline] fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {

@@ -262,16 +263,19 @@ None

} } +#[cfg(not(feature = "std"))] +impl algebra::Error for MerkleTreeError {} + /// Returns the log2 value of the given number. #[inline] fn log2(number: usize) -> usize { - (number as f64).log2() as usize + algebra::log2(number) as usize } /// Returns the height of the tree, given the size of the tree. #[inline] fn tree_height(tree_size: usize) -> usize { - log2(tree_size + 1) + log2(tree_size) } /// Returns true iff the index represents the root.

@@ -332,15 +336,13 @@ left: &H::Output,

right: &H::Output, buffer: &mut [u8], ) -> Result<H::Output, Error> { - use std::io::Cursor; - let mut writer = Cursor::new(buffer); + let mut writer = Cursor::new(&mut *buffer); // Construct left input. left.write(&mut writer)?; // Construct right input. right.write(&mut writer)?; - let buffer = writer.into_inner(); H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)]) }

@@ -350,11 +352,9 @@ parameters: &H::Parameters,

leaf: &L, buffer: &mut [u8], ) -> Result<H::Output, Error> { - use std::io::Cursor; - let mut writer = Cursor::new(buffer); + let mut writer = Cursor::new(&mut *buffer); leaf.write(&mut writer)?; - let buffer = writer.into_inner(); H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)]) }

@@ -395,7 +395,7 @@

fn generate_merkle_tree<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () { let mut rng = XorShiftRng::seed_from_u64(9174123u64); - let crh_parameters = Rc::new(H::setup(&mut rng).unwrap()); + let crh_parameters = H::setup(&mut rng).unwrap(); let tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap(); let root = tree.root(); for (i, leaf) in leaves.iter().enumerate() {

@@ -421,7 +421,7 @@

fn bad_merkle_tree_verify<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () { let mut rng = XorShiftRng::seed_from_u64(13423423u64); - let crh_parameters = Rc::new(H::setup(&mut rng).unwrap()); + let crh_parameters = H::setup(&mut rng).unwrap(); let tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap(); let root = JubJub::zero(); for (i, leaf) in leaves.iter().enumerate() {
M crypto-primitives/src/nizk/gm17/constraints.rs → crypto-primitives/src/nizk/gm17/constraints.rs

@@ -3,8 +3,8 @@ use algebra::{AffineCurve, Field, PairingEngine, ToConstraintField};

use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; use r1cs_std::prelude::*; +use core::{borrow::Borrow, marker::PhantomData}; use gm17::{Proof, VerifyingKey}; -use std::{borrow::Borrow, marker::PhantomData}; #[derive(Derivative)] #[derivative(Clone(bound = "P::G1Gadget: Clone, P::G2Gadget: Clone"))]

@@ -406,13 +406,13 @@ use super::*;

use algebra::{ curves::bls12_377::Bls12_377, fields::bls12_377::{Fq, Fr}, - BitIterator, PrimeField, + test_rng, BitIterator, PrimeField, }; use r1cs_std::{ boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget, test_constraint_system::TestConstraintSystem, }; - use rand::{thread_rng, Rng}; + use rand::Rng; type TestProofSystem = Gm17<Bls12_377, Bench<Fr>, Fr>; type TestVerifierGadget = Gm17VerifierGadget<Bls12_377, Fq, Bls12_377PairingGadget>;

@@ -469,7 +469,7 @@ #[test]

fn gm17_verifier_test() { let num_inputs = 100; let num_constraints = num_inputs; - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let mut inputs: Vec<Option<Fr>> = Vec::with_capacity(num_inputs); for _ in 0..num_inputs { inputs.push(Some(rng.gen()));
M crypto-primitives/src/nizk/gm17/mod.rs → crypto-primitives/src/nizk/gm17/mod.rs

@@ -8,7 +8,7 @@ use r1cs_core::ConstraintSynthesizer;

use rand::Rng; use algebra::ToConstraintField; -use std::marker::PhantomData; +use core::marker::PhantomData; use super::NIZK;
M crypto-primitives/src/nizk/groth16/constraints.rs → crypto-primitives/src/nizk/groth16/constraints.rs

@@ -3,8 +3,8 @@ use algebra::{AffineCurve, Field, PairingEngine, ToConstraintField};

use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; use r1cs_std::prelude::*; +use core::{borrow::Borrow, marker::PhantomData}; use groth16::{Proof, VerifyingKey}; -use std::{borrow::Borrow, marker::PhantomData}; #[derive(Derivative)] #[derivative(Clone(bound = "P::G1Gadget: Clone, P::G2Gadget: Clone"))]

@@ -353,13 +353,13 @@ use super::*;

use algebra::{ curves::bls12_377::Bls12_377, fields::bls12_377::{Fq, Fr}, - BitIterator, PrimeField, + test_rng, BitIterator, PrimeField, }; use r1cs_std::{ boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget, test_constraint_system::TestConstraintSystem, }; - use rand::{thread_rng, Rng}; + use rand::Rng; type TestProofSystem = Groth16<Bls12_377, Bench<Fr>, Fr>; type TestVerifierGadget = Groth16VerifierGadget<Bls12_377, Fq, Bls12_377PairingGadget>;

@@ -416,7 +416,7 @@ #[test]

fn groth16_verifier_test() { let num_inputs = 100; let num_constraints = num_inputs; - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let mut inputs: Vec<Option<Fr>> = Vec::with_capacity(num_inputs); for _ in 0..num_inputs { inputs.push(Some(rng.gen()));
M crypto-primitives/src/nizk/groth16/mod.rs → crypto-primitives/src/nizk/groth16/mod.rs

@@ -8,7 +8,7 @@ use r1cs_core::ConstraintSynthesizer;

use rand::Rng; use algebra::ToConstraintField; -use std::marker::PhantomData; +use core::marker::PhantomData; use super::NIZK;
M crypto-primitives/src/nizk/mod.rs → crypto-primitives/src/nizk/mod.rs

@@ -53,8 +53,8 @@ }

#[cfg(all(feature = "gm17", test))] mod test { - use rand::thread_rng; - use std::ops::AddAssign; + use algebra::test_rng; + use core::ops::AddAssign; #[test] fn test_gm17() {

@@ -102,7 +102,7 @@ let mut sum = Fr::one();

sum.add_assign(&Fr::one()); let circuit = R1CSCircuit::new(Fr::one(), sum, Fr::one()); - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let parameters = Gm17::<Bls12_381, R1CSCircuit, [Fr]>::setup(circuit, rng).unwrap();
M crypto-primitives/src/prf/blake2s/constraints.rs → crypto-primitives/src/prf/blake2s/constraints.rs

@@ -4,7 +4,7 @@

use crate::prf::PRFGadget; use r1cs_std::prelude::*; -use std::borrow::Borrow; +use core::borrow::Borrow; // 2.1. Parameters // The following table summarizes various parameters and their ranges:
M crypto-primitives/src/prf/constraints.rs → crypto-primitives/src/prf/constraints.rs

@@ -1,5 +1,5 @@

use algebra::Field; -use std::fmt::Debug; +use core::fmt::Debug; use crate::prf::PRF; use r1cs_core::{ConstraintSystem, SynthesisError};
M crypto-primitives/src/prf/mod.rs → crypto-primitives/src/prf/mod.rs

@@ -1,5 +1,5 @@

use algebra::bytes::{FromBytes, ToBytes}; -use std::{fmt::Debug, hash::Hash}; +use core::{fmt::Debug, hash::Hash}; use crate::CryptoError;
M crypto-primitives/src/signature/mod.rs → crypto-primitives/src/signature/mod.rs

@@ -1,7 +1,7 @@

use crate::Error; use algebra::bytes::ToBytes; +use core::hash::Hash; use rand::Rng; -use std::hash::Hash; #[cfg(feature = "r1cs")] pub mod constraints;

@@ -54,14 +54,13 @@ #[cfg(test)]

mod test { use crate::{signature::schnorr::SchnorrSignature, SignatureScheme}; use algebra::{ - curves::edwards_sw6::EdwardsAffine as Edwards, groups::Group, to_bytes, ToBytes, + curves::edwards_sw6::EdwardsAffine as Edwards, groups::Group, test_rng, to_bytes, ToBytes, UniformRand, }; use blake2::Blake2s; - use rand::thread_rng; fn sign_and_verify<S: SignatureScheme>(message: &[u8]) { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let parameters = S::setup::<_>(rng).unwrap(); let (pk, sk) = S::keygen(&parameters, rng).unwrap(); let sig = S::sign(&parameters, &sk, &message, rng).unwrap();

@@ -69,7 +68,7 @@ assert!(S::verify(&parameters, &pk, &message, &sig).unwrap());

} fn failed_verification<S: SignatureScheme>(message: &[u8], bad_message: &[u8]) { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let parameters = S::setup::<_>(rng).unwrap(); let (pk, sk) = S::keygen(&parameters, rng).unwrap(); let sig = S::sign(&parameters, &sk, message, rng).unwrap();

@@ -77,7 +76,7 @@ assert!(!S::verify(&parameters, &pk, bad_message, &sig).unwrap());

} fn randomize_and_verify<S: SignatureScheme>(message: &[u8], randomness: &[u8]) { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let parameters = S::setup::<_>(rng).unwrap(); let (pk, sk) = S::keygen(&parameters, rng).unwrap(); let sig = S::sign(&parameters, &sk, message, rng).unwrap();

@@ -90,7 +89,7 @@

#[test] fn schnorr_signature_test() { let message = "Hi, I am a Schnorr signature!"; - let rng = &mut thread_rng(); + let rng = &mut test_rng(); sign_and_verify::<SchnorrSignature<Edwards, Blake2s>>(message.as_bytes()); failed_verification::<SchnorrSignature<Edwards, Blake2s>>( message.as_bytes(),
M crypto-primitives/src/signature/schnorr/constraints.rs → crypto-primitives/src/signature/schnorr/constraints.rs

@@ -4,7 +4,7 @@ use r1cs_std::prelude::*;

use crate::signature::SigRandomizePkGadget; -use std::{borrow::Borrow, marker::PhantomData}; +use core::{borrow::Borrow, marker::PhantomData}; use crate::signature::schnorr::{SchnorrPublicKey, SchnorrSigParameters, SchnorrSignature}; use digest::Digest;
M crypto-primitives/src/signature/schnorr/mod.rs → crypto-primitives/src/signature/schnorr/mod.rs

@@ -1,17 +1,14 @@

-use crate::{Error, SignatureScheme}; +use crate::{Error, SignatureScheme, Vec}; use algebra::{ bytes::ToBytes, fields::{Field, PrimeField}, groups::Group, + io::{Result as IoResult, Write}, to_bytes, One, ToConstraintField, UniformRand, Zero, }; +use core::{hash::Hash, marker::PhantomData}; use digest::Digest; use rand::Rng; -use std::{ - hash::Hash, - io::{Result as IoResult, Write}, - marker::PhantomData, -}; #[cfg(feature = "r1cs")] pub mod constraints;