Start modularizing FROST tests as per https://github.com/serai-dex/serai/issues/9

This commit is contained in:
Luke Parker
2022-05-25 00:28:57 -04:00
parent 1eaf2f897b
commit 868a63a6b2
7 changed files with 182 additions and 52 deletions

View File

@@ -14,6 +14,8 @@ pub mod key_gen;
pub mod algorithm;
pub mod sign;
pub mod tests;
/// Set of errors for curve-related operations, namely encoding and decoding
#[derive(Error, Debug)]
pub enum CurveError {

View File

@@ -0,0 +1,32 @@
use rand_core::{RngCore, CryptoRng};
use crate::{
Curve, MultisigKeys,
tests::{schnorr::{sign, verify, batch_verify}, key_gen}
};
// Test generation of FROST keys
fn key_generation<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
// This alone verifies the verification shares and group key are agreed upon as expected
key_gen::<_, C>(rng);
}
// Test serialization of generated keys
fn keys_serialization<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
for (_, keys) in key_gen::<_, C>(rng) {
assert_eq!(&MultisigKeys::<C>::deserialize(&keys.serialize()).unwrap(), &*keys);
}
}
pub fn test_curve<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
// TODO: Test the Curve functions themselves
// Test Schnorr signatures work as expected
sign::<_, C>(rng);
verify::<_, C>(rng);
batch_verify::<_, C>(rng);
// Test FROST key generation and serialization of MultisigKeys works as expected
key_generation::<_, C>(rng);
keys_serialization::<_, C>(rng);
}

View File

@@ -0,0 +1,2 @@
mod secp256k1;
mod schnorr;

View File

@@ -0,0 +1,42 @@
use std::rc::Rc;
use rand::rngs::OsRng;
use crate::{
Curve, schnorr, algorithm::{Hram, Schnorr},
tests::{key_gen, algorithm_machines, sign as sign_test, actual::secp256k1::{Secp256k1, TestHram}}
};
const MESSAGE: &[u8] = b"Hello World";
#[test]
fn sign() {
sign_test(
&mut OsRng,
algorithm_machines(
&mut OsRng,
Schnorr::<Secp256k1, TestHram>::new(),
&key_gen::<_, Secp256k1>(&mut OsRng)
),
MESSAGE
);
}
#[test]
fn sign_with_offset() {
let mut keys = key_gen::<_, Secp256k1>(&mut OsRng);
let group_key = keys[&1].group_key();
let offset = Secp256k1::hash_to_F(b"offset");
for i in 1 ..= u16::try_from(keys.len()).unwrap() {
keys.insert(i, Rc::new(keys[&i].offset(offset)));
}
let offset_key = group_key + (Secp256k1::generator_table() * offset);
let sig = sign_test(
&mut OsRng,
algorithm_machines(&mut OsRng, Schnorr::<Secp256k1, TestHram>::new(), &keys),
MESSAGE
);
assert!(schnorr::verify(offset_key, TestHram::hram(&sig.R, &offset_key, MESSAGE), &sig));
}

View File

@@ -0,0 +1,114 @@
use core::convert::TryInto;
use rand::rngs::OsRng;
use ff::PrimeField;
use group::GroupEncoding;
use sha2::{Digest, Sha256, Sha512};
use k256::{
elliptic_curve::{generic_array::GenericArray, bigint::{ArrayEncoding, U512}, ops::Reduce},
Scalar,
ProjectivePoint
};
use crate::{CurveError, Curve, multiexp_vartime, algorithm::Hram, tests::curve::test_curve};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Secp256k1;
impl Curve for Secp256k1 {
type F = Scalar;
type G = ProjectivePoint;
type T = ProjectivePoint;
fn id() -> String {
"secp256k1".to_string()
}
fn id_len() -> u8 {
Self::id().len() as u8
}
fn generator() -> Self::G {
Self::G::GENERATOR
}
fn generator_table() -> Self::T {
Self::G::GENERATOR
}
fn multiexp_vartime(scalars: &[Self::F], points: &[Self::G]) -> Self::G {
multiexp_vartime(scalars, points, false)
}
// The IETF draft doesn't specify a secp256k1 ciphersuite
// This test just uses the simplest ciphersuite which would still be viable to deploy
fn hash_msg(msg: &[u8]) -> Vec<u8> {
(&Sha256::digest(msg)).to_vec()
}
// Use wide reduction for security
fn hash_to_F(data: &[u8]) -> Self::F {
Scalar::from_uint_reduced(
U512::from_be_byte_array(Sha512::new().chain_update("rho").chain_update(data).finalize())
)
}
fn F_len() -> usize {
32
}
fn G_len() -> usize {
33
}
fn F_from_slice(slice: &[u8]) -> Result<Self::F, CurveError> {
let bytes: [u8; 32] = slice.try_into()
.map_err(|_| CurveError::InvalidLength(32, slice.len()))?;
let scalar = Scalar::from_repr(bytes.into());
if scalar.is_none().unwrap_u8() == 1 {
Err(CurveError::InvalidScalar)?;
}
Ok(scalar.unwrap())
}
fn G_from_slice(slice: &[u8]) -> Result<Self::G, CurveError> {
let point = ProjectivePoint::from_bytes(GenericArray::from_slice(slice));
if point.is_none().unwrap_u8() == 1 {
Err(CurveError::InvalidScalar)?;
}
Ok(point.unwrap())
}
fn F_to_bytes(f: &Self::F) -> Vec<u8> {
(&f.to_bytes()).to_vec()
}
fn G_to_bytes(g: &Self::G) -> Vec<u8> {
(&g.to_bytes()).to_vec()
}
}
#[allow(non_snake_case)]
#[derive(Clone)]
pub struct TestHram {}
impl Hram<Secp256k1> for TestHram {
#[allow(non_snake_case)]
fn hram(R: &ProjectivePoint, A: &ProjectivePoint, m: &[u8]) -> Scalar {
Scalar::from_uint_reduced(
U512::from_be_byte_array(
Sha512::new()
.chain_update(Secp256k1::G_to_bytes(R))
.chain_update(Secp256k1::G_to_bytes(A))
.chain_update(m)
.finalize()
)
)
}
}
#[test]
fn secp256k1_curve() {
test_curve::<_, Secp256k1>(&mut OsRng);
}

