frost-dkg 0.6.0

An implementation of the FROST Distributed Key Generation protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
mod round1;
mod round2;
mod round3;

use super::*;
use elliptic_curve::group::GroupEncoding;
use elliptic_curve::subtle::ConditionallySelectable;
use elliptic_curve::{Field, Group};
use elliptic_curve_tools::{SumOfProducts, group, prime_field, prime_field_vec};
use rand_core::CryptoRng;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;
use vsss_rs::{
    DefaultShare, IdentifierPrimeField, ShareElement, ShareVerifierGroup, ValueGroup,
    ValuePrimeField, subtle::ConstantTimeEq,
};

/// A participant that contributes a secret.
pub type SecretParticipant<G> = Participant<SecretParticipantImpl<G>, G>;

/// A participant that refreshes an existing sharing.
pub type RefreshParticipant<G> = Participant<RefreshParticipantImpl<G>, G>;

/// The inner share representation.
pub type SecretShare<F> = DefaultShare<IdentifierPrimeField<F>, IdentifierPrimeField<F>>;

/// The inner Feldman share verifiers.
pub type FeldmanShareVerifier<G> = ShareVerifierGroup<G>;

/// A validated set of participant identifiers used to reconstruct a secret.
#[derive(Copy, Clone, Debug)]
pub struct ReconstructionSet<'a, F: ScalarHash> {
    identifiers: &'a [IdentifierPrimeField<F>],
}

impl<'a, F: ScalarHash> ReconstructionSet<'a, F> {
    /// Validate participant identifiers for secret reconstruction.
    pub fn new(identifiers: &'a [IdentifierPrimeField<F>]) -> DkgResult<Self> {
        if identifiers.len() < 2 {
            return Err(Error::Initialization(
                "A reconstruction set requires at least 2 participant identifiers".to_string(),
            ));
        }
        if identifiers.iter().any(|id| bool::from(id.is_zero())) {
            return Err(Error::Initialization(
                "Reconstruction participant identifiers cannot be zero".to_string(),
            ));
        }
        let unique_identifiers = identifiers.iter().copied().collect::<HashSet<_>>();
        if unique_identifiers.len() != identifiers.len() {
            return Err(Error::Initialization(
                "Reconstruction participant identifiers must be unique".to_string(),
            ));
        }
        Ok(Self { identifiers })
    }

    /// The validated participant identifiers.
    pub fn identifiers(&self) -> &[IdentifierPrimeField<F>] {
        self.identifiers
    }

    fn contains(&self, identifier: &IdentifierPrimeField<F>) -> bool {
        self.identifiers.contains(identifier)
    }
}

/// The participant implementation.
pub trait ParticipantImpl<G>
where
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    /// Get the participant type.
    fn get_type(&self) -> ParticipantType;
    /// Get the participant's secret.
    fn random_value(rng: impl CryptoRng) -> G::Scalar;
    /// Check the Feldman verifier at position 0.
    ///
    /// During new key generation or an update, this value is not the identity;
    /// during a refresh, it must be the identity.
    fn check_feldman_verifier(verifier: G) -> bool;
}

