From d4896ade47e0a2acaa6fb9b063cfbd87072e456f Mon Sep 17 00:00:00 2001 From: Marek Kotewicz Date: Thu, 20 Feb 2020 20:35:53 +0100 Subject: [PATCH] crypto-primitives no-std (#96) --- Cargo.toml | 1 + cp-benches/Cargo.toml | 58 +++++++++++++++++++ .../benches/crypto_primitives/comm.rs | 0 .../benches/crypto_primitives/crh.rs | 0 .../benches/crypto_primitives/nizk.rs | 0 .../benches/crypto_primitives/prf.rs | 0 .../benches/crypto_primitives/signature.rs | 0 crypto-primitives/Cargo.toml | 55 +++++------------- .../src/commitment/blake2s/constraints.rs | 9 ++- .../src/commitment/constraints.rs | 2 +- .../commitment/injective_map/constraints.rs | 2 +- .../src/commitment/injective_map/mod.rs | 2 +- crypto-primitives/src/commitment/mod.rs | 2 +- .../src/commitment/pedersen/constraints.rs | 16 +++-- .../src/commitment/pedersen/mod.rs | 6 +- .../src/crh/bowe_hopwood/constraints.rs | 15 ++--- crypto-primitives/src/crh/bowe_hopwood/mod.rs | 27 ++++----- crypto-primitives/src/crh/constraints.rs | 2 +- .../src/crh/injective_map/constraints.rs | 2 +- .../src/crh/injective_map/mod.rs | 2 +- crypto-primitives/src/crh/mod.rs | 2 +- .../src/crh/pedersen/constraints.rs | 14 +++-- crypto-primitives/src/crh/pedersen/mod.rs | 17 +++--- crypto-primitives/src/lib.rs | 23 +++++++- .../src/merkle_tree/constraints.rs | 6 +- crypto-primitives/src/merkle_tree/mod.rs | 36 ++++++------ .../src/nizk/gm17/constraints.rs | 8 +-- crypto-primitives/src/nizk/gm17/mod.rs | 2 +- .../src/nizk/groth16/constraints.rs | 8 +-- crypto-primitives/src/nizk/groth16/mod.rs | 2 +- crypto-primitives/src/nizk/mod.rs | 6 +- .../src/prf/blake2s/constraints.rs | 2 +- crypto-primitives/src/prf/constraints.rs | 2 +- crypto-primitives/src/prf/mod.rs | 2 +- crypto-primitives/src/signature/mod.rs | 13 ++--- .../src/signature/schnorr/constraints.rs | 2 +- .../src/signature/schnorr/mod.rs | 9 +-- 37 files changed, 202 insertions(+), 153 deletions(-) create mode 100644 cp-benches/Cargo.toml rename {crypto-primitives => cp-benches}/benches/crypto_primitives/comm.rs (100%) rename {crypto-primitives => cp-benches}/benches/crypto_primitives/crh.rs (100%) rename {crypto-primitives => cp-benches}/benches/crypto_primitives/nizk.rs (100%) rename {crypto-primitives => cp-benches}/benches/crypto_primitives/prf.rs (100%) rename {crypto-primitives => cp-benches}/benches/crypto_primitives/signature.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index bce5c74..1adbbf2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ members = [ "algebra", "algebra-benches", "bench-utils", + "cp-benches", "crypto-primitives", "dpc", "ff-fft", diff --git a/cp-benches/Cargo.toml b/cp-benches/Cargo.toml new file mode 100644 index 0000000..a97aa0e --- /dev/null +++ b/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 diff --git a/crypto-primitives/benches/crypto_primitives/comm.rs b/cp-benches/benches/crypto_primitives/comm.rs similarity index 100% rename from crypto-primitives/benches/crypto_primitives/comm.rs rename to cp-benches/benches/crypto_primitives/comm.rs diff --git a/crypto-primitives/benches/crypto_primitives/crh.rs b/cp-benches/benches/crypto_primitives/crh.rs similarity index 100% rename from crypto-primitives/benches/crypto_primitives/crh.rs rename to cp-benches/benches/crypto_primitives/crh.rs diff --git a/crypto-primitives/benches/crypto_primitives/nizk.rs b/cp-benches/benches/crypto_primitives/nizk.rs similarity index 100% rename from crypto-primitives/benches/crypto_primitives/nizk.rs rename to cp-benches/benches/crypto_primitives/nizk.rs diff --git a/crypto-primitives/benches/crypto_primitives/prf.rs b/cp-benches/benches/crypto_primitives/prf.rs similarity index 100% rename from crypto-primitives/benches/crypto_primitives/prf.rs rename to cp-benches/benches/crypto_primitives/prf.rs diff --git a/crypto-primitives/benches/crypto_primitives/signature.rs b/cp-benches/benches/crypto_primitives/signature.rs similarity index 100% rename from crypto-primitives/benches/crypto_primitives/signature.rs rename to cp-benches/benches/crypto_primitives/signature.rs diff --git a/crypto-primitives/Cargo.toml b/crypto-primitives/Cargo.toml index 01e99e3..01df103 100644 --- a/crypto-primitives/Cargo.toml +++ b/crypto-primitives/Cargo.toml @@ -22,51 +22,24 @@ edition = "2018" ################################# 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 diff --git a/crypto-primitives/src/commitment/blake2s/constraints.rs b/crypto-primitives/src/commitment/blake2s/constraints.rs index 0a575c2..d45ddd0 100644 --- a/crypto-primitives/src/commitment/blake2s/constraints.rs +++ b/crypto-primitives/src/commitment/blake2s/constraints.rs @@ -8,7 +8,7 @@ use crate::{ 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 @@ impl AllocGadget<[u8; 32], ConstraintF> for Blake2sRand #[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 @@ mod test { }, *, }; + 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 @@ mod test { let input = [1u8; 32]; - let rng = &mut thread_rng(); + let rng = &mut test_rng(); type TestCOMM = Blake2sCommitment; type TestCOMMGadget = Blake2sCommitmentGadget; diff --git a/crypto-primitives/src/commitment/constraints.rs b/crypto-primitives/src/commitment/constraints.rs index 639cf49..c3cfc90 100644 --- a/crypto-primitives/src/commitment/constraints.rs +++ b/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 { type OutputGadget: EqGadget diff --git a/crypto-primitives/src/commitment/injective_map/constraints.rs b/crypto-primitives/src/commitment/injective_map/constraints.rs index 767f1cb..67976fe 100644 --- a/crypto-primitives/src/commitment/injective_map/constraints.rs +++ b/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 where diff --git a/crypto-primitives/src/commitment/injective_map/mod.rs b/crypto-primitives/src/commitment/injective_map/mod.rs index f8f6a4d..18d97cc 100644 --- a/crypto-primitives/src/commitment/injective_map/mod.rs +++ b/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}, diff --git a/crypto-primitives/src/commitment/mod.rs b/crypto-primitives/src/commitment/mod.rs index e925a1d..3adf104 100644 --- a/crypto-primitives/src/commitment/mod.rs +++ b/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; diff --git a/crypto-primitives/src/commitment/pedersen/constraints.rs b/crypto-primitives/src/commitment/pedersen/constraints.rs index 55f17cf..63d606f 100644 --- a/crypto-primitives/src/commitment/pedersen/constraints.rs +++ b/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 @@ where #[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 @@ mod test { }, 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 @@ mod test { let input = [1u8; 4]; - let rng = &mut thread_rng(); + let rng = &mut test_rng(); type TestCOMM = PedersenCommitment; type TestCOMMGadget = PedersenCommitmentGadget; diff --git a/crypto-primitives/src/commitment/pedersen/mod.rs b/crypto-primitives/src/commitment/pedersen/mod.rs index 0be2fa4..f4fd0eb 100644 --- a/crypto-primitives/src/commitment/pedersen/mod.rs +++ b/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::{ diff --git a/crypto-primitives/src/crh/bowe_hopwood/constraints.rs b/crypto-primitives/src/crh/bowe_hopwood/constraints.rs index 60accf8..d270be8 100644 --- a/crypto-primitives/src/crh/bowe_hopwood/constraints.rs +++ b/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 @@ impl; type TestCRHGadget = BoweHopwoodPedersenCRHGadget; @@ -168,7 +169,7 @@ mod test { #[test] fn crh_primitive_gadget_test() { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let mut cs = TestConstraintSystem::::new(); let (input, input_bytes) = generate_input(&mut cs, rng); diff --git a/crypto-primitives/src/crh/bowe_hopwood/mod.rs b/crypto-primitives/src/crh/bowe_hopwood/mod.rs index f2addcd..eba24fa 100644 --- a/crypto-primitives/src/crh/bowe_hopwood/mod.rs +++ b/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 @@ impl FixedLengthCRH for BoweHopwoodPedersenCRH FixedLengthCRH for BoweHopwoodPedersenCRH() }) - .reduce(G::zero, |a, b| a + &b); + .sum::(); + end_timer!(eval_time); Ok(result) @@ -171,8 +173,7 @@ mod test { 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 @@ mod test { const NUM_WINDOWS: usize = 8; } - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let params = as FixedLengthCRH>::setup(rng) .unwrap(); diff --git a/crypto-primitives/src/crh/constraints.rs b/crypto-primitives/src/crh/constraints.rs index 84f62a8..a08de71 100644 --- a/crypto-primitives/src/crh/constraints.rs +++ b/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}; diff --git a/crypto-primitives/src/crh/injective_map/constraints.rs b/crypto-primitives/src/crh/injective_map/constraints.rs index 9319ef7..b78fc0d 100644 --- a/crypto-primitives/src/crh/injective_map/constraints.rs +++ b/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}, diff --git a/crypto-primitives/src/crh/injective_map/mod.rs b/crypto-primitives/src/crh/injective_map/mod.rs index c4b9f89..39fabd2 100644 --- a/crypto-primitives/src/crh/injective_map/mod.rs +++ b/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}, diff --git a/crypto-primitives/src/crh/mod.rs b/crypto-primitives/src/crh/mod.rs index 84200bd..a966f4f 100644 --- a/crypto-primitives/src/crh/mod.rs +++ b/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; diff --git a/crypto-primitives/src/crh/pedersen/constraints.rs b/crypto-primitives/src/crh/pedersen/constraints.rs index 7c4e9a8..cdd60b3 100644 --- a/crypto-primitives/src/crh/pedersen/constraints.rs +++ b/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 @@ impl; type TestCRHGadget = PedersenCRHGadget; @@ -156,7 +158,7 @@ mod test { #[test] fn crh_primitive_gadget_test() { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let mut cs = TestConstraintSystem::::new(); let (input, input_bytes) = generate_input(&mut cs, rng); diff --git a/crypto-primitives/src/crh/pedersen/mod.rs b/crypto-primitives/src/crh/pedersen/mod.rs index f626c83..453511f 100644 --- a/crypto-primitives/src/crh/pedersen/mod.rs +++ b/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 @@ impl FixedLengthCRH for PedersenCRH { ); // 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(¶meters.generators) .map(|(bits, generator_powers)| { let mut encoded = G::zero(); @@ -111,7 +113,8 @@ impl FixedLengthCRH for PedersenCRH { } encoded }) - .reduce(G::zero, |a, b| a + &b); + .sum::(); + end_timer!(eval_time); Ok(result) diff --git a/crypto-primitives/src/lib.rs b/crypto-primitives/src/lib.rs index 0f3a467..663d3bd 100644 --- a/crypto-primitives/src/lib.rs +++ b/crypto-primitives/src/lib.rs @@ -1,9 +1,20 @@ +#![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; pub mod merkle_tree; @@ -27,16 +38,20 @@ pub use self::{ signature::SigRandomizePkGadget, }; +#[cfg(feature = "std")] pub type Error = Box; +#[cfg(not(feature = "std"))] +pub type Error = Box; + #[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 @@ impl std::fmt::Display for CryptoError { } } +#[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 {} diff --git a/crypto-primitives/src/merkle_tree/constraints.rs b/crypto-primitives/src/merkle_tree/constraints.rs index 462549d..62bd09a 100644 --- a/crypto-primitives/src/merkle_tree/constraints.rs +++ b/crypto-primitives/src/merkle_tree/constraints.rs @@ -7,7 +7,7 @@ use crate::{ merkle_tree::*, }; -use std::borrow::Borrow; +use core::borrow::Borrow; pub struct MerkleTreePathGadget where @@ -178,8 +178,6 @@ where #[cfg(test)] mod test { - use std::rc::Rc; - use crate::{ crh::{ pedersen::{constraints::PedersenCRHGadget, PedersenCRH, PedersenWindow}, @@ -220,7 +218,7 @@ mod test { 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; diff --git a/crypto-primitives/src/merkle_tree/mod.rs b/crypto-primitives/src/merkle_tree/mod.rs index 90c22f0..306f3ef 100644 --- a/crypto-primitives/src/merkle_tree/mod.rs +++ b/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 @@ pub struct MerkleHashTree { ::Output, ::Output, )>, - parameters: Rc<::Parameters>, + parameters: ::Parameters, root: Option<::Output>, } impl MerkleHashTree

{ pub const HEIGHT: u8 = P::HEIGHT as u8; - pub fn blank(parameters: Rc<::Parameters>) -> Self { + pub fn blank(parameters: ::Parameters) -> Self { MerkleHashTree { tree: Vec::new(), padding_tree: Vec::new(), @@ -104,7 +104,7 @@ impl MerkleHashTree

{ } pub fn new( - parameters: Rc<::Parameters>, + parameters: ::Parameters, leaves: &[L], ) -> Result { let new_time = start_timer!(|| "MerkleTree::New"); @@ -243,8 +243,8 @@ pub enum MerkleTreeError { 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 @@ impl std::fmt::Display for MerkleTreeError { } } +#[cfg(feature = "std")] impl std::error::Error for MerkleTreeError { #[inline] fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { @@ -262,16 +263,19 @@ impl std::error::Error for MerkleTreeError { } } +#[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 @@ pub(crate) fn hash_inner_node( right: &H::Output, buffer: &mut [u8], ) -> Result { - 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 @@ pub(crate) fn hash_leaf( leaf: &L, buffer: &mut [u8], ) -> Result { - 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 @@ mod test { fn generate_merkle_tree(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 @@ mod test { fn bad_merkle_tree_verify(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() { diff --git a/crypto-primitives/src/nizk/gm17/constraints.rs b/crypto-primitives/src/nizk/gm17/constraints.rs index 1bf8cbd..0110d3a 100644 --- a/crypto-primitives/src/nizk/gm17/constraints.rs +++ b/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 @@ mod test { 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, Fr>; type TestVerifierGadget = Gm17VerifierGadget; @@ -469,7 +469,7 @@ mod 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> = Vec::with_capacity(num_inputs); for _ in 0..num_inputs { inputs.push(Some(rng.gen())); diff --git a/crypto-primitives/src/nizk/gm17/mod.rs b/crypto-primitives/src/nizk/gm17/mod.rs index 881cb24..aa16f14 100644 --- a/crypto-primitives/src/nizk/gm17/mod.rs +++ b/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; diff --git a/crypto-primitives/src/nizk/groth16/constraints.rs b/crypto-primitives/src/nizk/groth16/constraints.rs index 60fd0d6..059f498 100644 --- a/crypto-primitives/src/nizk/groth16/constraints.rs +++ b/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 @@ mod test { 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, Fr>; type TestVerifierGadget = Groth16VerifierGadget; @@ -416,7 +416,7 @@ mod 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> = Vec::with_capacity(num_inputs); for _ in 0..num_inputs { inputs.push(Some(rng.gen())); diff --git a/crypto-primitives/src/nizk/groth16/mod.rs b/crypto-primitives/src/nizk/groth16/mod.rs index 8e38a87..3a3f1e8 100644 --- a/crypto-primitives/src/nizk/groth16/mod.rs +++ b/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; diff --git a/crypto-primitives/src/nizk/mod.rs b/crypto-primitives/src/nizk/mod.rs index 1e8cae4..e98f920 100644 --- a/crypto-primitives/src/nizk/mod.rs +++ b/crypto-primitives/src/nizk/mod.rs @@ -53,8 +53,8 @@ pub trait NIZK { #[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 @@ mod test { 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::::setup(circuit, rng).unwrap(); diff --git a/crypto-primitives/src/prf/blake2s/constraints.rs b/crypto-primitives/src/prf/blake2s/constraints.rs index 6a37147..6979852 100644 --- a/crypto-primitives/src/prf/blake2s/constraints.rs +++ b/crypto-primitives/src/prf/blake2s/constraints.rs @@ -4,7 +4,7 @@ use r1cs_core::{ConstraintSystem, SynthesisError}; 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: diff --git a/crypto-primitives/src/prf/constraints.rs b/crypto-primitives/src/prf/constraints.rs index ca61edc..817ffdb 100644 --- a/crypto-primitives/src/prf/constraints.rs +++ b/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}; diff --git a/crypto-primitives/src/prf/mod.rs b/crypto-primitives/src/prf/mod.rs index 0729bea..d1f3096 100644 --- a/crypto-primitives/src/prf/mod.rs +++ b/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; diff --git a/crypto-primitives/src/signature/mod.rs b/crypto-primitives/src/signature/mod.rs index 546ef13..61dfabd 100644 --- a/crypto-primitives/src/signature/mod.rs +++ b/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 @@ pub trait SignatureScheme { 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(message: &[u8]) { - let rng = &mut thread_rng(); + let rng = &mut test_rng(); let parameters = S::setup::<_>(rng).unwrap(); let (pk, sk) = S::keygen(¶meters, rng).unwrap(); let sig = S::sign(¶meters, &sk, &message, rng).unwrap(); @@ -69,7 +68,7 @@ mod test { } fn failed_verification(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(¶meters, rng).unwrap(); let sig = S::sign(¶meters, &sk, message, rng).unwrap(); @@ -77,7 +76,7 @@ mod test { } fn randomize_and_verify(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(¶meters, rng).unwrap(); let sig = S::sign(¶meters, &sk, message, rng).unwrap(); @@ -90,7 +89,7 @@ mod test { #[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::>(message.as_bytes()); failed_verification::>( message.as_bytes(), diff --git a/crypto-primitives/src/signature/schnorr/constraints.rs b/crypto-primitives/src/signature/schnorr/constraints.rs index e8d31f2..6650d6a 100644 --- a/crypto-primitives/src/signature/schnorr/constraints.rs +++ b/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; diff --git a/crypto-primitives/src/signature/schnorr/mod.rs b/crypto-primitives/src/signature/schnorr/mod.rs index 8f45692..8a4e66d 100644 --- a/crypto-primitives/src/signature/schnorr/mod.rs +++ b/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;