use std::collections::BTreeMap;
use frost_secp256k1_tr::{
keys::dkg::{part1, part2, part3, round1, round2},
keys::{KeyPackage, PublicKeyPackage},
rand_core::OsRng,
Identifier,
};
use zeroize::Zeroizing;
use crate::error::{KeepError, Result};
pub const SOFTWARE_DKG_VERSION: u8 = 1;
pub struct SoftwareDkgSession {
identifier: Identifier,
max_signers: u16,
min_signers: u16,
our_index: u16,
state: DkgState,
}
enum DkgState {
Init,
AwaitingRound1 {
secret: round1::SecretPackage,
our_round1: round1::Package,
peer_round1: BTreeMap<Identifier, round1::Package>,
},
AwaitingRound2 {
secret: round2::SecretPackage,
round1: BTreeMap<Identifier, round1::Package>,
peer_round2: BTreeMap<Identifier, round2::Package>,
},
Finalized,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SoftwareRound1Wire {
pub software_dkg_version: u8,
pub sender_index: u16,
pub package_hex: String,
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct SoftwareRound2Wire {
pub software_dkg_version: u8,
pub sender_index: u16,
pub package_hex: String,
}
impl std::fmt::Debug for SoftwareRound2Wire {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SoftwareRound2Wire")
.field("software_dkg_version", &self.software_dkg_version)
.field("sender_index", &self.sender_index)
.field("package_hex", &"<redacted>")
.finish()
}
}
impl Drop for SoftwareRound2Wire {
fn drop(&mut self) {
use zeroize::Zeroize;
self.package_hex.zeroize();
}
}
pub struct SoftwareDkgResult {
pub key_package: KeyPackage,
pub public_key_package: PublicKeyPackage,
pub group_pubkey: [u8; 32],
pub our_index: u16,
}
impl SoftwareDkgSession {
pub fn init(threshold: u16, participants: u16, our_index: u16) -> Result<Self> {
if threshold < 2 || threshold > participants {
return Err(KeepError::Frost(format!(
"threshold must satisfy 2 <= t ({threshold}) <= n ({participants})"
)));
}
if our_index < 1 || our_index > participants {
return Err(KeepError::Frost(format!(
"share index must satisfy 1..={participants}, got {our_index}"
)));
}
let identifier = Identifier::try_from(our_index).map_err(|e| {
KeepError::Frost(format!(
"share index {our_index} is not a valid FROST identifier: {e}"
))
})?;
Ok(Self {
identifier,
max_signers: participants,
min_signers: threshold,
our_index,
state: DkgState::Init,
})
}
pub fn round1(&mut self) -> Result<SoftwareRound1Wire> {
if !matches!(self.state, DkgState::Init) {
return Err(KeepError::Frost(
"SoftwareDkgSession::round1 called out of order (already past round 1)".into(),
));
}
let (secret, package) = part1(self.identifier, self.max_signers, self.min_signers, OsRng)
.map_err(|e| KeepError::Frost(format!("DKG part1 failed: {e}")))?;
let package_bytes = package
.serialize()
.map_err(|e| KeepError::Frost(format!("serialize round1 package: {e}")))?;
let wire = SoftwareRound1Wire {
software_dkg_version: SOFTWARE_DKG_VERSION,
sender_index: self.our_index,
package_hex: hex::encode(&package_bytes),
};
self.state = DkgState::AwaitingRound1 {
secret,
our_round1: package,
peer_round1: BTreeMap::new(),
};
Ok(wire)
}
pub fn round1_peer(&mut self, wire: &SoftwareRound1Wire) -> Result<bool> {
let peer_round1 = match &mut self.state {
DkgState::AwaitingRound1 { peer_round1, .. } => peer_round1,
_ => {
return Err(KeepError::Frost(
"SoftwareDkgSession::round1_peer called out of order".into(),
));
}
};
if wire.software_dkg_version != SOFTWARE_DKG_VERSION {
return Err(KeepError::Frost(format!(
"peer round1 package uses unsupported software_dkg_version {}, expected {}",
wire.software_dkg_version, SOFTWARE_DKG_VERSION
)));
}
if wire.sender_index == self.our_index {
return Err(KeepError::Frost(
"peer round1 package echoes our own share index; refusing to self-mix".into(),
));
}
if wire.sender_index < 1 || wire.sender_index > self.max_signers {
return Err(KeepError::Frost(format!(
"peer round1 sender_index {} out of range [1, {}]",
wire.sender_index, self.max_signers,
)));
}
let peer_id = Identifier::try_from(wire.sender_index).map_err(|e| {
KeepError::Frost(format!(
"peer index {} is not a valid FROST identifier: {e}",
wire.sender_index
))
})?;
if peer_round1.contains_key(&peer_id) {
return Err(KeepError::Frost(format!(
"duplicate round1 package from peer {}",
wire.sender_index
)));
}
let bytes = hex::decode(&wire.package_hex)
.map_err(|e| KeepError::Frost(format!("decode round1 package hex: {e}")))?;
let package = round1::Package::deserialize(&bytes)
.map_err(|e| KeepError::Frost(format!("deserialize round1 package: {e}")))?;
peer_round1.insert(peer_id, package);
Ok(peer_round1.len() as u16 + 1 == self.max_signers)
}
pub fn round2(&mut self) -> Result<Vec<(u16, SoftwareRound2Wire)>> {
let (secret, our_round1, peer_round1) =
match std::mem::replace(&mut self.state, DkgState::Finalized) {
DkgState::AwaitingRound1 {
secret,
our_round1,
peer_round1,
} if (peer_round1.len() as u16) + 1 == self.max_signers => {
(secret, our_round1, peer_round1)
}
other => {
self.state = other;
return Err(KeepError::Frost(
"SoftwareDkgSession::round2 called before every peer's round1 arrived"
.into(),
));
}
};
let (round2_secret, round2_packages) =
part2(secret, &peer_round1).map_err(|e| KeepError::Frost(format!("DKG part2: {e}")))?;
let mut wires: Vec<(u16, SoftwareRound2Wire)> = Vec::new();
for (peer_id, package) in &round2_packages {
let recipient_index = identifier_to_u16(peer_id).ok_or_else(|| {
KeepError::Frost("DKG part2 returned package for unknown identifier".into())
})?;
let bytes = Zeroizing::new(
package
.serialize()
.map_err(|e| KeepError::Frost(format!("serialize round2 package: {e}")))?,
);
wires.push((
recipient_index,
SoftwareRound2Wire {
software_dkg_version: SOFTWARE_DKG_VERSION,
sender_index: self.our_index,
package_hex: hex::encode(&bytes),
},
));
}
let mut round1_all = peer_round1;
round1_all.insert(self.identifier, our_round1);
self.state = DkgState::AwaitingRound2 {
secret: round2_secret,
round1: round1_all,
peer_round2: BTreeMap::new(),
};
Ok(wires)
}
pub fn receive_share(&mut self, wire: &SoftwareRound2Wire) -> Result<bool> {
let peer_round2 = match &mut self.state {
DkgState::AwaitingRound2 { peer_round2, .. } => peer_round2,
_ => {
return Err(KeepError::Frost(
"SoftwareDkgSession::receive_share called out of order".into(),
));
}
};
if wire.software_dkg_version != SOFTWARE_DKG_VERSION {
return Err(KeepError::Frost(format!(
"peer round2 share uses unsupported software_dkg_version {}, expected {}",
wire.software_dkg_version, SOFTWARE_DKG_VERSION,
)));
}
if wire.sender_index == self.our_index {
return Err(KeepError::Frost(
"peer round2 share echoes our own share index; refusing to self-mix".into(),
));
}
if wire.sender_index < 1 || wire.sender_index > self.max_signers {
return Err(KeepError::Frost(format!(
"peer round2 sender_index {} out of range [1, {}]",
wire.sender_index, self.max_signers,
)));
}
let peer_id = Identifier::try_from(wire.sender_index).map_err(|e| {
KeepError::Frost(format!(
"peer index {} is not a valid FROST identifier: {e}",
wire.sender_index
))
})?;
if peer_round2.contains_key(&peer_id) {
return Err(KeepError::Frost(format!(
"duplicate round2 share from peer {}",
wire.sender_index
)));
}
let bytes = Zeroizing::new(
hex::decode(&wire.package_hex)
.map_err(|e| KeepError::Frost(format!("decode round2 share hex: {e}")))?,
);
let package = round2::Package::deserialize(&bytes)
.map_err(|e| KeepError::Frost(format!("deserialize round2 share: {e}")))?;
peer_round2.insert(peer_id, package);
Ok(peer_round2.len() as u16 + 1 == self.max_signers)
}
pub fn finalize(&mut self) -> Result<SoftwareDkgResult> {
let (secret, round1, round2) = match std::mem::replace(&mut self.state, DkgState::Finalized)
{
DkgState::AwaitingRound2 {
secret,
round1,
peer_round2,
} if (peer_round2.len() as u16) + 1 == self.max_signers => {
(secret, round1, peer_round2)
}
other => {
self.state = other;
return Err(KeepError::Frost(
"SoftwareDkgSession::finalize called before every peer's round2 arrived".into(),
));
}
};
let mut round1_peers = round1;
round1_peers.remove(&self.identifier);
let (key_package, public_key_package) = part3(&secret, &round1_peers, &round2)
.map_err(|e| KeepError::Frost(format!("DKG part3: {e}")))?;
let group_pubkey = super::dealer::extract_group_pubkey(&public_key_package)?;
Ok(SoftwareDkgResult {
key_package,
public_key_package,
group_pubkey,
our_index: self.our_index,
})
}
pub fn our_index(&self) -> u16 {
self.our_index
}
}
fn identifier_to_u16(id: &Identifier) -> Option<u16> {
let bytes = id.serialize();
if bytes.len() < 32 {
return None;
}
for &b in &bytes[..30] {
if b != 0 {
return None;
}
}
Some(u16::from_be_bytes([bytes[30], bytes[31]]))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::frost::signing::sign_with_local_shares;
use crate::frost::SharePackage;
#[test]
fn end_to_end_2_of_3_software_dkg() {
run_group(2, 3);
}
#[test]
fn end_to_end_3_of_5_software_dkg() {
run_group(3, 5);
}
fn run_group(threshold: u16, participants: u16) {
let mut sessions: Vec<SoftwareDkgSession> = (1..=participants)
.map(|idx| SoftwareDkgSession::init(threshold, participants, idx).unwrap())
.collect();
let round1_wires: Vec<SoftwareRound1Wire> =
sessions.iter_mut().map(|s| s.round1().unwrap()).collect();
for (i, session) in sessions.iter_mut().enumerate() {
for (j, wire) in round1_wires.iter().enumerate() {
if i == j {
continue;
}
session.round1_peer(wire).unwrap();
}
}
let mut per_session_round2: Vec<Vec<(u16, SoftwareRound2Wire)>> =
sessions.iter_mut().map(|s| s.round2().unwrap()).collect();
for (sender_i, wires) in per_session_round2.drain(..).enumerate() {
for (recipient_index, wire) in wires {
let recipient_i = (recipient_index - 1) as usize;
assert_ne!(recipient_i, sender_i, "no self-shares in round 2");
sessions[recipient_i].receive_share(&wire).unwrap();
}
}
let results: Vec<SoftwareDkgResult> =
sessions.iter_mut().map(|s| s.finalize().unwrap()).collect();
let first_group = results[0].group_pubkey;
for r in &results {
assert_eq!(r.group_pubkey, first_group);
}
let share_packages: Vec<SharePackage> = results
.iter()
.take(threshold as usize)
.map(|r| {
let metadata = crate::frost::ShareMetadata::new(
r.our_index,
threshold,
participants,
r.group_pubkey,
"dkg-test".into(),
);
SharePackage::new(metadata, &r.key_package, &r.public_key_package).unwrap()
})
.collect();
let message = b"software dkg produces spendable shares";
let sig = sign_with_local_shares(&share_packages, message).unwrap();
assert_eq!(sig.len(), 64);
}
#[test]
fn round1_peer_refuses_bad_version() {
let mut a = SoftwareDkgSession::init(2, 2, 1).unwrap();
let mut b = SoftwareDkgSession::init(2, 2, 2).unwrap();
let _ = a.round1().unwrap();
let mut b_wire = b.round1().unwrap();
b_wire.software_dkg_version = 99;
let err = a
.round1_peer(&b_wire)
.expect_err("bad version must be refused");
assert!(matches!(err, KeepError::Frost(_)));
}
#[test]
fn duplicate_round1_package_from_peer_refused() {
let mut a = SoftwareDkgSession::init(2, 2, 1).unwrap();
let mut b = SoftwareDkgSession::init(2, 2, 2).unwrap();
let _ = a.round1().unwrap();
let b_wire = b.round1().unwrap();
a.round1_peer(&b_wire).unwrap();
let err = a
.round1_peer(&b_wire)
.expect_err("duplicate round1 must be refused");
assert!(matches!(err, KeepError::Frost(_)));
}
#[test]
fn round2_before_full_round1_refuses() {
let mut s = SoftwareDkgSession::init(2, 3, 1).unwrap();
let _ = s.round1().unwrap();
let err = s
.round2()
.expect_err("incomplete round1 -> round2 must be refused");
assert!(matches!(err, KeepError::Frost(_)));
}
#[test]
fn init_rejects_bad_config() {
assert!(SoftwareDkgSession::init(1, 3, 1).is_err());
assert!(SoftwareDkgSession::init(4, 3, 1).is_err());
assert!(SoftwareDkgSession::init(2, 3, 0).is_err());
assert!(SoftwareDkgSession::init(2, 3, 4).is_err());
}
#[test]
fn end_to_end_3_of_3_software_dkg() {
run_group(3, 3);
}
type Round2Wires = Vec<(u16, SoftwareRound2Wire)>;
fn assert_frost_reason(err: KeepError, needle: &str) {
match err {
KeepError::Frost(msg) => assert!(
msg.contains(needle),
"expected Frost error containing {needle:?}, got: {msg}"
),
other => panic!("expected KeepError::Frost, got {other:?}"),
}
}
fn advanced_2of2() -> (
SoftwareDkgSession,
SoftwareDkgSession,
Round2Wires,
Round2Wires,
) {
let mut a = SoftwareDkgSession::init(2, 2, 1).unwrap();
let mut b = SoftwareDkgSession::init(2, 2, 2).unwrap();
let aw = a.round1().unwrap();
let bw = b.round1().unwrap();
a.round1_peer(&bw).unwrap();
b.round1_peer(&aw).unwrap();
let a2 = a.round2().unwrap();
let b2 = b.round2().unwrap();
(a, b, a2, b2)
}
#[test]
fn finalize_refuses_when_a_peer_round2_share_is_missing() {
let mut sessions: Vec<SoftwareDkgSession> = (1..=3)
.map(|idx| SoftwareDkgSession::init(2, 3, idx).unwrap())
.collect();
let round1_wires: Vec<SoftwareRound1Wire> =
sessions.iter_mut().map(|s| s.round1().unwrap()).collect();
for (i, session) in sessions.iter_mut().enumerate() {
for (j, wire) in round1_wires.iter().enumerate() {
if i != j {
session.round1_peer(wire).unwrap();
}
}
}
let per_session_round2: Vec<Vec<(u16, SoftwareRound2Wire)>> =
sessions.iter_mut().map(|s| s.round2().unwrap()).collect();
for (recipient_index, wire) in &per_session_round2[1] {
if *recipient_index == 1 {
sessions[0].receive_share(wire).unwrap();
}
}
match sessions[0].finalize() {
Err(err) => assert_frost_reason(err, "before every peer's round2 arrived"),
Ok(_) => panic!("a missing peer round2 share must refuse finalize"),
}
}
#[test]
fn duplicate_round2_share_refused() {
let (mut a, _b, _a2, b2) = advanced_2of2();
let (recipient, wire) = &b2[0];
assert_eq!(*recipient, 1);
a.receive_share(wire).unwrap();
let err = a
.receive_share(wire)
.expect_err("duplicate round2 share must be refused");
assert_frost_reason(err, "duplicate round2 share from peer");
}
#[test]
fn round2_share_echoing_our_index_refused() {
let (mut a, _b, a2, _b2) = advanced_2of2();
let (_recipient, own_wire) = &a2[0];
assert_eq!(own_wire.sender_index, 1);
let err = a
.receive_share(own_wire)
.expect_err("a self-echoed round2 share must be refused");
assert_frost_reason(err, "echoes our own share index");
}
#[test]
fn receive_share_out_of_order_refused() {
let (_a, _b, _a2, b2) = advanced_2of2();
let (_recipient, wire) = &b2[0];
let mut fresh = SoftwareDkgSession::init(2, 2, 1).unwrap();
let err = fresh
.receive_share(wire)
.expect_err("receive_share before round2 must be refused");
assert_frost_reason(err, "receive_share called out of order");
}
#[test]
fn identifier_round_trip() {
for idx in [1u16, 2, 5, 42, 255, 300, 1000, 65535] {
let id = Identifier::try_from(idx).unwrap();
assert_eq!(identifier_to_u16(&id), Some(idx));
}
}
}