organized code

This commit is contained in:
Conrado Gouvea 2022-10-18 15:46:33 -03:00
parent 828478a5eb
commit ce3a26f3d3
7 changed files with 419 additions and 137 deletions

View File

@ -30,7 +30,7 @@ pasta_curves = { version = "0.4", default-features = false }
rand_core = { version = "0.6", default-features = false }
serde = { version = "1", optional = true, features = ["derive"] }
thiserror = { version = "1.0", optional = true }
frost-core = { git = "https://github.com/ZcashFoundation/frost.git", rev = "683a7eb55456b2114b11e20c3b57cd00c4fe3b49", optional = true }
frost-core = { git = "https://github.com/ZcashFoundation/frost.git", rev = "79f0d647ae08e50bf9d7afd78e8f4ed3a0c1e7af", optional = true, features=["internals"] }
[dependencies.zeroize]
version = "1"
@ -46,7 +46,7 @@ proptest = "1.0"
rand = "0.8"
rand_chacha = "0.3"
serde_json = "1.0"
frost-core = { git = "https://github.com/ZcashFoundation/frost.git", rev = "683a7eb55456b2114b11e20c3b57cd00c4fe3b49", features=["test-impl"] }
frost-core = { git = "https://github.com/ZcashFoundation/frost.git", rev = "79f0d647ae08e50bf9d7afd78e8f4ed3a0c1e7af", features=["internals", "test-impl"] }
# `alloc` is only used in test code

1
rust-toolchain Normal file
View File

@ -0,0 +1 @@
1.56.0

View File

