Skip to content

Commit

Permalink
Not allowing zero as an x-coordinate in lagrange basis evaluation, ad…
Browse files Browse the repository at this point in the history
…ding a check for total > 1, downgrading wasmer version, and some docs

Signed-off-by: lovesh <[email protected]>
  • Loading branch information
lovesh committed May 17, 2024
1 parent 1ceec9a commit fe99471
Show file tree
Hide file tree
Showing 13 changed files with 87 additions and 37 deletions.
8 changes: 8 additions & 0 deletions bbs_plus/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use dock_crypto_utils::{
};
use oblivious_transfer_protocols::{error::OTError, ParticipantId};
use schnorr_pok::error::SchnorrError;
use secret_sharing_and_dkg::error::SSError;
use serde::Serialize;

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -57,6 +58,7 @@ pub enum BBSPlusError {
AlreadyHaveChallengesFrom(ParticipantId),
SenderEitherNotReadyForResponseOrAlreadySentIt(ParticipantId),
ReceiverEitherNotReadyForHashedKeysOrAlreadyVerifiedIt(ParticipantId),
SSError(SSError),
}

impl From<SchnorrError> for BBSPlusError {
Expand Down Expand Up @@ -88,3 +90,9 @@ impl From<OTError> for BBSPlusError {
Self::OTError(e)
}
}

impl From<SSError> for BBSPlusError {
fn from(e: SSError) -> Self {
Self::SSError(e)
}
}
1 change: 0 additions & 1 deletion bbs_plus/src/threshold/base_ot_phase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,6 @@ pub mod tests {
UniformRand,
};
use blake2::Blake2b512;
use std::time::Instant;

pub fn check_base_ot_keys(
choices: &[Bit],
Expand Down
2 changes: 1 addition & 1 deletion bbs_plus/src/threshold/randomness_generation_phase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl<F: PrimeField, const SALT_SIZE: usize> Phase1<F, SALT_SIZE> {
zero_shares,
self.id,
&others,
);
)?;
Ok((others, randomness, masked_signing_key_share, masked_r))
}

Expand Down
7 changes: 4 additions & 3 deletions bbs_plus/src/threshold/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,20 @@ use oblivious_transfer_protocols::ParticipantId;

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

