, Error> {
- Ok(Vec::new())
- }
-}
diff --git a/crypto-primitives/src/crh/bowe_hopwood/constraints.rs b/crypto-primitives/src/crh/bowe_hopwood/constraints.rs
deleted file mode 100644
index 7516cd2..0000000
--- a/crypto-primitives/src/crh/bowe_hopwood/constraints.rs
+++ /dev/null
@@ -1,180 +0,0 @@
-use core::{borrow::Borrow, marker::PhantomData};
-
-use crate::{
- crh::{
- bowe_hopwood::{Parameters, CHUNK_SIZE, CRH},
- pedersen::Window,
- FixedLengthCRHGadget,
- },
- Vec,
-};
-use algebra_core::{
- curves::{ModelParameters, TEModelParameters},
- Field,
-};
-use r1cs_core::{Namespace, SynthesisError};
-use r1cs_std::{
- alloc::AllocVar, groups::curves::twisted_edwards::AffineVar, prelude::*, uint8::UInt8,
-};
-
-use r1cs_std::bits::boolean::Boolean;
-
-type ConstraintF = <
::BaseField as Field>::BasePrimeField;
-
-#[derive(Derivative)]
-#[derivative(Clone(bound = "P: TEModelParameters, W: Window"))]
-pub struct ParametersVar {
- params: Parameters,
- #[doc(hidden)]
- _window: PhantomData,
-}
-
-pub struct CRHGadget>>
-where
- for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
-{
- #[doc(hidden)]
- _params: PhantomData,
- #[doc(hidden)]
- _base_field: PhantomData,
-}
-
-impl FixedLengthCRHGadget, ConstraintF> for CRHGadget
-where
- for<'a> &'a F: FieldOpsBounds<'a, P::BaseField, F>,
- F: FieldVar>,
- F: TwoBitLookupGadget, TableConstant = P::BaseField>
- + ThreeBitCondNegLookupGadget, TableConstant = P::BaseField>,
- P: TEModelParameters,
- W: Window,
-{
- type OutputVar = AffineVar;
- type ParametersVar = ParametersVar
;
-
- #[tracing::instrument(target = "r1cs", skip(parameters, input))]
- fn evaluate(
- parameters: &Self::ParametersVar,
- input: &[UInt8>],
- ) -> Result {
- // Pad the input if it is not the current length.
- let mut input_in_bits: Vec> = input
- .iter()
- .flat_map(|byte| byte.to_bits_le().unwrap())
- .collect();
- if (input_in_bits.len()) % CHUNK_SIZE != 0 {
- let current_length = input_in_bits.len();
- for _ in 0..(CHUNK_SIZE - current_length % CHUNK_SIZE) {
- input_in_bits.push(Boolean::constant(false));
- }
- }
- assert!(input_in_bits.len() % CHUNK_SIZE == 0);
- assert_eq!(parameters.params.generators.len(), W::NUM_WINDOWS);
- for generators in parameters.params.generators.iter() {
- assert_eq!(generators.len(), W::WINDOW_SIZE);
- }
-
- // Allocate new variable for the result.
- let input_in_bits = input_in_bits
- .chunks(W::WINDOW_SIZE * CHUNK_SIZE)
- .map(|x| x.chunks(CHUNK_SIZE).collect::>())
- .collect::>();
- let result = AffineVar::precomputed_base_3_bit_signed_digit_scalar_mul(
- ¶meters.params.generators,
- &input_in_bits,
- )?;
-
- Ok(result)
- }
-}
-
-impl AllocVar, ConstraintF> for ParametersVar
-where
- P: TEModelParameters,
- W: Window,
-{
- #[tracing::instrument(target = "r1cs", skip(_cs, f))]
- fn new_variable>>(
- _cs: impl Into>>,
- f: impl FnOnce() -> Result,
- _mode: AllocationMode,
- ) -> Result {
- let params = f()?.borrow().clone();
- Ok(ParametersVar {
- params,
- _window: PhantomData,
- })
- }
-}
-
-#[cfg(test)]
-mod test {
- use rand::Rng;
-
- use crate::crh::{
- bowe_hopwood::{constraints::CRHGadget, CRH},
- pedersen::Window as PedersenWindow,
- FixedLengthCRH, FixedLengthCRHGadget,
- };
- use algebra::{
- ed_on_bls12_381::{EdwardsParameters, Fq as Fr},
- test_rng, ProjectiveCurve,
- };
- use r1cs_core::{ConstraintSystem, ConstraintSystemRef};
- use r1cs_std::{alloc::AllocVar, ed_on_bls12_381::FqVar, uint8::UInt8, R1CSVar};
-
- type TestCRH = CRH;
- type TestCRHGadget = CRHGadget;
-
- #[derive(Clone, PartialEq, Eq, Hash)]
- pub(super) struct Window;
-
- impl PedersenWindow for Window {
- const WINDOW_SIZE: usize = 63;
- const NUM_WINDOWS: usize = 8;
- }
-
- fn generate_input(
- cs: ConstraintSystemRef,
- rng: &mut R,
- ) -> ([u8; 189], Vec>) {
- let mut input = [1u8; 189];
- rng.fill_bytes(&mut input);
-
- let mut input_bytes = vec![];
- for byte in input.iter() {
- input_bytes.push(UInt8::new_witness(cs.clone(), || Ok(byte)).unwrap());
- }
- (input, input_bytes)
- }
-
- #[test]
- fn test_native_equality() {
- let rng = &mut test_rng();
- let cs = ConstraintSystem::::new_ref();
-
- let (input, input_var) = generate_input(cs.clone(), rng);
- println!("number of constraints for input: {}", cs.num_constraints());
-
- let parameters = TestCRH::setup(rng).unwrap();
- let primitive_result = TestCRH::evaluate(¶meters, &input).unwrap();
-
- let parameters_var =
- >::ParametersVar::new_witness(
- r1cs_core::ns!(cs, "parameters_var"),
- || Ok(¶meters),
- )
- .unwrap();
- println!(
- "number of constraints for input + params: {}",
- cs.num_constraints()
- );
-
- let result_var = TestCRHGadget::evaluate(¶meters_var, &input_var).unwrap();
-
- println!("number of constraints total: {}", cs.num_constraints());
-
- let primitive_result = primitive_result.into_affine();
- assert_eq!(primitive_result, result_var.value().unwrap().into_affine());
- assert!(cs.is_satisfied().unwrap());
- }
-}
diff --git a/crypto-primitives/src/crh/bowe_hopwood/mod.rs b/crypto-primitives/src/crh/bowe_hopwood/mod.rs
deleted file mode 100644
index 3d5f5d2..0000000
--- a/crypto-primitives/src/crh/bowe_hopwood/mod.rs
+++ /dev/null
@@ -1,197 +0,0 @@
-use crate::{Error, Vec};
-use core::{
- fmt::{Debug, Formatter, Result as FmtResult},
- marker::PhantomData,
-};
-use rand::Rng;
-#[cfg(feature = "parallel")]
-use rayon::prelude::*;
-
-use super::pedersen;
-use crate::crh::FixedLengthCRH;
-use algebra_core::{
- biginteger::BigInteger, curves::twisted_edwards_extended::GroupProjective as TEProjective,
- fields::PrimeField, ProjectiveCurve, TEModelParameters, UniformRand,
-};
-use ff_fft::cfg_chunks;
-
-#[cfg(feature = "r1cs")]
-pub mod constraints;
-
-pub const CHUNK_SIZE: usize = 3;
-
-#[derive(Derivative)]
-#[derivative(Clone(bound = ""), Default(bound = ""))]
-pub struct Parameters {
- pub generators: Vec>>,
-}
-
-pub struct CRH {
- group: PhantomData,
- window: PhantomData,
-}
-
-impl CRH {
- pub fn create_generators(rng: &mut R) -> Vec>> {
- let mut generators = Vec::new();
- for _ in 0..W::NUM_WINDOWS {
- let mut generators_for_segment = Vec::new();
- let mut base = TEProjective::rand(rng);
- for _ in 0..W::WINDOW_SIZE {
- generators_for_segment.push(base);
- for _ in 0..4 {
- base.double_in_place();
- }
- }
- generators.push(generators_for_segment);
- }
- generators
- }
-}
-
-impl FixedLengthCRH for CRH {
- const INPUT_SIZE_BITS: usize = pedersen::CRH::, W>::INPUT_SIZE_BITS;
- type Output = TEProjective;
- type Parameters = Parameters
;
-
- fn setup(rng: &mut R) -> Result {
- fn calculate_num_chunks_in_segment() -> usize {
- let upper_limit = F::modulus_minus_one_div_two();
- let mut c = 0;
- let mut range = F::BigInt::from(2_u64);
- while range < upper_limit {
- range.muln(4);
- c += 1;
- }
-
- c
- }
-
- let maximum_num_chunks_in_segment = calculate_num_chunks_in_segment::();
- if W::WINDOW_SIZE > maximum_num_chunks_in_segment {
- return Err(format!(
- "Bowe-Hopwood-PedersenCRH hash must have a window size resulting in scalars < (p-1)/2, \
- maximum segment size is {}",
- maximum_num_chunks_in_segment
- )
- .into());
- }
-
- let time = start_timer!(|| format!(
- "Bowe-Hopwood-PedersenCRH::Setup: {} segments of {} 3-bit chunks; {{0,1}}^{{{}}} -> P",
- W::NUM_WINDOWS,
- W::WINDOW_SIZE,
- W::WINDOW_SIZE * W::NUM_WINDOWS * CHUNK_SIZE
- ));
- let generators = Self::create_generators(rng);
- end_timer!(time);
- Ok(Self::Parameters { generators })
- }
-
- fn evaluate(parameters: &Self::Parameters, input: &[u8]) -> Result {
- let eval_time = start_timer!(|| "BoweHopwoodPedersenCRH::Eval");
-
- if (input.len() * 8) > W::WINDOW_SIZE * W::NUM_WINDOWS * CHUNK_SIZE {
- panic!(
- "incorrect input length {:?} for window params {:?}x{:?}x{}",
- input.len(),
- W::WINDOW_SIZE,
- W::NUM_WINDOWS,
- CHUNK_SIZE,
- );
- }
-
- let mut padded_input = Vec::with_capacity(input.len());
- let input = pedersen::bytes_to_bits(input);
- // Pad the input if it is not the current length.
- padded_input.extend_from_slice(&input);
- if input.len() % CHUNK_SIZE != 0 {
- let current_length = input.len();
- for _ in 0..(CHUNK_SIZE - current_length % CHUNK_SIZE) {
- padded_input.push(false);
- }
- }
-
- assert_eq!(padded_input.len() % CHUNK_SIZE, 0);
-
- assert_eq!(
- parameters.generators.len(),
- W::NUM_WINDOWS,
- "Incorrect pp of size {:?} for window params {:?}x{:?}x{}",
- parameters.generators.len(),
- W::WINDOW_SIZE,
- W::NUM_WINDOWS,
- CHUNK_SIZE,
- );
- for generators in parameters.generators.iter() {
- assert_eq!(generators.len(), W::WINDOW_SIZE);
- }
- assert_eq!(CHUNK_SIZE, 3);
-
- // Compute sum of h_i^{sum of
- // (1-2*c_{i,j,2})*(1+c_{i,j,0}+2*c_{i,j,1})*2^{4*(j-1)} for all j in segment}
- // for all i. Described in section 5.4.1.7 in the Zcash protocol
- // specification.
-
- let result = cfg_chunks!(padded_input, W::WINDOW_SIZE * CHUNK_SIZE)
- .zip(¶meters.generators)
- .map(|(segment_bits, segment_generators)| {
- cfg_chunks!(segment_bits, CHUNK_SIZE)
- .zip(segment_generators)
- .map(|(chunk_bits, generator)| {
- let mut encoded = generator.clone();
- if chunk_bits[0] {
- encoded = encoded + generator;
- }
- if chunk_bits[1] {
- encoded += &generator.double();
- }
- if chunk_bits[2] {
- encoded = -encoded;
- }
- encoded
- })
- .sum::>()
- })
- .sum::>();
-
- end_timer!(eval_time);
-
- Ok(result)
- }
-}
-
-impl Debug for Parameters {
- fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
- write!(f, "Bowe-Hopwood-Pedersen Hash Parameters {{\n")?;
- for (i, g) in self.generators.iter().enumerate() {
- write!(f, "\t Generator {}: {:?}\n", i, g)?;
- }
- write!(f, "}}\n")
- }
-}
-
-#[cfg(test)]
-mod test {
- use crate::{
- crh::{bowe_hopwood::CRH, pedersen::Window},
- FixedLengthCRH,
- };
- use algebra::{ed_on_bls12_381::EdwardsParameters, test_rng};
-
- #[test]
- fn test_simple_bh() {
- #[derive(Clone)]
- struct TestWindow {}
- impl Window for TestWindow {
- const WINDOW_SIZE: usize = 63;
- const NUM_WINDOWS: usize = 8;
- }
-
- let rng = &mut test_rng();
- let params = as FixedLengthCRH>::setup(rng).unwrap();
- let _ =
- as FixedLengthCRH>::evaluate(¶ms, &[1, 2, 3])
- .unwrap();
- }
-}
diff --git a/crypto-primitives/src/crh/constraints.rs b/crypto-primitives/src/crh/constraints.rs
deleted file mode 100644
index 16eeba6..0000000
--- a/crypto-primitives/src/crh/constraints.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-use algebra_core::Field;
-use core::fmt::Debug;
-
-use crate::crh::FixedLengthCRH;
-use r1cs_core::SynthesisError;
-
-use r1cs_std::prelude::*;
-
-pub trait FixedLengthCRHGadget: Sized {
- type OutputVar: EqGadget
- + ToBytesGadget
- + CondSelectGadget
- + AllocVar
- + R1CSVar
- + Debug
- + Clone
- + Sized;
-
- type ParametersVar: AllocVar + Clone;
-
- fn evaluate(
- parameters: &Self::ParametersVar,
- input: &[UInt8],
- ) -> Result;
-}
diff --git a/crypto-primitives/src/crh/injective_map/constraints.rs b/crypto-primitives/src/crh/injective_map/constraints.rs
deleted file mode 100644
index 88116b0..0000000
--- a/crypto-primitives/src/crh/injective_map/constraints.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-use core::{fmt::Debug, marker::PhantomData};
-
-use crate::crh::{
- injective_map::{InjectiveMap, PedersenCRHCompressor, TECompressor},
- pedersen::{constraints as ped_constraints, Window},
- FixedLengthCRHGadget,
-};
-
-use algebra_core::{
- curves::{
- models::{ModelParameters, TEModelParameters},
- twisted_edwards_extended::GroupProjective as TEProjective,
- },
- fields::{Field, PrimeField, SquareRootField},
- ProjectiveCurve,
-};
-use r1cs_core::SynthesisError;
-use r1cs_std::{
- fields::fp::FpVar,
- groups::{curves::twisted_edwards::AffineVar as TEVar, CurveVar},
- prelude::*,
-};
-
-type ConstraintF = <::BaseField as Field>::BasePrimeField;
-
-pub trait InjectiveMapGadget<
- C: ProjectiveCurve,
- I: InjectiveMap,
- GG: CurveVar>,
-> where
- for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
-{
- type OutputVar: EqGadget>
- + ToBytesGadget>
- + CondSelectGadget>
- + AllocVar>
- + R1CSVar, Value = I::Output>
- + Debug
- + Clone
- + Sized;
-
- fn evaluate(ge: &GG) -> Result;
-}
-
-pub struct TECompressorGadget;
-
-impl InjectiveMapGadget, TECompressor, TEVar>>
- for TECompressorGadget
-where
- F: PrimeField + SquareRootField,
- P: TEModelParameters + ModelParameters,
-{
- type OutputVar = FpVar;
-
- fn evaluate(ge: &TEVar>) -> Result {
- Ok(ge.x.clone())
- }
-}
-
-pub struct PedersenCRHCompressorGadget
-where
- C: ProjectiveCurve,
- I: InjectiveMap,
- W: Window,
- GG: CurveVar>,
- for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
- IG: InjectiveMapGadget,
-{
- #[doc(hidden)]
- _compressor: PhantomData,
- #[doc(hidden)]
- _compressor_gadget: PhantomData,
- #[doc(hidden)]
- _crh: ped_constraints::CRHGadget,
-}
-
-impl FixedLengthCRHGadget, ConstraintF>
- for PedersenCRHCompressorGadget
-where
- C: ProjectiveCurve,
- I: InjectiveMap,
- GG: CurveVar>,
- for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
- IG: InjectiveMapGadget,
- W: Window,
-{
- type OutputVar = IG::OutputVar;
- type ParametersVar = ped_constraints::CRHParametersVar;
-
- #[tracing::instrument(target = "r1cs", skip(parameters, input))]
- fn evaluate(
- parameters: &Self::ParametersVar,
- input: &[UInt8>],
- ) -> Result {
- let result = ped_constraints::CRHGadget::::evaluate(parameters, input)?;
- IG::evaluate(&result)
- }
-}
diff --git a/crypto-primitives/src/crh/injective_map/mod.rs b/crypto-primitives/src/crh/injective_map/mod.rs
deleted file mode 100644
index 51dde7f..0000000
--- a/crypto-primitives/src/crh/injective_map/mod.rs
+++ /dev/null
@@ -1,59 +0,0 @@
-use crate::{CryptoError, Error};
-use algebra_core::bytes::ToBytes;
-use core::{fmt::Debug, hash::Hash, marker::PhantomData};
-use rand::Rng;
-
-use super::{pedersen, FixedLengthCRH};
-use algebra_core::curves::{
- models::{ModelParameters, TEModelParameters},
- twisted_edwards_extended::{GroupAffine as TEAffine, GroupProjective as TEProjective},
- ProjectiveCurve,
-};
-
-#[cfg(feature = "r1cs")]
-pub mod constraints;
-
-pub trait InjectiveMap {
- type Output: ToBytes + Clone + Eq + Hash + Default + Debug;
-
- fn injective_map(ge: &C::Affine) -> Result;
-}
-
-pub struct TECompressor;
-
-impl InjectiveMap> for TECompressor {
- type Output =