@ -9,11 +9,19 @@ use pasta_curves::pallas;
use rand_core::{CryptoRng, RngCore};
use frost_core::{frost, Ciphersuite, Field, Group, Scalar};
use frost_core::{
frost::{self},
Ciphersuite, Field, Group,
};
pub use frost_core::Error;
use crate::{hash::HStar, orchard, private::Sealed};
use crate::{
hash::HStar,
orchard,
private::Sealed,
randomized_frost::{self, RandomizedParams},
};
#[derive(Clone, Copy)]
/// An implementation of the FROST Pallas Blake2b-512 ciphersuite scalar field.
@ -61,6 +69,10 @@ impl Field for PallasScalarField {
scalar.to_repr().into()
}
fn little_endian_serialize(scalar: &Self::Scalar) -> Self::Serialization {
Self::serialize(scalar)
}
fn deserialize(buf: &Self::Serialization) -> Result<Self::Scalar, Error> {
match pallas::Scalar::from_repr(*buf).into() {
Some(s) => Ok(s),
@ -173,8 +185,8 @@ pub mod keys {
///
pub fn keygen_with_dealer<RNG: RngCore + CryptoRng>(
num_signers: u8,
threshold: u8,
num_signers: u16,
threshold: u16,
mut rng: RNG,
) -> Result<(Vec<SecretShare>, PublicKeyPackage), &'static str> {
frost::keys::keygen_with_dealer(num_signers, threshold, &mut rng)
@ -219,6 +231,8 @@ pub type SigningPackage = frost::SigningPackage<P>;
///
pub mod round2 {
use crate::randomized_frost;
use super::*;
///
@ -232,8 +246,14 @@ pub mod round2 {
signing_package: &SigningPackage,
signer_nonces: &round1::SigningNonces,
key_package: &keys::KeyPackage,
randomizer_point: &<<P as Ciphersuite>::Group as Group>::Element,
) -> Result<SignatureShare, &'static str> {
frost::round2::sign(signing_package, signer_nonces, key_package)
randomized_frost::sign(
signing_package,
signer_nonces,
key_package,
randomizer_point,
)
}
}
@ -245,9 +265,14 @@ pub fn aggregate(
signing_package: &round2::SigningPackage,
signature_shares: &[round2::SignatureShare],
pubkeys: &keys::PublicKeyPackage,
randomizer: Option<Scalar<P>>,
randomized_params: &RandomizedParams<P>,
) -> Result<Signature, &'static str> {
frost::aggregate(signing_package, signature_shares, pubkeys, randomizer)
randomized_frost::aggregate(
signing_package,
signature_shares,
pubkeys,
randomized_params,
)
}
///

View File

@ -28,6 +28,8 @@ mod error;
pub mod frost_redpallas;
mod hash;
pub mod orchard;
#[cfg(feature = "std")]
pub mod randomized_frost;
pub mod sapling;
#[cfg(feature = "alloc")]
mod scalar_mul;

247
src/randomized_frost.rs Normal file
View File

@ -0,0 +1,247 @@
//! Randomized FROST support.
//!
#![allow(non_snake_case)]
use alloc::vec::Vec;
use frost_core::{frost::keys::PublicKeyPackage, VerifyingKey};
#[cfg(feature = "alloc")]
use frost_core::{
frost::{self},
Ciphersuite, Field, Group,
};
pub use frost_core::Error;
use rand_core::{CryptoRng, RngCore};
/// Compute the preimages to H3 to compute the per-signer rhos
// We separate this out into its own method so it can be tested
fn binding_factor_preimages<C: Ciphersuite>(
signing_package: &frost::SigningPackage<C>,
randomizer_point: &<C::Group as Group>::Element,
) -> Vec<(frost::Identifier<C>, Vec<u8>)> {
let mut binding_factor_input_prefix = vec![];
binding_factor_input_prefix
.extend_from_slice(C::H4(signing_package.message().as_slice()).as_ref());
binding_factor_input_prefix.extend_from_slice(
C::H5(&frost::round1::encode_group_commitments(signing_package.signing_commitments())[..])
.as_ref(),
);
binding_factor_input_prefix
.extend_from_slice(<C::Group as Group>::serialize(randomizer_point).as_ref());
signing_package
.signing_commitments()
.iter()
.map(|c| {
let mut binding_factor_input = vec![];
binding_factor_input.extend_from_slice(&binding_factor_input_prefix);
binding_factor_input.extend_from_slice(c.identifier.serialize().as_ref());
(c.identifier, binding_factor_input)
})
.collect()
}
fn compute_binding_factor_list<C>(
signing_package: &frost::SigningPackage<C>,
randomizer_point: &<C::Group as Group>::Element,
) -> frost::BindingFactorList<C>
where
C: Ciphersuite,
{
let preimages = binding_factor_preimages(signing_package, randomizer_point);
frost::BindingFactorList::new(
preimages
.iter()
.map(|(identifier, preimage)| {
let binding_factor = C::H1(preimage);
(*identifier, frost::BindingFactor::new(binding_factor))
})
.collect(),
)
}
/// Performed once by each participant selected for the signing operation.
///
/// Implements [`sign`] from the spec.
///
/// Receives the message to be signed and a set of signing commitments and a set
/// of randomizing commitments to be used in that signing operation, including
/// that for this participant.
///
/// Assumes the participant has already determined which nonce corresponds with
/// the commitment that was assigned by the coordinator in the SigningPackage.
///
/// [`sign`]: https://www.ietf.org/archive/id/draft-irtf-cfrg-frost-10.html#name-round-two-signature-share-g
pub fn sign<C: Ciphersuite>(
signing_package: &frost::SigningPackage<C>,
signer_nonces: &frost::round1::SigningNonces<C>,
key_package: &frost::keys::KeyPackage<C>,
randomizer_point: &<C::Group as Group>::Element,
) -> Result<frost::round2::SignatureShare<C>, &'static str> {
let public_key = key_package.group_public.to_element() + *randomizer_point;
// Encodes the signing commitment list produced in round one as part of generating [`Rho`], the
// binding factor.
let binding_factor_list = compute_binding_factor_list(signing_package, randomizer_point);
let rho: frost::BindingFactor<C> = binding_factor_list[key_package.identifier].clone();
// Compute the group commitment from signing commitments produced in round one.
let group_commitment = frost::compute_group_commitment(signing_package, &binding_factor_list)?;
// Compute Lagrange coefficient.
let lambda_i = frost::derive_lagrange_coeff(key_package.identifier(), signing_package)?;
// Compute the per-message challenge.
let challenge = frost_core::challenge::<C>(
&group_commitment.to_element(),
&public_key,
signing_package.message().as_slice(),
);
// Compute the Schnorr signature share.
let z_share: <<C::Group as Group>::Field as Field>::Scalar =
signer_nonces.hiding.clone().to_scalar()
+ (signer_nonces.binding.clone().to_scalar() * rho.to_scalar())
+ (lambda_i * key_package.secret_share.to_scalar() * challenge.to_scalar());
let signature_share = frost::round2::SignatureShare::<C> {
identifier: *key_package.identifier(),
signature: frost::round2::SignatureResponse::<C> { z_share },
};
Ok(signature_share)
}
/// Verifies each participant's signature share, and if all are valid,
/// aggregates the shares into a signature to publish.
///
/// Resulting signature is compatible with verification of a plain SpendAuth
/// signature.
///
/// This operation is performed by a coordinator that can communicate with all
/// the signing participants before publishing the final signature. The
/// coordinator can be one of the participants or a semi-trusted third party
/// (who is trusted to not perform denial of service attacks, but does not learn
/// any secret information). Note that because the coordinator is trusted to
/// report misbehaving parties in order to avoid publishing an invalid
/// signature, if the coordinator themselves is a signer and misbehaves, they
/// can avoid that step. However, at worst, this results in a denial of
/// service attack due to publishing an invalid signature.
pub fn aggregate<C>(
signing_package: &frost::SigningPackage<C>,
signature_shares: &[frost::round2::SignatureShare<C>],
pubkeys: &frost::keys::PublicKeyPackage<C>,
randomized_params: &RandomizedParams<C>,
) -> Result<frost_core::Signature<C>, &'static str>
where
C: Ciphersuite,
{
let public_key = pubkeys.group_public.to_element() + *randomized_params.randomizer_point();
// Encodes the signing commitment list produced in round one as part of generating [`Rho`], the
// binding factor.
let binding_factor_list =
compute_binding_factor_list(signing_package, randomized_params.randomizer_point());
// Compute the group commitment from signing commitments produced in round one.
let group_commitment = frost::compute_group_commitment(signing_package, &binding_factor_list)?;
// Compute the per-message challenge.
let challenge = frost_core::challenge::<C>(
&group_commitment.clone().to_element(),
&public_key,
signing_package.message().as_slice(),
);
// Verify the signature shares.
for signature_share in signature_shares {
// Look up the public key for this signer, where `signer_pubkey` = _G.ScalarBaseMult(s[i])_,
// and where s[i] is a secret share of the constant term of _f_, the secret polynomial.
let signer_pubkey = pubkeys
.signer_pubkeys
.get(&signature_share.identifier)
.unwrap();
// Compute Lagrange coefficient.
let lambda_i = frost::derive_lagrange_coeff(&signature_share.identifier, signing_package)?;
let rho = binding_factor_list[signature_share.identifier].clone();
// Compute the commitment share.
let R_share = signing_package
.signing_commitment(&signature_share.identifier)
.to_group_commitment_share(&rho);
// Compute relation values to verify this signature share.
signature_share.verify(&R_share, signer_pubkey, lambda_i, &challenge)?;
}
// The aggregation of the signature shares by summing them up, resulting in
// a plain Schnorr signature.
//
// Implements [`aggregate`] from the spec.
//
// [`aggregate`]: https://www.ietf.org/archive/id/draft-irtf-cfrg-frost-10.html#section-5.3
let mut z = <<C::Group as Group>::Field as Field>::zero();
for signature_share in signature_shares {
z = z + signature_share.signature.z_share;
}
z = z + challenge.to_scalar() * randomized_params.randomizer;
Ok(frost_core::Signature::new(group_commitment.to_element(), z))
}
/// Randomized params for a signing instance of randomized FROST.
pub struct RandomizedParams<C: Ciphersuite> {
/// The randomizer, also called `alpha`
randomizer: frost_core::Scalar<C>,
/// The generator multiplied by the randomizer.
randomizer_point: <C::Group as Group>::Element,
/// The randomized group public key. The group public key added to the randomizer point.
randomized_group_public_key: frost_core::VerifyingKey<C>,
}
impl<C> RandomizedParams<C>
where
C: Ciphersuite,
{
/// Create a new RandomizedParams for the given [`PublicKeyPackage`]
pub fn new<R: RngCore + CryptoRng>(
public_key_package: &PublicKeyPackage<C>,
mut rng: R,
) -> Self {
let randomizer = <<C::Group as Group>::Field as Field>::random(&mut rng);
let randomizer_point = <C::Group as Group>::generator() * randomizer;
let group_public_point = public_key_package.group_public.to_element();
let randomized_group_public_point = group_public_point + randomizer_point;
let randomized_group_public_key = VerifyingKey::new(randomized_group_public_point);
Self {
randomizer,
randomizer_point,
randomized_group_public_key,
}
}
/// Return the randomizer point.
///
/// It must be sent by the coordinator to each participant when signing.
pub fn randomizer_point(&self) -> &<C::Group as Group>::Element {
&self.randomizer_point
}
/// Return the randomizer point.
///
/// It must be sent by the coordinator to each participant when signing.
pub fn randomized_group_public_key(&self) -> &frost_core::VerifyingKey<C> {
&self.randomized_group_public_key
}
}