/// A DKG participant finite-state machine.
///
/// This type contains secret key material. Its serialized representation is
/// plaintext and must only be stored or transported using authenticated
/// encryption or an equivalently protected mechanism. Deserializing
/// unauthenticated participant state can violate protocol invariants.
#[derive(Serialize, Deserialize)]
pub struct Participant<I, G>
where
    I: ParticipantImpl<G> + Default,
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    pub(crate) ordinal: usize,
    #[serde(bound(
        serialize = "IdentifierPrimeField<G::Scalar>: Serialize",
        deserialize = "IdentifierPrimeField<G::Scalar>: Deserialize<'de>"
    ))]
    pub(crate) id: IdentifierPrimeField<G::Scalar>,
    pub(crate) threshold: usize,
    pub(crate) limit: usize,
    pub(crate) round: Round,
    pub(crate) completed: bool,
    #[serde(bound(
        serialize = "SecretShare<G::Scalar>: Serialize",
        deserialize = "SecretShare<G::Scalar>: Deserialize<'de>"
    ))]
    pub(crate) secret_shares: Vec<SecretShare<G::Scalar>>,
    #[serde(bound(
        serialize = "ValueGroup<G>: Serialize",
        deserialize = "ValueGroup<G>: Deserialize<'de>"
    ))]
    pub(crate) feldman_verifiers: Vec<ValueGroup<G>>,
    #[serde(with = "prime_field")]
    pub(crate) original_secret: G::Scalar,
    #[serde(with = "group")]
    pub(crate) verifying_share: G,
    #[serde(bound(
        serialize = "SecretShare<G::Scalar>: Serialize",
        deserialize = "SecretShare<G::Scalar>: Deserialize<'de>"
    ))]
    pub(crate) secret_share: SecretShare<G::Scalar>,
    #[serde(with = "group")]
    pub(crate) message_generator: G,
    #[serde(bound(
        serialize = "ValueGroup<G>: Serialize",
        deserialize = "ValueGroup<G>: Deserialize<'de>"
    ))]
    pub(crate) public_key: ValueGroup<G>,
    #[serde(with = "prime_field_vec")]
    pub(crate) powers_of_i: Vec<G::Scalar>,
    #[serde(bound(
        serialize = "Round1Data<G>: Serialize",
        deserialize = "Round1Data<G>: Deserialize<'de>"
    ))]
    pub(crate) received_round1_data: Vec<Option<Round1Data<G>>>,
    #[serde(bound(
        serialize = "Round2Data<G::Scalar>: Serialize",
        deserialize = "Round2Data<G::Scalar>: Deserialize<'de>"
    ))]
    pub(crate) received_round2_data: Vec<Option<Round2Data<G::Scalar>>>,
    #[serde(bound(
        serialize = "IdentifierPrimeField<G::Scalar>: Serialize",
        deserialize = "IdentifierPrimeField<G::Scalar>: Deserialize<'de>"
    ))]
    pub(crate) all_participant_ids: Vec<IdentifierPrimeField<G::Scalar>>,
    #[serde(bound(
        serialize = "IdentifierPrimeField<G::Scalar>: Serialize",
        deserialize = "IdentifierPrimeField<G::Scalar>: Deserialize<'de>"
    ))]
    pub(crate) valid_participant_ids: Vec<Option<IdentifierPrimeField<G::Scalar>>>,
    pub(crate) participant_impl: I,
}

impl<I, G> Debug for Participant<I, G>
where
    I: ParticipantImpl<G> + Default,
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Participant")
            .field("ordinal", &self.ordinal)
            .field("id", &self.id)
            .field("threshold", &self.threshold)
            .field("limit", &self.limit)
            .field("round", &self.round)
            .field("completed", &self.completed)
            .field("feldman_verifiers", &self.feldman_verifiers)
            .field("public_key", &self.public_key)
            .field("powers_of_i", &self.powers_of_i)
            .finish()
    }
}

impl<G> Participant<SecretParticipantImpl<G>, G>
where
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    /// Create a participant that generates a new key share.
    pub fn new_secret(
        id: IdentifierPrimeField<G::Scalar>,
        parameters: &Parameters<G>,
    ) -> DkgResult<Self> {
        let rng = rand::rng();
        let secret = SecretParticipantImpl::<G>::random_value(rng);
        Self::initialize(id, parameters, IdentifierPrimeField(secret), None)
    }

    /// Create a participant with an existing secret share.
    ///
    /// This updates the polynomial instead of only refreshing the shares.
    pub fn with_secret(
        new_identifier: IdentifierPrimeField<G::Scalar>,
        old_share: &SecretShare<G::Scalar>,
        parameters: &Parameters<G>,
        reconstruction_set: &ReconstructionSet<'_, G::Scalar>,
    ) -> DkgResult<Self> {
        if !reconstruction_set.contains(&old_share.identifier) {
            return Err(Error::Initialization(
                "The old share is not included in the reconstruction set".to_string(),
            ));
        }
        let secret = *old_share.value * *Self::lagrange(old_share, reconstruction_set);
        Self::initialize(
            new_identifier,
            parameters,
            IdentifierPrimeField(secret),
            None,
        )
    }
}

