Skip to content

Commit

Permalink
Helpers and refactoring
Browse files Browse the repository at this point in the history
Signed-off-by: lovesh <[email protected]>
  • Loading branch information
lovesh committed Nov 17, 2022
1 parent eb3bc88 commit 5ae2bd4
Show file tree
Hide file tree
Showing 42 changed files with 248 additions and 311 deletions.
4 changes: 2 additions & 2 deletions bbs_plus/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "bbs_plus"
version = "0.8.0"
version = "0.9.0"
edition.workspace = true
authors.workspace = true
license.workspace = true
Expand All @@ -19,7 +19,7 @@ ark-std.workspace = true
digest.workspace = true
rayon = {workspace = true, optional = true}
schnorr_pok = { version = "0.7.0", default-features = false, path = "../schnorr_pok" }
dock_crypto_utils = { version = "0.5.0", default-features = false, path = "../utils" }
dock_crypto_utils = { version = "0.6.0", default-features = false, path = "../utils" }
serde.workspace = true
serde_with.workspace = true
zeroize.workspace = true
Expand Down
1 change: 1 addition & 0 deletions bbs_plus/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use serde::Serialize;

#[derive(Debug, Serialize)]
pub enum BBSPlusError {
CannotInvert0,
NoMessageToSign,
MessageCountIncompatibleWithSigParams(usize, usize),
InvalidMessageIdx(usize),
Expand Down
2 changes: 1 addition & 1 deletion bbs_plus/src/proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ where

let r1 = E::Fr::rand(rng);
let r2 = E::Fr::rand(rng);
let r3 = r1.inverse().unwrap();
let r3 = r1.inverse().ok_or(BBSPlusError::CannotInvert0)?;

// b = (e+x) * A = g1 + h_0*s + sum(h_i*m_i) for all i in I
let b = params.b(
Expand Down
18 changes: 8 additions & 10 deletions bbs_plus/src/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
//! ```
use crate::error::BBSPlusError;
use ark_ec::{msm::VariableBaseMSM, AffineCurve, PairingEngine, ProjectiveCurve};
use ark_ec::{AffineCurve, PairingEngine, ProjectiveCurve};
use ark_ff::{to_bytes, PrimeField, SquareRootField};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, SerializationError};
use ark_std::collections::BTreeMap;
Expand All @@ -49,6 +49,7 @@ use zeroize::Zeroize;
use dock_crypto_utils::hashing_utils::{
field_elem_from_seed, projective_group_elem_from_try_and_incr,
};
use dock_crypto_utils::msm::variable_base_msm;
use dock_crypto_utils::serde_utils::*;

#[cfg(feature = "parallel")]
Expand Down Expand Up @@ -207,10 +208,7 @@ macro_rules! impl_sig_params {
blinding: &E::Fr,
) -> Result<E::$group_affine, BBSPlusError> {
#[cfg(feature = "parallel")]
let (mut bases, mut scalars): (
Vec<E::$group_affine>,
Vec<<<E as ark_ec::PairingEngine>::Fr as PrimeField>::BigInt>,
) = {
let (mut bases, mut scalars): (Vec<E::$group_affine>, Vec<E::Fr>) = {
// Need to manually check that no message index exceeds the maximum number of messages allowed
// because this function can be called with only uncommitted messages; so size of BTreeMap is
// not representative of the number of messages
Expand All @@ -220,12 +218,12 @@ macro_rules! impl_sig_params {
}
}
cfg_into_iter!(messages)
.map(|(i, msg)| (self.h[i].clone(), msg.into_repr()))
.map(|(i, msg)| (self.h[i].clone(), *msg))
.unzip()
};

#[cfg(not(feature = "parallel"))]
let (mut bases, mut scalars) = {
let (mut bases, mut scalars): (Vec<E::$group_affine>, Vec<E::Fr>) = {
let mut bases = Vec::with_capacity(messages.len());
let mut scalars = Vec::with_capacity(messages.len());
for (i, msg) in messages.into_iter() {
Expand All @@ -234,14 +232,14 @@ macro_rules! impl_sig_params {
return Err(BBSPlusError::InvalidMessageIdx(i));
}
bases.push(self.h[i].clone());
scalars.push(msg.into_repr());
scalars.push(*msg);
}
(bases, scalars)
};

bases.push(self.h_0.clone());
scalars.push(blinding.into_repr());
Ok(VariableBaseMSM::multi_scalar_mul(&bases, &scalars).into_affine())
scalars.push(*blinding);
Ok(variable_base_msm(&bases, &scalars).into_affine())
}

/// Compute `b` from the paper (equivalently 'A*{e+x}').
Expand Down
2 changes: 1 addition & 1 deletion bbs_plus/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ macro_rules! impl_signature_alg {

let e = E::Fr::rand(rng);
// 1/(e+x)
let e_plus_x_inv = (e + sk.0).inverse().unwrap();
let e_plus_x_inv = (e + sk.0).inverse().ok_or(BBSPlusError::CannotInvert0)?;

// {commitment + b} * {1/(e+x)}
let commitment_plus_b = b.add_mixed(commitment);
Expand Down
4 changes: 2 additions & 2 deletions benches/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ authors.workspace = true
license.workspace = true

[dependencies]
bbs_plus = { version = "0.8.0", default-features = false, path = "../bbs_plus" }
bbs_plus = { version = "0.9.0", default-features = false, path = "../bbs_plus" }
schnorr_pok = { version = "0.7.0", default-features = false, path = "../schnorr_pok" }
vb_accumulator = { version = "0.9.0", default-features = false, path = "../vb_accumulator" }
vb_accumulator = { version = "0.10.0", default-features = false, path = "../vb_accumulator" }
test_utils = { version = "0.1.0", default-features = false, path = "../test_utils" }
ark-ff.workspace = true
ark-ec.workspace = true
Expand Down
7 changes: 1 addition & 6 deletions benches/benches/schnorr_protocol.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use ark_bls12_381::Bls12_381;
use ark_ec::msm::VariableBaseMSM;
use ark_ec::PairingEngine;
use ark_ec::{AffineCurve, ProjectiveCurve};
use ark_ff::PrimeField;
Expand Down Expand Up @@ -74,11 +73,7 @@ macro_rules! bench_vector {
.into_iter()
.map(|_| Fr::rand(&mut rng))
.collect::<Vec<_>>();
let y = VariableBaseMSM::multi_scalar_mul(
&bases,
&witnesses.iter().map(|w| w.into_repr()).collect::<Vec<_>>(),
)
.into_affine();
let y = variable_base_msm(&bases, &witnesses).into_affine();
bases_vec.push(bases);
witnesses_vec.push(witnesses);
y_vec.push(y);
Expand Down
4 changes: 2 additions & 2 deletions compressed_sigma/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "compressed_sigma"
version = "0.0.1"
version = "0.0.2"
edition.workspace = true
authors.workspace = true
license.workspace = true
Expand All @@ -15,7 +15,7 @@ ark-sponge = { version = "^0.3.0", default-features = false }
ark-poly = { version = "^0.3.0", default-features = false }
rayon = {workspace = true, optional = true}
digest.workspace = true
dock_crypto_utils = { version = "0.5.0", default-features = false, path = "../utils" }
dock_crypto_utils = { version = "0.6.0", default-features = false, path = "../utils" }

[dev-dependencies]
blake2.workspace = true
Expand Down
7 changes: 4 additions & 3 deletions compressed_sigma/src/amortized_homomorphism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ use ark_std::{
};
use digest::Digest;

use dock_crypto_utils::msm::variable_base_msm;

use crate::compressed_homomorphism;
use crate::error::CompSigmaError;
use crate::transforms::Homomorphism;

use crate::utils::{amortized_response, get_n_powers};

#[cfg(feature = "parallel")]
use rayon::prelude::*;

Expand Down Expand Up @@ -62,8 +64,7 @@ where
(0..max_size).map(|_| G::ScalarField::rand(rng)).collect()
};
let t = f.eval(&r).unwrap();
let scalars = cfg_iter!(r).map(|b| b.into_repr()).collect::<Vec<_>>();
let A = VariableBaseMSM::multi_scalar_mul(g, &scalars);
let A = variable_base_msm(g, &r);
Ok(Self {
max_size,
r,
Expand Down
27 changes: 8 additions & 19 deletions compressed_sigma/src/amortized_homomorphisms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,23 @@
//! This is for the relation R_{AMORHOM} where a many homomorphisms are applied over a single witness vector and
//! there is a commitment to the witness vector.
use ark_ec::msm::VariableBaseMSM;
use ark_ec::{AffineCurve, ProjectiveCurve};
use ark_ff::{One, PrimeField, Zero};
use ark_ff::{One, PrimeField};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, SerializationError};
use ark_std::{cfg_iter, vec, vec::Vec, UniformRand};
use ark_std::{
io::{Read, Write},
marker::PhantomData,
ops::Add,
rand::RngCore,
};
use ark_std::{vec, vec::Vec, UniformRand};
use digest::Digest;

use crate::error::CompSigmaError;
use crate::transforms::Homomorphism;

use dock_crypto_utils::hashing_utils::field_elem_from_try_and_incr;
use dock_crypto_utils::{hashing_utils::field_elem_from_try_and_incr, msm::variable_base_msm};

use crate::compressed_homomorphism;
use crate::error::CompSigmaError;
use crate::transforms::Homomorphism;
use crate::utils::get_n_powers;
#[cfg(feature = "parallel")]
use rayon::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq, CanonicalSerialize, CanonicalDeserialize)]
pub struct RandomCommitment<G: AffineCurve> {
Expand Down Expand Up @@ -93,10 +88,7 @@ impl<G: AffineCurve, F: Homomorphism<G::ScalarField, Output = G>> AmortizeHomomo
ys: &[G],
rho_powers: &[G::ScalarField],
) -> G::Projective {
let r = cfg_iter!(rho_powers[..ys.len()])
.map(|r| r.into_repr())
.collect::<Vec<_>>();
VariableBaseMSM::multi_scalar_mul(ys, &r)
variable_base_msm(ys, &rho_powers[..ys.len()])
}

/// Inner product of vectors `fs` and `rho_powers`.
Expand Down Expand Up @@ -136,9 +128,7 @@ where
(0..g.len()).map(|_| G::ScalarField::rand(rng)).collect()
};
let t = f_rho.eval(&r).unwrap();
let scalars = cfg_iter!(r).map(|b| b.into_repr()).collect::<Vec<_>>();

let A = VariableBaseMSM::multi_scalar_mul(g, &scalars);
let A = variable_base_msm(g, &r);
Ok(Self {
r,
A: A.into_affine(),
Expand Down Expand Up @@ -183,10 +173,9 @@ where
return Err(CompSigmaError::VectorLenMismatch);
}

let z_repr = cfg_iter!(self.z).map(|z| z.into_repr()).collect::<Vec<_>>();
let challenge_repr = challenge.into_repr();

if VariableBaseMSM::multi_scalar_mul(g, &z_repr) != P.mul(challenge_repr).add_mixed(A) {
if variable_base_msm(g, &self.z) != P.mul(challenge_repr).add_mixed(A) {
return Err(CompSigmaError::InvalidResponse);
}

Expand Down
33 changes: 8 additions & 25 deletions compressed_sigma/src/amortized_linear_form.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
//! Amortized sigma protocol as described in Appendix B of the paper "Compressed Sigma Protocol Theory..."
use ark_ec::msm::VariableBaseMSM;
use ark_ec::{AffineCurve, ProjectiveCurve};
use ark_ff::{PrimeField, Zero};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, SerializationError};
use ark_std::{cfg_iter, vec::Vec, UniformRand};
use ark_std::{
io::{Read, Write},
ops::Add,
rand::RngCore,
};
use ark_std::{vec::Vec, UniformRand};
use digest::Digest;

use dock_crypto_utils::ff::inner_product;
use dock_crypto_utils::{ff::inner_product, msm::variable_base_msm};

use crate::compressed_linear_form;
use crate::error::CompSigmaError;
use crate::transforms::LinearForm;

use crate::utils::{amortized_response, get_n_powers};

#[cfg(feature = "parallel")]
use rayon::prelude::*;

#[derive(Clone, Debug, PartialEq, Eq, CanonicalSerialize, CanonicalDeserialize)]
pub struct RandomCommitment<G: AffineCurve> {
/// Maximum size of the witness vectors
Expand Down Expand Up @@ -64,9 +59,8 @@ where
};
let rho = G::ScalarField::rand(rng);
let t = linear_form.eval(&r);
let scalars = cfg_iter!(r).map(|b| b.into_repr()).collect::<Vec<_>>();
// h * rho is done separately to avoid copying g
let A = VariableBaseMSM::multi_scalar_mul(g, &scalars).add(&h.mul(rho.into_repr()));
let A = variable_base_msm(g, &r).add(&h.mul(rho.into_repr()));
Ok(Self {
max_size,
r,
Expand Down Expand Up @@ -127,19 +121,13 @@ where
let count_commitments = commitments.len();
// `challenge_powers` is of form [c, c^2, c^3, ..., c^n]
let challenge_powers = get_n_powers(challenge.clone(), count_commitments);
let challenge_powers_repr = cfg_iter!(challenge_powers)
.map(|c| c.into_repr())
.collect::<Vec<_>>();

// P_tilde = A + \sum_{i}(P_i * c^i)
let mut P_tilde = A.into_projective();
P_tilde += VariableBaseMSM::multi_scalar_mul(commitments, &challenge_powers_repr);
P_tilde += variable_base_msm(commitments, &challenge_powers);

// Check g*z_tilde + h*phi == P_tilde
let z_tilde_repr = cfg_iter!(self.z_tilde)
.map(|z| z.into_repr())
.collect::<Vec<_>>();
let g_z = VariableBaseMSM::multi_scalar_mul(g, &z_tilde_repr);
let g_z = variable_base_msm(g, &self.z_tilde);
let h_phi = h.mul(self.phi);
if (g_z + h_phi) != P_tilde {
return Err(CompSigmaError::InvalidResponse);
Expand Down Expand Up @@ -221,10 +209,7 @@ pub fn prepare_for_compression<G: AffineCurve, L: LinearForm<G::ScalarField>>(
let L_tilde = linear_form.scale(new_challenge);

let challenge_powers = get_n_powers(challenge.clone(), Ps.len());
let challenge_powers_repr = cfg_iter!(challenge_powers)
.map(|c| c.into_repr())
.collect::<Vec<_>>();
let P = VariableBaseMSM::multi_scalar_mul(Ps, &challenge_powers_repr);
let P = variable_base_msm(Ps, &challenge_powers);
let Y = challenge_powers
.iter()
.zip(ys.iter())
Expand All @@ -247,10 +232,7 @@ fn calculate_Q<G: AffineCurve>(
new_challenge: &G::ScalarField,
) -> G::Projective {
let challenge_powers = get_n_powers(challenge.clone(), Ps.len());
let challenge_powers_repr = cfg_iter!(challenge_powers)
.map(|c| c.into_repr())
.collect::<Vec<_>>();
let P = VariableBaseMSM::multi_scalar_mul(Ps, &challenge_powers_repr);
let P = variable_base_msm(Ps, &challenge_powers);
let Y = challenge_powers
.iter()
.zip(ys.iter())
Expand All @@ -266,6 +248,7 @@ fn calculate_Q<G: AffineCurve>(
mod tests {
use super::*;
use ark_bls12_381::Bls12_381;
use ark_ec::msm::VariableBaseMSM;
use ark_ec::PairingEngine;
use ark_ff::Zero;
use ark_std::{
Expand Down
21 changes: 7 additions & 14 deletions compressed_sigma/src/compressed_homomorphism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ use crate::transforms::Homomorphism;
use dock_crypto_utils::hashing_utils::field_elem_from_try_and_incr;

use crate::utils::{elements_to_element_products, get_g_multiples_for_verifying_compression};
use dock_crypto_utils::ec::batch_normalize_projective_into_affine;
use dock_crypto_utils::{ec::batch_normalize_projective_into_affine, msm::variable_base_msm};

#[cfg(feature = "parallel")]
use rayon::prelude::*;

Expand Down Expand Up @@ -66,9 +67,8 @@ where
(0..g.len()).map(|_| G::ScalarField::rand(rng)).collect()
};
let t = homomorphism.eval(&r).unwrap();
let scalars = cfg_iter!(r).map(|b| b.into_repr()).collect::<Vec<_>>();

let A_hat = VariableBaseMSM::multi_scalar_mul(g, &scalars);
let A_hat = variable_base_msm(g, &r);
Ok(Self {
r,
A_hat: A_hat.into_affine(),
Expand Down Expand Up @@ -127,14 +127,8 @@ where
// Split `f` into 2 halves, `f_l` will be the 1st half and `f_r` will be the 2nd
let (f_l, f_r) = f.split_in_half();

let A = VariableBaseMSM::multi_scalar_mul(
&g_r,
&z.iter().map(|z| z.into_repr()).collect::<Vec<_>>(),
);
let B = VariableBaseMSM::multi_scalar_mul(
&g,
&z_r.iter().map(|z| z.into_repr()).collect::<Vec<_>>(),
);
let A = variable_base_msm(&g_r, &z);
let B = variable_base_msm(&g, &z_r);
let a = f_r.eval(&z).unwrap();
let b = f_l.eval(&z_r).unwrap();

Expand Down Expand Up @@ -334,9 +328,8 @@ where
let all_challenges_product = challenge_products.remove(0);

// `B_multiples` is of form [c_1^2*c_2*c_3*..*c_n, c_2^2*c_3*c_4..*c_n, ..., c_{n-1}^2*c_n, c_n^2]
let B_multiples = challenge_products
.iter()
.zip(challenge_squares.iter())
let B_multiples = cfg_iter!(challenge_products)
.zip(cfg_iter!(challenge_squares))
.map(|(c, c_sqr)| (*c * c_sqr).into_repr())
.collect::<Vec<_>>();

Expand Down
Loading

0 comments on commit 5ae2bd4

Please sign in to comment.