1use std::collections::BTreeMap;
40
41use frost_secp256k1_tr::{
42 keys::dkg::{part1, part2, part3, round1, round2},
43 keys::{KeyPackage, PublicKeyPackage},
44 rand_core::OsRng,
45 Identifier,
46};
47use zeroize::Zeroizing;
48
49use crate::error::{KeepError, Result};
50
51pub const SOFTWARE_DKG_VERSION: u8 = 1;
54
55pub struct SoftwareDkgSession {
63 identifier: Identifier,
64 max_signers: u16,
65 min_signers: u16,
66 our_index: u16,
67 state: DkgState,
68}
69
70enum DkgState {
71 Init,
72 AwaitingRound1 {
73 secret: round1::SecretPackage,
74 our_round1: round1::Package,
75 peer_round1: BTreeMap<Identifier, round1::Package>,
76 },
77 AwaitingRound2 {
78 secret: round2::SecretPackage,
79 round1: BTreeMap<Identifier, round1::Package>,
80 peer_round2: BTreeMap<Identifier, round2::Package>,
81 },
82 Finalized,
83}
84
85#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
89pub struct SoftwareRound1Wire {
90 pub software_dkg_version: u8,
93 pub sender_index: u16,
95 pub package_hex: String,
98}
99
100#[derive(Clone, serde::Serialize, serde::Deserialize)]
107pub struct SoftwareRound2Wire {
108 pub software_dkg_version: u8,
110 pub sender_index: u16,
112 pub package_hex: String,
114}
115
116impl std::fmt::Debug for SoftwareRound2Wire {
117 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118 f.debug_struct("SoftwareRound2Wire")
119 .field("software_dkg_version", &self.software_dkg_version)
120 .field("sender_index", &self.sender_index)
121 .field("package_hex", &"<redacted>")
122 .finish()
123 }
124}
125
126impl Drop for SoftwareRound2Wire {
127 fn drop(&mut self) {
128 use zeroize::Zeroize;
132 self.package_hex.zeroize();
133 }
134}
135
136pub struct SoftwareDkgResult {
139 pub key_package: KeyPackage,
142 pub public_key_package: PublicKeyPackage,
145 pub group_pubkey: [u8; 32],
147 pub our_index: u16,
149}
150
151impl SoftwareDkgSession {
152 pub fn init(threshold: u16, participants: u16, our_index: u16) -> Result<Self> {
158 if threshold < 2 || threshold > participants {
159 return Err(KeepError::Frost(format!(
160 "threshold must satisfy 2 <= t ({threshold}) <= n ({participants})"
161 )));
162 }
163 if our_index < 1 || our_index > participants {
164 return Err(KeepError::Frost(format!(
165 "share index must satisfy 1..={participants}, got {our_index}"
166 )));
167 }
168 let identifier = Identifier::try_from(our_index).map_err(|e| {
169 KeepError::Frost(format!(
170 "share index {our_index} is not a valid FROST identifier: {e}"
171 ))
172 })?;
173 Ok(Self {
174 identifier,
175 max_signers: participants,
176 min_signers: threshold,
177 our_index,
178 state: DkgState::Init,
179 })
180 }
181
182 pub fn round1(&mut self) -> Result<SoftwareRound1Wire> {
186 if !matches!(self.state, DkgState::Init) {
187 return Err(KeepError::Frost(
188 "SoftwareDkgSession::round1 called out of order (already past round 1)".into(),
189 ));
190 }
191 let (secret, package) = part1(self.identifier, self.max_signers, self.min_signers, OsRng)
192 .map_err(|e| KeepError::Frost(format!("DKG part1 failed: {e}")))?;
193 let package_bytes = package
194 .serialize()
195 .map_err(|e| KeepError::Frost(format!("serialize round1 package: {e}")))?;
196 let wire = SoftwareRound1Wire {
197 software_dkg_version: SOFTWARE_DKG_VERSION,
198 sender_index: self.our_index,
199 package_hex: hex::encode(&package_bytes),
200 };
201 self.state = DkgState::AwaitingRound1 {
202 secret,
203 our_round1: package,
204 peer_round1: BTreeMap::new(),
205 };
206 Ok(wire)
207 }
208
209 pub fn round1_peer(&mut self, wire: &SoftwareRound1Wire) -> Result<bool> {
213 let peer_round1 = match &mut self.state {
214 DkgState::AwaitingRound1 { peer_round1, .. } => peer_round1,
215 _ => {
216 return Err(KeepError::Frost(
217 "SoftwareDkgSession::round1_peer called out of order".into(),
218 ));
219 }
220 };
221 if wire.software_dkg_version != SOFTWARE_DKG_VERSION {
222 return Err(KeepError::Frost(format!(
223 "peer round1 package uses unsupported software_dkg_version {}, expected {}",
224 wire.software_dkg_version, SOFTWARE_DKG_VERSION
225 )));
226 }
227 if wire.sender_index == self.our_index {
228 return Err(KeepError::Frost(
229 "peer round1 package echoes our own share index; refusing to self-mix".into(),
230 ));
231 }
232 if wire.sender_index < 1 || wire.sender_index > self.max_signers {
233 return Err(KeepError::Frost(format!(
234 "peer round1 sender_index {} out of range [1, {}]",
235 wire.sender_index, self.max_signers,
236 )));
237 }
238 let peer_id = Identifier::try_from(wire.sender_index).map_err(|e| {
239 KeepError::Frost(format!(
240 "peer index {} is not a valid FROST identifier: {e}",
241 wire.sender_index
242 ))
243 })?;
244 if peer_round1.contains_key(&peer_id) {
245 return Err(KeepError::Frost(format!(
246 "duplicate round1 package from peer {}",
247 wire.sender_index
248 )));
249 }
250 let bytes = hex::decode(&wire.package_hex)
251 .map_err(|e| KeepError::Frost(format!("decode round1 package hex: {e}")))?;
252 let package = round1::Package::deserialize(&bytes)
253 .map_err(|e| KeepError::Frost(format!("deserialize round1 package: {e}")))?;
254 peer_round1.insert(peer_id, package);
255 Ok(peer_round1.len() as u16 + 1 == self.max_signers)
256 }
257
258 pub fn round2(&mut self) -> Result<Vec<(u16, SoftwareRound2Wire)>> {
262 let (secret, our_round1, peer_round1) =
263 match std::mem::replace(&mut self.state, DkgState::Finalized) {
264 DkgState::AwaitingRound1 {
265 secret,
266 our_round1,
267 peer_round1,
268 } if (peer_round1.len() as u16) + 1 == self.max_signers => {
269 (secret, our_round1, peer_round1)
270 }
271 other => {
272 self.state = other;
277 return Err(KeepError::Frost(
278 "SoftwareDkgSession::round2 called before every peer's round1 arrived"
279 .into(),
280 ));
281 }
282 };
283 let (round2_secret, round2_packages) =
286 part2(secret, &peer_round1).map_err(|e| KeepError::Frost(format!("DKG part2: {e}")))?;
287
288 let mut wires: Vec<(u16, SoftwareRound2Wire)> = Vec::new();
289 for (peer_id, package) in &round2_packages {
290 let recipient_index = identifier_to_u16(peer_id).ok_or_else(|| {
291 KeepError::Frost("DKG part2 returned package for unknown identifier".into())
292 })?;
293 let bytes = Zeroizing::new(
296 package
297 .serialize()
298 .map_err(|e| KeepError::Frost(format!("serialize round2 package: {e}")))?,
299 );
300 wires.push((
301 recipient_index,
302 SoftwareRound2Wire {
303 software_dkg_version: SOFTWARE_DKG_VERSION,
304 sender_index: self.our_index,
305 package_hex: hex::encode(&bytes),
306 },
307 ));
308 }
309
310 let mut round1_all = peer_round1;
312 round1_all.insert(self.identifier, our_round1);
313
314 self.state = DkgState::AwaitingRound2 {
315 secret: round2_secret,
316 round1: round1_all,
317 peer_round2: BTreeMap::new(),
318 };
319 Ok(wires)
320 }
321
322 pub fn receive_share(&mut self, wire: &SoftwareRound2Wire) -> Result<bool> {
326 let peer_round2 = match &mut self.state {
327 DkgState::AwaitingRound2 { peer_round2, .. } => peer_round2,
328 _ => {
329 return Err(KeepError::Frost(
330 "SoftwareDkgSession::receive_share called out of order".into(),
331 ));
332 }
333 };
334 if wire.software_dkg_version != SOFTWARE_DKG_VERSION {
335 return Err(KeepError::Frost(format!(
336 "peer round2 share uses unsupported software_dkg_version {}, expected {}",
337 wire.software_dkg_version, SOFTWARE_DKG_VERSION,
338 )));
339 }
340 if wire.sender_index == self.our_index {
341 return Err(KeepError::Frost(
342 "peer round2 share echoes our own share index; refusing to self-mix".into(),
343 ));
344 }
345 if wire.sender_index < 1 || wire.sender_index > self.max_signers {
346 return Err(KeepError::Frost(format!(
347 "peer round2 sender_index {} out of range [1, {}]",
348 wire.sender_index, self.max_signers,
349 )));
350 }
351 let peer_id = Identifier::try_from(wire.sender_index).map_err(|e| {
352 KeepError::Frost(format!(
353 "peer index {} is not a valid FROST identifier: {e}",
354 wire.sender_index
355 ))
356 })?;
357 if peer_round2.contains_key(&peer_id) {
358 return Err(KeepError::Frost(format!(
359 "duplicate round2 share from peer {}",
360 wire.sender_index
361 )));
362 }
363 let bytes = Zeroizing::new(
364 hex::decode(&wire.package_hex)
365 .map_err(|e| KeepError::Frost(format!("decode round2 share hex: {e}")))?,
366 );
367 let package = round2::Package::deserialize(&bytes)
368 .map_err(|e| KeepError::Frost(format!("deserialize round2 share: {e}")))?;
369 peer_round2.insert(peer_id, package);
370 Ok(peer_round2.len() as u16 + 1 == self.max_signers)
371 }
372
373 pub fn finalize(&mut self) -> Result<SoftwareDkgResult> {
377 let (secret, round1, round2) = match std::mem::replace(&mut self.state, DkgState::Finalized)
378 {
379 DkgState::AwaitingRound2 {
380 secret,
381 round1,
382 peer_round2,
383 } if (peer_round2.len() as u16) + 1 == self.max_signers => {
384 (secret, round1, peer_round2)
385 }
386 other => {
387 self.state = other;
388 return Err(KeepError::Frost(
389 "SoftwareDkgSession::finalize called before every peer's round2 arrived".into(),
390 ));
391 }
392 };
393
394 let mut round1_peers = round1;
397 round1_peers.remove(&self.identifier);
398
399 let (key_package, public_key_package) = part3(&secret, &round1_peers, &round2)
400 .map_err(|e| KeepError::Frost(format!("DKG part3: {e}")))?;
401
402 let group_pubkey = super::dealer::extract_group_pubkey(&public_key_package)?;
405
406 Ok(SoftwareDkgResult {
407 key_package,
408 public_key_package,
409 group_pubkey,
410 our_index: self.our_index,
411 })
412 }
413
414 pub fn our_index(&self) -> u16 {
416 self.our_index
417 }
418}
419
420fn identifier_to_u16(id: &Identifier) -> Option<u16> {
421 let bytes = id.serialize();
425 if bytes.len() < 32 {
426 return None;
427 }
428 for &b in &bytes[..30] {
429 if b != 0 {
430 return None;
431 }
432 }
433 Some(u16::from_be_bytes([bytes[30], bytes[31]]))
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439 use crate::frost::signing::sign_with_local_shares;
440 use crate::frost::SharePackage;
441
442 #[test]
445 fn end_to_end_2_of_3_software_dkg() {
446 run_group(2, 3);
447 }
448
449 #[test]
453 fn end_to_end_3_of_5_software_dkg() {
454 run_group(3, 5);
455 }
456
457 fn run_group(threshold: u16, participants: u16) {
458 let mut sessions: Vec<SoftwareDkgSession> = (1..=participants)
459 .map(|idx| SoftwareDkgSession::init(threshold, participants, idx).unwrap())
460 .collect();
461
462 let round1_wires: Vec<SoftwareRound1Wire> =
464 sessions.iter_mut().map(|s| s.round1().unwrap()).collect();
465
466 for (i, session) in sessions.iter_mut().enumerate() {
468 for (j, wire) in round1_wires.iter().enumerate() {
469 if i == j {
470 continue;
471 }
472 session.round1_peer(wire).unwrap();
473 }
474 }
475
476 let mut per_session_round2: Vec<Vec<(u16, SoftwareRound2Wire)>> =
478 sessions.iter_mut().map(|s| s.round2().unwrap()).collect();
479
480 for (sender_i, wires) in per_session_round2.drain(..).enumerate() {
482 for (recipient_index, wire) in wires {
483 let recipient_i = (recipient_index - 1) as usize;
484 assert_ne!(recipient_i, sender_i, "no self-shares in round 2");
485 sessions[recipient_i].receive_share(&wire).unwrap();
486 }
487 }
488
489 let results: Vec<SoftwareDkgResult> =
491 sessions.iter_mut().map(|s| s.finalize().unwrap()).collect();
492 let first_group = results[0].group_pubkey;
493 for r in &results {
494 assert_eq!(r.group_pubkey, first_group);
495 }
496
497 let share_packages: Vec<SharePackage> = results
501 .iter()
502 .take(threshold as usize)
503 .map(|r| {
504 let metadata = crate::frost::ShareMetadata::new(
505 r.our_index,
506 threshold,
507 participants,
508 r.group_pubkey,
509 "dkg-test".into(),
510 );
511 SharePackage::new(metadata, &r.key_package, &r.public_key_package).unwrap()
512 })
513 .collect();
514
515 let message = b"software dkg produces spendable shares";
516 let sig = sign_with_local_shares(&share_packages, message).unwrap();
517 assert_eq!(sig.len(), 64);
518 }
519
520 #[test]
523 fn round1_peer_refuses_bad_version() {
524 let mut a = SoftwareDkgSession::init(2, 2, 1).unwrap();
525 let mut b = SoftwareDkgSession::init(2, 2, 2).unwrap();
526 let _ = a.round1().unwrap();
527 let mut b_wire = b.round1().unwrap();
528 b_wire.software_dkg_version = 99;
529 let err = a
530 .round1_peer(&b_wire)
531 .expect_err("bad version must be refused");
532 assert!(matches!(err, KeepError::Frost(_)));
533 }
534
535 #[test]
538 fn duplicate_round1_package_from_peer_refused() {
539 let mut a = SoftwareDkgSession::init(2, 2, 1).unwrap();
540 let mut b = SoftwareDkgSession::init(2, 2, 2).unwrap();
541 let _ = a.round1().unwrap();
542 let b_wire = b.round1().unwrap();
543 a.round1_peer(&b_wire).unwrap();
544 let err = a
545 .round1_peer(&b_wire)
546 .expect_err("duplicate round1 must be refused");
547 assert!(matches!(err, KeepError::Frost(_)));
548 }
549
550 #[test]
553 fn round2_before_full_round1_refuses() {
554 let mut s = SoftwareDkgSession::init(2, 3, 1).unwrap();
555 let _ = s.round1().unwrap();
556 let err = s
557 .round2()
558 .expect_err("incomplete round1 -> round2 must be refused");
559 assert!(matches!(err, KeepError::Frost(_)));
560 }
561
562 #[test]
565 fn init_rejects_bad_config() {
566 assert!(SoftwareDkgSession::init(1, 3, 1).is_err());
567 assert!(SoftwareDkgSession::init(4, 3, 1).is_err());
568 assert!(SoftwareDkgSession::init(2, 3, 0).is_err());
569 assert!(SoftwareDkgSession::init(2, 3, 4).is_err());
570 }
571
572 #[test]
575 fn end_to_end_3_of_3_software_dkg() {
576 run_group(3, 3);
577 }
578
579 type Round2Wires = Vec<(u16, SoftwareRound2Wire)>;
580
581 fn assert_frost_reason(err: KeepError, needle: &str) {
585 match err {
586 KeepError::Frost(msg) => assert!(
587 msg.contains(needle),
588 "expected Frost error containing {needle:?}, got: {msg}"
589 ),
590 other => panic!("expected KeepError::Frost, got {other:?}"),
591 }
592 }
593
594 fn advanced_2of2() -> (
598 SoftwareDkgSession,
599 SoftwareDkgSession,
600 Round2Wires,
601 Round2Wires,
602 ) {
603 let mut a = SoftwareDkgSession::init(2, 2, 1).unwrap();
604 let mut b = SoftwareDkgSession::init(2, 2, 2).unwrap();
605 let aw = a.round1().unwrap();
606 let bw = b.round1().unwrap();
607 a.round1_peer(&bw).unwrap();
608 b.round1_peer(&aw).unwrap();
609 let a2 = a.round2().unwrap();
610 let b2 = b.round2().unwrap();
611 (a, b, a2, b2)
612 }
613
614 #[test]
618 fn finalize_refuses_when_a_peer_round2_share_is_missing() {
619 let mut sessions: Vec<SoftwareDkgSession> = (1..=3)
620 .map(|idx| SoftwareDkgSession::init(2, 3, idx).unwrap())
621 .collect();
622 let round1_wires: Vec<SoftwareRound1Wire> =
623 sessions.iter_mut().map(|s| s.round1().unwrap()).collect();
624 for (i, session) in sessions.iter_mut().enumerate() {
625 for (j, wire) in round1_wires.iter().enumerate() {
626 if i != j {
627 session.round1_peer(wire).unwrap();
628 }
629 }
630 }
631 let per_session_round2: Vec<Vec<(u16, SoftwareRound2Wire)>> =
632 sessions.iter_mut().map(|s| s.round2().unwrap()).collect();
633
634 for (recipient_index, wire) in &per_session_round2[1] {
637 if *recipient_index == 1 {
638 sessions[0].receive_share(wire).unwrap();
639 }
640 }
641
642 match sessions[0].finalize() {
648 Err(err) => assert_frost_reason(err, "before every peer's round2 arrived"),
649 Ok(_) => panic!("a missing peer round2 share must refuse finalize"),
650 }
651 }
652
653 #[test]
656 fn duplicate_round2_share_refused() {
657 let (mut a, _b, _a2, b2) = advanced_2of2();
658 let (recipient, wire) = &b2[0];
660 assert_eq!(*recipient, 1);
661 a.receive_share(wire).unwrap();
662 let err = a
663 .receive_share(wire)
664 .expect_err("duplicate round2 share must be refused");
665 assert_frost_reason(err, "duplicate round2 share from peer");
666 }
667
668 #[test]
671 fn round2_share_echoing_our_index_refused() {
672 let (mut a, _b, a2, _b2) = advanced_2of2();
673 let (_recipient, own_wire) = &a2[0];
675 assert_eq!(own_wire.sender_index, 1);
676 let err = a
677 .receive_share(own_wire)
678 .expect_err("a self-echoed round2 share must be refused");
679 assert_frost_reason(err, "echoes our own share index");
680 }
681
682 #[test]
685 fn receive_share_out_of_order_refused() {
686 let (_a, _b, _a2, b2) = advanced_2of2();
687 let (_recipient, wire) = &b2[0];
688 let mut fresh = SoftwareDkgSession::init(2, 2, 1).unwrap();
690 let err = fresh
691 .receive_share(wire)
692 .expect_err("receive_share before round2 must be refused");
693 assert_frost_reason(err, "receive_share called out of order");
694 }
695
696 #[test]
697 fn identifier_round_trip() {
698 for idx in [1u16, 2, 5, 42, 255, 300, 1000, 65535] {
699 let id = Identifier::try_from(idx).unwrap();
700 assert_eq!(identifier_to_u16(&id), Some(idx));
701 }
702 }
703}