pub fn compute_masked_arguments_to_multiply<F: PrimeField>(
signing_key: &F,
r: Vec<F>,
mut zero_shares: Vec<F>,
self_id: ParticipantId,
others: &[ParticipantId],
) -> (Vec<F>, Vec<F>) {
) -> Result<(Vec<F>, Vec<F>), SSError> {
let batch_size = r.len();
debug_assert_eq!(zero_shares.len(), 2 * batch_size);
let alphas = zero_shares.drain(0..batch_size).collect::<Vec<_>>();
let betas = zero_shares;
let lambda = secret_sharing_and_dkg::common::lagrange_basis_at_0::<F>(&others, self_id);
let lambda = secret_sharing_and_dkg::common::lagrange_basis_at_0::<F>(&others, self_id)?;
let (masked_signing_key_shares, masked_rs) = cfg_into_iter!(r)
.zip(cfg_into_iter!(alphas).zip(cfg_into_iter!(betas)))
.map(|(r, (alpha, beta))| {
Expand All @@ -30,7 +31,7 @@ pub fn compute_masked_arguments_to_multiply<F: PrimeField>(
.collect::<Vec<_>>()
.into_iter()
.multiunzip::<(Vec<F>, Vec<F>)>();
(masked_signing_key_shares, masked_rs)
Ok((masked_signing_key_shares, masked_rs))
}

pub fn compute_R_and_u<G: AffineRepr>(
Expand Down
19 changes: 18 additions & 1 deletion coconut/src/signature/aggregated_signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};
use ark_ec::pairing::Pairing;

use ark_serialize::*;
use ark_std::cfg_iter;
use utils::iter::validate;

use super::{error::AggregatedPSError, ps_signature::Signature};
Expand Down Expand Up @@ -49,7 +50,9 @@ impl<E: Pairing> AggregatedSignature<E> {
if s.is_empty() {
Err(AggregatedPSError::NoSignatures)?
}

if cfg_iter!(participant_ids).any(|p| *p == 0) {
return Err(AggregatedPSError::ParticipantIdCantBeZero);
}
let l = lagrange_basis_at_0(participant_ids)
.map(<E::ScalarField as PrimeField>::into_bigint)
.collect();
Expand Down Expand Up @@ -171,4 +174,18 @@ mod aggregated_signature_tests {
Err(AggregatedPSError::NoSignatures)
);
}

#[test]
fn zero_participant_id() {
let mut rng = StdRng::seed_from_u64(0u64);
let h = G1::rand(&mut rng).into_affine();

let sig1 = Signature::<Bls12_381>::combine(h.clone(), G1::rand(&mut rng).into_affine());
let sig2 = Signature::<Bls12_381>::combine(h.clone(), G1::rand(&mut rng).into_affine());
let aggr_sigs = vec![(0, &sig1), (1, &sig2)];
assert_eq!(
AggregatedSignature::new(aggr_sigs, &h),
Err(AggregatedPSError::ParticipantIdCantBeZero)
)
}
}
1 change: 1 addition & 0 deletions coconut/src/signature/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub enum AggregatedPSError {
InvalidSigma1For(ParticipantId),
ParticipantIdsMustBeUniqueAndSorted(InvalidPair<ParticipantId>),
PSError(PSError),
ParticipantIdCantBeZero,
}

impl From<InvalidPair<ParticipantId>> for AggregatedPSError {
Expand Down
2 changes: 1 addition & 1 deletion legogroth16/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ ark-r1cs-std = { workspace = true, optional = true }
tracing = { version = "0.1", default-features = false, features = [ "attributes" ], optional = true }
derivative = { version = "2.0", features = ["use_core"], optional = true }
rayon = { workspace = true, optional = true }
wasmer = { version = "4.3.0", optional = true, default-features = false }
wasmer = { version = "3.3.0", optional = true, default-features = false }
fnv = { version = "1.0.3", default-features = false, optional = true }
num-bigint = { version = "0.4", default-features = false, optional = true }
log = "0.4"
Expand Down
41 changes: 30 additions & 11 deletions secret_sharing_and_dkg/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use zeroize::{Zeroize, ZeroizeOnDrop};

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

/// ShareId must be greater than 0
pub type ShareId = u16;

/// ParticipantId must be greater than 0
pub type ParticipantId = u16;

/// Share used in Shamir secret sharing and Feldman verifiable secret sharing
Expand Down Expand Up @@ -81,7 +84,7 @@ pub struct VerifiableShare<F: PrimeField> {
#[serde(bound = "")]
pub struct VerifiableShares<F: PrimeField>(pub Vec<VerifiableShare<F>>);

/// Commitments to coefficients of the of the polynomial created during secret sharing. Each commitment
/// Commitments to coefficients of the polynomial created during secret sharing. Each commitment
/// in the vector could be a Pedersen commitment or a computationally hiding and computationally binding
/// commitment (scalar multiplication of the coefficient with a public group element). The former is used
/// in Pedersen secret sharing and the latter in Feldman
Expand Down Expand Up @@ -155,11 +158,15 @@ impl<G: AffineRepr> PublicKeyBase<G> {
/// Return the Lagrange basis polynomial at x = 0 given the `x` coordinates
/// `(x_coords[0]) * (x_coords[1]) * ... / ((x_coords[0] - i) * (x_coords[1] - i) * ...)`
/// Assumes all `x` coordinates are distinct and appropriate number of coordinates are provided
pub fn lagrange_basis_at_0<F: PrimeField>(x_coords: &[ShareId], i: ShareId) -> F {
pub fn lagrange_basis_at_0<F: PrimeField>(x_coords: &[ShareId], i: ShareId) -> Result<F, SSError> {
let mut numerator = F::one();
let mut denominator = F::one();
let i_f = F::from(i as u64);
for x in x_coords {
// Ensure no x-coordinate can be 0 since we are evaluating basis polynomial at 0
if *x == 0 {
return Err(SSError::XCordCantBeZero);
}
if *x == i {
continue;
}
Expand All @@ -168,20 +175,26 @@ pub fn lagrange_basis_at_0<F: PrimeField>(x_coords: &[ShareId], i: ShareId) -> F
denominator *= x - i_f;
}
denominator.inverse_in_place().unwrap();
numerator * denominator
Ok(numerator * denominator)
}

/// Return the Lagrange basis polynomial at x = 0 for each of the given `x` coordinates. Faster than
/// doing multiple calls to `lagrange_basis_at_0`
pub fn lagrange_basis_at_0_for_all<F: PrimeField>(x_coords: Vec<ShareId>) -> Vec<F> {
pub fn lagrange_basis_at_0_for_all<F: PrimeField>(
x_coords: Vec<ShareId>,
) -> Result<Vec<F>, SSError> {
let x = cfg_into_iter!(x_coords.as_slice())
.map(|x| F::from(*x as u64))
.collect::<Vec<_>>();
// Ensure no x-coordinate can be 0 since we are evaluating basis polynomials at 0
if cfg_iter!(x).any(|x_i| x_i.is_zero()) {
return Err(SSError::XCordCantBeZero);
}

// Product of all `x`, i.e. \prod_{i}(x_i}
let product = cfg_iter!(x).product::<F>();

cfg_into_iter!(x.clone())
let r = cfg_into_iter!(x.clone())
.map(move |i| {
let mut denominator = cfg_iter!(x)
.filter(|&j| &i != j)
Expand All @@ -195,21 +208,27 @@ pub fn lagrange_basis_at_0_for_all<F: PrimeField>(x_coords: Vec<ShareId>) -> Vec

denominator * numerator
})
.collect::<Vec<_>>()
.collect::<Vec<_>>();
Ok(r)
}

#[cfg(test)]
pub mod tests {
use super::*;
use ark_bls12_381::Bls12_381;
use ark_ec::pairing::Pairing;
use ark_bls12_381::Fr;
use ark_std::{
rand::{prelude::StdRng, SeedableRng},
UniformRand,
};
use std::time::Instant;

type Fr = <Bls12_381 as Pairing>::ScalarField;
#[test]
fn cannot_compute_lagrange_basis_at_0_with_0_as_x_coordinate() {
assert!(lagrange_basis_at_0::<Fr>(&[0, 1, 2, 4], 2).is_err());
assert!(lagrange_basis_at_0::<Fr>(&[1, 0, 2, 4], 2).is_err());
assert!(lagrange_basis_at_0_for_all::<Fr>(vec![1, 0, 2, 4]).is_err());
assert!(lagrange_basis_at_0_for_all::<Fr>(vec![1, 3, 0, 4]).is_err());
}

#[test]
fn compare_lagrange_basis_at_0() {
Expand All @@ -222,12 +241,12 @@ pub mod tests {

let start = Instant::now();
let single = cfg_iter!(x)
.map(|i| lagrange_basis_at_0(&x, *i))
.map(|i| lagrange_basis_at_0(&x, *i).unwrap())
.collect::<Vec<Fr>>();
println!("For {} x, single took {:?}", count, start.elapsed());

let start = Instant::now();
let multiple = lagrange_basis_at_0_for_all(x);
let multiple = lagrange_basis_at_0_for_all(x).unwrap();
println!("For {} x, multiple took {:?}", count, start.elapsed());

assert_eq!(single, multiple);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,16 +209,12 @@ macro_rules! impl_protocol {
if threshold > len {
return Err(SSError::BelowThreshold(threshold, len));
}
let share_ids = &shares[0..threshold as usize]
let share_ids = shares[0..threshold as usize]
.iter()
.map(|s| s.id)
.collect::<Vec<_>>();
let result = cfg_into_iter!(&shares[0..threshold as usize])
.map(|s| {
s.share * common::lagrange_basis_at_0::<E::ScalarField>(&share_ids, s.id)
})
.sum::<PairingOutput<E>>();
Ok(result)
let basis = common::lagrange_basis_at_0_for_all::<E::ScalarField>(share_ids)?;
Ok(cfg_into_iter!(basis).zip(cfg_into_iter!(shares)).map(|(b, s)| s.share * b).sum::<PairingOutput<E>>())
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
};
use ark_ec::{AffineRepr, CurveGroup, VariableBaseMSM};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::{cfg_into_iter, rand::RngCore, vec, vec::Vec, UniformRand};
use ark_std::{rand::RngCore, vec, vec::Vec, UniformRand};
use digest::Digest;
use dock_crypto_utils::serde_utils::ArkObjectBytes;
use schnorr_pok::{
Expand Down Expand Up @@ -122,13 +122,11 @@ impl<G: AffineRepr> ComputationShare<G> {
if threshold > len {
return Err(SSError::BelowThreshold(threshold, len));
}
let share_ids = &shares[0..threshold as usize]
let share_ids = shares[0..threshold as usize]
.iter()
.map(|s| s.id)
.collect::<Vec<_>>();
let basis = cfg_into_iter!(&shares[0..threshold as usize])
.map(|s| common::lagrange_basis_at_0::<G::ScalarField>(&share_ids, s.id))
.collect::<Vec<_>>();
let basis = common::lagrange_basis_at_0_for_all::<G::ScalarField>(share_ids)?;
let shares = &shares[0..threshold as usize]
.iter()
.map(|s| s.share)
Expand Down
4 changes: 3 additions & 1 deletion secret_sharing_and_dkg/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::common::{ParticipantId, ShareId};
use schnorr_pok::error::SchnorrError;
use serde::Serialize;

#[derive(Debug)]
#[derive(Debug, Serialize)]
pub enum SSError {
InvalidThresholdOrTotal(ShareId, ShareId),
BelowThreshold(ShareId, ShareId),
Expand All @@ -22,6 +23,7 @@ pub enum SSError {
InvalidComputationShareProof(ShareId),
UnequalNoOfProofsAndShares(usize, usize),
UnequalNoOfProofsAndCommitments(usize, usize),
XCordCantBeZero,
}

impl From<SchnorrError> for SSError {
Expand Down
5 changes: 2 additions & 3 deletions secret_sharing_and_dkg/src/feldman_dvss_dkg.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Feldman Distributed Verifiable secret sharing and distributed key generation.
use crate::{
common,
common::{lagrange_basis_at_0, CommitmentToCoefficients, ParticipantId, Share, ShareId},
error::SSError,
};
Expand Down Expand Up @@ -181,9 +182,7 @@ pub fn reconstruct_threshold_public_key<G: AffineRepr>(
let pkt = &public_keys[0..threshold as usize];
let pk_ids = pkt.iter().map(|(i, _)| *i).collect::<Vec<_>>();
let pks = pkt.iter().map(|(_, pk)| *pk).collect::<Vec<_>>();
let lcs = cfg_iter!(pk_ids)
.map(|i| lagrange_basis_at_0::<G::ScalarField>(&pk_ids, *i))
.collect::<Vec<_>>();
let lcs = common::lagrange_basis_at_0_for_all::<G::ScalarField>(pk_ids)?;
Ok(G::Group::msm_unchecked(&pks, &lcs).into_affine())
}

Expand Down
16 changes: 13 additions & 3 deletions secret_sharing_and_dkg/src/shamir_ss.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,10 @@ impl<F: PrimeField> Shares<F> {
}
let shares = &self.0[0..threshold as usize];
let share_ids = shares.iter().map(|s| s.id).collect::<Vec<_>>();
Ok(cfg_iter!(shares)
.map(|s| common::lagrange_basis_at_0::<F>(&share_ids, s.id) * s.share)
let basis = common::lagrange_basis_at_0_for_all::<F>(share_ids)?;
Ok(cfg_into_iter!(basis)
.zip(cfg_into_iter!(shares))
.map(|(b, s)| b * s.share)
.sum::<F>())
}
}
Expand All @@ -71,11 +73,19 @@ impl<F: PrimeField> Shares<F> {
pub mod tests {
use super::*;
use crate::common::Share;
use ark_bls12_381::{Bls12_381, Fr};
use ark_bls12_381::Fr;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::rand::{rngs::StdRng, SeedableRng};
use test_utils::test_serialization;

#[test]
fn invalid_recombine_zero_id() {
let mut rng = StdRng::seed_from_u64(0u64);
let (_, mut shares, _) = deal_random_secret::<_, Fr>(&mut rng, 2, 3).unwrap();
shares.0[0].id = 0;
assert!(shares.reconstruct_secret().is_err());
}

#[test]
fn shamir_secret_sharing() {
let mut rng = StdRng::seed_from_u64(0u64);
Expand Down

0 comments on commit fe99471

Please sign in to comment.