Browse Source

crypto-primitives no-std (#96)

master
Marek Kotewicz 4 years ago
committed by GitHub
parent
commit
d4896ade47
37 changed files with 202 additions and 153 deletions
  1. +1
    -0
      Cargo.toml
  2. +58
    -0
      cp-benches/Cargo.toml
  3. +0
    -0
      cp-benches/benches/crypto_primitives/comm.rs
  4. +0
    -0
      cp-benches/benches/crypto_primitives/crh.rs
  5. +0
    -0
      cp-benches/benches/crypto_primitives/nizk.rs
  6. +0
    -0
      cp-benches/benches/crypto_primitives/prf.rs
  7. +0
    -0
      cp-benches/benches/crypto_primitives/signature.rs
  8. +14
    -41
      crypto-primitives/Cargo.toml
  9. +4
    -5
      crypto-primitives/src/commitment/blake2s/constraints.rs
  10. +1
    -1
      crypto-primitives/src/commitment/constraints.rs
  11. +1
    -1
      crypto-primitives/src/commitment/injective_map/constraints.rs
  12. +1
    -1
      crypto-primitives/src/commitment/injective_map/mod.rs
  13. +1
    -1
      crypto-primitives/src/commitment/mod.rs
  14. +7
    -9
      crypto-primitives/src/commitment/pedersen/constraints.rs
  15. +3
    -3
      crypto-primitives/src/commitment/pedersen/mod.rs
  16. +8
    -7
      crypto-primitives/src/crh/bowe_hopwood/constraints.rs
  17. +14
    -13
      crypto-primitives/src/crh/bowe_hopwood/mod.rs
  18. +1
    -1
      crypto-primitives/src/crh/constraints.rs
  19. +1
    -1
      crypto-primitives/src/crh/injective_map/constraints.rs
  20. +1
    -1
      crypto-primitives/src/crh/injective_map/mod.rs
  21. +1
    -1
      crypto-primitives/src/crh/mod.rs
  22. +8
    -6
      crypto-primitives/src/crh/pedersen/constraints.rs
  23. +10
    -7
      crypto-primitives/src/crh/pedersen/mod.rs
  24. +21
    -2
      crypto-primitives/src/lib.rs
  25. +2
    -4
      crypto-primitives/src/merkle_tree/constraints.rs
  26. +18
    -18
      crypto-primitives/src/merkle_tree/mod.rs
  27. +4
    -4
      crypto-primitives/src/nizk/gm17/constraints.rs
  28. +1
    -1
      crypto-primitives/src/nizk/gm17/mod.rs
  29. +4
    -4
      crypto-primitives/src/nizk/groth16/constraints.rs
  30. +1
    -1
      crypto-primitives/src/nizk/groth16/mod.rs
  31. +3
    -3
      crypto-primitives/src/nizk/mod.rs
  32. +1
    -1
      crypto-primitives/src/prf/blake2s/constraints.rs
  33. +1
    -1
      crypto-primitives/src/prf/constraints.rs
  34. +1
    -1
      crypto-primitives/src/prf/mod.rs
  35. +6
    -7
      crypto-primitives/src/signature/mod.rs
  36. +1
    -1
      crypto-primitives/src/signature/schnorr/constraints.rs
  37. +3
    -6
      crypto-primitives/src/signature/schnorr/mod.rs

+ 1
- 0
Cargo.toml

@ -4,6 +4,7 @@ members = [
"algebra", "algebra",
"algebra-benches", "algebra-benches",
"bench-utils", "bench-utils",
"cp-benches",
"crypto-primitives", "crypto-primitives",
"dpc", "dpc",
"ff-fft", "ff-fft",

+ 58
- 0
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

crypto-primitives/benches/crypto_primitives/comm.rs → cp-benches/benches/crypto_primitives/comm.rs


crypto-primitives/benches/crypto_primitives/crh.rs → cp-benches/benches/crypto_primitives/crh.rs


crypto-primitives/benches/crypto_primitives/nizk.rs → cp-benches/benches/crypto_primitives/nizk.rs


crypto-primitives/benches/crypto_primitives/prf.rs → cp-benches/benches/crypto_primitives/prf.rs


crypto-primitives/benches/crypto_primitives/signature.rs → cp-benches/benches/crypto_primitives/signature.rs


+ 14
- 41
crypto-primitives/Cargo.toml

@ -22,51 +22,24 @@ edition = "2018"
################################# Dependencies ################################ ################################# Dependencies ################################
[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" } bench-utils = { path = "../bench-utils" }
blake2 = { version = "0.7", default-features = false }
derivative = { version = "1.0", features = ["use_core"] }
digest = "0.7" 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] [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] [dev-dependencies]
criterion = "0.3.1"
rand_xorshift = { version = "0.2" } 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

+ 4
- 5
crypto-primitives/src/commitment/blake2s/constraints.rs

@ -8,7 +8,7 @@ use crate::{
use algebra::{Field, PrimeField}; use algebra::{Field, PrimeField};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use std::borrow::Borrow;
use core::borrow::Borrow;
#[derive(Clone)] #[derive(Clone)]
pub struct Blake2sParametersGadget; pub struct Blake2sParametersGadget;
@ -110,9 +110,6 @@ impl AllocGadget<[u8; 32], ConstraintF> for Blake2sRand
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use algebra::fields::bls12_381::Fr;
use rand::{thread_rng, Rng};
use crate::{ use crate::{
commitment::blake2s::{ commitment::blake2s::{
constraints::{Blake2sCommitmentGadget, Blake2sRandomnessGadget}, constraints::{Blake2sCommitmentGadget, Blake2sRandomnessGadget},
@ -120,8 +117,10 @@ mod test {
}, },
*, *,
}; };
use algebra::{fields::bls12_381::Fr, test_rng};
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
use r1cs_std::{prelude::*, test_constraint_system::TestConstraintSystem}; use r1cs_std::{prelude::*, test_constraint_system::TestConstraintSystem};
use rand::Rng;
#[test] #[test]
fn commitment_gadget_test() { fn commitment_gadget_test() {
@ -129,7 +128,7 @@ mod test {
let input = [1u8; 32]; let input = [1u8; 32];
let rng = &mut thread_rng();
let rng = &mut test_rng();
type TestCOMM = Blake2sCommitment; type TestCOMM = Blake2sCommitment;
type TestCOMMGadget = Blake2sCommitmentGadget; type TestCOMMGadget = Blake2sCommitmentGadget;

+ 1
- 1
crypto-primitives/src/commitment/constraints.rs

@ -1,8 +1,8 @@
use crate::CommitmentScheme; use crate::CommitmentScheme;
use algebra::Field; use algebra::Field;
use core::fmt::Debug;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use std::fmt::Debug;
pub trait CommitmentGadget<C: CommitmentScheme, ConstraintF: Field> { pub trait CommitmentGadget<C: CommitmentScheme, ConstraintF: Field> {
type OutputGadget: EqGadget<ConstraintF> type OutputGadget: EqGadget<ConstraintF>

+ 1
- 1
crypto-primitives/src/commitment/injective_map/constraints.rs

@ -16,7 +16,7 @@ use algebra::groups::Group;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::{groups::GroupGadget, uint8::UInt8}; use r1cs_std::{groups::GroupGadget, uint8::UInt8};
use std::marker::PhantomData;
use core::marker::PhantomData;
pub struct PedersenCommitmentCompressorGadget<G, I, ConstraintF, GG, IG> pub struct PedersenCommitmentCompressorGadget<G, I, ConstraintF, GG, IG>
where where

+ 1
- 1
crypto-primitives/src/commitment/injective_map/mod.rs

@ -1,6 +1,6 @@
use crate::Error; use crate::Error;
use core::marker::PhantomData;
use rand::Rng; use rand::Rng;
use std::marker::PhantomData;
use super::{ use super::{
pedersen::{PedersenCommitment, PedersenParameters, PedersenRandomness, PedersenWindow}, pedersen::{PedersenCommitment, PedersenParameters, PedersenRandomness, PedersenWindow},

+ 1
- 1
crypto-primitives/src/commitment/mod.rs

@ -1,6 +1,6 @@
use algebra::UniformRand; use algebra::UniformRand;
use core::{fmt::Debug, hash::Hash};
use rand::Rng; use rand::Rng;
use std::{fmt::Debug, hash::Hash};
use algebra::bytes::ToBytes; use algebra::bytes::ToBytes;

+ 7
- 9
crypto-primitives/src/commitment/pedersen/constraints.rs

@ -7,8 +7,8 @@ use r1cs_core::{ConstraintSystem, SynthesisError};
use crate::commitment::CommitmentGadget; use crate::commitment::CommitmentGadget;
use algebra::fields::{Field, PrimeField}; use algebra::fields::{Field, PrimeField};
use core::{borrow::Borrow, marker::PhantomData};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use std::{borrow::Borrow, marker::PhantomData};
#[derive(Derivative)] #[derive(Derivative)]
#[derivative(Clone(bound = "G: Group, W: PedersenWindow, ConstraintF: Field"))] #[derivative(Clone(bound = "G: Group, W: PedersenWindow, ConstraintF: Field"))]
@ -171,12 +171,6 @@ where
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use algebra::{
fields::jubjub::{fq::Fq, fr::Fr},
UniformRand,
};
use rand::thread_rng;
use crate::{ use crate::{
commitment::{ commitment::{
pedersen::{ pedersen::{
@ -186,7 +180,11 @@ mod test {
}, },
crh::pedersen::PedersenWindow, 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_core::ConstraintSystem;
use r1cs_std::{ use r1cs_std::{
groups::jubjub::JubJubGadget, prelude::*, test_constraint_system::TestConstraintSystem, groups::jubjub::JubJubGadget, prelude::*, test_constraint_system::TestConstraintSystem,
@ -206,7 +204,7 @@ mod test {
let input = [1u8; 4]; let input = [1u8; 4];
let rng = &mut thread_rng();
let rng = &mut test_rng();
type TestCOMM = PedersenCommitment<JubJub, Window>; type TestCOMM = PedersenCommitment<JubJub, Window>;
type TestCOMMGadget = PedersenCommitmentGadget<JubJub, Fq, JubJubGadget>; type TestCOMMGadget = PedersenCommitmentGadget<JubJub, Fq, JubJubGadget>;

+ 3
- 3
crypto-primitives/src/commitment/pedersen/mod.rs

@ -1,14 +1,14 @@
use crate::Error;
use crate::{Error, Vec};
use algebra::{ use algebra::{
bytes::ToBytes, groups::Group, BitIterator, Field, FpParameters, PrimeField, ToConstraintField, bytes::ToBytes, groups::Group, BitIterator, Field, FpParameters, PrimeField, ToConstraintField,
UniformRand, UniformRand,
}; };
use core::marker::PhantomData;
use rand::Rng; use rand::Rng;
use std::marker::PhantomData;
use super::CommitmentScheme; use super::CommitmentScheme;
use std::io::{Result as IoResult, Write};
use algebra::io::{Result as IoResult, Write};
pub use crate::crh::pedersen::PedersenWindow; pub use crate::crh::pedersen::PedersenWindow;
use crate::crh::{ use crate::crh::{

+ 8
- 7
crypto-primitives/src/crh/bowe_hopwood/constraints.rs

@ -1,5 +1,5 @@
use algebra::Field; use algebra::Field;
use std::hash::Hash;
use core::hash::Hash;
use crate::crh::{ use crate::crh::{
bowe_hopwood::{BoweHopwoodPedersenCRH, BoweHopwoodPedersenParameters, CHUNK_SIZE}, bowe_hopwood::{BoweHopwoodPedersenCRH, BoweHopwoodPedersenParameters, CHUNK_SIZE},
@ -10,8 +10,8 @@ use algebra::groups::Group;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::{alloc::AllocGadget, groups::GroupGadget, uint8::UInt8}; use r1cs_std::{alloc::AllocGadget, groups::GroupGadget, uint8::UInt8};
use core::{borrow::Borrow, marker::PhantomData};
use r1cs_std::bits::boolean::Boolean; use r1cs_std::bits::boolean::Boolean;
use std::{borrow::Borrow, marker::PhantomData};
#[derive(Derivative)] #[derive(Derivative)]
#[derivative(Clone( #[derivative(Clone(
@ -125,20 +125,21 @@ impl
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use algebra::fields::sw6::fr::Fr;
use rand::{thread_rng, Rng};
use crate::crh::{ use crate::crh::{
bowe_hopwood::{constraints::BoweHopwoodPedersenCRHGadget, BoweHopwoodPedersenCRH}, bowe_hopwood::{constraints::BoweHopwoodPedersenCRHGadget, BoweHopwoodPedersenCRH},
pedersen::PedersenWindow, pedersen::PedersenWindow,
FixedLengthCRH, FixedLengthCRHGadget, 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_core::ConstraintSystem;
use r1cs_std::{ use r1cs_std::{
alloc::AllocGadget, groups::curves::twisted_edwards::edwards_sw6::EdwardsSWGadget, alloc::AllocGadget, groups::curves::twisted_edwards::edwards_sw6::EdwardsSWGadget,
test_constraint_system::TestConstraintSystem, uint8::UInt8, test_constraint_system::TestConstraintSystem, uint8::UInt8,
}; };
use rand::Rng;
type TestCRH = BoweHopwoodPedersenCRH<Edwards, Window>; type TestCRH = BoweHopwoodPedersenCRH<Edwards, Window>;
type TestCRHGadget = BoweHopwoodPedersenCRHGadget<Edwards, Fr, EdwardsSWGadget>; type TestCRHGadget = BoweHopwoodPedersenCRHGadget<Edwards, Fr, EdwardsSWGadget>;
@ -168,7 +169,7 @@ mod test {
#[test] #[test]
fn crh_primitive_gadget_test() { fn crh_primitive_gadget_test() {
let rng = &mut thread_rng();
let rng = &mut test_rng();
let mut cs = TestConstraintSystem::<Fr>::new(); let mut cs = TestConstraintSystem::<Fr>::new();
let (input, input_bytes) = generate_input(&mut cs, rng); let (input, input_bytes) = generate_input(&mut cs, rng);

+ 14
- 13
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}, fmt::{Debug, Formatter, Result as FmtResult},
marker::PhantomData, marker::PhantomData,
}; };
use rand::Rng;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use super::pedersen::{bytes_to_bits, PedersenCRH, PedersenWindow}; use super::pedersen::{bytes_to_bits, PedersenCRH, PedersenWindow};
use crate::crh::FixedLengthCRH; use crate::crh::FixedLengthCRH;
use algebra::{biginteger::BigInteger, fields::PrimeField, groups::Group}; use algebra::{biginteger::BigInteger, fields::PrimeField, groups::Group};
use ff_fft::cfg_chunks;
#[cfg(feature = "r1cs")] #[cfg(feature = "r1cs")]
pub mod constraints; pub mod constraints;
@ -126,12 +128,11 @@ impl FixedLengthCRH for BoweHopwoodPedersenCRH
// (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} // (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 // for all i. Described in section 5.4.1.7 in the Zcash protocol
// specification. // 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) .zip(&parameters.generators)
.map(|(segment_bits, segment_generators)| { .map(|(segment_bits, segment_generators)| {
segment_bits
.par_chunks(CHUNK_SIZE)
cfg_chunks!(segment_bits, CHUNK_SIZE)
.zip(segment_generators) .zip(segment_generators)
.map(|(chunk_bits, generator)| { .map(|(chunk_bits, generator)| {
let mut encoded = generator.clone(); let mut encoded = generator.clone();
@ -146,9 +147,10 @@ impl FixedLengthCRH for BoweHopwoodPedersenCRH
} }
encoded encoded
}) })
.reduce(G::zero, |a, b| a + &b)
.sum::<G>()
}) })
.reduce(G::zero, |a, b| a + &b);
.sum::<G>();
end_timer!(eval_time); end_timer!(eval_time);
Ok(result) Ok(result)
@ -171,8 +173,7 @@ mod test {
crh::{bowe_hopwood::BoweHopwoodPedersenCRH, pedersen::PedersenWindow}, crh::{bowe_hopwood::BoweHopwoodPedersenCRH, pedersen::PedersenWindow},
FixedLengthCRH, FixedLengthCRH,
}; };
use algebra::curves::edwards_sw6::EdwardsProjective;
use rand::thread_rng;
use algebra::{curves::edwards_sw6::EdwardsProjective, test_rng};
#[test] #[test]
fn test_simple_bh() { fn test_simple_bh() {
@ -183,7 +184,7 @@ mod test {
const NUM_WINDOWS: usize = 8; const NUM_WINDOWS: usize = 8;
} }
let rng = &mut thread_rng();
let rng = &mut test_rng();
let params = let params =
<BoweHopwoodPedersenCRH<EdwardsProjective, TestWindow> as FixedLengthCRH>::setup(rng) <BoweHopwoodPedersenCRH<EdwardsProjective, TestWindow> as FixedLengthCRH>::setup(rng)
.unwrap(); .unwrap();

+ 1
- 1
crypto-primitives/src/crh/constraints.rs

@ -1,5 +1,5 @@
use algebra::Field; use algebra::Field;
use std::fmt::Debug;
use core::fmt::Debug;
use crate::crh::FixedLengthCRH; use crate::crh::FixedLengthCRH;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};

+ 1
- 1
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::{ use crate::crh::{
injective_map::{InjectiveMap, PedersenCRHCompressor, TECompressor}, injective_map::{InjectiveMap, PedersenCRHCompressor, TECompressor},

+ 1
- 1
crypto-primitives/src/crh/injective_map/mod.rs

@ -1,7 +1,7 @@
use crate::{CryptoError, Error}; use crate::{CryptoError, Error};
use algebra::bytes::ToBytes; use algebra::bytes::ToBytes;
use core::{fmt::Debug, hash::Hash, marker::PhantomData};
use rand::Rng; use rand::Rng;
use std::{fmt::Debug, hash::Hash, marker::PhantomData};
use super::{ use super::{
pedersen::{PedersenCRH, PedersenParameters, PedersenWindow}, pedersen::{PedersenCRH, PedersenParameters, PedersenWindow},

+ 1
- 1
crypto-primitives/src/crh/mod.rs

@ -1,6 +1,6 @@
use algebra::bytes::ToBytes; use algebra::bytes::ToBytes;
use core::hash::Hash;
use rand::Rng; use rand::Rng;
use std::hash::Hash;
pub mod bowe_hopwood; pub mod bowe_hopwood;
pub mod injective_map; pub mod injective_map;

+ 8
- 6
crypto-primitives/src/crh/pedersen/constraints.rs

@ -6,7 +6,7 @@ use algebra::{Field, Group};
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use std::{borrow::Borrow, marker::PhantomData};
use core::{borrow::Borrow, marker::PhantomData};
#[derive(Derivative)] #[derive(Derivative)]
#[derivative(Clone( #[derivative(Clone(
@ -114,19 +114,21 @@ impl
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use algebra::fields::bls12_381::fr::Fr;
use rand::{thread_rng, Rng};
use crate::crh::{ use crate::crh::{
pedersen::{constraints::PedersenCRHGadget, PedersenCRH, PedersenWindow}, pedersen::{constraints::PedersenCRHGadget, PedersenCRH, PedersenWindow},
FixedLengthCRH, FixedLengthCRHGadget, 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_core::ConstraintSystem;
use r1cs_std::{ use r1cs_std::{
groups::curves::twisted_edwards::jubjub::JubJubGadget, prelude::*, groups::curves::twisted_edwards::jubjub::JubJubGadget, prelude::*,
test_constraint_system::TestConstraintSystem, test_constraint_system::TestConstraintSystem,
}; };
use rand::Rng;
type TestCRH = PedersenCRH<JubJub, Window>; type TestCRH = PedersenCRH<JubJub, Window>;
type TestCRHGadget = PedersenCRHGadget<JubJub, Fr, JubJubGadget>; type TestCRHGadget = PedersenCRHGadget<JubJub, Fr, JubJubGadget>;
@ -156,7 +158,7 @@ mod test {
#[test] #[test]
fn crh_primitive_gadget_test() { fn crh_primitive_gadget_test() {
let rng = &mut thread_rng();
let rng = &mut test_rng();
let mut cs = TestConstraintSystem::<Fr>::new(); let mut cs = TestConstraintSystem::<Fr>::new();
let (input, input_bytes) = generate_input(&mut cs, rng); let (input, input_bytes) = generate_input(&mut cs, rng);

+ 10
- 7
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}, fmt::{Debug, Formatter, Result as FmtResult},
marker::PhantomData, marker::PhantomData,
}; };
use rand::Rng;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use crate::crh::FixedLengthCRH; use crate::crh::FixedLengthCRH;
use algebra::{groups::Group, Field, ToConstraintField}; use algebra::{groups::Group, Field, ToConstraintField};
use ff_fft::cfg_chunks;
#[cfg(feature = "r1cs")] #[cfg(feature = "r1cs")]
pub mod constraints; pub mod constraints;
@ -99,8 +101,8 @@ impl FixedLengthCRH for PedersenCRH {
); );
// Compute sum of h_i^{m_i} for all i. // 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) .zip(&parameters.generators)
.map(|(bits, generator_powers)| { .map(|(bits, generator_powers)| {
let mut encoded = G::zero(); let mut encoded = G::zero();
@ -111,7 +113,8 @@ impl FixedLengthCRH for PedersenCRH {
} }
encoded encoded
}) })
.reduce(G::zero, |a, b| a + &b);
.sum::<G>();
end_timer!(eval_time); end_timer!(eval_time);
Ok(result) Ok(result)

+ 21
- 2
crypto-primitives/src/lib.rs

@ -1,9 +1,20 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[macro_use] #[macro_use]
extern crate bench_utils; extern crate bench_utils;
#[macro_use] #[macro_use]
extern crate derivative; 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 commitment;
pub mod crh; pub mod crh;
pub mod merkle_tree; pub mod merkle_tree;
@ -27,16 +38,20 @@ pub use self::{
signature::SigRandomizePkGadget, signature::SigRandomizePkGadget,
}; };
#[cfg(feature = "std")]
pub type Error = Box<dyn std::error::Error>; pub type Error = Box<dyn std::error::Error>;
#[cfg(not(feature = "std"))]
pub type Error = Box<dyn algebra::Error>;
#[derive(Debug)] #[derive(Debug)]
pub enum CryptoError { pub enum CryptoError {
IncorrectInputLength(usize), IncorrectInputLength(usize),
NotPrimeOrder, 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 { let msg = match self {
CryptoError::IncorrectInputLength(len) => format!("input length is wrong: {}", len), CryptoError::IncorrectInputLength(len) => format!("input length is wrong: {}", len),
CryptoError::NotPrimeOrder => "element is not prime order".to_owned(), 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 { impl std::error::Error for CryptoError {
#[inline] #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None None
} }
} }
#[cfg(not(feature = "std"))]
impl algebra::Error for CryptoError {}

+ 2
- 4
crypto-primitives/src/merkle_tree/constraints.rs

@ -7,7 +7,7 @@ use crate::{
merkle_tree::*, merkle_tree::*,
}; };
use std::borrow::Borrow;
use core::borrow::Borrow;
pub struct MerkleTreePathGadget<P, HGadget, ConstraintF> pub struct MerkleTreePathGadget<P, HGadget, ConstraintF>
where where
@ -178,8 +178,6 @@ where
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::rc::Rc;
use crate::{ use crate::{
crh::{ crh::{
pedersen::{constraints::PedersenCRHGadget, PedersenCRH, PedersenWindow}, pedersen::{constraints::PedersenCRHGadget, PedersenCRH, PedersenWindow},
@ -220,7 +218,7 @@ mod test {
fn generate_merkle_tree(leaves: &[[u8; 30]], use_bad_root: bool) -> () { fn generate_merkle_tree(leaves: &[[u8; 30]], use_bad_root: bool) -> () {
let mut rng = XorShiftRng::seed_from_u64(9174123u64); 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 tree = JubJubMerkleTree::new(crh_parameters.clone(), leaves).unwrap();
let root = tree.root(); let root = tree.root();
let mut satisfied = true; let mut satisfied = true;

+ 18
- 18
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")] #[cfg(feature = "r1cs")]
pub mod constraints; pub mod constraints;
@ -87,14 +87,14 @@ pub struct MerkleHashTree {
<P::H as FixedLengthCRH>::Output, <P::H as FixedLengthCRH>::Output,
<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>, root: Option<<P::H as FixedLengthCRH>::Output>,
} }
impl<P: MerkleTreeConfig> MerkleHashTree<P> { impl<P: MerkleTreeConfig> MerkleHashTree<P> {
pub const HEIGHT: u8 = P::HEIGHT as u8; 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 { MerkleHashTree {
tree: Vec::new(), tree: Vec::new(),
padding_tree: Vec::new(), padding_tree: Vec::new(),
@ -104,7 +104,7 @@ impl MerkleHashTree

{

} }
pub fn new<L: ToBytes>( pub fn new<L: ToBytes>(
parameters: Rc<<P::H as FixedLengthCRH>::Parameters>,
parameters: <P::H as FixedLengthCRH>::Parameters,
leaves: &[L], leaves: &[L],
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let new_time = start_timer!(|| "MerkleTree::New"); let new_time = start_timer!(|| "MerkleTree::New");
@ -243,8 +243,8 @@ pub enum MerkleTreeError {
IncorrectPathLength(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 { let msg = match self {
MerkleTreeError::IncorrectLeafIndex(index) => { MerkleTreeError::IncorrectLeafIndex(index) => {
format!("incorrect leaf index: {}", 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 { impl std::error::Error for MerkleTreeError {
#[inline] #[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { 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. /// Returns the log2 value of the given number.
#[inline] #[inline]
fn log2(number: usize) -> usize { 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. /// Returns the height of the tree, given the size of the tree.
#[inline] #[inline]
fn tree_height(tree_size: usize) -> usize { fn tree_height(tree_size: usize) -> usize {
log2(tree_size + 1)
log2(tree_size)
} }
/// Returns true iff the index represents the root. /// Returns true iff the index represents the root.
@ -332,15 +336,13 @@ pub(crate) fn hash_inner_node(
right: &H::Output, right: &H::Output,
buffer: &mut [u8], buffer: &mut [u8],
) -> Result<H::Output, Error> { ) -> Result<H::Output, Error> {
use std::io::Cursor;
let mut writer = Cursor::new(buffer);
let mut writer = Cursor::new(&mut *buffer);
// Construct left input. // Construct left input.
left.write(&mut writer)?; left.write(&mut writer)?;
// Construct right input. // Construct right input.
right.write(&mut writer)?; right.write(&mut writer)?;
let buffer = writer.into_inner();
H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)]) H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)])
} }
@ -350,11 +352,9 @@ pub(crate) fn hash_leaf(
leaf: &L, leaf: &L,
buffer: &mut [u8], buffer: &mut [u8],
) -> Result<H::Output, Error> { ) -> 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)?; leaf.write(&mut writer)?;
let buffer = writer.into_inner();
H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)]) H::evaluate(parameters, &buffer[..(H::INPUT_SIZE_BITS / 8)])
} }
@ -395,7 +395,7 @@ mod test {
fn generate_merkle_tree<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () { fn generate_merkle_tree<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () {
let mut rng = XorShiftRng::seed_from_u64(9174123u64); 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 tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap();
let root = tree.root(); let root = tree.root();
for (i, leaf) in leaves.iter().enumerate() { for (i, leaf) in leaves.iter().enumerate() {
@ -421,7 +421,7 @@ mod test {
fn bad_merkle_tree_verify<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () { fn bad_merkle_tree_verify<L: ToBytes + Clone + Eq>(leaves: &[L]) -> () {
let mut rng = XorShiftRng::seed_from_u64(13423423u64); 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 tree = JubJubMerkleTree::new(crh_parameters.clone(), &leaves).unwrap();
let root = JubJub::zero(); let root = JubJub::zero();
for (i, leaf) in leaves.iter().enumerate() { for (i, leaf) in leaves.iter().enumerate() {

+ 4
- 4
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_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use core::{borrow::Borrow, marker::PhantomData};
use gm17::{Proof, VerifyingKey}; use gm17::{Proof, VerifyingKey};
use std::{borrow::Borrow, marker::PhantomData};
#[derive(Derivative)] #[derive(Derivative)]
#[derivative(Clone(bound = "P::G1Gadget: Clone, P::G2Gadget: Clone"))] #[derivative(Clone(bound = "P::G1Gadget: Clone, P::G2Gadget: Clone"))]
@ -406,13 +406,13 @@ mod test {
use algebra::{ use algebra::{
curves::bls12_377::Bls12_377, curves::bls12_377::Bls12_377,
fields::bls12_377::{Fq, Fr}, fields::bls12_377::{Fq, Fr},
BitIterator, PrimeField,
test_rng, BitIterator, PrimeField,
}; };
use r1cs_std::{ use r1cs_std::{
boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget, boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget,
test_constraint_system::TestConstraintSystem, test_constraint_system::TestConstraintSystem,
}; };
use rand::{thread_rng, Rng};
use rand::Rng;
type TestProofSystem = Gm17<Bls12_377, Bench<Fr>, Fr>; type TestProofSystem = Gm17<Bls12_377, Bench<Fr>, Fr>;
type TestVerifierGadget = Gm17VerifierGadget<Bls12_377, Fq, Bls12_377PairingGadget>; type TestVerifierGadget = Gm17VerifierGadget<Bls12_377, Fq, Bls12_377PairingGadget>;
@ -469,7 +469,7 @@ mod test {
fn gm17_verifier_test() { fn gm17_verifier_test() {
let num_inputs = 100; let num_inputs = 100;
let num_constraints = num_inputs; 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); let mut inputs: Vec<Option<Fr>> = Vec::with_capacity(num_inputs);
for _ in 0..num_inputs { for _ in 0..num_inputs {
inputs.push(Some(rng.gen())); inputs.push(Some(rng.gen()));

+ 1
- 1
crypto-primitives/src/nizk/gm17/mod.rs

@ -8,7 +8,7 @@ use r1cs_core::ConstraintSynthesizer;
use rand::Rng; use rand::Rng;
use algebra::ToConstraintField; use algebra::ToConstraintField;
use std::marker::PhantomData;
use core::marker::PhantomData;
use super::NIZK; use super::NIZK;

+ 4
- 4
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_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use core::{borrow::Borrow, marker::PhantomData};
use groth16::{Proof, VerifyingKey}; use groth16::{Proof, VerifyingKey};
use std::{borrow::Borrow, marker::PhantomData};
#[derive(Derivative)] #[derive(Derivative)]
#[derivative(Clone(bound = "P::G1Gadget: Clone, P::G2Gadget: Clone"))] #[derivative(Clone(bound = "P::G1Gadget: Clone, P::G2Gadget: Clone"))]
@ -353,13 +353,13 @@ mod test {
use algebra::{ use algebra::{
curves::bls12_377::Bls12_377, curves::bls12_377::Bls12_377,
fields::bls12_377::{Fq, Fr}, fields::bls12_377::{Fq, Fr},
BitIterator, PrimeField,
test_rng, BitIterator, PrimeField,
}; };
use r1cs_std::{ use r1cs_std::{
boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget, boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget,
test_constraint_system::TestConstraintSystem, test_constraint_system::TestConstraintSystem,
}; };
use rand::{thread_rng, Rng};
use rand::Rng;
type TestProofSystem = Groth16<Bls12_377, Bench<Fr>, Fr>; type TestProofSystem = Groth16<Bls12_377, Bench<Fr>, Fr>;
type TestVerifierGadget = Groth16VerifierGadget<Bls12_377, Fq, Bls12_377PairingGadget>; type TestVerifierGadget = Groth16VerifierGadget<Bls12_377, Fq, Bls12_377PairingGadget>;
@ -416,7 +416,7 @@ mod test {
fn groth16_verifier_test() { fn groth16_verifier_test() {
let num_inputs = 100; let num_inputs = 100;
let num_constraints = num_inputs; 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); let mut inputs: Vec<Option<Fr>> = Vec::with_capacity(num_inputs);
for _ in 0..num_inputs { for _ in 0..num_inputs {
inputs.push(Some(rng.gen())); inputs.push(Some(rng.gen()));

+ 1
- 1
crypto-primitives/src/nizk/groth16/mod.rs

@ -8,7 +8,7 @@ use r1cs_core::ConstraintSynthesizer;
use rand::Rng; use rand::Rng;
use algebra::ToConstraintField; use algebra::ToConstraintField;
use std::marker::PhantomData;
use core::marker::PhantomData;
use super::NIZK; use super::NIZK;

+ 3
- 3
crypto-primitives/src/nizk/mod.rs

@ -53,8 +53,8 @@ pub trait NIZK {
#[cfg(all(feature = "gm17", test))] #[cfg(all(feature = "gm17", test))]
mod test { mod test {
use rand::thread_rng;
use std::ops::AddAssign;
use algebra::test_rng;
use core::ops::AddAssign;
#[test] #[test]
fn test_gm17() { fn test_gm17() {
@ -102,7 +102,7 @@ mod test {
sum.add_assign(&Fr::one()); sum.add_assign(&Fr::one());
let circuit = R1CSCircuit::new(Fr::one(), sum, 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(); let parameters = Gm17::<Bls12_381, R1CSCircuit, [Fr]>::setup(circuit, rng).unwrap();

+ 1
- 1
crypto-primitives/src/prf/blake2s/constraints.rs

@ -4,7 +4,7 @@ use r1cs_core::{ConstraintSystem, SynthesisError};
use crate::prf::PRFGadget; use crate::prf::PRFGadget;
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use std::borrow::Borrow;
use core::borrow::Borrow;
// 2.1. Parameters // 2.1. Parameters
// The following table summarizes various parameters and their ranges: // The following table summarizes various parameters and their ranges:

+ 1
- 1
crypto-primitives/src/prf/constraints.rs

@ -1,5 +1,5 @@
use algebra::Field; use algebra::Field;
use std::fmt::Debug;
use core::fmt::Debug;
use crate::prf::PRF; use crate::prf::PRF;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};

+ 1
- 1
crypto-primitives/src/prf/mod.rs

@ -1,5 +1,5 @@
use algebra::bytes::{FromBytes, ToBytes}; use algebra::bytes::{FromBytes, ToBytes};
use std::{fmt::Debug, hash::Hash};
use core::{fmt::Debug, hash::Hash};
use crate::CryptoError; use crate::CryptoError;

+ 6
- 7
crypto-primitives/src/signature/mod.rs

@ -1,7 +1,7 @@
use crate::Error; use crate::Error;
use algebra::bytes::ToBytes; use algebra::bytes::ToBytes;
use core::hash::Hash;
use rand::Rng; use rand::Rng;
use std::hash::Hash;
#[cfg(feature = "r1cs")] #[cfg(feature = "r1cs")]
pub mod constraints; pub mod constraints;
@ -54,14 +54,13 @@ pub trait SignatureScheme {
mod test { mod test {
use crate::{signature::schnorr::SchnorrSignature, SignatureScheme}; use crate::{signature::schnorr::SchnorrSignature, SignatureScheme};
use algebra::{ 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, UniformRand,
}; };
use blake2::Blake2s; use blake2::Blake2s;
use rand::thread_rng;
fn sign_and_verify<S: SignatureScheme>(message: &[u8]) { 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 parameters = S::setup::<_>(rng).unwrap();
let (pk, sk) = S::keygen(&parameters, rng).unwrap(); let (pk, sk) = S::keygen(&parameters, rng).unwrap();
let sig = S::sign(&parameters, &sk, &message, rng).unwrap(); let sig = S::sign(&parameters, &sk, &message, rng).unwrap();
@ -69,7 +68,7 @@ mod test {
} }
fn failed_verification<S: SignatureScheme>(message: &[u8], bad_message: &[u8]) { 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 parameters = S::setup::<_>(rng).unwrap();
let (pk, sk) = S::keygen(&parameters, rng).unwrap(); let (pk, sk) = S::keygen(&parameters, rng).unwrap();
let sig = S::sign(&parameters, &sk, message, rng).unwrap(); let sig = S::sign(&parameters, &sk, message, rng).unwrap();
@ -77,7 +76,7 @@ mod test {
} }
fn randomize_and_verify<S: SignatureScheme>(message: &[u8], randomness: &[u8]) { 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 parameters = S::setup::<_>(rng).unwrap();
let (pk, sk) = S::keygen(&parameters, rng).unwrap(); let (pk, sk) = S::keygen(&parameters, rng).unwrap();
let sig = S::sign(&parameters, &sk, message, rng).unwrap(); let sig = S::sign(&parameters, &sk, message, rng).unwrap();
@ -90,7 +89,7 @@ mod test {
#[test] #[test]
fn schnorr_signature_test() { fn schnorr_signature_test() {
let message = "Hi, I am a Schnorr signature!"; 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()); sign_and_verify::<SchnorrSignature<Edwards, Blake2s>>(message.as_bytes());
failed_verification::<SchnorrSignature<Edwards, Blake2s>>( failed_verification::<SchnorrSignature<Edwards, Blake2s>>(
message.as_bytes(), message.as_bytes(),

+ 1
- 1
crypto-primitives/src/signature/schnorr/constraints.rs

@ -4,7 +4,7 @@ use r1cs_std::prelude::*;
use crate::signature::SigRandomizePkGadget; use crate::signature::SigRandomizePkGadget;
use std::{borrow::Borrow, marker::PhantomData};
use core::{borrow::Borrow, marker::PhantomData};
use crate::signature::schnorr::{SchnorrPublicKey, SchnorrSigParameters, SchnorrSignature}; use crate::signature::schnorr::{SchnorrPublicKey, SchnorrSigParameters, SchnorrSignature};
use digest::Digest; use digest::Digest;

+ 3
- 6
crypto-primitives/src/signature/schnorr/mod.rs

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

Loading…
Cancel
Save