impl<G> Participant<RefreshParticipantImpl<G>, G>
where
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    /// Create a participant that refreshes an existing key share, if supplied.
    ///
    /// If no share is supplied, other participants must possess valid shares of
    /// the original secret.
    pub fn new_refresh(
        id: IdentifierPrimeField<G::Scalar>,
        existing_share: Option<&SecretShare<G::Scalar>>,
        parameters: &Parameters<G>,
    ) -> DkgResult<Self> {
        if existing_share.is_some_and(|share| share.identifier != id) {
            return Err(Error::Initialization(
                "The existing share identifier does not match the refresh participant".to_string(),
            ));
        }
        let secret = existing_share
            .map(|share| share.value.0)
            .unwrap_or_else(|| G::Scalar::random(&mut rand::rng()));
        Self::initialize(
            id,
            parameters,
            IdentifierPrimeField(secret),
            Some(parameters.message_generator * secret),
        )
    }
}

impl<I, G> Participant<I, G>
where
    I: ParticipantImpl<G> + Default,
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    fn initialize(
        id: IdentifierPrimeField<G::Scalar>,
        parameters: &Parameters<G>,
        secret: ValuePrimeField<G::Scalar>,
        verifying_share: Option<G>,
    ) -> DkgResult<Self> {
        let rng = rand::rng();

        let mut powers_of_i = vec![G::Scalar::ONE; parameters.threshold];
        powers_of_i[1] = *id;
        for i in 2..parameters.threshold {
            powers_of_i[i] = powers_of_i[i - 1] * *id;
        }

        let participant_type = I::default().get_type();
        let secret_to_split = match participant_type {
            ParticipantType::Secret => secret,
            ParticipantType::Refresh => IdentifierPrimeField(G::Scalar::ZERO),
        };

        let (shares, verifiers) = vsss_rs::feldman::split_secret_with_participant_generators::<
            SecretShare<G::Scalar>,
            ShareVerifierGroup<G>,
        >(
            parameters.threshold,
            parameters.limit,
            &secret_to_split,
            Some(ValueGroup(parameters.message_generator)),
            rng,
            &parameters.participant_number_generators,
        )?;
        let verifiers = verifiers.iter().skip(1).copied().collect::<Vec<_>>();

        let verifying_share = match participant_type {
            ParticipantType::Secret => verifiers[0].0,
            ParticipantType::Refresh => verifying_share.ok_or(Error::Initialization(
                "Verifying share is required for refresh".to_string(),
            ))?,
        };

        if verifiers.iter().skip(1).any(|c| c.is_identity().into())
            || !I::check_feldman_verifier(*verifiers[0])
        {
            return Err(Error::Initialization(
                "Invalid Feldman verifier".to_string(),
            ));
        }

        let ordinal = shares
            .iter()
            .position(|s| s.identifier == id)
            .ok_or_else(|| {
                Error::Initialization(format!(
                    "Invalid participant ID '{id}'; it is not in the generated set of shares"
                ))
            })?;

        let all_participant_ids = shares.iter().map(|share| share.identifier).collect();
        Ok(Self {
            ordinal,
            id,
            threshold: parameters.threshold,
            limit: parameters.limit,
            completed: false,
            round: Round::One,
            original_secret: secret.0,
            verifying_share,
            secret_shares: shares,
            feldman_verifiers: verifiers,
            secret_share: SecretShare::<G::Scalar>::default(),
            message_generator: parameters.message_generator,
            public_key: ValueGroup::<G>::identity(),
            powers_of_i,
            received_round1_data: std::iter::repeat_with(|| None)
                .take(parameters.limit)
                .collect(),
            received_round2_data: std::iter::repeat_with(|| None)
                .take(parameters.limit)
                .collect(),
            all_participant_ids,
            valid_participant_ids: vec![None; parameters.limit],
            participant_impl: Default::default(),
        })
    }

    /// The ordinal index of this participant.
    pub fn ordinal(&self) -> usize {
        self.ordinal
    }

    /// The identifier associated with this participant.
    pub fn id(&self) -> IdentifierPrimeField<G::Scalar> {
        self.id
    }

    /// Return whether this participant has completed the protocol.
    pub fn completed(&self) -> bool {
        self.completed
    }

    /// Return the current round.
    pub fn round(&self) -> Round {
        self.round
    }

    /// Return the configured threshold.
    pub fn threshold(&self) -> usize {
        self.threshold
    }

    /// Return the configured participant limit.
    pub fn limit(&self) -> usize {
        self.limit
    }

    /// Computed secret share.
    /// This value is unavailable until at least two rounds have run, so [`None`]
    /// is returned until completion.
    pub fn secret_share(&self) -> Option<SecretShare<G::Scalar>> {
        if self.completed {
            Some(self.secret_share)
        } else {
            None
        }
    }

    /// Computed public key.
    ///
    /// This value is unavailable until every round has run, so [`None`] is
    /// returned until completion.
    pub fn public_key(&self) -> Option<G> {
        if self.completed {
            Some(*self.public_key)
        } else {
            None
        }
    }

    /// Return all participants that started the protocol.
    pub fn all_participant_ids(&self) -> &[IdentifierPrimeField<G::Scalar>] {
        &self.all_participant_ids
    }

    /// Return the valid participant IDs.
    pub fn valid_participant_ids(&self) -> &[Option<IdentifierPrimeField<G::Scalar>>] {
        &self.valid_participant_ids
    }

    /// Return the Feldman verifiers.
    pub fn feldman_verifiers(&self) -> &[ShareVerifierGroup<G>] {
        &self.feldman_verifiers
    }

    /// Get the round 1 data received so far.
    pub fn received_round1_data(&self) -> &[Option<Round1Data<G>>] {
        &self.received_round1_data
    }

    /// Get the round 2 data received so far.
    pub fn received_round2_data(&self) -> &[Option<Round2Data<G::Scalar>>] {
        &self.received_round2_data
    }

    /// The verifying share used by this participant.
    pub fn verifying_share(&self) -> G {
        self.verifying_share
    }

    /// The final transcript hash over received protocol messages.
    pub fn final_transcript_hash(&self) -> [u8; 32] {
        get_final_transcript_hash(&self.received_round1_data, &self.received_round2_data)
    }

    /// Consume a completed participant and return its final DKG output.
    ///
    /// Consuming the participant avoids cloning its secret share.
    pub fn into_output(self) -> DkgResult<DkgOutput<G>> {
        if !self.completed {
            return Err(Error::Round(
                "Protocol is not complete; no output is available".to_string(),
            ));
        }

        let transcript_hash =
            get_final_transcript_hash(&self.received_round1_data, &self.received_round2_data);
        Ok(DkgOutput {
            secret_share: self.secret_share,
            public_key: self.public_key.0,
            feldman_verifiers: self.feldman_verifiers,
            participant_ids: self.valid_participant_ids,
            transcript_hash,
        })
    }

    /// The ordinal index of this participant.
    #[deprecated(since = "0.6.0", note = "use `ordinal` instead")]
    pub fn get_ordinal(&self) -> usize {
        self.ordinal()
    }

    /// The identifier associated with this participant.
    #[deprecated(since = "0.6.0", note = "use `id` instead")]
    pub fn get_id(&self) -> IdentifierPrimeField<G::Scalar> {
        self.id()
    }

    /// Return the current round.
    #[deprecated(since = "0.6.0", note = "use `round` instead")]
    pub fn get_round(&self) -> Round {
        self.round()
    }

    /// Return the configured threshold.
    #[deprecated(since = "0.6.0", note = "use `threshold` instead")]
    pub fn get_threshold(&self) -> usize {
        self.threshold()
    }

    /// Return the configured participant limit.
    #[deprecated(since = "0.6.0", note = "use `limit` instead")]
    pub fn get_limit(&self) -> usize {
        self.limit()
    }

    /// Computed secret share, if the protocol is complete.
    #[deprecated(since = "0.6.0", note = "use `secret_share` instead")]
    pub fn get_secret_share(&self) -> Option<SecretShare<G::Scalar>> {
        self.secret_share()
    }

    /// Computed public key, if the protocol is complete.
    #[deprecated(since = "0.6.0", note = "use `public_key` instead")]
    pub fn get_public_key(&self) -> Option<G> {
        self.public_key()
    }

    /// Return all participants that started the protocol.
    #[deprecated(since = "0.6.0", note = "use `all_participant_ids` instead")]
    pub fn get_all_participant_ids(&self) -> &[IdentifierPrimeField<G::Scalar>] {
        self.all_participant_ids()
    }

    /// Return the valid participant IDs.
    #[deprecated(since = "0.6.0", note = "use `valid_participant_ids` instead")]
    pub fn get_valid_participant_ids(&self) -> &[Option<IdentifierPrimeField<G::Scalar>>] {
        self.valid_participant_ids()
    }

    /// Return the Feldman verifiers.
    #[deprecated(since = "0.6.0", note = "use `feldman_verifiers` instead")]
    pub fn get_feldman_verifiers(&self) -> Vec<ShareVerifierGroup<G>> {
        self.feldman_verifiers().to_vec()
    }

    /// Get the round 1 data received so far.
    #[deprecated(since = "0.6.0", note = "use `received_round1_data` instead")]
    pub fn get_received_round1_data(&self) -> &[Option<Round1Data<G>>] {
        self.received_round1_data()
    }

    /// Get the round 2 data received so far.
    #[deprecated(since = "0.6.0", note = "use `received_round2_data` instead")]
    pub fn get_received_round2_data(&self) -> &[Option<Round2Data<G::Scalar>>] {
        self.received_round2_data()
    }

    /// Receive data from another participant.
    pub fn receive(&mut self, data: &[u8]) -> DkgResult<()> {
        let (&round, payload) = data
            .split_first()
            .ok_or_else(|| Error::InvalidMessage("message is empty".to_string()))?;
        let round = Round::try_from(round).map_err(Error::InvalidMessage)?;
        match round {
            Round::One => {
                let round1_payload = postcard::from_bytes::<Round1Data<G>>(payload)?;
                self.receive_round1data(round1_payload)
            }
            Round::Two => {
                let round2_payload = postcard::from_bytes::<Round2Data<G::Scalar>>(payload)?;
                self.receive_round2data(round2_payload)
            }
            _ => Err(Error::Round("Protocol is complete".to_string())),
        }
    }

    /// Run the next step in the protocol.
    pub fn run(&mut self) -> DkgResult<RoundOutputGenerator<G>> {
        match self.round {
            Round::One => self.round1(),
            Round::Two => self.round2(),
            Round::Three => self.round3(),
            Round::Four => Err(Error::Round("Protocol is complete".to_string())),
        }
    }

    /// Advance the protocol by one round.
    ///
    /// Protocol messages are serialized automatically and returned with only
    /// the transport routing information callers need.
    pub fn advance(&mut self) -> DkgResult<AdvanceResult<G::Scalar>> {
        match self.run()? {
            RoundOutputGenerator::Round3 => Ok(AdvanceResult::Complete),
            output => Ok(AdvanceResult::Messages(output.into_messages()?)),
        }
    }

    pub(crate) fn check_sending_participant_id(
        &self,
        round: Round,
        sender_ordinal: usize,
        sender_id: IdentifierPrimeField<G::Scalar>,
    ) -> DkgResult<()> {
        let id = self
            .all_participant_ids
            .get(sender_ordinal)
            .ok_or_else(|| {
                Error::Round(format!(
                    "Round {round}: Unknown sender ordinal, {sender_ordinal}"
                ))
            })?;
        if *id != sender_id {
            return Err(Error::Round(format!(
                "Round {round}: Sender id mismatch, expected '{id}', got '{sender_id}'"
            )));
        }
        if sender_id.is_zero().into() {
            return Err(Error::Round(format!("Round {round}: Sender id is zero")));
        }
        if self.id.ct_eq(&sender_id).into() {
            return Err(Error::Round(format!(
                "Round {round}: Sender id is equal to our id",
            )));
        }
        Ok(())
    }

    pub(crate) fn lagrange(
        share: &SecretShare<G::Scalar>,
        reconstruction_set: &ReconstructionSet<'_, G::Scalar>,
    ) -> ValuePrimeField<G::Scalar> {
        let mut num = G::Scalar::ONE;
        let mut den = G::Scalar::ONE;
        for &x_j in reconstruction_set.identifiers() {
            if x_j == share.identifier {
                continue;
            }
            num *= *x_j;
            den *= *x_j - *share.identifier;
        }

        // The validated reconstruction set contains unique identifiers,
        // including the share identifier, so this denominator is nonzero.
        let den_inverse = den.invert().unwrap_or(G::Scalar::ZERO);
        IdentifierPrimeField(num * den_inverse)
    }
}

