Browse Source

Refactor `algebra` API, split into `algebra` and `algebra-core`. (#100)

master
Pratyush Mishra 4 years ago
committed by GitHub
parent
commit
8bf042a029
68 changed files with 417 additions and 572 deletions
  1. +1
    -0
      Cargo.toml
  2. +11
    -5
      crypto-primitives/Cargo.toml
  3. +2
    -2
      crypto-primitives/src/commitment/blake2s/constraints.rs
  4. +1
    -1
      crypto-primitives/src/commitment/constraints.rs
  5. +2
    -2
      crypto-primitives/src/commitment/injective_map/constraints.rs
  6. +1
    -1
      crypto-primitives/src/commitment/injective_map/mod.rs
  7. +2
    -2
      crypto-primitives/src/commitment/mod.rs
  8. +10
    -8
      crypto-primitives/src/commitment/pedersen/constraints.rs
  9. +5
    -4
      crypto-primitives/src/commitment/pedersen/mod.rs
  10. +13
    -14
      crypto-primitives/src/crh/bowe_hopwood/constraints.rs
  11. +5
    -5
      crypto-primitives/src/crh/bowe_hopwood/mod.rs
  12. +1
    -1
      crypto-primitives/src/crh/constraints.rs
  13. +1
    -1
      crypto-primitives/src/crh/injective_map/constraints.rs
  14. +2
    -2
      crypto-primitives/src/crh/injective_map/mod.rs
  15. +1
    -1
      crypto-primitives/src/crh/mod.rs
  16. +4
    -6
      crypto-primitives/src/crh/pedersen/constraints.rs
  17. +1
    -1
      crypto-primitives/src/crh/pedersen/mod.rs
  18. +2
    -2
      crypto-primitives/src/lib.rs
  19. +3
    -6
      crypto-primitives/src/merkle_tree/constraints.rs
  20. +4
    -4
      crypto-primitives/src/merkle_tree/mod.rs
  21. +1
    -1
      crypto-primitives/src/nizk/constraints.rs
  22. +3
    -4
      crypto-primitives/src/nizk/gm17/constraints.rs
  23. +2
    -2
      crypto-primitives/src/nizk/gm17/mod.rs
  24. +3
    -4
      crypto-primitives/src/nizk/groth16/constraints.rs
  25. +2
    -2
      crypto-primitives/src/nizk/groth16/mod.rs
  26. +8
    -5
      crypto-primitives/src/nizk/mod.rs
  27. +2
    -2
      crypto-primitives/src/prf/blake2s/constraints.rs
  28. +1
    -1
      crypto-primitives/src/prf/constraints.rs
  29. +1
    -1
      crypto-primitives/src/prf/mod.rs
  30. +1
    -1
      crypto-primitives/src/signature/constraints.rs
  31. +6
    -7
      crypto-primitives/src/signature/mod.rs
  32. +1
    -1
      crypto-primitives/src/signature/schnorr/constraints.rs
  33. +1
    -1
      crypto-primitives/src/signature/schnorr/mod.rs
  34. +12
    -1
      r1cs-std/Cargo.toml
  35. +1
    -1
      r1cs-std/src/bits/boolean.rs
  36. +1
    -1
      r1cs-std/src/bits/uint32.rs
  37. +1
    -1
      r1cs-std/src/bits/uint8.rs
  38. +0
    -8
      r1cs-std/src/fields/bls12_377.rs
  39. +0
    -4
      r1cs-std/src/fields/edwards_bls12.rs
  40. +0
    -4
      r1cs-std/src/fields/edwards_sw6.rs
  41. +0
    -6
      r1cs-std/src/fields/jubjub.rs
  42. +18
    -101
      r1cs-std/src/fields/mod.rs
  43. +2
    -5
      r1cs-std/src/groups/curves/short_weierstrass/bls12/mod.rs
  44. +0
    -30
      r1cs-std/src/groups/curves/twisted_edwards/edwards_bls12.rs
  45. +0
    -30
      r1cs-std/src/groups/curves/twisted_edwards/edwards_sw6.rs
  46. +0
    -30
      r1cs-std/src/groups/curves/twisted_edwards/jubjub.rs
  47. +62
    -6
      r1cs-std/src/groups/curves/twisted_edwards/mod.rs
  48. +0
    -72
      r1cs-std/src/groups/curves/twisted_edwards/test.rs
  49. +14
    -31
      r1cs-std/src/groups/mod.rs
  50. +15
    -22
      r1cs-std/src/instantiated/bls12_377/curves.rs
  51. +27
    -0
      r1cs-std/src/instantiated/bls12_377/fields.rs
  52. +7
    -0
      r1cs-std/src/instantiated/bls12_377/mod.rs
  53. +8
    -0
      r1cs-std/src/instantiated/bls12_377/pairing.rs
  54. +11
    -0
      r1cs-std/src/instantiated/edwards_bls12/curves.rs
  55. +9
    -0
      r1cs-std/src/instantiated/edwards_bls12/fields.rs
  56. +5
    -0
      r1cs-std/src/instantiated/edwards_bls12/mod.rs
  57. +11
    -0
      r1cs-std/src/instantiated/edwards_sw6/curves.rs
  58. +9
    -0
      r1cs-std/src/instantiated/edwards_sw6/fields.rs
  59. +5
    -0
      r1cs-std/src/instantiated/edwards_sw6/mod.rs
  60. +11
    -0
      r1cs-std/src/instantiated/jubjub/curves.rs
  61. +8
    -0
      r1cs-std/src/instantiated/jubjub/fields.rs
  62. +5
    -0
      r1cs-std/src/instantiated/jubjub/mod.rs
  63. +11
    -0
      r1cs-std/src/instantiated/mod.rs
  64. +21
    -33
      r1cs-std/src/lib.rs
  65. +0
    -4
      r1cs-std/src/pairing/bls12/bls12_377.rs
  66. +0
    -0
      r1cs-std/src/pairing/bls12/bls12_381.rs
  67. +3
    -30
      r1cs-std/src/pairing/bls12/mod.rs
  68. +36
    -52
      r1cs-std/src/pairing/mod.rs

+ 1
- 0
Cargo.toml

@ -1,6 +1,7 @@
[workspace] [workspace]
members = [ members = [
"algebra-core",
"algebra", "algebra",
"algebra-benches", "algebra-benches",
"bench-utils", "bench-utils",

+ 11
- 5
crypto-primitives/Cargo.toml

@ -22,24 +22,30 @@ edition = "2018"
################################# Dependencies ################################ ################################# Dependencies ################################
[dependencies] [dependencies]
algebra = { path = "../algebra", default-features = false }
algebra-core = { path = "../algebra-core", default-features = false }
bench-utils = { path = "../bench-utils" } bench-utils = { path = "../bench-utils" }
blake2 = { version = "0.7", default-features = false } blake2 = { version = "0.7", default-features = false }
derivative = { version = "1.0", features = ["use_core"] }
digest = "0.7" digest = "0.7"
ff-fft = { path = "../ff-fft", default-features = false } ff-fft = { path = "../ff-fft", default-features = false }
gm17 = { path = "../gm17", optional = true, default-features = false } gm17 = { path = "../gm17", optional = true, default-features = false }
groth16 = { path = "../groth16", optional = true, default-features = false } groth16 = { path = "../groth16", optional = true, default-features = false }
r1cs-core = { path = "../r1cs-core", 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 } r1cs-std = { path = "../r1cs-std", optional = true, default-features = false }
rand = { version = "0.7", default-features = false } rand = { version = "0.7", default-features = false }
rayon = { version = "1.0", optional = true } rayon = { version = "1.0", optional = true }
derivative = { version = "1.0", features = ["use_core"] }
[features] [features]
default = ["parallel"]
default = ["std"]
r1cs = ["r1cs-core", "r1cs-std"] 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"]
std = ["r1cs", "algebra-core/std", "r1cs-core/std", "r1cs-std/std"]
parallel = ["std", "rayon", "gm17/parallel", "groth16/parallel", "ff-fft/parallel"]
[dev-dependencies] [dev-dependencies]
algebra = { path = "../algebra", default-features = false, features = [ "jubjub", "bls12_377" ] }
r1cs-std = { path = "../r1cs-std", default-features = false, features = [ "jubjub", "bls12_377" ] }
rand_xorshift = { version = "0.2" } rand_xorshift = { version = "0.2" }

+ 2
- 2
crypto-primitives/src/commitment/blake2s/constraints.rs

@ -5,7 +5,7 @@ use crate::{
prf::blake2s::constraints::{blake2s_gadget, Blake2sOutputGadget}, prf::blake2s::constraints::{blake2s_gadget, Blake2sOutputGadget},
CommitmentGadget, CommitmentGadget,
}; };
use algebra::{Field, PrimeField};
use algebra_core::{Field, PrimeField};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
use core::borrow::Borrow; use core::borrow::Borrow;
@ -117,7 +117,7 @@ mod test {
}, },
*, *,
}; };
use algebra::{fields::bls12_381::Fr, test_rng};
use algebra::{jubjub::Fq as 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; use rand::Rng;

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

@ -1,5 +1,5 @@
use crate::CommitmentScheme; use crate::CommitmentScheme;
use algebra::Field;
use algebra_core::Field;
use core::fmt::Debug; use core::fmt::Debug;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;

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

@ -1,4 +1,4 @@
use algebra::{Field, PrimeField};
use algebra_core::{Field, PrimeField};
use crate::commitment::{ use crate::commitment::{
injective_map::{InjectiveMap, PedersenCommCompressor}, injective_map::{InjectiveMap, PedersenCommCompressor},
@ -12,7 +12,7 @@ use crate::commitment::{
}; };
pub use crate::crh::injective_map::constraints::InjectiveMapGadget; pub use crate::crh::injective_map::constraints::InjectiveMapGadget;
use algebra::groups::Group;
use algebra_core::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};

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

@ -7,7 +7,7 @@ use super::{
CommitmentScheme, CommitmentScheme,
}; };
pub use crate::crh::injective_map::InjectiveMap; pub use crate::crh::injective_map::InjectiveMap;
use algebra::groups::Group;
use algebra_core::groups::Group;
#[cfg(feature = "r1cs")] #[cfg(feature = "r1cs")]
pub mod constraints; pub mod constraints;

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