130
tests/frost.rs Normal file
View File

@ -0,0 +1,130 @@
use std::{collections::HashMap, convert::TryFrom};
use frost_core::{frost, Ciphersuite};
use rand_core::{CryptoRng, RngCore};
use reddsa::{
frost_redpallas::*,
orchard,
randomized_frost::{self, RandomizedParams},
};
pub fn check_randomized_sign_with_dealer<C: Ciphersuite, R: RngCore + CryptoRng>(mut rng: R) {
////////////////////////////////////////////////////////////////////////////
// Key generation
////////////////////////////////////////////////////////////////////////////
let numsigners = 5;
let threshold = 3;
let (shares, pubkeys) = keys::keygen_with_dealer(numsigners, threshold, &mut rng).unwrap();
// Verifies the secret shares from the dealer
let key_packages: HashMap<frost::Identifier<_>, frost::keys::KeyPackage<_>> = shares
.into_iter()
.map(|share| {
(
share.identifier,
frost::keys::KeyPackage::try_from(share).unwrap(),
)
})
.collect();
let mut nonces: HashMap<frost::Identifier<_>, frost::round1::SigningNonces<_>> = HashMap::new();
let mut commitments: HashMap<frost::Identifier<_>, frost::round1::SigningCommitments<_>> =
HashMap::new();
let randomizer_params = RandomizedParams::new(&pubkeys, &mut rng);
////////////////////////////////////////////////////////////////////////////
// Round 1: generating nonces and signing commitments for each participant
////////////////////////////////////////////////////////////////////////////
for participant_index in 1..(threshold as u16 + 1) {
let participant_identifier = participant_index.try_into().expect("should be nonzero");
// Generate one (1) nonce and one SigningCommitments instance for each
// participant, up to _threshold_.
let (nonce, commitment) = frost::round1::commit(
participant_identifier,
key_packages
.get(&participant_identifier)
.unwrap()
.secret_share(),
&mut rng,
);
nonces.insert(participant_identifier, nonce);
commitments.insert(participant_identifier, commitment);
}
// This is what the signature aggregator / coordinator needs to do:
// - decide what message to sign
// - take one (unused) commitment per signing participant
let mut signature_shares: Vec<frost::round2::SignatureShare<_>> = Vec::new();
let message = "message to sign".as_bytes();
let comms = commitments.clone().into_values().collect();
let signing_package = frost::SigningPackage::new(comms, message.to_vec());
////////////////////////////////////////////////////////////////////////////
// Round 2: each participant generates their signature share
////////////////////////////////////////////////////////////////////////////
for participant_identifier in nonces.keys() {
let key_package = key_packages.get(participant_identifier).unwrap();
let nonces_to_use = &nonces.get(participant_identifier).unwrap();
// Each participant generates their signature share.
let signature_share = randomized_frost::sign(
&signing_package,
nonces_to_use,
key_package,
randomizer_params.randomizer_point(),
)
.unwrap();
signature_shares.push(signature_share);
}
////////////////////////////////////////////////////////////////////////////
// Aggregation: collects the signing shares from all participants,
// generates the final signature.
////////////////////////////////////////////////////////////////////////////
// Aggregate (also verifies the signature shares)
let group_signature_res = randomized_frost::aggregate(
&signing_package,
&signature_shares[..],
&pubkeys,
&randomizer_params,
);
assert!(group_signature_res.is_ok());
let group_signature = group_signature_res.unwrap();
// Check that the threshold signature can be verified by the randomized group public
// key (the verification key).
assert!(randomizer_params
.randomized_group_public_key()
.verify(message, &group_signature)
.is_ok());
// Note that key_package.group_public can't be used to verify the signature
// since those are non-randomized.
// Check that the threshold signature can be verified by the `reddsa` crate
// public key (interoperability test)
let sig = {
let bytes: [u8; 64] = group_signature.to_bytes();
reddsa::Signature::<orchard::SpendAuth>::from(bytes)
};
let pk_bytes = {
let bytes: [u8; 32] = randomizer_params.randomized_group_public_key().to_bytes();
reddsa::VerificationKeyBytes::<orchard::SpendAuth>::from(bytes)
};
// Check that the verification key is a valid RedDSA verification key.
let pub_key = reddsa::VerificationKey::try_from(pk_bytes)
.expect("The test verification key to be well-formed.");
// Check that signature validation has the expected result.
assert!(pub_key.verify(message, &sig).is_ok());
}