/// The secret participant implementation.
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SecretParticipantImpl<G>(PhantomData<G>);

impl<G> ParticipantImpl<G> for SecretParticipantImpl<G>
where
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    fn get_type(&self) -> ParticipantType {
        ParticipantType::Secret
    }

    fn random_value(mut rng: impl CryptoRng) -> <G as Group>::Scalar {
        G::Scalar::random(&mut rng)
    }

    fn check_feldman_verifier(verifier: G) -> bool {
        verifier.is_identity().unwrap_u8() == 0u8
    }
}

/// The refresh participant implementation.
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct RefreshParticipantImpl<G>(PhantomData<G>);

impl<G> ParticipantImpl<G> for RefreshParticipantImpl<G>
where
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    fn get_type(&self) -> ParticipantType {
        ParticipantType::Refresh
    }

    fn random_value(_rng: impl CryptoRng) -> <G as Group>::Scalar {
        G::Scalar::ZERO
    }

    fn check_feldman_verifier(verifier: G) -> bool {
        verifier.is_identity().into()
    }
}

/// A trait that enables dynamic dispatch over participants.
pub trait AnyParticipant<G>: Send + Sync + Debug
where
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    /// The ordinal index of this participant.
    fn ordinal(&self) -> usize;
    /// The identifier associated with this participant.
    fn id(&self) -> IdentifierPrimeField<G::Scalar>;
    /// The threshold.
    fn threshold(&self) -> usize;
    /// The participant limit.
    fn limit(&self) -> usize;
    /// The current round.
    fn round(&self) -> Round;
    /// The secret share, if the protocol is complete.
    fn secret_share(&self) -> Option<SecretShare<G::Scalar>>;
    /// The public key, if the protocol is complete.
    fn public_key(&self) -> Option<G>;
    /// The valid participant IDs from the last round.
    fn valid_participant_ids(&self) -> &[Option<IdentifierPrimeField<G::Scalar>>];
    /// All participant IDs that started the protocol.
    fn all_participant_ids(&self) -> &[IdentifierPrimeField<G::Scalar>];
    /// The Feldman verifiers.
    fn feldman_verifiers(&self) -> &[ShareVerifierGroup<G>];
    /// The round 1 data received so far.
    fn received_round1_data(&self) -> &[Option<Round1Data<G>>];
    /// The round 2 data received so far.
    fn received_round2_data(&self) -> &[Option<Round2Data<G::Scalar>>];
    /// The verifying share.
    fn verifying_share(&self) -> G;
    /// The final transcript hash.
    fn final_transcript_hash(&self) -> [u8; 32];
    /// Return whether the participant has completed the protocol.
    fn completed(&self) -> bool;
    /// Receive data from another participant.
    fn receive(&mut self, data: &[u8]) -> DkgResult<()>;
    /// Run the next round after receiving data from other participants.
    fn run(&mut self) -> DkgResult<RoundOutputGenerator<G>>;
    /// Advance the protocol and produce opaque, transport-aware messages.
    fn advance(&mut self) -> DkgResult<AdvanceResult<G::Scalar>>;
    /// Consume a completed participant and return its final DKG output.
    fn into_output(self: Box<Self>) -> DkgResult<DkgOutput<G>>;

    /// Get the ordinal index of this participant.
    #[deprecated(since = "0.6.0", note = "use `ordinal` instead")]
    fn get_ordinal(&self) -> usize {
        self.ordinal()
    }

    /// Get the identifier associated with this participant.
    #[deprecated(since = "0.6.0", note = "use `id` instead")]
    fn get_id(&self) -> IdentifierPrimeField<G::Scalar> {
        self.id()
    }

    /// Get the threshold.
    #[deprecated(since = "0.6.0", note = "use `threshold` instead")]
    fn get_threshold(&self) -> usize {
        self.threshold()
    }

    /// Get the participant limit.
    #[deprecated(since = "0.6.0", note = "use `limit` instead")]
    fn get_limit(&self) -> usize {
        self.limit()
    }

    /// Get the current round.
    #[deprecated(since = "0.6.0", note = "use `round` instead")]
    fn get_round(&self) -> Round {
        self.round()
    }

    /// Get the secret share if completed.
    #[deprecated(since = "0.6.0", note = "use `secret_share` instead")]
    fn get_secret_share(&self) -> Option<SecretShare<G::Scalar>> {
        self.secret_share()
    }

    /// Get the public key if completed.
    #[deprecated(since = "0.6.0", note = "use `public_key` instead")]
    fn get_public_key(&self) -> Option<G> {
        self.public_key()
    }

    /// Get the valid participant IDs from the last round.
    #[deprecated(since = "0.6.0", note = "use `valid_participant_ids` instead")]
    fn get_valid_participant_ids(&self) -> &[Option<IdentifierPrimeField<G::Scalar>>] {
        self.valid_participant_ids()
    }

    /// Get all participant IDs that started the protocol.
    #[deprecated(since = "0.6.0", note = "use `all_participant_ids` instead")]
    fn get_all_participant_ids(&self) -> &[IdentifierPrimeField<G::Scalar>] {
        self.all_participant_ids()
    }

    /// Return the Feldman verifiers.
    #[deprecated(since = "0.6.0", note = "use `feldman_verifiers` instead")]
    fn get_feldman_verifiers(&self) -> Vec<ShareVerifierGroup<G>> {
        self.feldman_verifiers().to_vec()
    }

    /// Get the round 1 data received so far.
    #[deprecated(since = "0.6.0", note = "use `received_round1_data` instead")]
    fn get_received_round1_data(&self) -> &[Option<Round1Data<G>>] {
        self.received_round1_data()
    }

    /// Get the round 2 data received so far.
    #[deprecated(since = "0.6.0", note = "use `received_round2_data` instead")]
    fn get_received_round2_data(&self) -> &[Option<Round2Data<G::Scalar>>] {
        self.received_round2_data()
    }

    /// Get the verifying share.
    #[deprecated(since = "0.6.0", note = "use `verifying_share` instead")]
    fn get_verifying_share(&self) -> G {
        self.verifying_share()
    }

    /// Get the final transcript hash.
    #[deprecated(since = "0.6.0", note = "use `final_transcript_hash` instead")]
    fn get_final_transcript_hash(&self) -> [u8; 32] {
        self.final_transcript_hash()
    }
}