View File

@@ -0,0 +1,160 @@
use std::{rc::Rc, collections::HashMap};
use rand_core::{RngCore, CryptoRng};
use crate::{
Curve,
MultisigParams, MultisigKeys,
key_gen,
algorithm::Algorithm,
sign::{StateMachine, AlgorithmMachine}
};
// Internal tests
mod schnorr;
// Test suites for public usage
pub mod curve;
// Literal test definitions to run during `cargo test`
#[cfg(test)]
mod literal;
pub const PARTICIPANTS: u16 = 5;
pub const THRESHOLD: u16 = ((PARTICIPANTS / 3) * 2) + 1;
pub fn clone_without<K: Clone + std::cmp::Eq + std::hash::Hash, V: Clone>(
map: &HashMap<K, V>,
without: &K
) -> HashMap<K, V> {
let mut res = map.clone();
res.remove(without).unwrap();
res
}
pub fn key_gen<R: RngCore + CryptoRng, C: Curve>(
rng: &mut R
) -> HashMap<u16, Rc<MultisigKeys<C>>> {
let mut params = HashMap::new();
let mut machines = HashMap::new();
let mut commitments = HashMap::new();
for i in 1 ..= PARTICIPANTS {
params.insert(
i,
MultisigParams::new(
THRESHOLD,
PARTICIPANTS,
i
).unwrap()
);
machines.insert(
i,
key_gen::StateMachine::<C>::new(
params[&i],
"FROST test key_gen".to_string()
)
);
commitments.insert(
i,
machines.get_mut(&i).unwrap().generate_coefficients(rng).unwrap()
);
}
let mut secret_shares = HashMap::new();
for (l, machine) in machines.iter_mut() {
secret_shares.insert(
*l,
machine.generate_secret_shares(rng, clone_without(&commitments, l)).unwrap()
);
}
let mut verification_shares = None;
let mut group_key = None;
let mut keys = HashMap::new();
for (i, machine) in machines.iter_mut() {
let mut our_secret_shares = HashMap::new();
for (l, shares) in &secret_shares {
if i == l {
continue;
}
our_secret_shares.insert(*l, shares[&i].clone());
}
let these_keys = machine.complete(our_secret_shares).unwrap();
// Verify the verification_shares are agreed upon
if verification_shares.is_none() {
verification_shares = Some(these_keys.verification_shares());
}
assert_eq!(verification_shares.as_ref().unwrap(), &these_keys.verification_shares());
// Verify the group keys are agreed upon
if group_key.is_none() {
group_key = Some(these_keys.group_key());
}
assert_eq!(group_key.unwrap(), these_keys.group_key());
keys.insert(*i, Rc::new(these_keys));
}
keys
}
pub fn algorithm_machines<R: RngCore, C: Curve, A: Algorithm<C>>(
rng: &mut R,
algorithm: A,
keys: &HashMap<u16, Rc<MultisigKeys<C>>>,
) -> HashMap<u16, AlgorithmMachine<C, A>> {
let mut included = vec![];
while included.len() < usize::from(keys[&1].params().t()) {
let n = u16::try_from((rng.next_u64() % u64::try_from(keys.len()).unwrap()) + 1).unwrap();
if included.contains(&n) {
continue;
}
included.push(n);
}
keys.iter().filter_map(
|(i, keys)| if included.contains(&i) {
Some((
*i,
AlgorithmMachine::new(
algorithm.clone(),
keys.clone(),
&included.clone()
).unwrap()
))
} else {
None
}
).collect()
}
pub fn sign<R: RngCore + CryptoRng, M: StateMachine>(
rng: &mut R,
mut machines: HashMap<u16, M>,
msg: &[u8]
) -> M::Signature {
let mut commitments = HashMap::new();
for (i, machine) in machines.iter_mut() {
commitments.insert(*i, machine.preprocess(rng).unwrap());
}
let mut shares = HashMap::new();
for (i, machine) in machines.iter_mut() {
shares.insert(
*i,
machine.sign(clone_without(&commitments, i), msg).unwrap()
);
}
let mut signature = None;
for (i, machine) in machines.iter_mut() {
let sig = machine.complete(clone_without(&shares, i)).unwrap();
if signature.is_none() {
signature = Some(sig.clone());
}
assert_eq!(&sig, signature.as_ref().unwrap());
}
signature.unwrap()
}

View File

@@ -0,0 +1,32 @@
use rand_core::{RngCore, CryptoRng};
use ff::Field;
use crate::{Curve, schnorr, algorithm::SchnorrSignature};
pub(crate) fn sign<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
let private_key = C::F::random(&mut *rng);
let nonce = C::F::random(&mut *rng);
let challenge = C::F::random(rng); // Doesn't bother to craft an HRAM
assert!(
schnorr::verify::<C>(
C::generator_table() * private_key,
challenge,
&schnorr::sign(private_key, nonce, 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<R: RngCore + CryptoRng, C: Curve>(rng: &mut R) {
assert!(
!schnorr::verify::<C>(
C::generator_table() * C::F::random(&mut *rng),
C::F::random(rng),
&SchnorrSignature { R: C::generator_table() * C::F::zero(), s: C::F::zero() }
)
);
}