Skip to main content

keep_core/frost/
dkg.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! In-process DKG (#454) using the standard frost-secp256k1-tr 3-round protocol.
5//!
6//! `keep frost network dkg` today requires `--hardware <path>` so the private
7//! polynomial coefficients live entirely on an attached signer (M5Stack ESP32,
8//! etc.). That is safer for production but blocks any user without hardware
9//! from participating and blocks CI from exercising DKG end-to-end (#436).
10//!
11//! [`SoftwareDkgSession`] wraps `frost-secp256k1-tr::keys::dkg::{part1,part2,
12//! part3}` behind the same six-step state machine `keep-cli` uses to drive
13//! the hardware signer (`init` -> `round1` -> `round1_peer` -> `round2` ->
14//! `receive_share` -> `finalize`), so the CLI can dispatch on the presence
15//! of `--hardware` without any protocol-level branching.
16//!
17//! ## Wire compatibility
18//!
19//! This module speaks a **software-only** wire format ([`SOFTWARE_DKG_VERSION`]
20//! is emitted alongside every round1 package). The keep-esp32 firmware ships
21//! its own binary format the software side does not know how to parse, and
22//! the mirror is also true, so software peers and hardware peers cannot DKG
23//! with each other on this branch. Mixed groups must all be one or the
24//! other; the CLI marks this explicitly so a bystander does not silently
25//! DKG-with-nobody.
26//!
27//! ## Threat model reminder
28//!
29//! Software DKG puts every participant's polynomial + coefficient
30//! commitments in that participant's process memory for the duration of
31//! the run. That is the same trust surface `frost generate` (trusted
32//! dealer) has for the full group secret, but SPLIT across the group and
33//! reset once `part3` finishes: no single machine ever sees any other
34//! participant's polynomial. That is materially better than trusted-dealer,
35//! materially worse than hardware DKG. Operators of high-value groups
36//! should still prefer hardware; software is here to unblock everyone else
37//! and to give CI a real DKG path.
38
39use 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
51/// Wire discriminator. Bumped when the serialized package layout changes so
52/// old peers reject the newer packages loudly rather than mis-decoding.
53pub const SOFTWARE_DKG_VERSION: u8 = 1;
54
55/// One participant's software DKG state machine. Same six-step public
56/// interface `keep-cli` drives against the hardware signer, so the CLI
57/// dispatches on the presence of `--hardware` without any protocol branching.
58///
59/// The state machine is linear and validates every transition, so an
60/// out-of-order call (e.g. `dkg_round2` before every peer's round1 arrived)
61/// returns a clear error rather than silently producing garbage.
62pub 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/// Wire-format round1 package emitted by [`SoftwareDkgSession::round1`]. The
86/// CLI encodes this as JSON and publishes it on the DKG topic; peers running
87/// this same version decode it back via [`SoftwareDkgSession::round1_peer`].
88#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
89pub struct SoftwareRound1Wire {
90    /// Discriminator so hardware peers reject the payload rather than
91    /// silently mis-decoding. Must equal [`SOFTWARE_DKG_VERSION`].
92    pub software_dkg_version: u8,
93    /// The 1-indexed participant identifier that produced this package.
94    pub sender_index: u16,
95    /// Hex-encoded `frost_secp256k1_tr::keys::dkg::round1::Package::serialize`
96    /// output.
97    pub package_hex: String,
98}
99
100/// Wire-format round2 share, one per recipient. Encrypted per-recipient at
101/// the CLI level (nip44) before publishing.
102///
103/// `package_hex` is a secret signing share, so `Debug` is redacted and must
104/// stay that way: this struct crosses `#[tracing::instrument]` boundaries in
105/// the CLI where a derived `Debug` would leak the share into logs.
106#[derive(Clone, serde::Serialize, serde::Deserialize)]
107pub struct SoftwareRound2Wire {
108    /// Discriminator, same rule as [`SoftwareRound1Wire`].
109    pub software_dkg_version: u8,
110    /// The 1-indexed participant identifier that produced this share.
111    pub sender_index: u16,
112    /// Hex-encoded `round2::Package` for the specific recipient. Secret.
113    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        // `package_hex` is a plaintext signing share. Scrub it on drop so the
129        // hex string does not linger in freed heap; this covers both the wire
130        // we produce in `round2()` and the one serde deserializes on receive.
131        use zeroize::Zeroize;
132        self.package_hex.zeroize();
133    }
134}
135
136/// Result returned from [`SoftwareDkgSession::finalize`], mirroring the
137/// hardware finalize shape so the CLI can share printing / storage code.
138pub struct SoftwareDkgResult {
139    /// This participant's finalized KeyPackage. Store via
140    /// `Keep::frost_store_dkg_share`.
141    pub key_package: KeyPackage,
142    /// The group's PublicKeyPackage. Also stored via the same helper so the
143    /// verifying shares for every peer are available during aggregation.
144    pub public_key_package: PublicKeyPackage,
145    /// The BIP-340 x-only 32-byte group pubkey the shares reconstruct to.
146    pub group_pubkey: [u8; 32],
147    /// This participant's 1-indexed share number.
148    pub our_index: u16,
149}
150
151impl SoftwareDkgSession {
152    /// Set up state for a `threshold`-of-`participants` DKG run where this
153    /// process holds share `our_index` (1-indexed). Rejects thresholds
154    /// outside `2..=participants` and indexes outside `1..=participants` so
155    /// a caller cannot pass a validated config to `part1` and get an
156    /// `UnknownIdentifier` late in the run.
157    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    /// Run frost-core's `part1` and return the round1 wire package this
183    /// participant broadcasts to every peer. Must be called before any
184    /// `round1_peer` step and exactly once per session.
185    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    /// Consume a peer's round1 wire package. Rejects a duplicate sender, a
210    /// self-echo, and a version mismatch. Returns `true` if this call
211    /// completed the round1 set (`peers = participants - 1`).
212    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    /// Run frost-core's `part2` and return the per-recipient round2 wire
259    /// packages. Refuses to run until every peer's round1 package has
260    /// landed.
261    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                    // Restore the pre-call state on an out-of-order call so the
273                    // caller keeps its round1 collection. This recovery only
274                    // covers the guard-mismatch arm; once the guard passes below,
275                    // the state has already advanced to `Finalized`.
276                    self.state = other;
277                    return Err(KeepError::Frost(
278                        "SoftwareDkgSession::round2 called before every peer's round1 arrived"
279                            .into(),
280                    ));
281                }
282            };
283        // Past this point the state is already `Finalized`: a `part2` failure is
284        // a terminal protocol error, so the session is intentionally not rewound.
285        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            // `bytes` is a plaintext signing share; keep it in a scrubbed
294            // buffer so it does not linger in freed heap after this loop.
295            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        // Rebuild the full round1 map with our own entry, which `part3` needs.
311        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    /// Consume a peer's round2 share targeted at us. Same version + range +
323    /// duplicate checks as `round1_peer`. Returns `true` if this call
324    /// completed the round2 set.
325    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    /// Finalize the DKG. Refuses to run until every peer's round2 share has
374    /// arrived. On success the session state is consumed; further method
375    /// calls return an error.
376    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        // part3 wants round1 packages from peers only (not our own), so strip
395        // our identifier out before handing the map in.
396        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        // Single source of truth for x-only group pubkey extraction, shared with
403        // the trusted-dealer path so both handle the 32- and 33-byte encodings.
404        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    /// This participant's 1-indexed share number.
415    pub fn our_index(&self) -> u16 {
416        self.our_index
417    }
418}
419
420fn identifier_to_u16(id: &Identifier) -> Option<u16> {
421    // frost-core's `Identifier` serialize is a big-endian 32-byte scalar
422    // where the value we care about lives in the last two bytes for
423    // participant indexes 1..=u16::MAX.
424    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    /// Run a full 2-of-3 software DKG and verify the resulting shares can
443    /// aggregate a valid signature under the derived group pubkey.
444    #[test]
445    fn end_to_end_2_of_3_software_dkg() {
446        run_group(2, 3);
447    }
448
449    /// A larger 3-of-5 group, exercising deeper participant sets and
450    /// verifying the aggregated signature still verifies under the derived
451    /// group pubkey.
452    #[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        // Round 1: every session emits a wire package.
463        let round1_wires: Vec<SoftwareRound1Wire> =
464            sessions.iter_mut().map(|s| s.round1().unwrap()).collect();
465
466        // Every session ingests every OTHER session's round1 wire.
467        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        // Round 2: each session emits per-recipient wires.
477        let mut per_session_round2: Vec<Vec<(u16, SoftwareRound2Wire)>> =
478            sessions.iter_mut().map(|s| s.round2().unwrap()).collect();
479
480        // Deliver each round2 share to its intended recipient.
481        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        // Finalize every session and check group_pubkey agreement.
490        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        // Assemble SharePackages for the threshold set and produce a real
498        // signature. If any DKG step corrupted a share this would fail at
499        // aggregation time.
500        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    /// A version-tag mismatch on a peer's round1 package MUST refuse rather
521    /// than silently mis-decoding a future / stranger wire format.
522    #[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    /// A peer sending two round1 packages is refused; otherwise a hostile
536    /// peer could bias the resulting key with a late substitution.
537    #[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    /// Calling `round2` before every peer's round1 lands must refuse without
551    /// destroying the state we already have.
552    #[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    /// Invalid config (threshold above participants, threshold below 2, or
563    /// out-of-range index) fails at init.
564    #[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    /// An n-of-n group (threshold == participants) completes DKG and its full
573    /// set of shares aggregates a valid signature.
574    #[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    /// Assert `err` is a `KeepError::Frost` whose message names the specific
582    /// guard, so a negative test cannot pass on a different Frost error (bad
583    /// hex, deserialize failure, wrong state) than the one it means to pin.
584    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    /// Two 2-of-2 sessions advanced through the round1 exchange and round2
595    /// emission, each in `AwaitingRound2` and holding the other's round2 wires.
596    /// `a`'s wires carry `sender_index == 1`, `b`'s carry `sender_index == 2`.
597    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    /// Peer drop mid-round-2: a participant that never receives one peer's
615    /// round2 share must refuse to finalize rather than derive a key from an
616    /// incomplete set.
617    #[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        // Deliver to participant 1 only participant 2's share; participant 3's
635        // share is intentionally dropped.
636        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        // `SoftwareDkgResult` holds key material and is intentionally not
643        // `Debug`, so match on the error directly rather than `expect_err`.
644        // Pin the pre-`part3` completeness guard by name: without the message
645        // check a deleted guard would still be masked by part3's own failure
646        // on the incomplete set.
647        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    /// A peer sending two round2 shares is refused; a late substitution could
654    /// otherwise bias the recipient's key material.
655    #[test]
656    fn duplicate_round2_share_refused() {
657        let (mut a, _b, _a2, b2) = advanced_2of2();
658        // b2 carries b's share destined for recipient 1 (a).
659        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    /// A round2 share whose `sender_index` equals our own is refused, so a
669    /// participant cannot be tricked into mixing its own share back in.
670    #[test]
671    fn round2_share_echoing_our_index_refused() {
672        let (mut a, _b, a2, _b2) = advanced_2of2();
673        // a2 is a's own share (sender_index == 1) destined for recipient 2.
674        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    /// `receive_share` before `round2` (wrong state) is refused without
683    /// corrupting session state.
684    #[test]
685    fn receive_share_out_of_order_refused() {
686        let (_a, _b, _a2, b2) = advanced_2of2();
687        let (_recipient, wire) = &b2[0];
688        // A fresh session is still in the initial state, not AwaitingRound2.
689        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}