impl<I, G> AnyParticipant<G> for Participant<I, G>
where
    I: ParticipantImpl<G> + Default + Send + Sync,
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    fn ordinal(&self) -> usize {
        self.ordinal
    }

    fn id(&self) -> IdentifierPrimeField<G::Scalar> {
        self.id
    }

    fn threshold(&self) -> usize {
        self.threshold
    }

    fn limit(&self) -> usize {
        self.limit
    }

    fn round(&self) -> Round {
        self.round
    }

    fn secret_share(&self) -> Option<SecretShare<G::Scalar>> {
        self.secret_share()
    }

    fn public_key(&self) -> Option<G> {
        self.public_key()
    }

    fn valid_participant_ids(&self) -> &[Option<IdentifierPrimeField<G::Scalar>>] {
        &self.valid_participant_ids
    }

    fn all_participant_ids(&self) -> &[IdentifierPrimeField<G::Scalar>] {
        &self.all_participant_ids
    }

    fn feldman_verifiers(&self) -> &[ShareVerifierGroup<G>] {
        &self.feldman_verifiers
    }

    fn received_round1_data(&self) -> &[Option<Round1Data<G>>] {
        &self.received_round1_data
    }

    fn received_round2_data(&self) -> &[Option<Round2Data<G::Scalar>>] {
        &self.received_round2_data
    }

    fn verifying_share(&self) -> G {
        self.verifying_share
    }

    fn final_transcript_hash(&self) -> [u8; 32] {
        get_final_transcript_hash(&self.received_round1_data, &self.received_round2_data)
    }

    fn completed(&self) -> bool {
        self.completed()
    }

    fn receive(&mut self, data: &[u8]) -> DkgResult<()> {
        self.receive(data)
    }

    fn run(&mut self) -> DkgResult<RoundOutputGenerator<G>> {
        self.run()
    }

    fn advance(&mut self) -> DkgResult<AdvanceResult<G::Scalar>> {
        self.advance()
    }

    fn into_output(self: Box<Self>) -> DkgResult<DkgOutput<G>> {
        (*self).into_output()
    }
}