@ -1,8 +1,8 @@
use algebra::UniformRand;
use algebra_core::UniformRand;
use core::{fmt::Debug, hash::Hash}; use core::{fmt::Debug, hash::Hash};
use rand::Rng; use rand::Rng;
use algebra::bytes::ToBytes;
use algebra_core::bytes::ToBytes;
pub mod blake2s; pub mod blake2s;
pub mod injective_map; pub mod injective_map;

+ 10
- 8
crypto-primitives/src/commitment/pedersen/constraints.rs

@ -2,11 +2,13 @@ use crate::{
commitment::pedersen::{PedersenCommitment, PedersenParameters, PedersenRandomness}, commitment::pedersen::{PedersenCommitment, PedersenParameters, PedersenRandomness},
crh::pedersen::PedersenWindow, crh::pedersen::PedersenWindow,
}; };
use algebra::{to_bytes, Group, ToBytes};
use algebra_core::{
fields::{Field, PrimeField},
to_bytes, Group, ToBytes,
};
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use crate::commitment::CommitmentGadget; use crate::commitment::CommitmentGadget;
use algebra::fields::{Field, PrimeField};
use core::{borrow::Borrow, marker::PhantomData}; use core::{borrow::Borrow, marker::PhantomData};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
@ -171,6 +173,11 @@ where
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use algebra::{
jubjub::{Fq, Fr, JubJubProjective as JubJub},
test_rng, ProjectiveCurve, UniformRand,
};
use crate::{ use crate::{
commitment::{ commitment::{
pedersen::{ pedersen::{
@ -180,14 +187,9 @@ mod test {
}, },
crh::pedersen::PedersenWindow, crh::pedersen::PedersenWindow,
}; };
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,
jubjub::JubJubGadget, prelude::*, test_constraint_system::TestConstraintSystem,
}; };
#[test] #[test]

+ 5
- 4
crypto-primitives/src/commitment/pedersen/mod.rs

@ -1,14 +1,15 @@
use crate::{Error, Vec}; use crate::{Error, Vec};
use algebra::{
bytes::ToBytes, groups::Group, BitIterator, Field, FpParameters, PrimeField, ToConstraintField,
UniformRand,
use algebra_core::{
bytes::ToBytes,
groups::Group,
io::{Result as IoResult, Write},
BitIterator, Field, FpParameters, PrimeField, ToConstraintField, UniformRand,
}; };
use core::marker::PhantomData; use core::marker::PhantomData;
use rand::Rng; use rand::Rng;
use super::CommitmentScheme; use super::CommitmentScheme;
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::{

+ 13
- 14
crypto-primitives/src/crh/bowe_hopwood/constraints.rs

@ -1,16 +1,14 @@
use algebra::Field;
use core::hash::Hash;
use core::{borrow::Borrow, hash::Hash, marker::PhantomData};
use crate::crh::{ use crate::crh::{
bowe_hopwood::{BoweHopwoodPedersenCRH, BoweHopwoodPedersenParameters, CHUNK_SIZE}, bowe_hopwood::{BoweHopwoodPedersenCRH, BoweHopwoodPedersenParameters, CHUNK_SIZE},
pedersen::PedersenWindow, pedersen::PedersenWindow,
FixedLengthCRHGadget, FixedLengthCRHGadget,
}; };
use algebra::groups::Group;
use algebra_core::{groups::Group, Field};
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;
#[derive(Derivative)] #[derive(Derivative)]
@ -125,38 +123,39 @@ impl
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use rand::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::{ use algebra::{
curves::edwards_sw6::EdwardsProjective as Edwards, fields::sw6::fr::Fr, test_rng,
ProjectiveCurve,
jubjub::{Fq as Fr, JubJubProjective as JubJub},
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,
test_constraint_system::TestConstraintSystem, uint8::UInt8,
alloc::AllocGadget, jubjub::JubJubGadget, test_constraint_system::TestConstraintSystem,
uint8::UInt8,
}; };
use rand::Rng;
type TestCRH = BoweHopwoodPedersenCRH<Edwards, Window>;
type TestCRHGadget = BoweHopwoodPedersenCRHGadget<Edwards, Fr, EdwardsSWGadget>;
type TestCRH = BoweHopwoodPedersenCRH<JubJub, Window>;
type TestCRHGadget = BoweHopwoodPedersenCRHGadget<JubJub, Fr, JubJubGadget>;
#[derive(Clone, PartialEq, Eq, Hash)] #[derive(Clone, PartialEq, Eq, Hash)]
pub(super) struct Window; pub(super) struct Window;
impl PedersenWindow for Window { impl PedersenWindow for Window {
const WINDOW_SIZE: usize = 90;
const WINDOW_SIZE: usize = 63;
const NUM_WINDOWS: usize = 8; const NUM_WINDOWS: usize = 8;
} }
fn generate_input<CS: ConstraintSystem<Fr>, R: Rng>( fn generate_input<CS: ConstraintSystem<Fr>, R: Rng>(
mut cs: CS, mut cs: CS,
rng: &mut R, rng: &mut R,
) -> ([u8; 270], Vec<UInt8>) {
let mut input = [1u8; 270];
) -> ([u8; 189], Vec<UInt8>) {
let mut input = [1u8; 189];
rng.fill_bytes(&mut input); rng.fill_bytes(&mut input);
let mut input_bytes = vec![]; let mut input_bytes = vec![];

+ 5
- 5
crypto-primitives/src/crh/bowe_hopwood/mod.rs

@ -9,7 +9,7 @@ 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_core::{biginteger::BigInteger, fields::PrimeField, groups::Group};
use ff_fft::cfg_chunks; use ff_fft::cfg_chunks;
#[cfg(feature = "r1cs")] #[cfg(feature = "r1cs")]
@ -173,22 +173,22 @@ mod test {
crh::{bowe_hopwood::BoweHopwoodPedersenCRH, pedersen::PedersenWindow}, crh::{bowe_hopwood::BoweHopwoodPedersenCRH, pedersen::PedersenWindow},
FixedLengthCRH, FixedLengthCRH,
}; };
use algebra::{curves::edwards_sw6::EdwardsProjective, test_rng};
use algebra::{jubjub::JubJubProjective, test_rng};
#[test] #[test]
fn test_simple_bh() { fn test_simple_bh() {
#[derive(Clone)] #[derive(Clone)]
struct TestWindow {} struct TestWindow {}
impl PedersenWindow for TestWindow { impl PedersenWindow for TestWindow {
const WINDOW_SIZE: usize = 90;
const WINDOW_SIZE: usize = 63;
const NUM_WINDOWS: usize = 8; const NUM_WINDOWS: usize = 8;
} }
let rng = &mut test_rng(); let rng = &mut test_rng();
let params = let params =
<BoweHopwoodPedersenCRH<EdwardsProjective, TestWindow> as FixedLengthCRH>::setup(rng)
<BoweHopwoodPedersenCRH<JubJubProjective, TestWindow> as FixedLengthCRH>::setup(rng)
.unwrap(); .unwrap();
<BoweHopwoodPedersenCRH<EdwardsProjective, TestWindow> as FixedLengthCRH>::evaluate(
<BoweHopwoodPedersenCRH<JubJubProjective, TestWindow> as FixedLengthCRH>::evaluate(
&params, &params,
&[1, 2, 3], &[1, 2, 3],
) )

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

@ -1,4 +1,4 @@
use algebra::Field;
use algebra_core::Field;
use core::fmt::Debug; use core::fmt::Debug;
use crate::crh::FixedLengthCRH; use crate::crh::FixedLengthCRH;

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

@ -9,7 +9,7 @@ use crate::crh::{
FixedLengthCRHGadget, FixedLengthCRHGadget,
}; };
use algebra::{
use algebra_core::{
curves::{ curves::{
models::{ModelParameters, TEModelParameters}, models::{ModelParameters, TEModelParameters},
twisted_edwards_extended::{GroupAffine as TEAffine, GroupProjective as TEProjective}, twisted_edwards_extended::{GroupAffine as TEAffine, GroupProjective as TEProjective},

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

@ -1,5 +1,5 @@
use crate::{CryptoError, Error}; use crate::{CryptoError, Error};
use algebra::bytes::ToBytes;
use algebra_core::bytes::ToBytes;
use core::{fmt::Debug, hash::Hash, marker::PhantomData}; use core::{fmt::Debug, hash::Hash, marker::PhantomData};
use rand::Rng; use rand::Rng;
@ -7,7 +7,7 @@ use super::{
pedersen::{PedersenCRH, PedersenParameters, PedersenWindow}, pedersen::{PedersenCRH, PedersenParameters, PedersenWindow},
FixedLengthCRH, FixedLengthCRH,
}; };
use algebra::{
use algebra_core::{
curves::{ curves::{
models::{ModelParameters, TEModelParameters}, models::{ModelParameters, TEModelParameters},
twisted_edwards_extended::{GroupAffine as TEAffine, GroupProjective as TEProjective}, twisted_edwards_extended::{GroupAffine as TEAffine, GroupProjective as TEProjective},

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

@ -1,4 +1,4 @@
use algebra::bytes::ToBytes;
use algebra_core::bytes::ToBytes;
use core::hash::Hash; use core::hash::Hash;
use rand::Rng; use rand::Rng;

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

@ -2,7 +2,7 @@ use crate::crh::{
pedersen::{PedersenCRH, PedersenParameters, PedersenWindow}, pedersen::{PedersenCRH, PedersenParameters, PedersenWindow},
FixedLengthCRHGadget, FixedLengthCRHGadget,
}; };
use algebra::{Field, Group};
use algebra_core::{Field, Group};
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
@ -119,14 +119,12 @@ mod test {
FixedLengthCRH, FixedLengthCRHGadget, FixedLengthCRH, FixedLengthCRHGadget,
}; };
use algebra::{ use algebra::{
curves::{jubjub::JubJubProjective as JubJub, ProjectiveCurve},
fields::bls12_381::fr::Fr,
test_rng,
jubjub::{Fq as Fr, JubJubProjective as JubJub},
test_rng, ProjectiveCurve,
}; };
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
use r1cs_std::{ use r1cs_std::{
groups::curves::twisted_edwards::jubjub::JubJubGadget, prelude::*,
test_constraint_system::TestConstraintSystem,
jubjub::JubJubGadget, prelude::*, test_constraint_system::TestConstraintSystem,
}; };
use rand::Rng; use rand::Rng;

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

@ -8,7 +8,7 @@ use rand::Rng;
use rayon::prelude::*; use rayon::prelude::*;
use crate::crh::FixedLengthCRH; use crate::crh::FixedLengthCRH;
use algebra::{groups::Group, Field, ToConstraintField};
use algebra_core::{groups::Group, Field, ToConstraintField};
use ff_fft::cfg_chunks; use ff_fft::cfg_chunks;
#[cfg(feature = "r1cs")] #[cfg(feature = "r1cs")]

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

@ -42,7 +42,7 @@ pub use self::{
pub type Error = Box<dyn std::error::Error>; pub type Error = Box<dyn std::error::Error>;
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
pub type Error = Box<dyn algebra::Error>;
pub type Error = Box<dyn algebra_core::Error>;
#[derive(Debug)] #[derive(Debug)]
pub enum CryptoError { pub enum CryptoError {
@ -69,4 +69,4 @@ impl std::error::Error for CryptoError {
} }
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
impl algebra::Error for CryptoError {}
impl algebra_core::Error for CryptoError {}

+ 3
- 6
crypto-primitives/src/merkle_tree/constraints.rs

@ -1,4 +1,4 @@
use algebra::Field;
use algebra_core::Field;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::{boolean::AllocatedBit, prelude::*}; use r1cs_std::{boolean::AllocatedBit, prelude::*};
@ -185,16 +185,13 @@ mod test {
}, },
merkle_tree::*, merkle_tree::*,
}; };
use algebra::{curves::jubjub::JubJubAffine as JubJub, fields::jubjub::fq::Fq};
use algebra::jubjub::{Fq, JubJubAffine as JubJub};
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
use rand::SeedableRng; use rand::SeedableRng;
use rand_xorshift::XorShiftRng; use rand_xorshift::XorShiftRng;
use super::*; use super::*;
use r1cs_std::{
groups::curves::twisted_edwards::jubjub::JubJubGadget,
test_constraint_system::TestConstraintSystem,
};
use r1cs_std::{jubjub::JubJubGadget, test_constraint_system::TestConstraintSystem};
#[derive(Clone)] #[derive(Clone)]
pub(super) struct Window4x256; pub(super) struct Window4x256;

+ 4
- 4
crypto-primitives/src/merkle_tree/mod.rs

@ -1,5 +1,5 @@
use crate::{crh::FixedLengthCRH, Error, Vec}; use crate::{crh::FixedLengthCRH, Error, Vec};
use algebra::{bytes::ToBytes, io::Cursor};
use algebra_core::{bytes::ToBytes, io::Cursor};
use core::fmt; use core::fmt;
#[cfg(feature = "r1cs")] #[cfg(feature = "r1cs")]
@ -264,12 +264,12 @@ impl std::error::Error for MerkleTreeError {
} }
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
impl algebra::Error for MerkleTreeError {}
impl algebra_core::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 {
algebra::log2(number) as usize
algebra_core::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.
@ -371,7 +371,7 @@ mod test {
crh::{pedersen::*, *}, crh::{pedersen::*, *},
merkle_tree::*, merkle_tree::*,
}; };
use algebra::{curves::jubjub::JubJubAffine as JubJub, Zero};
use algebra::{jubjub::JubJubAffine as JubJub, Zero};
use rand::SeedableRng; use rand::SeedableRng;
use rand_xorshift::XorShiftRng; use rand_xorshift::XorShiftRng;

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

@ -1,4 +1,4 @@
use algebra::Field;
use algebra_core::Field;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;

+ 3
- 4
crypto-primitives/src/nizk/gm17/constraints.rs

@ -1,5 +1,5 @@
use crate::nizk::{gm17::Gm17, NIZKVerifierGadget}; use crate::nizk::{gm17::Gm17, NIZKVerifierGadget};
use algebra::{AffineCurve, Field, PairingEngine, ToConstraintField};
use algebra_core::{AffineCurve, Field, PairingEngine, ToConstraintField};
use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
@ -404,12 +404,11 @@ mod test {
use super::*; use super::*;
use algebra::{ use algebra::{
curves::bls12_377::Bls12_377,
fields::bls12_377::{Fq, Fr},
bls12_377::{Bls12_377, Fq, Fr},
test_rng, BitIterator, PrimeField, test_rng, BitIterator, PrimeField,
}; };
use r1cs_std::{ use r1cs_std::{
boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget,
bls12_377::PairingGadget as Bls12_377PairingGadget, boolean::Boolean,
test_constraint_system::TestConstraintSystem, test_constraint_system::TestConstraintSystem,
}; };
use rand::Rng; use rand::Rng;

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

@ -1,5 +1,5 @@
use crate::Error; use crate::Error;
use algebra::PairingEngine;
use algebra_core::PairingEngine;
use gm17::{ use gm17::{
create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof, create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof,
Parameters, PreparedVerifyingKey, Proof, VerifyingKey, Parameters, PreparedVerifyingKey, Proof, VerifyingKey,
@ -7,7 +7,7 @@ use gm17::{
use r1cs_core::ConstraintSynthesizer; use r1cs_core::ConstraintSynthesizer;
use rand::Rng; use rand::Rng;
use algebra::ToConstraintField;
use algebra_core::ToConstraintField;
use core::marker::PhantomData; use core::marker::PhantomData;
use super::NIZK; use super::NIZK;

+ 3
- 4
crypto-primitives/src/nizk/groth16/constraints.rs

@ -1,5 +1,5 @@
use crate::nizk::{groth16::Groth16, NIZKVerifierGadget}; use crate::nizk::{groth16::Groth16, NIZKVerifierGadget};
use algebra::{AffineCurve, Field, PairingEngine, ToConstraintField};
use algebra_core::{AffineCurve, Field, PairingEngine, ToConstraintField};
use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;
@ -351,12 +351,11 @@ mod test {
use super::*; use super::*;
use algebra::{ use algebra::{
curves::bls12_377::Bls12_377,
fields::bls12_377::{Fq, Fr},
bls12_377::{Bls12_377, Fq, Fr},
test_rng, BitIterator, PrimeField, test_rng, BitIterator, PrimeField,
}; };
use r1cs_std::{ use r1cs_std::{
boolean::Boolean, pairing::bls12_377::PairingGadget as Bls12_377PairingGadget,
bls12_377::PairingGadget as Bls12_377PairingGadget, boolean::Boolean,
test_constraint_system::TestConstraintSystem, test_constraint_system::TestConstraintSystem,
}; };
use rand::Rng; use rand::Rng;

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

@ -1,5 +1,5 @@
use crate::Error; use crate::Error;
use algebra::PairingEngine;
use algebra_core::PairingEngine;
use groth16::{ use groth16::{
create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof, create_random_proof, generate_random_parameters, prepare_verifying_key, verify_proof,
Parameters, PreparedVerifyingKey, Proof, VerifyingKey, Parameters, PreparedVerifyingKey, Proof, VerifyingKey,
@ -7,7 +7,7 @@ use groth16::{
use r1cs_core::ConstraintSynthesizer; use r1cs_core::ConstraintSynthesizer;
use rand::Rng; use rand::Rng;
use algebra::ToConstraintField;
use algebra_core::ToConstraintField;
use core::marker::PhantomData; use core::marker::PhantomData;
use super::NIZK; use super::NIZK;

+ 8
- 5
crypto-primitives/src/nizk/mod.rs

@ -1,4 +1,4 @@
use algebra::bytes::ToBytes;
use algebra_core::bytes::ToBytes;
use rand::Rng; use rand::Rng;
#[cfg(feature = "gm17")] #[cfg(feature = "gm17")]
@ -59,7 +59,10 @@ mod test {
#[test] #[test]
fn test_gm17() { fn test_gm17() {
use crate::nizk::{gm17::Gm17, NIZK}; use crate::nizk::{gm17::Gm17, NIZK};
use algebra::{curves::bls12_381::Bls12_381, fields::bls12_381::Fr, One};
use algebra::{
bls12_377::{Bls12_377, Fr},
One,
};
use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSynthesizer, ConstraintSystem, SynthesisError};
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
@ -104,13 +107,13 @@ mod test {
let rng = &mut test_rng(); let rng = &mut test_rng();
let parameters = Gm17::<Bls12_381, R1CSCircuit, [Fr]>::setup(circuit, rng).unwrap();
let parameters = Gm17::<Bls12_377, R1CSCircuit, [Fr]>::setup(circuit, rng).unwrap();
let proof = let proof =
Gm17::<Bls12_381, R1CSCircuit, [Fr]>::prove(&parameters.0, circuit, rng).unwrap();
Gm17::<Bls12_377, R1CSCircuit, [Fr]>::prove(&parameters.0, circuit, rng).unwrap();
let result = let result =
Gm17::<Bls12_381, R1CSCircuit, [Fr]>::verify(&parameters.1, &[Fr::one(), sum], &proof)
Gm17::<Bls12_377, R1CSCircuit, [Fr]>::verify(&parameters.1, &[Fr::one(), sum], &proof)
.unwrap(); .unwrap();
assert!(result); assert!(result);
} }

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

@ -1,4 +1,4 @@
use algebra::PrimeField;
use algebra_core::PrimeField;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use crate::prf::PRFGadget; use crate::prf::PRFGadget;
@ -499,7 +499,7 @@ impl PRFGadget for Blake2sGadget
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use algebra::fields::bls12_377::fr::Fr;
use algebra::jubjub::Fq as Fr;
use digest::{FixedOutput, Input}; use digest::{FixedOutput, Input};
use rand::{Rng, SeedableRng}; use rand::{Rng, SeedableRng};
use rand_xorshift::XorShiftRng; use rand_xorshift::XorShiftRng;

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

@ -1,4 +1,4 @@
use algebra::Field;
use algebra_core::Field;
use core::fmt::Debug; use core::fmt::Debug;
use crate::prf::PRF; use crate::prf::PRF;

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

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

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

@ -1,4 +1,4 @@
use algebra::Field;
use algebra_core::Field;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;

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

@ -1,5 +1,5 @@
use crate::Error; use crate::Error;
use algebra::bytes::ToBytes;
use algebra_core::bytes::ToBytes;
use core::hash::Hash; use core::hash::Hash;
use rand::Rng; use rand::Rng;
@ -54,8 +54,7 @@ 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, test_rng, to_bytes, ToBytes,
UniformRand,
groups::Group, jubjub::JubJubAffine as JubJub, test_rng, to_bytes, ToBytes, UniformRand,
}; };
use blake2::Blake2s; use blake2::Blake2s;
@ -90,13 +89,13 @@ mod 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 test_rng(); let rng = &mut test_rng();
sign_and_verify::<SchnorrSignature<Edwards, Blake2s>>(message.as_bytes());
failed_verification::<SchnorrSignature<Edwards, Blake2s>>(
sign_and_verify::<SchnorrSignature<JubJub, Blake2s>>(message.as_bytes());
failed_verification::<SchnorrSignature<JubJub, Blake2s>>(
message.as_bytes(), message.as_bytes(),
"Bad message".as_bytes(), "Bad message".as_bytes(),
); );
let random_scalar = to_bytes!(<Edwards as Group>::ScalarField::rand(rng)).unwrap();
randomize_and_verify::<SchnorrSignature<Edwards, Blake2s>>(
let random_scalar = to_bytes!(<JubJub as Group>::ScalarField::rand(rng)).unwrap();
randomize_and_verify::<SchnorrSignature<JubJub, Blake2s>>(
message.as_bytes(), message.as_bytes(),
&random_scalar.as_slice(), &random_scalar.as_slice(),
); );

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

@ -1,4 +1,4 @@
use algebra::{groups::Group, Field};
use algebra_core::{groups::Group, Field};
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
use r1cs_std::prelude::*; use r1cs_std::prelude::*;

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

@ -1,5 +1,5 @@
use crate::{Error, SignatureScheme, Vec}; use crate::{Error, SignatureScheme, Vec};
use algebra::{
use algebra_core::{
bytes::ToBytes, bytes::ToBytes,
fields::{Field, PrimeField}, fields::{Field, PrimeField},
groups::Group, groups::Group,

+ 12
- 1
r1cs-std/Cargo.toml

@ -29,7 +29,18 @@ derivative = { version = "1", features = ["use_core"] }
[dev-dependencies] [dev-dependencies]
rand = { version = "0.7", default-features = false } rand = { version = "0.7", default-features = false }
rand_xorshift = { version = "0.2" } rand_xorshift = { version = "0.2" }
# Currently this means that all downstream users of `r1cs-std` will be using
# `algebra` with the `bls12_381` feature.
algebra = { path = "../algebra", default-features = false, features = [ "bls12_381" ] }
[features] [features]
default = ["std"] default = ["std"]
std = ["algebra/std", "r1cs-core/std"]
full = [ "bls12_377", "jubjub", "edwards_bls12", "edwards_sw6", ]
bls12_377 = [ "algebra/bls12_377" ]
jubjub = [ "algebra/jubjub" ]
edwards_bls12 = [ "algebra/edwards_bls12" ]
edwards_sw6 = [ "algebra/edwards_sw6" ]
std = [ "algebra/std" ]
parallel = [ "std", "algebra/parallel" ]

+ 1
- 1
r1cs-std/src/bits/boolean.rs

@ -834,7 +834,7 @@ impl CondSelectGadget for Boolean {
mod test { mod test {
use super::{AllocatedBit, Boolean}; use super::{AllocatedBit, Boolean};
use crate::{prelude::*, test_constraint_system::TestConstraintSystem}; use crate::{prelude::*, test_constraint_system::TestConstraintSystem};
use algebra::{fields::bls12_381::Fr, BitIterator, Field, One, PrimeField, UniformRand, Zero};
use algebra::{bls12_381::Fr, BitIterator, Field, One, PrimeField, UniformRand, Zero};
use core::str::FromStr; use core::str::FromStr;
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
use rand::SeedableRng; use rand::SeedableRng;

+ 1
- 1
r1cs-std/src/bits/uint32.rs

@ -344,7 +344,7 @@ impl ConditionalEqGadget for UInt32 {
mod test { mod test {
use super::UInt32; use super::UInt32;
use crate::{bits::boolean::Boolean, test_constraint_system::TestConstraintSystem, Vec}; use crate::{bits::boolean::Boolean, test_constraint_system::TestConstraintSystem, Vec};
use algebra::{fields::bls12_381::Fr, One, Zero};
use algebra::{bls12_381::Fr, One, Zero};
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
use rand::{Rng, SeedableRng}; use rand::{Rng, SeedableRng};
use rand_xorshift::XorShiftRng; use rand_xorshift::XorShiftRng;

+ 1
- 1
r1cs-std/src/bits/uint8.rs

@ -298,7 +298,7 @@ impl AllocGadget for UInt8 {
mod test { mod test {
use super::UInt8; use super::UInt8;
use crate::{prelude::*, test_constraint_system::TestConstraintSystem, Vec}; use crate::{prelude::*, test_constraint_system::TestConstraintSystem, Vec};
use algebra::fields::bls12_381::Fr;
use algebra::bls12_381::Fr;
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
use rand::{Rng, SeedableRng}; use rand::{Rng, SeedableRng};
use rand_xorshift::XorShiftRng; use rand_xorshift::XorShiftRng;

+ 0
- 8
r1cs-std/src/fields/bls12_377.rs

@ -1,8 +0,0 @@
use algebra::fields::bls12_377::{Fq, Fq12Parameters, Fq2Parameters, Fq6Parameters};
use super::{fp::FpGadget, fp12::Fp12Gadget, fp2::Fp2Gadget, fp6_3over2::Fp6Gadget};
pub type FqGadget = FpGadget<Fq>;
pub type Fq2Gadget = Fp2Gadget<Fq2Parameters, Fq>;
pub type Fq6Gadget = Fp6Gadget<Fq6Parameters, Fq>;
pub type Fq12Gadget = Fp12Gadget<Fq12Parameters, Fq>;

+ 0
- 4
r1cs-std/src/fields/edwards_bls12.rs

@ -1,4 +0,0 @@
use crate::fields::fp::FpGadget;
use algebra::fields::edwards_bls12::fq::Fq;
pub type FqGadget = FpGadget<Fq>;

+ 0
- 4
r1cs-std/src/fields/edwards_sw6.rs

@ -1,4 +0,0 @@
use crate::fields::fp::FpGadget;
use algebra::fields::edwards_sw6::fq::Fq;
pub type FqGadget = FpGadget<Fq>;

+ 0
- 6
r1cs-std/src/fields/jubjub.rs

@ -1,6 +0,0 @@
use algebra::fields::jubjub::fq::Fq;
use crate::fields::fp::FpGadget;
// JubJub Fq uses BLS12-381 Fr.
pub type FqGadget = FpGadget<Fq>;

+ 18
- 101
r1cs-std/src/fields/mod.rs

@ -9,11 +9,6 @@ pub mod fp12;
pub mod fp2; pub mod fp2;
pub mod fp6_3over2; pub mod fp6_3over2;
pub mod bls12_377;
pub mod edwards_bls12;
pub mod edwards_sw6;
pub mod jubjub;
pub trait FieldGadget<F: Field, ConstraintF: Field>: pub trait FieldGadget<F: Field, ConstraintF: Field>:
Sized Sized
+ Clone + Clone
@ -235,7 +230,7 @@ pub trait FieldGadget:
} }
#[cfg(test)] #[cfg(test)]
mod test {
pub(crate) mod tests {
use rand::{self, SeedableRng}; use rand::{self, SeedableRng};
use rand_xorshift::XorShiftRng; use rand_xorshift::XorShiftRng;
@ -243,18 +238,15 @@ mod test {
use algebra::{test_rng, BitIterator, Field, UniformRand}; use algebra::{test_rng, BitIterator, Field, UniformRand};
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
fn field_test<
FE: Field,
ConstraintF: Field,
F: FieldGadget<FE, ConstraintF>,
CS: ConstraintSystem<ConstraintF>,
>(
mut cs: CS,
a: F,
b: F,
) {
let a_native = a.get_value().unwrap();
let b_native = b.get_value().unwrap();
#[allow(dead_code)]
pub(crate) fn field_test<FE: Field, ConstraintF: Field, F: FieldGadget<FE, ConstraintF>>() {
let mut cs = TestConstraintSystem::<ConstraintF>::new();
let mut rng = test_rng();
let a_native = FE::rand(&mut rng);
let b_native = FE::rand(&mut rng);
let a = F::alloc(&mut cs.ns(|| "generate_a"), || Ok(a_native)).unwrap();
let b = F::alloc(&mut cs.ns(|| "generate_b"), || Ok(b_native)).unwrap();
let zero = F::zero(cs.ns(|| "zero")).unwrap(); let zero = F::zero(cs.ns(|| "zero")).unwrap();
let zero_native = zero.get_value().unwrap(); let zero_native = zero.get_value().unwrap();
@ -447,17 +439,22 @@ mod test {
) )
.unwrap(); .unwrap();
assert_eq!(ab_true.get_value().unwrap(), a_native + &b_native); assert_eq!(ab_true.get_value().unwrap(), a_native + &b_native);
if !cs.is_satisfied() {
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
assert!(cs.is_satisfied());
} }
fn random_frobenius_tests<
#[allow(dead_code)]
pub(crate) fn frobenius_tests<
FE: Field, FE: Field,
ConstraintF: Field, ConstraintF: Field,
F: FieldGadget<FE, ConstraintF>, F: FieldGadget<FE, ConstraintF>,
CS: ConstraintSystem<ConstraintF>,
>( >(
mut cs: CS,
maxpower: usize, maxpower: usize,
) { ) {
let mut cs = TestConstraintSystem::<ConstraintF>::new();
let mut rng = XorShiftRng::seed_from_u64(1231275789u64); let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
for i in 0..=maxpower { for i in 0..=maxpower {
let mut a = FE::rand(&mut rng); let mut a = FE::rand(&mut rng);
@ -469,87 +466,7 @@ mod test {
assert_eq!(a_gadget.get_value().unwrap(), a); assert_eq!(a_gadget.get_value().unwrap(), a);
} }
}
#[test]
fn bls12_377_field_gadgets_test() {
use crate::fields::bls12_377::{Fq12Gadget, Fq2Gadget, Fq6Gadget, FqGadget};
use algebra::fields::bls12_377::{Fq, Fq12, Fq2, Fq6};
let mut cs = TestConstraintSystem::<Fq>::new();
let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
let a = FqGadget::alloc(&mut cs.ns(|| "generate_a"), || Ok(Fq::rand(&mut rng))).unwrap();
let b = FqGadget::alloc(&mut cs.ns(|| "generate_b"), || Ok(Fq::rand(&mut rng))).unwrap();
field_test(cs.ns(|| "test_fq"), a, b);
if !cs.is_satisfied() {
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
let c = Fq2Gadget::alloc(&mut cs.ns(|| "generate_c"), || Ok(Fq2::rand(&mut rng))).unwrap();
let d = Fq2Gadget::alloc(&mut cs.ns(|| "generate_d"), || Ok(Fq2::rand(&mut rng))).unwrap();
field_test(cs.ns(|| "test_fq2"), c, d);
random_frobenius_tests::<Fq2, _, Fq2Gadget, _>(cs.ns(|| "test_frob_fq2"), 13);
if !cs.is_satisfied() {
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
let a = Fq6Gadget::alloc(&mut cs.ns(|| "generate_e"), || Ok(Fq6::rand(&mut rng))).unwrap();
let b = Fq6Gadget::alloc(&mut cs.ns(|| "generate_f"), || Ok(Fq6::rand(&mut rng))).unwrap();
field_test(cs.ns(|| "test_fq6"), a, b);
random_frobenius_tests::<Fq6, _, Fq6Gadget, _>(cs.ns(|| "test_frob_fq6"), 13);
if !cs.is_satisfied() {
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
let c =
Fq12Gadget::alloc(&mut cs.ns(|| "generate_g"), || Ok(Fq12::rand(&mut rng))).unwrap();
let d =
Fq12Gadget::alloc(&mut cs.ns(|| "generate_h"), || Ok(Fq12::rand(&mut rng))).unwrap();
field_test(cs.ns(|| "test_fq12"), c, d);
random_frobenius_tests::<Fq12, _, Fq12Gadget, _>(cs.ns(|| "test_frob_fq12"), 13);
if !cs.is_satisfied() {
println!("Here!");
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
assert!(cs.is_satisfied());
}
#[test]
fn jubjub_field_gadgets_test() {
use crate::fields::jubjub::FqGadget;
use algebra::fields::jubjub::fq::Fq;
let mut cs = TestConstraintSystem::<Fq>::new();
let mut rng = test_rng();
let a = FqGadget::alloc(&mut cs.ns(|| "generate_a"), || Ok(Fq::rand(&mut rng))).unwrap();
let b = FqGadget::alloc(&mut cs.ns(|| "generate_b"), || Ok(Fq::rand(&mut rng))).unwrap();
field_test(cs.ns(|| "test_fq"), a, b);
if !cs.is_satisfied() {
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
assert!(cs.is_satisfied());
}
#[test]
fn edwards_field_gadgets_test() {
use crate::fields::edwards_bls12::FqGadget;
use algebra::fields::edwards_bls12::fq::Fq;
let mut cs = TestConstraintSystem::<Fq>::new();
let mut rng = test_rng();
let a = FqGadget::alloc(&mut cs.ns(|| "generate_a"), || Ok(Fq::rand(&mut rng))).unwrap();
let b = FqGadget::alloc(&mut cs.ns(|| "generate_b"), || Ok(Fq::rand(&mut rng))).unwrap();
field_test(cs.ns(|| "test_fq"), a, b);
if !cs.is_satisfied() {
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
assert!(cs.is_satisfied()); assert!(cs.is_satisfied());
} }
} }

+ 2
- 5
r1cs-std/src/groups/curves/short_weierstrass/bls12/mod.rs

@ -14,13 +14,12 @@ use crate::{
use core::fmt::Debug; use core::fmt::Debug;
pub mod bls12_377;
pub type G1Gadget<P> = AffineGadget< pub type G1Gadget<P> = AffineGadget<
<P as Bls12Parameters>::G1Parameters, <P as Bls12Parameters>::G1Parameters,
<P as Bls12Parameters>::Fp, <P as Bls12Parameters>::Fp,
FpGadget<<P as Bls12Parameters>::Fp>, FpGadget<<P as Bls12Parameters>::Fp>,
>; >;
pub type G2Gadget<P> = pub type G2Gadget<P> =
AffineGadget<<P as Bls12Parameters>::G2Parameters, <P as Bls12Parameters>::Fp, Fp2G<P>>; AffineGadget<<P as Bls12Parameters>::G2Parameters, <P as Bls12Parameters>::Fp, Fp2G<P>>;
@ -33,9 +32,7 @@ pub struct G1PreparedGadget(pub G1Gadget

);

impl<P: Bls12Parameters> G1PreparedGadget<P> { impl<P: Bls12Parameters> G1PreparedGadget<P> {
pub fn get_value(&self) -> Option<G1Prepared<P>> { pub fn get_value(&self) -> Option<G1Prepared<P>> {
Some(G1Prepared::from_affine(
self.0.get_value().unwrap().into_affine(),
))
Some(G1Prepared::from(self.0.get_value().unwrap().into_affine()))
} }
pub fn from_affine<CS: ConstraintSystem<P::Fp>>( pub fn from_affine<CS: ConstraintSystem<P::Fp>>(

+ 0
- 30
r1cs-std/src/groups/curves/twisted_edwards/edwards_bls12.rs

@ -1,30 +0,0 @@
use crate::groups::curves::twisted_edwards::AffineGadget;
use algebra::{curves::edwards_bls12::EdwardsParameters, fields::edwards_bls12::fq::Fq};
use crate::fields::edwards_bls12::FqGadget;
pub type EdwardsBlsGadget = AffineGadget<EdwardsParameters, Fq, FqGadget>;
#[cfg(test)]
mod test {
use super::EdwardsBlsGadget as EdwardsG;
use crate::{
groups::curves::twisted_edwards::test::{edwards_constraint_costs, edwards_test},
test_constraint_system::TestConstraintSystem,
};
use algebra::{curves::edwards_bls12::EdwardsParameters, fields::edwards_bls12::fq::Fq};
#[test]
fn edwards_constraint_costs_test() {
let mut cs = TestConstraintSystem::<Fq>::new();
edwards_constraint_costs::<_, EdwardsParameters, EdwardsG, _>(&mut cs);
assert!(cs.is_satisfied());
}
#[test]
fn edwards_bls12_gadget_test() {
let mut cs = TestConstraintSystem::<Fq>::new();
edwards_test::<_, EdwardsParameters, EdwardsG, _>(&mut cs);
assert!(cs.is_satisfied());
}
}

+ 0
- 30
r1cs-std/src/groups/curves/twisted_edwards/edwards_sw6.rs

@ -1,30 +0,0 @@
use crate::groups::curves::twisted_edwards::AffineGadget;
use algebra::{curves::edwards_sw6::EdwardsParameters, fields::edwards_sw6::fq::Fq};
use crate::fields::edwards_sw6::FqGadget;
pub type EdwardsSWGadget = AffineGadget<EdwardsParameters, Fq, FqGadget>;
#[cfg(test)]
mod test {
use super::EdwardsSWGadget as EdwardsG;
use crate::{
groups::curves::twisted_edwards::test::{edwards_constraint_costs, edwards_test},
test_constraint_system::TestConstraintSystem,
};
use algebra::{curves::edwards_sw6::EdwardsParameters, fields::edwards_sw6::fq::Fq};
#[test]
fn edwards_constraint_costs_test() {
let mut cs = TestConstraintSystem::<Fq>::new();
edwards_constraint_costs::<_, EdwardsParameters, EdwardsG, _>(&mut cs);
assert!(cs.is_satisfied());
}
#[test]
fn edwards_sw6_gadget_test() {
let mut cs = TestConstraintSystem::<Fq>::new();
edwards_test::<_, EdwardsParameters, EdwardsG, _>(&mut cs);
assert!(cs.is_satisfied());
}
}

+ 0
- 30
r1cs-std/src/groups/curves/twisted_edwards/jubjub.rs

@ -1,30 +0,0 @@
use crate::groups::curves::twisted_edwards::AffineGadget;
use algebra::{curves::jubjub::JubJubParameters, fields::jubjub::fq::Fq};
use crate::fields::jubjub::FqGadget;
pub type JubJubGadget = AffineGadget<JubJubParameters, Fq, FqGadget>;
#[cfg(test)]
mod test {
use super::JubJubGadget as EdwardsG;
use crate::{
groups::curves::twisted_edwards::test::{edwards_constraint_costs, edwards_test},
test_constraint_system::TestConstraintSystem,
};
use algebra::{curves::jubjub::JubJubParameters as EdwardsParameters, fields::jubjub::fq::Fq};
#[test]
fn edwards_constraint_costs_test() {
let mut cs = TestConstraintSystem::<Fq>::new();
edwards_constraint_costs::<_, EdwardsParameters, EdwardsG, _>(&mut cs);
assert!(cs.is_satisfied());
}
#[test]
fn jubjub_gadget_test() {
let mut cs = TestConstraintSystem::<Fq>::new();
edwards_test::<_, EdwardsParameters, EdwardsG, _>(&mut cs);
assert!(cs.is_satisfied());
}
}

+ 62
- 6
r1cs-std/src/groups/curves/twisted_edwards/mod.rs

@ -12,12 +12,6 @@ use crate::{prelude::*, Vec};
use core::{borrow::Borrow, marker::PhantomData}; use core::{borrow::Borrow, marker::PhantomData};
pub mod edwards_bls12;
pub mod edwards_sw6;
pub mod jubjub;
#[cfg(test)]
mod test;
#[derive(Derivative)] #[derive(Derivative)]
#[derivative(Debug, Clone)] #[derivative(Debug, Clone)]
#[derivative(Debug(bound = "P: TEModelParameters, ConstraintF: Field"))] #[derivative(Debug(bound = "P: TEModelParameters, ConstraintF: Field"))]
@ -1404,3 +1398,65 @@ where
Ok(x_bytes) Ok(x_bytes)
} }
} }
#[cfg(test)]
#[allow(dead_code)]
pub(crate) fn test<ConstraintF, P, GG>()
where
ConstraintF: Field,
P: TEModelParameters,
GG: GroupGadget<TEAffine<P>, ConstraintF, Value = TEAffine<P>>,
{
use crate::{
boolean::AllocatedBit, groups::test::group_test, prelude::*,
test_constraint_system::TestConstraintSystem,
};
use algebra::{test_rng, Group, PrimeField, UniformRand};
use rand::Rng;
group_test::<ConstraintF, TEAffine<P>, GG>();
let mut cs = TestConstraintSystem::new();
let a: TEAffine<P> = UniformRand::rand(&mut test_rng());
let gadget_a = GG::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
// Check mul_bits
let scalar: <TEAffine<P> as Group>::ScalarField = UniformRand::rand(&mut test_rng());
let native_result = a.mul(&scalar);
let mut scalar: Vec<bool> = BitIterator::new(scalar.into_repr()).collect();
// Get the scalar bits into little-endian form.
scalar.reverse();
let input = Vec::<Boolean>::alloc(cs.ns(|| "Input"), || Ok(scalar)).unwrap();
let zero = GG::zero(cs.ns(|| "zero")).unwrap();
let result = gadget_a
.mul_bits(cs.ns(|| "mul_bits"), &zero, input.iter())
.unwrap();
let gadget_value = result.get_value().expect("Gadget_result failed");
assert_eq!(native_result, gadget_value);
assert!(cs.is_satisfied());
// Test the cost of allocation, conditional selection, and point addition.
let mut cs = TestConstraintSystem::new();
let bit = AllocatedBit::alloc(&mut cs.ns(|| "bool"), || Ok(true))
.unwrap()
.into();
let mut rng = test_rng();
let a: TEAffine<P> = rng.gen();
let b: TEAffine<P> = rng.gen();
let gadget_a = GG::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
let gadget_b = GG::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap();
let alloc_cost = cs.num_constraints();
let _ =
GG::conditionally_select(&mut cs.ns(|| "cond_select"), &bit, &gadget_a, &gadget_b).unwrap();
let cond_select_cost = cs.num_constraints() - alloc_cost;
let _ = gadget_a.add(&mut cs.ns(|| "ab"), &gadget_b).unwrap();
let add_cost = cs.num_constraints() - cond_select_cost - alloc_cost;
assert_eq!(cond_select_cost, <GG as CondSelectGadget<_>>::cost());
assert_eq!(add_cost, GG::cost_of_add());
assert!(cs.is_satisfied());
}

+ 0
- 72
r1cs-std/src/groups/curves/twisted_edwards/test.rs

@ -1,72 +0,0 @@
use crate::{groups::test::group_test, prelude::*, Vec};
use algebra::{
curves::{models::TEModelParameters, twisted_edwards_extended::GroupAffine as TEAffine},
test_rng, BitIterator, Field, Group, PrimeField, UniformRand,
};
use rand::Rng;
use r1cs_core::ConstraintSystem;
pub(crate) fn edwards_test<ConstraintF, P, GG, CS>(cs: &mut CS)
where
ConstraintF: Field,
P: TEModelParameters,
GG: GroupGadget<TEAffine<P>, ConstraintF, Value = TEAffine<P>>,
CS: ConstraintSystem<ConstraintF>,
{
let a: TEAffine<P> = UniformRand::rand(&mut test_rng());
let b: TEAffine<P> = UniformRand::rand(&mut test_rng());
let gadget_a = GG::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
let gadget_b = GG::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap();
assert_eq!(gadget_a.get_value().unwrap(), a);
assert_eq!(gadget_b.get_value().unwrap(), b);
group_test::<ConstraintF, TEAffine<P>, GG, _>(
&mut cs.ns(|| "GroupTest(a, b)"),
gadget_a.clone(),
gadget_b,
);
// Check mul_bits
let scalar: <TEAffine<P> as Group>::ScalarField = UniformRand::rand(&mut test_rng());
let native_result = a.mul(&scalar);
let mut scalar: Vec<bool> = BitIterator::new(scalar.into_repr()).collect();
// Get the scalar bits into little-endian form.
scalar.reverse();
let input = Vec::<Boolean>::alloc(cs.ns(|| "Input"), || Ok(scalar)).unwrap();
let zero = GG::zero(cs.ns(|| "zero")).unwrap();
let result = gadget_a
.mul_bits(cs.ns(|| "mul_bits"), &zero, input.iter())
.unwrap();
let gadget_value = result.get_value().expect("Gadget_result failed");
assert_eq!(native_result, gadget_value);
}
pub(crate) fn edwards_constraint_costs<ConstraintF, P, GG, CS>(cs: &mut CS)
where
ConstraintF: Field,
P: TEModelParameters,
GG: GroupGadget<TEAffine<P>, ConstraintF, Value = TEAffine<P>>,
CS: ConstraintSystem<ConstraintF>,
{
use crate::boolean::AllocatedBit;
let bit = AllocatedBit::alloc(&mut cs.ns(|| "bool"), || Ok(true))
.unwrap()
.into();
let mut rng = test_rng();
let a: TEAffine<P> = rng.gen();
let b: TEAffine<P> = rng.gen();
let gadget_a = GG::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
let gadget_b = GG::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap();
let alloc_cost = cs.num_constraints();
let _ =
GG::conditionally_select(&mut cs.ns(|| "cond_select"), &bit, &gadget_a, &gadget_b).unwrap();
let cond_select_cost = cs.num_constraints() - alloc_cost;
let _ = gadget_a.add(&mut cs.ns(|| "ab"), &gadget_b).unwrap();
let add_cost = cs.num_constraints() - cond_select_cost - alloc_cost;
assert_eq!(cond_select_cost, <GG as CondSelectGadget<_>>::cost());
assert_eq!(add_cost, GG::cost_of_add());
}

+ 14
- 31
r1cs-std/src/groups/mod.rs

@ -6,10 +6,7 @@ use core::{borrow::Borrow, fmt::Debug};
pub mod curves; pub mod curves;
pub use self::curves::{
short_weierstrass::bls12,
twisted_edwards::{edwards_sw6, jubjub},
};
pub use self::curves::short_weierstrass::bls12;
pub trait GroupGadget<G: Group, ConstraintF: Field>: pub trait GroupGadget<G: Group, ConstraintF: Field>:
Sized Sized
@ -165,21 +162,19 @@ pub trait GroupGadget:
mod test { mod test {
use algebra::{test_rng, Field}; use algebra::{test_rng, Field};
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
use rand::Rng;
use crate::{prelude::*, test_constraint_system::TestConstraintSystem}; use crate::{prelude::*, test_constraint_system::TestConstraintSystem};
use algebra::groups::Group; use algebra::groups::Group;
pub(crate) fn group_test<
ConstraintF: Field,
G: Group,
GG: GroupGadget<G, ConstraintF>,
CS: ConstraintSystem<ConstraintF>,
>(
cs: &mut CS,
a: GG,
b: GG,
) {
pub(crate) fn group_test<ConstraintF: Field, G: Group, GG: GroupGadget<G, ConstraintF>>() {
let mut cs = TestConstraintSystem::<ConstraintF>::new();
let mut rng = test_rng();
let a_native = G::rand(&mut rng);
let b_native = G::rand(&mut rng);
let a = GG::alloc(&mut cs.ns(|| "generate_a"), || Ok(a_native)).unwrap();
let b = GG::alloc(&mut cs.ns(|| "generate_b"), || Ok(b_native)).unwrap();
let zero = GG::zero(cs.ns(|| "Zero")).unwrap(); let zero = GG::zero(cs.ns(|| "Zero")).unwrap();
assert_eq!(zero, zero); assert_eq!(zero, zero);
@ -217,21 +212,9 @@ mod test {
let _ = b let _ = b
.to_bytes_strict(&mut cs.ns(|| "b ToBytes Strict")) .to_bytes_strict(&mut cs.ns(|| "b ToBytes Strict"))
.unwrap(); .unwrap();
}
#[test]
fn jubjub_group_gadgets_test() {
use crate::groups::jubjub::JubJubGadget;
use algebra::{curves::jubjub::JubJubProjective, fields::jubjub::fq::Fq};
let mut cs = TestConstraintSystem::<Fq>::new();
let mut rng = test_rng();
let a: JubJubProjective = rng.gen();
let b: JubJubProjective = rng.gen();
let a = JubJubGadget::alloc(&mut cs.ns(|| "generate_a"), || Ok(a)).unwrap();
let b = JubJubGadget::alloc(&mut cs.ns(|| "generate_b"), || Ok(b)).unwrap();
group_test::<_, JubJubProjective, _, _>(&mut cs.ns(|| "GroupTest(a, b)"), a, b);
if !cs.is_satisfied() {
println!("{:?}", cs.which_is_unsatisfied().unwrap());
}
assert!(cs.is_satisfied());
} }
} }

r1cs-std/src/groups/curves/short_weierstrass/bls12/bls12_377.rs → r1cs-std/src/instantiated/bls12_377/curves.rs

@ -1,14 +1,11 @@
use crate::groups::bls12::{
G1Gadget as Bls12G1Gadget, G1PreparedGadget as Bls12G1PreparedGadget,
G2Gadget as Bls12G2Gadget, G2PreparedGadget as Bls12G2PreparedGadget,
};
use algebra::curves::bls12_377::Bls12_377Parameters;
use crate::groups::bls12;
use algebra::bls12_377::Parameters;
pub type G1Gadget = Bls12G1Gadget<Bls12_377Parameters>;
pub type G2Gadget = Bls12G2Gadget<Bls12_377Parameters>;
pub type G1Gadget = bls12::G1Gadget<Parameters>;
pub type G2Gadget = bls12::G2Gadget<Parameters>;
pub type G1PreparedGadget = Bls12G1PreparedGadget<Bls12_377Parameters>;
pub type G2PreparedGadget = Bls12G2PreparedGadget<Bls12_377Parameters>;
pub type G1PreparedGadget = bls12::G1PreparedGadget<Parameters>;
pub type G2PreparedGadget = bls12::G2PreparedGadget<Parameters>;
#[cfg(test)] #[cfg(test)]
mod test { mod test {
@ -16,11 +13,7 @@ mod test {
use super::{G1Gadget, G2Gadget}; use super::{G1Gadget, G2Gadget};
use crate::{prelude::*, test_constraint_system::TestConstraintSystem, Vec}; use crate::{prelude::*, test_constraint_system::TestConstraintSystem, Vec};
use algebra::{
curves::bls12_377::{G1Projective as G1, G2Projective as G2},
fields::bls12_377::{Fq, Fr},
test_rng, AffineCurve, BitIterator, PrimeField, ProjectiveCurve,
};
use algebra::{bls12_377::*, test_rng, AffineCurve, BitIterator, PrimeField, ProjectiveCurve};
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
#[test] #[test]
@ -34,8 +27,8 @@ mod test {
.into(); .into();
let mut rng = test_rng(); let mut rng = test_rng();
let a: G1 = rng.gen();
let b: G1 = rng.gen();
let a: G1Projective = rng.gen();
let b: G1Projective = rng.gen();
let gadget_a = G1Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap(); let gadget_a = G1Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
let gadget_b = G1Gadget::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap(); let gadget_b = G1Gadget::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap();
let alloc_cost = cs.num_constraints(); let alloc_cost = cs.num_constraints();
@ -67,8 +60,8 @@ mod test {
.into(); .into();
let mut rng = test_rng(); let mut rng = test_rng();
let a: G2 = rng.gen();
let b: G2 = rng.gen();
let a: G2Projective = rng.gen();
let b: G2Projective = rng.gen();
let gadget_a = G2Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap(); let gadget_a = G2Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
let gadget_b = G2Gadget::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap(); let gadget_b = G2Gadget::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap();
let alloc_cost = cs.num_constraints(); let alloc_cost = cs.num_constraints();
@ -98,8 +91,8 @@ mod test {
let mut cs = TestConstraintSystem::<Fq>::new(); let mut cs = TestConstraintSystem::<Fq>::new();
let a = G1::rand(&mut rng);
let b = G1::rand(&mut rng);
let a = G1Projective::rand(&mut rng);
let b = G1Projective::rand(&mut rng);
let a_affine = a.into_affine(); let a_affine = a.into_affine();
let b_affine = b.into_affine(); let b_affine = b.into_affine();
let mut gadget_a = G1Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap(); let mut gadget_a = G1Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
@ -167,8 +160,8 @@ mod test {
let mut cs = TestConstraintSystem::<Fq>::new(); let mut cs = TestConstraintSystem::<Fq>::new();
let mut rng = test_rng(); let mut rng = test_rng();
let a: G2 = rng.gen();
let b: G2 = rng.gen();
let a: G2Projective = rng.gen();
let b: G2Projective = rng.gen();
let a_affine = a.into_affine(); let a_affine = a.into_affine();
let b_affine = b.into_affine(); let b_affine = b.into_affine();

+ 27
- 0
r1cs-std/src/instantiated/bls12_377/fields.rs

@ -0,0 +1,27 @@
use algebra::bls12_377::{Fq, Fq12Parameters, Fq2Parameters, Fq6Parameters};
use crate::fields::{fp::FpGadget, fp12::Fp12Gadget, fp2::Fp2Gadget, fp6_3over2::Fp6Gadget};
pub type FqGadget = FpGadget<Fq>;
pub type Fq2Gadget = Fp2Gadget<Fq2Parameters, Fq>;
pub type Fq6Gadget = Fp6Gadget<Fq6Parameters, Fq>;
pub type Fq12Gadget = Fp12Gadget<Fq12Parameters, Fq>;
#[test]
fn bls12_377_field_gadgets_test() {
use super::*;
use crate::fields::tests::*;
use algebra::bls12_377::{Fq, Fq12, Fq2, Fq6};
field_test::<_, Fq, FqGadget>();
frobenius_tests::<Fq, Fq, FqGadget>(13);
field_test::<_, Fq, Fq2Gadget>();
frobenius_tests::<Fq2, Fq, Fq2Gadget>(13);
field_test::<_, Fq, Fq6Gadget>();
frobenius_tests::<Fq6, Fq, Fq6Gadget>(13);
field_test::<_, Fq, Fq12Gadget>();
frobenius_tests::<Fq12, Fq, Fq12Gadget>(13);
}

+ 7
- 0
r1cs-std/src/instantiated/bls12_377/mod.rs

@ -0,0 +1,7 @@
mod curves;
mod fields;
mod pairing;
pub use curves::*;
pub use fields::*;
pub use pairing::*;

+ 8
- 0
r1cs-std/src/instantiated/bls12_377/pairing.rs

@ -0,0 +1,8 @@
use algebra::bls12_377::Parameters;
pub type PairingGadget = crate::pairing::bls12::PairingGadget<Parameters>;
#[test]
fn test() {
crate::pairing::tests::bilinearity_test::<algebra::Bls12_377, _, PairingGadget>()
}

+ 11
- 0
r1cs-std/src/instantiated/edwards_bls12/curves.rs

@ -0,0 +1,11 @@
use crate::groups::curves::twisted_edwards::AffineGadget;
use algebra::edwards_bls12::*;
use crate::edwards_bls12::FqGadget;
pub type EdwardsBlsGadget = AffineGadget<EdwardsParameters, Fq, FqGadget>;
#[test]
fn test() {
crate::groups::curves::twisted_edwards::test::<_, EdwardsParameters, EdwardsBlsGadget>();
}

+ 9
- 0
r1cs-std/src/instantiated/edwards_bls12/fields.rs

@ -0,0 +1,9 @@
use crate::fields::fp::FpGadget;
use algebra::edwards_bls12::fq::Fq;
pub type FqGadget = FpGadget<Fq>;
#[test]
fn test() {
crate::fields::tests::field_test::<_, Fq, FqGadget>();
}

+ 5
- 0
r1cs-std/src/instantiated/edwards_bls12/mod.rs

@ -0,0 +1,5 @@
mod curves;
mod fields;
pub use curves::*;
pub use fields::*;

+ 11
- 0
r1cs-std/src/instantiated/edwards_sw6/curves.rs

@ -0,0 +1,11 @@
use crate::groups::curves::twisted_edwards::AffineGadget;
use algebra::edwards_sw6::*;
use crate::edwards_sw6::FqGadget;
pub type EdwardsSWGadget = AffineGadget<EdwardsParameters, Fq, FqGadget>;
#[test]
fn test() {
crate::groups::curves::twisted_edwards::test::<_, EdwardsParameters, EdwardsSWGadget>();
}

+ 9
- 0
r1cs-std/src/instantiated/edwards_sw6/fields.rs

@ -0,0 +1,9 @@
use crate::fields::fp::FpGadget;
use algebra::edwards_sw6::fq::Fq;
pub type FqGadget = FpGadget<Fq>;
#[test]
fn test() {
crate::fields::tests::field_test::<_, Fq, FqGadget>();
}

+ 5
- 0
r1cs-std/src/instantiated/edwards_sw6/mod.rs

@ -0,0 +1,5 @@
mod curves;
mod fields;
pub use curves::*;
pub use fields::*;

+ 11
- 0
r1cs-std/src/instantiated/jubjub/curves.rs

@ -0,0 +1,11 @@
use crate::groups::curves::twisted_edwards::AffineGadget;
use algebra::jubjub::*;
use crate::jubjub::FqGadget;
pub type JubJubGadget = AffineGadget<JubJubParameters, Fq, FqGadget>;
#[test]
fn test() {
crate::groups::curves::twisted_edwards::test::<Fq, _, JubJubGadget>();
}

+ 8
- 0
r1cs-std/src/instantiated/jubjub/fields.rs

@ -0,0 +1,8 @@
use crate::fields::fp::FpGadget;
pub type FqGadget = FpGadget<algebra::jubjub::Fq>;
#[test]
fn test() {
crate::fields::tests::field_test::<_, algebra::jubjub::Fq, FqGadget>();
}

+ 5
- 0
r1cs-std/src/instantiated/jubjub/mod.rs

@ -0,0 +1,5 @@
mod curves;
mod fields;
pub use curves::*;
pub use fields::*;

+ 11
- 0
r1cs-std/src/instantiated/mod.rs

@ -0,0 +1,11 @@
#[cfg(feature = "bls12_377")]
pub mod bls12_377;
#[cfg(feature = "edwards_bls12")]
pub mod edwards_bls12;
#[cfg(feature = "edwards_sw6")]
pub mod edwards_sw6;
#[cfg(feature = "jubjub")]
pub mod jubjub;

+ 21
- 33
r1cs-std/src/lib.rs

@ -1,37 +1,10 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
#![deny(
unused_import_braces,
unused_qualifications,
trivial_casts,
trivial_numeric_casts
)]
#![deny(
unused_qualifications,
variant_size_differences,
stable_features,
unreachable_pub
)]
#![deny(
non_shorthand_field_patterns,
unused_attributes,
unused_imports,
unused_extern_crates
)]
#![deny(
renamed_and_removed_lints,
stable_features,
unused_allocation,
unused_comparisons,
bare_trait_objects
)]
#![deny(
const_err,
unused_must_use,
unused_mut,
unused_unsafe,
private_in_public,
unsafe_code
)]
#![deny(unused_import_braces, unused_qualifications, trivial_casts)]
#![deny(trivial_numeric_casts, variant_size_differences, unreachable_pub)]
#![deny(non_shorthand_field_patterns, unused_attributes, unused_imports)]
#![deny(unused_extern_crates, renamed_and_removed_lints, unused_allocation)]
#![deny(unused_comparisons, bare_trait_objects, const_err, unused_must_use)]
#![deny(unused_mut, unused_unsafe, private_in_public, unsafe_code)]
#![forbid(unsafe_code)] #![forbid(unsafe_code)]
#[cfg(all(test, not(feature = "std")))] #[cfg(all(test, not(feature = "std")))]
@ -69,6 +42,20 @@ pub mod fields;
pub mod groups; pub mod groups;
mod instantiated;
#[cfg(feature = "bls12_377")]
pub use instantiated::bls12_377;
#[cfg(feature = "edwards_bls12")]
pub use instantiated::edwards_bls12;
#[cfg(feature = "edwards_sw6")]
pub use instantiated::edwards_sw6;
#[cfg(feature = "jubjub")]
pub use instantiated::jubjub;
pub mod pairing; pub mod pairing;
pub mod alloc; pub mod alloc;
@ -82,6 +69,7 @@ pub mod prelude {
eq::*, eq::*,
fields::FieldGadget, fields::FieldGadget,
groups::GroupGadget, groups::GroupGadget,
instantiated::*,
pairing::PairingGadget, pairing::PairingGadget,
select::*, select::*,
}; };

+ 0
- 4
r1cs-std/src/pairing/bls12/bls12_377.rs

@ -1,4 +0,0 @@
use crate::pairing::bls12::PairingGadget as Bls12PG;
use algebra::curves::bls12_377::Bls12_377Parameters;
pub type PairingGadget = Bls12PG<Bls12_377Parameters>;

+ 0
- 0
r1cs-std/src/pairing/bls12/bls12_381.rs


+ 3
- 30
r1cs-std/src/pairing/bls12/mod.rs

@ -7,20 +7,11 @@ use crate::{
groups::bls12::{G1Gadget, G1PreparedGadget, G2Gadget, G2PreparedGadget}, groups::bls12::{G1Gadget, G1PreparedGadget, G2Gadget, G2PreparedGadget},
}; };
use algebra::{ use algebra::{
curves::{
bls12::{
Bls12, Bls12Parameters, G1Affine, G1Prepared, G1Projective, G2Affine, G2Prepared,
G2Projective, TwistType,
},
models::ModelParameters,
PairingCurve,
},
fields::{fp12_2over3over2::Fp12, BitIterator},
curves::bls12::{Bls12, Bls12Parameters, TwistType},
fields::BitIterator,
}; };
use core::marker::PhantomData; use core::marker::PhantomData;
pub mod bls12_377;
pub struct PairingGadget<P: Bls12Parameters>(PhantomData<P>); pub struct PairingGadget<P: Bls12Parameters>(PhantomData<P>);
type Fp2G<P> = Fp2Gadget<<P as Bls12Parameters>::Fp2Params, <P as Bls12Parameters>::Fp>; type Fp2G<P> = Fp2Gadget<<P as Bls12Parameters>::Fp2Params, <P as Bls12Parameters>::Fp>;
@ -71,25 +62,7 @@ impl PairingGadget

{

} }
} }
impl<P: Bls12Parameters> PG<Bls12<P>, P::Fp> for PairingGadget<P>
where
G1Affine<P>: PairingCurve<
BaseField = <P::G1Parameters as ModelParameters>::BaseField,
ScalarField = <P::G1Parameters as ModelParameters>::ScalarField,
Projective = G1Projective<P>,
PairWith = G2Affine<P>,
Prepared = G1Prepared<P>,
PairingResult = Fp12<P::Fp12Params>,
>,
G2Affine<P>: PairingCurve<
BaseField = <P::G2Parameters as ModelParameters>::BaseField,
ScalarField = <P::G1Parameters as ModelParameters>::ScalarField,
Projective = G2Projective<P>,
PairWith = G1Affine<P>,
Prepared = G2Prepared<P>,
PairingResult = Fp12<P::Fp12Params>,
>,
{
impl<P: Bls12Parameters> PG<Bls12<P>, P::Fp> for PairingGadget<P> {
type G1Gadget = G1Gadget<P>; type G1Gadget = G1Gadget<P>;
type G2Gadget = G2Gadget<P>; type G2Gadget = G2Gadget<P>;
type G1PreparedGadget = G1PreparedGadget<P>; type G1PreparedGadget = G1PreparedGadget<P>;

+ 36
- 52
r1cs-std/src/pairing/mod.rs

@ -4,7 +4,6 @@ use core::fmt::Debug;
use r1cs_core::{ConstraintSystem, SynthesisError}; use r1cs_core::{ConstraintSystem, SynthesisError};
pub mod bls12; pub mod bls12;
pub use self::bls12::bls12_377;
pub trait PairingGadget<PairingE: PairingEngine, ConstraintF: Field> { pub trait PairingGadget<PairingE: PairingEngine, ConstraintF: Field> {
type G1Gadget: GroupGadget<PairingE::G1Projective, ConstraintF>; type G1Gadget: GroupGadget<PairingE::G1Projective, ConstraintF>;
@ -56,67 +55,53 @@ pub trait PairingGadget {
} }
#[cfg(test)] #[cfg(test)]
mod test {
use crate::{test_constraint_system::TestConstraintSystem, Vec};
use algebra::{BitIterator, Field, One};
pub(crate) mod tests {
use crate::{
bits::boolean::Boolean, prelude::*, test_constraint_system::TestConstraintSystem, Vec,
};
use algebra::{
test_rng, BitIterator, Field, PairingEngine, PrimeField, ProjectiveCurve, UniformRand,
};
use r1cs_core::ConstraintSystem; use r1cs_core::ConstraintSystem;
#[test]
fn bls12_377_gadget_bilinearity_test() {
use algebra::{
fields::{
bls12_377::{fq::Fq, fr::Fr},
PrimeField,
},
PairingEngine, ProjectiveCurve,
};
use super::bls12_377::PairingGadget;
use crate::{
groups::bls12::bls12_377::{G1Gadget, G1PreparedGadget, G2Gadget, G2PreparedGadget},
pairing::PairingGadget as _,
prelude::*,
};
use algebra::curves::bls12_377::{Bls12_377, G1Projective, G2Projective};
use core::ops::Mul;
let mut cs = TestConstraintSystem::<Fq>::new();
// let a: G1Projective = rand::random();
// let b: G2Projective = rand::random();
// let s: Fr = rand::random();
#[allow(dead_code)]
pub(crate) fn bilinearity_test<
E: PairingEngine,
ConstraintF: Field,
P: PairingGadget<E, ConstraintF>,
>() {
let mut cs = TestConstraintSystem::<ConstraintF>::new();
let a: G1Projective = G1Projective::prime_subgroup_generator();
let b: G2Projective = G2Projective::prime_subgroup_generator();
let s: Fr = Fr::one() + &Fr::one();
let mut rng = test_rng();
let a = E::G1Projective::rand(&mut rng);
let b = E::G2Projective::rand(&mut rng);
let s = E::Fr::rand(&mut rng);
let sa = a.mul(&s);
let sb = b.mul(&s);
let mut sa = a;
sa.mul_assign(s);
let mut sb = b;
sb.mul_assign(s);
let a_g = G1Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
let b_g = G2Gadget::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap();
let sa_g = G1Gadget::alloc(&mut cs.ns(|| "sa"), || Ok(sa)).unwrap();
let sb_g = G2Gadget::alloc(&mut cs.ns(|| "sb"), || Ok(sb)).unwrap();
let a_g = P::G1Gadget::alloc(&mut cs.ns(|| "a"), || Ok(a)).unwrap();
let b_g = P::G2Gadget::alloc(&mut cs.ns(|| "b"), || Ok(b)).unwrap();
let sa_g = P::G1Gadget::alloc(&mut cs.ns(|| "sa"), || Ok(sa)).unwrap();
let sb_g = P::G2Gadget::alloc(&mut cs.ns(|| "sb"), || Ok(sb)).unwrap();
let a_prep_g = G1PreparedGadget::from_affine(&mut cs.ns(|| "a_prep"), &a_g).unwrap();
let b_prep_g = G2PreparedGadget::from_affine(&mut cs.ns(|| "b_prep"), &b_g).unwrap();
let a_prep_g = P::prepare_g1(&mut cs.ns(|| "a_prep"), &a_g).unwrap();
let b_prep_g = P::prepare_g2(&mut cs.ns(|| "b_prep"), &b_g).unwrap();
let sa_prep_g = G1PreparedGadget::from_affine(&mut cs.ns(|| "sa_prep"), &sa_g).unwrap();
let sb_prep_g = G2PreparedGadget::from_affine(&mut cs.ns(|| "sb_prep"), &sb_g).unwrap();
let sa_prep_g = P::prepare_g1(&mut cs.ns(|| "sa_prep"), &sa_g).unwrap();
let sb_prep_g = P::prepare_g2(&mut cs.ns(|| "sb_prep"), &sb_g).unwrap();
let (ans1_g, ans1_n) = { let (ans1_g, ans1_n) = {
let ans_g =
PairingGadget::pairing(cs.ns(|| "pair(sa, b)"), sa_prep_g, b_prep_g.clone())
.unwrap();
let ans_n = Bls12_377::pairing(sa, b);
let ans_g = P::pairing(cs.ns(|| "pair(sa, b)"), sa_prep_g, b_prep_g.clone()).unwrap();
let ans_n = E::pairing(sa, b);
(ans_g, ans_n) (ans_g, ans_n)
}; };
let (ans2_g, ans2_n) = { let (ans2_g, ans2_n) = {
let ans_g =
PairingGadget::pairing(cs.ns(|| "pair(a, sb)"), a_prep_g.clone(), sb_prep_g)
.unwrap();
let ans_n = Bls12_377::pairing(a, sb);
let ans_g = P::pairing(cs.ns(|| "pair(a, sb)"), a_prep_g.clone(), sb_prep_g).unwrap();
let ans_n = E::pairing(a, sb);
(ans_g, ans_n) (ans_g, ans_n)
}; };
@ -125,9 +110,8 @@ mod test {
.map(Boolean::constant) .map(Boolean::constant)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut ans_g =
PairingGadget::pairing(cs.ns(|| "pair(a, b)"), a_prep_g, b_prep_g).unwrap();
let mut ans_n = Bls12_377::pairing(a, b);
let mut ans_g = P::pairing(cs.ns(|| "pair(a, b)"), a_prep_g, b_prep_g).unwrap();
let mut ans_n = E::pairing(a, b);
ans_n = ans_n.pow(s.into_repr()); ans_n = ans_n.pow(s.into_repr());
ans_g = ans_g.pow(cs.ns(|| "pow"), &s_iter).unwrap(); ans_g = ans_g.pow(cs.ns(|| "pow"), &s_iter).unwrap();

Loading…
Cancel
Save