Skip to content

Commit

Permalink
Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/…
Browse files Browse the repository at this point in the history
…350.pdf

Relevant to #99.
  • Loading branch information
kayabaNerve committed Jul 26, 2023
1 parent 62a63df commit f733bbe
Show file tree
Hide file tree
Showing 4 changed files with 251 additions and 0 deletions.
13 changes: 13 additions & 0 deletions crypto/schnorr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,22 @@ std-shims = { path = "../../common/std-shims", version = "0.1", default-features

rand_core = { version = "0.6", default-features = false }

<<<<<<< HEAD
zeroize = { version = "^1.5", default-features = false, features = ["zeroize_derive"] }
=======
digest = "0.10"

group = "0.12"
ciphersuite = { path = "../ciphersuite", version = "0.1" }
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)

transcript = { package = "flexible-transcript", path = "../transcript", version = "0.3", default-features = false }

ciphersuite = { path = "../ciphersuite", version = "0.3", default-features = false, features = ["alloc"] }
multiexp = { path = "../multiexp", version = "0.3", default-features = false, features = ["batch"] }

[dev-dependencies]
<<<<<<< HEAD
hex = "0.4"

rand_core = { version = "0.6", features = ["std"] }
Expand All @@ -37,3 +45,8 @@ ciphersuite = { path = "../ciphersuite", version = "0.3", features = ["ed25519"]
[features]
std = ["std-shims/std", "ciphersuite/std", "multiexp/std"]
default = ["std"]
=======
blake2 = "0.10"
dalek-ff-group = { path = "../dalek-ff-group", version = "^0.1.2" }
ciphersuite = { path = "../ciphersuite", version = "0.1", features = ["ristretto"] }
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
129 changes: 129 additions & 0 deletions crypto/schnorr/src/aggregate.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<<<<<<< HEAD
use std_shims::{
vec::Vec,
io::{self, Read, Write},
Expand Down Expand Up @@ -61,16 +62,84 @@ fn weight<D: Send + Clone + SecureDigest, F: PrimeField>(digest: &mut DigestTran
remaining -= i;
i = 0;
}
=======
use std::io::{self, Read, Write};

use zeroize::Zeroize;

use digest::Digest;

use group::{
ff::{Field, PrimeField},
Group, GroupEncoding,
prime::PrimeGroup,
};

use multiexp::multiexp_vartime;

use ciphersuite::Ciphersuite;

use crate::SchnorrSignature;

fn digest<D: Digest>() -> D {
D::new_with_prefix(b"Schnorr Aggregate")
}

// A secure challenge will include the nonce and whatever message
// Depending on the environment, a secure challenge *may* not include the public key, even if
// the modern consensus is it should
// Accordingly, transcript both here, even if ideally only the latter would need to be
fn digest_accumulate<D: Digest, G: PrimeGroup>(digest: &mut D, key: G, challenge: G::Scalar) {
digest.update(key.to_bytes().as_ref());
digest.update(challenge.to_repr().as_ref());
}

// Performs a big-endian modular reduction of the hash value
// This is used by the below aggregator to prevent mutability
// Only an 128-bit scalar is needed to offer 128-bits of security against malleability per
// https://cr.yp.to/badbatch/badbatch-20120919.pdf
// Accordingly, while a 256-bit hash used here with a 256-bit ECC will have bias, it shouldn't be
// an issue
fn scalar_from_digest<D: Digest, F: PrimeField>(digest: D) -> F {
let bytes = digest.finalize();
debug_assert_eq!(bytes.len() % 8, 0);

let mut res = F::zero();
let mut i = 0;
while i < bytes.len() {
if i != 0 {
for _ in 0 .. 8 {
res += res;
}
}
res += F::from(u64::from_be_bytes(bytes[i .. (i + 8)].try_into().unwrap()));
i += 8;
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
}
res
}

<<<<<<< HEAD
/// Aggregate Schnorr signature as defined in <https://eprint.iacr.org/2021/350>.
#[allow(non_snake_case)]
#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
pub struct SchnorrAggregate<C: Ciphersuite> {
Rs: Vec<C::G>,
s: C::F,
=======
fn digest_yield<D: Digest, F: PrimeField>(digest: D, i: usize) -> F {
scalar_from_digest(digest.chain_update(
u32::try_from(i).expect("more than 4 billion signatures in aggregate").to_le_bytes(),
))
}

/// Aggregate Schnorr signature as defined in https://eprint.iacr.org/2021/350.pdf.
#[allow(non_snake_case)]
#[derive(Clone, PartialEq, Eq, Debug, Zeroize)]
pub struct SchnorrAggregate<C: Ciphersuite> {
pub Rs: Vec<C::G>,
pub s: C::F,
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
}

impl<C: Ciphersuite> SchnorrAggregate<C> {
Expand All @@ -88,9 +157,13 @@ impl<C: Ciphersuite> SchnorrAggregate<C> {
Ok(SchnorrAggregate { Rs, s: C::read_F(reader)? })
}

<<<<<<< HEAD
/// Write a SchnorrAggregate to something implementing Write.
///
/// This will panic if more than 4 billion signatures were aggregated.
=======
/// Write a SchnorrAggregate to something implementing Read.
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
writer.write_all(
&u32::try_from(self.Rs.len())
Expand All @@ -104,14 +177,19 @@ impl<C: Ciphersuite> SchnorrAggregate<C> {
writer.write_all(self.s.to_repr().as_ref())
}

<<<<<<< HEAD
/// Serialize a SchnorrAggregate, returning a `Vec<u8>`.
=======
/// Serialize a SchnorrAggregate, returning a Vec<u8>.
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
pub fn serialize(&self) -> Vec<u8> {
let mut buf = vec![];
self.write(&mut buf).unwrap();
buf
}

/// Perform signature verification.
<<<<<<< HEAD
///
/// Challenges must be properly crafted, which means being binding to the public key, nonce, and
/// any message. Failure to do so will let a malicious adversary to forge signatures for
Expand All @@ -121,19 +199,33 @@ impl<C: Ciphersuite> SchnorrAggregate<C> {
/// challenges.
#[must_use]
pub fn verify(&self, dst: &'static [u8], keys_and_challenges: &[(C::G, C::F)]) -> bool {
=======
#[must_use]
pub fn verify<D: Clone + Digest>(&self, keys_and_challenges: &[(C::G, C::F)]) -> bool {
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
if self.Rs.len() != keys_and_challenges.len() {
return false;
}

<<<<<<< HEAD
let mut digest = DigestTranscript::<C::H>::new(dst);
digest.domain_separate(b"signatures");
for (_, challenge) in keys_and_challenges {
digest.append_message(b"challenge", challenge.to_repr());
=======
let mut digest = digest::<D>();
for (key, challenge) in keys_and_challenges {
digest_accumulate(&mut digest, *key, *challenge);
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
}

let mut pairs = Vec::with_capacity((2 * keys_and_challenges.len()) + 1);
for (i, (key, challenge)) in keys_and_challenges.iter().enumerate() {
<<<<<<< HEAD
let z = weight(&mut digest);
=======
let z = digest_yield(digest.clone(), i);
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
pairs.push((z, self.Rs[i]));
pairs.push((z * challenge, *key));
}
Expand All @@ -142,6 +234,7 @@ impl<C: Ciphersuite> SchnorrAggregate<C> {
}
}

<<<<<<< HEAD
/// A signature aggregator capable of consuming signatures in order to produce an aggregate.
#[allow(non_snake_case)]
#[derive(Clone, Debug, Zeroize)]
Expand All @@ -164,19 +257,55 @@ impl<C: Ciphersuite> SchnorrAggregator<C> {
/// Aggregate a signature.
pub fn aggregate(&mut self, challenge: C::F, sig: SchnorrSignature<C>) {
self.digest.append_message(b"challenge", challenge.to_repr());
=======
#[allow(non_snake_case)]
#[derive(Clone, Debug, Zeroize)]
pub struct SchnorrAggregator<D: Clone + Digest, C: Ciphersuite> {
digest: D,
sigs: Vec<SchnorrSignature<C>>,
}

impl<D: Clone + Digest, C: Ciphersuite> Default for SchnorrAggregator<D, C> {
fn default() -> Self {
Self { digest: digest(), sigs: vec![] }
}
}

impl<D: Clone + Digest, C: Ciphersuite> SchnorrAggregator<D, C> {
/// Create a new aggregator.
pub fn new() -> Self {
Self::default()
}

/// Aggregate a signature.
pub fn aggregate(&mut self, public_key: C::G, challenge: C::F, sig: SchnorrSignature<C>) {
digest_accumulate(&mut self.digest, public_key, challenge);
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
self.sigs.push(sig);
}

/// Complete aggregation, returning None if none were aggregated.
<<<<<<< HEAD
pub fn complete(mut self) -> Option<SchnorrAggregate<C>> {
=======
pub fn complete(self) -> Option<SchnorrAggregate<C>> {
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
if self.sigs.is_empty() {
return None;
}

<<<<<<< HEAD
let mut aggregate = SchnorrAggregate { Rs: Vec::with_capacity(self.sigs.len()), s: C::F::ZERO };
for i in 0 .. self.sigs.len() {
aggregate.Rs.push(self.sigs[i].R);
aggregate.s += self.sigs[i].s * weight::<_, C::F>(&mut self.digest);
=======
let mut aggregate =
SchnorrAggregate { Rs: Vec::with_capacity(self.sigs.len()), s: C::F::zero() };
for i in 0 .. self.sigs.len() {
aggregate.Rs.push(self.sigs[i].R);
aggregate.s += self.sigs[i].s * digest_yield::<_, C::F>(self.digest.clone(), i);
>>>>>>> 1a3b6dc4 (Implement Schnorr half-aggregation from https://eprint.iacr.org/2021/350.pdf)
}
Some(aggregate)
}
Expand Down
2 changes: 2 additions & 0 deletions crypto/schnorr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ use multiexp::{multiexp_vartime, BatchVerifier};
/// Half-aggregation from <https://eprint.iacr.org/2021/350>.
pub mod aggregate;

pub mod aggregate;

#[cfg(test)]
mod tests;

Expand Down
107 changes: 107 additions & 0 deletions crypto/schnorr/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
use rand_core::OsRng;

use blake2::{digest::typenum::U32, Blake2b};
type Blake2b256 = Blake2b<U32>;

use group::{ff::Field, Group};

use multiexp::BatchVerifier;

use ciphersuite::{Ciphersuite, Ristretto};
use crate::{
SchnorrSignature,
aggregate::{SchnorrAggregator, SchnorrAggregate},
};

pub(crate) fn sign<C: Ciphersuite>() {
let private_key = C::random_nonzero_F(&mut OsRng);
let nonce = C::random_nonzero_F(&mut OsRng);
let challenge = C::random_nonzero_F(&mut OsRng); // Doesn't bother to craft an HRAm
assert!(SchnorrSignature::<C>::sign(private_key, nonce, challenge)
.verify(C::generator() * private_key, challenge));
}

// The above sign function verifies signing works
// This verifies invalid signatures don't pass, using zero signatures, which should effectively be
// random
pub(crate) fn verify<C: Ciphersuite>() {
assert!(!SchnorrSignature::<C> { R: C::G::identity(), s: C::F::zero() }
.verify(C::generator() * C::random_nonzero_F(&mut OsRng), C::random_nonzero_F(&mut OsRng)));
}

pub(crate) fn batch_verify<C: Ciphersuite>() {
// Create 5 signatures
let mut keys = vec![];
let mut challenges = vec![];
let mut sigs = vec![];
for i in 0 .. 5 {
keys.push(C::random_nonzero_F(&mut OsRng));
challenges.push(C::random_nonzero_F(&mut OsRng));
sigs.push(SchnorrSignature::<C>::sign(keys[i], C::random_nonzero_F(&mut OsRng), challenges[i]));
}

// Batch verify
{
let mut batch = BatchVerifier::new(5);
for (i, sig) in sigs.iter().enumerate() {
sig.batch_verify(&mut OsRng, &mut batch, i, C::generator() * keys[i], challenges[i]);
}
batch.verify_with_vartime_blame().unwrap();
}

// Shift 1 from s from one to another and verify it fails
// This test will fail if unique factors aren't used per-signature, hence its inclusion
{
let mut batch = BatchVerifier::new(5);
for (i, mut sig) in sigs.clone().drain(..).enumerate() {
if i == 1 {
sig.s += C::F::one();
}
if i == 2 {
sig.s -= C::F::one();
}
sig.batch_verify(&mut OsRng, &mut batch, i, C::generator() * keys[i], challenges[i]);
}
if let Err(blame) = batch.verify_with_vartime_blame() {
assert!((blame == 1) || (blame == 2));
} else {
panic!("Batch verification considered malleated signatures valid");
}
}
}

pub(crate) fn aggregate<C: Ciphersuite>() {
// Create 5 signatures
let mut keys = vec![];
let mut challenges = vec![];
let mut aggregator = SchnorrAggregator::<Blake2b256, C>::new();
for i in 0 .. 5 {
keys.push(C::random_nonzero_F(&mut OsRng));
challenges.push(C::random_nonzero_F(&mut OsRng));
aggregator.aggregate(
C::generator() * keys[i],
challenges[i],
SchnorrSignature::<C>::sign(keys[i], C::random_nonzero_F(&mut OsRng), challenges[i]),
);
}

let aggregate = aggregator.complete().unwrap();
let aggregate =
SchnorrAggregate::<C>::read::<&[u8]>(&mut aggregate.serialize().as_ref()).unwrap();
assert!(aggregate.verify::<Blake2b256>(
keys
.iter()
.map(|key| C::generator() * key)
.zip(challenges.iter().cloned())
.collect::<Vec<_>>()
.as_ref()
));
}

#[test]
fn test() {
sign::<Ristretto>();
verify::<Ristretto>();
batch_verify::<Ristretto>();
aggregate::<Ristretto>();
}

0 comments on commit f733bbe

Please sign in to comment.