fn get_final_transcript_hash<G>(
    received_round1_data: &[Option<Round1Data<G>>],
    received_round2_data: &[Option<Round2Data<G::Scalar>>],
) -> [u8; 32]
where
    G: SumOfProducts + GroupEncoding + Default + ConditionallySelectable,
    G::Scalar: ScalarHash,
{
    let mut transcript = merlin::Transcript::new(b"Frost DKG - Final Transcript");
    for round1data in received_round1_data.iter().flatten() {
        round1data.add_to_transcript(&mut transcript);
    }
    for round2data in received_round2_data.iter().flatten() {
        round2data.add_to_transcript(&mut transcript);
    }
    let mut transcript_hash = [0u8; 32];
    transcript.challenge_bytes(b"final result", &mut transcript_hash);
    transcript_hash
}

#[cfg(test)]
mod tests {
    use super::*;
    use k256::{ProjectivePoint, Scalar};
    use std::num::NonZeroUsize;
    use vsss_rs::Share;

    #[test]
    fn receive_rejects_empty_message() {
        let parameters = Parameters::new(
            NonZeroUsize::new(2).expect("threshold is non-zero"),
            NonZeroUsize::new(2).expect("limit is non-zero"),
        )
        .expect("valid parameters");
        let mut participant = SecretParticipant::<ProjectivePoint>::new_secret(
            IdentifierPrimeField::ONE,
            &parameters,
        )
        .expect("create participant");

        let result = participant.receive(&[]);

        assert!(
            matches!(result, Err(Error::InvalidMessage(message)) if message == "message is empty")
        );
    }