View File

@ -1,9 +1,7 @@
use std::{collections::HashMap, convert::TryFrom};
use frost_core::{frost, Ciphersuite, Field, Group};
use group::GroupEncoding;
use rand::thread_rng;
use reddsa::{frost_redpallas::*, orchard};
use reddsa::frost_redpallas::PallasBlake2b512;
mod frost;
#[test]
fn check_sign_with_dealer() {
@ -14,128 +12,7 @@ fn check_sign_with_dealer() {
#[test]
fn check_randomized_sign_with_dealer() {
let mut rng = thread_rng();
let rng = thread_rng();
////////////////////////////////////////////////////////////////////////////
// Key generation
////////////////////////////////////////////////////////////////////////////
let numsigners = 5;
let threshold = 3;
let (shares, pubkeys) = keys::keygen_with_dealer(numsigners, threshold, &mut rng).unwrap();
// Verifies the secret shares from the dealer
let key_packages: HashMap<frost::Identifier<_>, frost::keys::KeyPackage<_>> = shares
.into_iter()
.map(|share| {
(
share.identifier,
frost::keys::KeyPackage::try_from(share).unwrap(),
)
})
.collect();
let mut nonces: HashMap<frost::Identifier<_>, frost::round1::SigningNonces<_>> = HashMap::new();
let mut commitments: HashMap<frost::Identifier<_>, frost::round1::SigningCommitments<_>> =
HashMap::new();
////////////////////////////////////////////////////////////////////////////
// Round 1: generating nonces and signing commitments for each participant
////////////////////////////////////////////////////////////////////////////
for participant_index in 1..(threshold as u16 + 1) {
let participant_identifier = participant_index.try_into().expect("should be nonzero");
// Generate one (1) nonce and one SigningCommitments instance for each
// participant, up to _threshold_.
let (nonce, commitment) = frost::round1::commit(
participant_identifier,
key_packages
.get(&participant_identifier)
.unwrap()
.secret_share(),
&mut rng,
);
nonces.insert(participant_identifier, nonce);
commitments.insert(participant_identifier, commitment);
}
let randomizer = PallasScalarField::random(&mut rng);
let randomizer_point =
<<PallasBlake2b512 as Ciphersuite>::Group as Group>::generator() * randomizer;
// This is what the signature aggregator / coordinator needs to do:
// - decide what message to sign
// - take one (unused) commitment per signing participant
let mut signature_shares: Vec<frost::round2::SignatureShare<_>> = Vec::new();
let message = "message to sign".as_bytes();
let comms = commitments.clone().into_values().collect();
let signing_package =
frost::SigningPackage::with_randomizer(comms, message.to_vec(), randomizer_point);
////////////////////////////////////////////////////////////////////////////
// Round 2: each participant generates their signature share
////////////////////////////////////////////////////////////////////////////
for participant_identifier in nonces.keys() {
let key_package = key_packages.get(participant_identifier).unwrap();
let nonces_to_use = &nonces.get(participant_identifier).unwrap();
// Each participant generates their signature share.
let signature_share =
frost::round2::sign(&signing_package, nonces_to_use, key_package).unwrap();
signature_shares.push(signature_share);
}
////////////////////////////////////////////////////////////////////////////
// Aggregation: collects the signing shares from all participants,
// generates the final signature.
////////////////////////////////////////////////////////////////////////////
// Aggregate (also verifies the signature shares)
let group_signature_res = frost::aggregate(
&signing_package,
&signature_shares[..],
&pubkeys,
Some(randomizer),
);
assert!(group_signature_res.is_ok());
let group_signature = group_signature_res.unwrap();
let group_public_point = PallasGroup::deserialize(&pubkeys.group_public.to_bytes())
.expect("should deserialize since it was just serialized");
let randomized_group_public_point = group_public_point + PallasGroup::generator() * randomizer;
let randomized_group_public =
VerifyingKey::from_bytes(randomized_group_public_point.to_bytes())
.expect("should work since it was just serialized");
// Check that the threshold signature can be verified by the randomized group public
// key (the verification key).
assert!(randomized_group_public
.verify(message, &group_signature)
.is_ok());
// Note that key_package.group_public can't be used to verify the signature
// since those are non-randomized.
// Check that the threshold signature can be verified by the `reddsa` crate
// public key (interoperability test)
let sig = {
let bytes: [u8; 64] = group_signature.to_bytes();
reddsa::Signature::<orchard::SpendAuth>::from(bytes)
};
let pk_bytes = {
let bytes: [u8; 32] = randomized_group_public.to_bytes();
reddsa::VerificationKeyBytes::<orchard::SpendAuth>::from(bytes)
};
// Check that the verification key is a valid RedDSA verification key.
let pub_key = reddsa::VerificationKey::try_from(pk_bytes)
.expect("The test verification key to be well-formed.");
// Check that signature validation has the expected result.
assert!(pub_key.verify(message, &sig).is_ok());
frost::check_randomized_sign_with_dealer::<PallasBlake2b512, _>(rng);
}