    #[test]
    fn debug_redacts_secret_state() {
        let parameters = Parameters::new(
            NonZeroUsize::new(2).expect("threshold is non-zero"),
            NonZeroUsize::new(2).expect("limit is non-zero"),
        )
        .expect("valid parameters");
        let participant = SecretParticipant::<ProjectivePoint>::new_secret(
            IdentifierPrimeField::ONE,
            &parameters,
        )
        .expect("create participant");

        assert_eq!(participant.feldman_verifiers().len(), 2);
        let debug = format!("{participant:?}");

        assert!(!debug.contains("original_secret"));
        assert!(!debug.contains("secret_share"));
        assert!(!debug.contains("secret_shares"));
        assert!(!debug.contains("received_round2_data"));
    }

    #[test]
    fn output_is_unavailable_before_completion() {
        let parameters = Parameters::new(
            NonZeroUsize::new(2).expect("threshold is non-zero"),
            NonZeroUsize::new(2).expect("limit is non-zero"),
        )
        .expect("valid parameters");
        let participant = SecretParticipant::<ProjectivePoint>::new_secret(
            IdentifierPrimeField::ONE,
            &parameters,
        )
        .expect("create participant");

        let result = participant.into_output();

        assert!(matches!(result, Err(Error::Round(message)) if message.contains("not complete")));
    }

    #[test]
    fn reconstruction_set_rejects_duplicate_identifiers() {
        let identifier = IdentifierPrimeField(Scalar::ONE);
        let identifiers = [identifier, identifier];

        let result = ReconstructionSet::new(&identifiers);

        assert!(matches!(result, Err(Error::Initialization(_))));
    }

    #[test]
    fn refresh_rejects_a_share_with_a_different_identifier() {
        let parameters = Parameters::new(
            NonZeroUsize::new(2).expect("threshold is non-zero"),
            NonZeroUsize::new(2).expect("limit is non-zero"),
        )
        .expect("valid parameters");
        let share = SecretShare::with_identifier_and_value(
            IdentifierPrimeField(Scalar::ONE),
            IdentifierPrimeField(Scalar::ONE),
        );

        let result = RefreshParticipant::<ProjectivePoint>::new_refresh(
            IdentifierPrimeField(Scalar::from(2u64)),
            Some(&share),
            &parameters,
        );

        assert!(
            matches!(result, Err(Error::Initialization(message)) if message.contains("does not match"))
        );
    }

    #[test]
    fn resharing_rejects_a_share_missing_from_the_reconstruction_set() {
        let parameters = Parameters::new(
            NonZeroUsize::new(2).expect("threshold is non-zero"),
            NonZeroUsize::new(3).expect("limit is non-zero"),
        )
        .expect("valid parameters");
        let share = SecretShare::with_identifier_and_value(
            IdentifierPrimeField(Scalar::ONE),
            IdentifierPrimeField(Scalar::ONE),
        );
        let identifiers = [
            IdentifierPrimeField(Scalar::from(2u64)),
            IdentifierPrimeField(Scalar::from(3u64)),
        ];
        let reconstruction_set =
            ReconstructionSet::new(&identifiers).expect("valid reconstruction set");

        let result = SecretParticipant::<ProjectivePoint>::with_secret(
            IdentifierPrimeField::ONE,
            &share,
            &parameters,
            &reconstruction_set,
        );

        assert!(
            matches!(result, Err(Error::Initialization(message)) if message.contains("not included"))
        );
    }
}