kyber-rs 0.1.0-alpha.9

A toolbox of advanced cryptographic primitives for Rust
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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
/// module [`pedersen::vss`] implements the verifiable secret sharing scheme from
/// "Non-Interactive and Information-Theoretic Secure Verifiable Secret Sharing"
/// by Torben Pryds Pedersen.
/// https://link.springer.com/content/pdf/10.1007/3-540-46766-1_9.pdf
use core::fmt::{Debug, Display, Formatter};
use core::ops::{Deref, DerefMut};
use std::collections::HashMap;
use std::io::Write;

use byteorder::{LittleEndian, WriteBytesExt};
use digest::Digest;
use serde::{Deserialize, Serialize};

use crate::{
    dh::{AEAD, NONCE_SIZE},
    encoding::{self, unmarshal_binary, BinaryMarshaler, Marshaling, MarshallingError},
    group::{PointCanCheckCanonicalAndSmallOrder, ScalarCanCheckCanonical},
    share::{
        self,
        poly::{new_pri_poly, PriShare},
        vss::{suite::Suite, VSSError},
    },
    sign::schnorr,
    Point, Scalar,
};

/// [`Dealer`] encapsulates for creating and distributing the shares and for
/// replying to any Responses.
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dealer<SUITE: Suite> {
    suite: SUITE,
    // reader: STREAM,
    /// `long` is the longterm key of the Dealer
    pub(crate) long: <SUITE::POINT as Point>::SCALAR,
    pub(crate) pubb: SUITE::POINT,
    pub secret: <SUITE::POINT as Point>::SCALAR,
    secret_commits: Vec<SUITE::POINT>,
    secret_poly: share::poly::PriPoly<SUITE>,
    pub(crate) verifiers: Vec<SUITE::POINT>,
    hkdf_context: Vec<u8>,
    /// `threshold` of shares that is needed to reconstruct the secret
    pub t: usize,
    /// `session_id` is a unique identifier for the whole session of the scheme
    session_id: Vec<u8>,
    /// list of `deals` this Dealer has generated
    pub(crate) deals: Vec<Deal<SUITE>>,
    pub(crate) aggregator: Aggregator<SUITE>,
}

impl<SUITE: Suite> Debug for Dealer<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Dealer")
            .field("suite", &self.suite)
            .field("pubb", &self.pubb)
            .field("verifiers", &self.verifiers)
            .field("hkdf_context", &self.hkdf_context)
            .field("t", &self.t)
            .field("session_id", &self.session_id)
            .field("deals", &self.deals)
            .field("aggregator", &self.aggregator)
            .finish()
    }
}

impl<SUITE: Suite> Display for Dealer<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "Dealer( public_key: {},", self.pubb)?;

        write!(f, " verifiers: [")?;
        let verifiers = self
            .verifiers
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(",");
        write!(f, "{}],", verifiers)?;

        write!(
            f,
            " hkdf_context: 0x{}, threshold: {}, session_id: 0x{},",
            hex::encode(&self.hkdf_context),
            self.t,
            hex::encode(&self.session_id),
        )?;

        write!(f, " deals: [")?;
        let deals = self
            .deals
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(",");
        write!(f, "{}],", deals)?;

        write!(f, " aggregator: {} )", self.aggregator)
    }
}

impl<SUITE: Suite> Deref for Dealer<SUITE> {
    type Target = Aggregator<SUITE>;

    fn deref(&self) -> &Self::Target {
        &self.aggregator
    }
}

impl<SUITE: Suite> DerefMut for Dealer<SUITE> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.aggregator
    }
}

/// [`Deal`] encapsulates the verifiable secret share and is sent by the dealer to a verifier.
#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Eq)]
pub struct Deal<SUITE: Suite> {
    /// Unique session identifier for this protocol run
    pub(crate) session_id: Vec<u8>,
    /// Private share generated by the dealer
    pub(crate) sec_share: PriShare<<SUITE::POINT as Point>::SCALAR>,
    /// Threshold used for this secret sharing run
    pub(crate) t: usize,
    // Commitments are the coefficients used to verify the shares against
    pub(crate) commitments: Vec<SUITE::POINT>,
}

impl<SUITE: Suite> Debug for Deal<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Deal")
            .field("session_id", &self.session_id)
            .field("t", &self.t)
            .field("commitments", &self.commitments)
            .finish()
    }
}

impl<SUITE: Suite> Display for Deal<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write! {f, "Deal( session_id: 0x{}, threshold: {},)",
            hex::encode(&self.session_id),
            self.t,
        }?;

        write!(f, " commitments: [")?;
        let commitments = self
            .commitments
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(",");
        write!(f, "{}] )", commitments)
    }
}

impl<SUITE: Suite> Deal<SUITE> {
    fn decode(buff: &[u8]) -> Result<Deal<SUITE>, VSSError> {
        let mut d = Deal::default();
        unmarshal_binary(&mut d, buff)?;
        Ok(d)
    }
}

impl<SUITE: Suite> BinaryMarshaler for Deal<SUITE> {
    fn marshal_binary(&self) -> Result<Vec<u8>, MarshallingError> {
        encoding::marshal_binary(self)
    }
}

/// [`EncryptedDeal`] contains the deal in a encrypted form only decipherable by the
/// correct recipient. The encryption is performed in a similar manner as what is
/// done in TLS. The dealer generates a temporary key pair, signs it with its
/// longterm secret key.
#[derive(Clone, Serialize, Deserialize, Debug, Default, PartialEq, Eq)]
pub struct EncryptedDeal<POINT: Point> {
    /// Ephemeral Diffie Hellman key
    #[serde(deserialize_with = "POINT::deserialize")]
    pub(crate) dhkey: POINT,
    /// Signature of the DH key by the longterm key of the dealer
    pub(crate) signature: Vec<u8>,
    /// Nonce used for the encryption
    nonce: Vec<u8>,
    /// AEAD encryption of the deal
    pub(crate) cipher: Vec<u8>,
}

impl<POINT: Point> Display for EncryptedDeal<POINT> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write! {f, "EncyptedDeal( dh_key: {}, signature: 0x{}, nonce: 0x{}, cipher: 0x{} )",
            self.dhkey,
            hex::encode(&self.signature),
            hex::encode(&self.nonce),
            hex::encode(&self.cipher),
        }
    }
}

/// [`Response`] is sent by the verifiers to all participants and holds each
/// individual validation or refusal of a [`Deal`].
#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Response {
    /// SessionID related to this run of the protocol
    pub session_id: Vec<u8>,
    /// Index of the verifier issuing this Response
    pub index: u32,
    /// false = NO APPROVAL == Complaint , true = APPROVAL
    pub status: bool,
    /// Signature over the whole packet
    pub signature: Vec<u8>,
}

impl Display for Response {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write! {f, "Response( session_id: 0x{}, index: {}, status: {}, signature: 0x{} )",
        hex::encode(&self.session_id),
        self.index,
        self.status,
        hex::encode(&self.signature)
        }
    }
}

impl Response {
    /// [`hash()`] returns the Hash representation of the [`Response`]
    pub fn hash<SUITE: Suite>(&self, s: &SUITE) -> Result<Vec<u8>, VSSError> {
        let mut h = s.hash();
        h.write_all("response".as_bytes())?;
        h.write_all(&self.session_id)?;
        h.write_u32::<LittleEndian>(self.index)?;
        h.write_u32::<LittleEndian>(self.status as u32)?;
        Ok(h.finalize().to_vec())
    }
}

/// [`STATUS_COMPLAINT`] is a constant value meaning that a verifier issues
/// a Complaint against its Dealer.
pub const STATUS_COMPLAINT: bool = false;
/// [`STATUS_APPROVAL`] is a constant value meaning that a verifier agrees with
/// the share it received.
pub const STATUS_APPROVAL: bool = true;

/// [`Justification`] is a message that is broadcasted by the Dealer in response to
/// a Complaint. It contains the original Complaint as well as the shares
/// distributed to the complainer.
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct Justification<SUITE: Suite> {
    /// SessionID related to the current run of the protocol
    pub(crate) session_id: Vec<u8>,
    /// Index of the verifier who issued the Complaint,i.e. index of this Deal
    pub(crate) index: u32,
    /// Deal in cleartext
    pub(crate) deal: Deal<SUITE>,
    /// Signature over the whole packet
    pub(crate) signature: Vec<u8>,
}

impl<SUITE: Suite> Display for Justification<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write! {f, "Justification( session_id: 0x{}, index: {}, deal: {}, signature: 0x{} )",
        hex::encode(&self.session_id),
        self.index,
        self.deal,
        hex::encode(&self.signature)
        }
    }
}

impl<SUITE: Suite> Justification<SUITE> {
    /// [`hash()`] returns the hash of a [`Justification`].
    fn hash(self, s: SUITE) -> Result<Vec<u8>, VSSError> {
        let mut h = s.hash();
        h.update("justification".as_bytes());
        h.update(&self.session_id);

        h.write_u32::<LittleEndian>(self.index)?;
        let buff = self.deal.marshal_binary()?;
        h.update(&buff);

        Ok(h.finalize().to_vec())
    }
}

/// [`new_dealer()`] returns a [`Dealer`] capable of leading the secret sharing scheme. It
/// does not have to be trusted by other Verifiers. The security parameter t is
/// the number of shares required to reconstruct the secret. It is HIGHLY
/// RECOMMENDED to use a threshold higher or equal than what the method
/// [`minimum_t()`] returns, otherwise it breaks the security assumptions of the whole
/// scheme. It returns an [`Error`](VSSError::InvalidThreshold) if the t is inferior or equal to 2.
pub fn new_dealer<SUITE: Suite>(
    suite: SUITE,
    longterm: <SUITE::POINT as Point>::SCALAR,
    secret: <SUITE::POINT as Point>::SCALAR,
    verifiers: &[SUITE::POINT],
    t: usize,
) -> Result<Dealer<SUITE>, VSSError> {
    if !valid_t(t, verifiers) {
        return Err(VSSError::InvalidThreshold(format!("dealer: t {t} invalid")));
    }
    // 	d.t = t

    let f = new_pri_poly(suite, t, Some(secret.clone()), suite.random_stream());
    let d_pubb = suite.point().mul(&longterm, None);

    // Compute public polynomial coefficients
    let f_p = f.commit(Some(&suite.point().base()));
    let (_, secret_commits) = f_p.info();

    let session_id = session_id(&suite, &d_pubb, verifiers, &secret_commits, t)?;

    let aggregator = new_aggregator(&suite, &d_pubb, verifiers, &secret_commits, t, &session_id);

    // C = F + G
    let mut deals: Vec<Deal<SUITE>> = Vec::with_capacity(verifiers.len());
    for i in 0..verifiers.len() {
        let fi = f.eval(i);
        deals.push(Deal {
            session_id: session_id.clone(),
            sec_share: fi,
            commitments: secret_commits.clone(),
            t,
        });
    }

    let hkdf_context = context(suite, &d_pubb, verifiers).to_vec();
    Ok(Dealer {
        suite,
        long: longterm,
        secret,
        verifiers: verifiers.to_vec(),
        pubb: d_pubb,
        secret_commits,
        secret_poly: f,
        hkdf_context,
        t,
        session_id,
        aggregator,
        deals,
    })
}

impl<SUITE: Suite> Dealer<SUITE>
where
    SUITE::POINT: PointCanCheckCanonicalAndSmallOrder,
    <SUITE::POINT as Point>::SCALAR: ScalarCanCheckCanonical,
{
    /// [`plaintext_deal()`] returns the plaintext version of the deal destined for peer `i`.
    /// Use this only for testing.
    pub fn plaintext_deal(&mut self, i: usize) -> Result<&mut Deal<SUITE>, VSSError> {
        if i >= self.deals.len() {
            return Err(VSSError::DealerWrongIndex);
        }
        let d = &mut self.deals[i];
        Ok(d)
    }

    /// [`encrypted_deal()`] returns the encryption of the deal that must be given to the
    /// verifier at index `i`.
    /// The dealer first generates a temporary Diffie Hellman key, signs it using its
    /// longterm key, and computes the shared key depending on its longterm and
    /// ephemeral key and the verifier's public key.
    /// This shared key is then fed into a HKDF whose output is the key to a AEAD
    /// (AES256-GCM) scheme to encrypt the deal.
    pub fn encrypted_deal(&self, i: usize) -> Result<EncryptedDeal<SUITE::POINT>, VSSError> {
        let v_pub = find_pub(&self.verifiers, i).ok_or(VSSError::DealerWrongIndex)?;
        // gen ephemeral key
        let dh_secret = self.suite.scalar().pick(&mut self.suite.random_stream());
        let dh_public = self.suite.point().mul(&dh_secret, None);
        // signs the public key
        let dh_public_buff = dh_public.marshal_binary()?;
        let signature = schnorr::sign(&self.suite, &self.long, &dh_public_buff)?;

        // AES128-GCM
        let pre = SUITE::dh_exchange(self.suite, dh_secret, v_pub);
        let gcm = AEAD::<SUITE>::new(pre, &self.hkdf_context)?;
        let nonce = [0u8; NONCE_SIZE];
        // let dealBuff = protobuf.Encode(self.deals[i])?;
        let deal_buf = self.deals[i].marshal_binary()?;
        let encrypted = gcm.seal(None, &nonce, &deal_buf, Some(&self.hkdf_context))?;
        Ok(EncryptedDeal {
            dhkey: dh_public,
            signature,
            nonce: nonce.to_vec(),
            cipher: encrypted,
        })
    }

    /// [`encrypted_deals()`] calls [`encrypted_deal()`] for each index of the verifier and
    /// returns the list of encrypted deals. Each index in the returned slice
    /// corresponds to the index in the list of verifiers.
    pub fn encrypted_deals(&self) -> Result<Vec<EncryptedDeal<SUITE::POINT>>, VSSError> {
        // deals := make([]*EncryptedDeal, len(d.verifiers));
        let mut deals = vec![];
        // var err error
        for i in 0..self.verifiers.len() {
            let deal = self.encrypted_deal(i)?;
            deals.push(deal);
        }
        Ok(deals)
    }

    /// [`process_response()`] analyzes the given [`Response`]. If it's a valid complaint, then
    /// it returns a [`Justification`]. This [`Justification`] must be broadcasted to every
    /// participants. If it's an invalid complaint, it returns an error about the
    /// complaint. The verifiers will also ignore an invalid Complaint.
    pub fn process_response(
        &mut self,
        r: &Response,
    ) -> Result<Option<Justification<SUITE>>, VSSError> {
        self.aggregator.verify_response(r)?;

        if r.status == STATUS_APPROVAL {
            return Ok(None);
        }

        let mut j = Justification {
            session_id: self.session_id.clone(),
            // index is guaranteed to be good because of d.verifyResponse before
            index: r.index,
            deal: self.deals[r.index as usize].clone(),
            signature: vec![],
        };

        let msg = &j.clone().hash(self.suite)?;
        let sig = schnorr::sign(&self.suite, &self.long, msg)?;
        j.signature = sig;

        Ok(Some(j))
    }

    /// [`secret_commit()`] returns the commitment of the secret being shared by this
    /// dealer. This function is only to be called once the deal has enough approvals
    /// and is verified otherwise it returns nil.
    pub fn secret_commit(&self) -> Option<SUITE::POINT> {
        if !self.aggregator.deal_certified() {
            return None;
        }
        Some(self.suite.point().mul(&self.secret, None))
    }

    /// [`commits()`] returns the commitments of the coefficient of the secret polynomial
    /// the Dealer is sharing.
    pub fn commits(&self) -> Vec<SUITE::POINT> {
        self.secret_commits.clone()
    }

    /// [`key()`] returns the longterm key pair used by this Dealer.
    pub fn key(&self) -> (<SUITE::POINT as Point>::SCALAR, SUITE::POINT) {
        (self.long.clone(), self.pubb.clone())
    }

    /// [`session_id()`] returns the current session id generated by this dealer for this
    /// protocol run.
    pub fn session_id(&self) -> Vec<u8> {
        self.session_id.clone()
    }

    /// [`set_timeout()`] marks the end of a round, invalidating any missing (or future) response
    /// for this DKG protocol round. The caller is expected to call this after a long timeout
    /// so each DKG node can still compute its share if enough [`deals`](Deal) are valid.
    pub fn set_timeout(&mut self) {
        self.aggregator.timeout = true
    }

    /// [`private_poly()`] returns the private polynomial used to generate the [`deal`](Deal). This
    /// private polynomial can be saved and then later on used to generate new
    /// shares.  This information SHOULD STAY PRIVATE and thus MUST never be given
    /// to any third party.
    pub fn private_poly(&self) -> share::poly::PriPoly<SUITE> {
        self.secret_poly.clone()
    }
}

/// [`Verifier`] receives a [`Deal`] from a [`Dealer`], can reply with a Complaint, and can
/// collaborate with other Verifiers to reconstruct a secret.
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Verifier<SUITE: Suite> {
    suite: SUITE,
    pub(crate) longterm: <SUITE::POINT as Point>::SCALAR,
    pub(crate) pubb: SUITE::POINT,
    dealer: SUITE::POINT,
    pub(crate) index: usize,
    verifiers: Vec<SUITE::POINT>,
    hkdf_context: Vec<u8>,
    pub(crate) aggregator: Option<Aggregator<SUITE>>,
}

impl<SUITE: Suite> Debug for Verifier<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Verifier")
            .field("suite", &self.suite)
            .field("pubb", &self.pubb)
            .field("dealer", &self.dealer)
            .field("index", &self.index)
            .field("verifiers", &self.verifiers)
            .field("hkdf_context", &self.hkdf_context)
            .field("aggregator", &self.aggregator)
            .finish()
    }
}

impl<SUITE: Suite> Display for Verifier<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write! {f, "Verifier( suite: {}, pubb: {}, dealer: {}, index: {},",
            self.suite,
            self.pubb,
            self.dealer,
            self.index
        }?;

        write!(f, " verifiers: [")?;
        let verifiers = self
            .verifiers
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(",");
        write!(f, "{}],", verifiers)?;

        write!(f, " hkdf_context: 0x{},", hex::encode(&self.hkdf_context))?;

        write!(f, " aggregator: ")?;
        match self.aggregator {
            Some(ref a) => write!(f, "Some({}) )", a),
            None => write!(f, "None )"),
        }
    }
}

/// [`new_verifier()`] returns a [`Verifier`] out of:
///   - its `longterm secret key`
///   - the `longterm dealer public key`
///   - the `list of public key of verifiers`. The list MUST include the public key of this Verifier also.
///
/// The security parameter t of the secret sharing scheme is automatically set to
/// a default safe value. If a different t value is required, it is possible to set
/// it with [`verifier.set_t()`].
pub fn new_verifier<SUITE: Suite>(
    suite: SUITE,
    longterm: &<SUITE::POINT as Point>::SCALAR,
    dealer_key: &SUITE::POINT,
    verifiers: &[SUITE::POINT],
) -> Result<Verifier<SUITE>, VSSError> {
    let pubb = suite.point().mul(longterm, None);
    let mut ok = false;
    let mut index = 0;
    for (i, v) in verifiers.iter().enumerate() {
        if v.eq(&pubb) {
            ok = true;
            index = i;
            break;
        }
    }
    if !ok {
        return Err(VSSError::PublicKeyNotFound);
    }
    let c = context(suite, dealer_key, verifiers);
    Ok(Verifier {
        suite,
        longterm: longterm.clone(),
        dealer: dealer_key.clone(),
        verifiers: verifiers.to_vec(),
        pubb,
        index,
        hkdf_context: c,
        aggregator: Some(new_empty_aggregator(suite, verifiers)),
    })
}

impl<SUITE: Suite> Deref for Verifier<SUITE> {
    type Target = Aggregator<SUITE>;

    fn deref(&self) -> &Self::Target {
        self.aggregator.as_ref().unwrap()
    }
}

impl<SUITE: Suite> DerefMut for Verifier<SUITE> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.aggregator.as_mut().unwrap()
    }
}

impl<SUITE: Suite> Verifier<SUITE>
where
    SUITE::POINT: PointCanCheckCanonicalAndSmallOrder,
    <SUITE::POINT as Point>::SCALAR: ScalarCanCheckCanonical,
{
    /// [`process_encrypted_deal()`] decrypt the [`Deal`] received from the [`Dealer`].
    /// If the deal is valid, i.e. the [`Verifier`] can verify its shares
    /// against the public coefficients and the signature is valid, an approval
    /// response is returned and must be broadcasted to every participants
    /// including the dealer.
    /// If the deal itself is invalid, it returns a complaint response that must be
    /// broadcasted to every other participants including the dealer.
    /// If the deal has already been received, or the signature generation of the
    /// response failed, it returns an [`Error`](VSSError) without any responses.
    pub fn process_encrypted_deal(
        &mut self,
        e: &EncryptedDeal<SUITE::POINT>,
    ) -> Result<Response, VSSError> {
        let d = self.decrypt_deal(e)?;
        if d.sec_share.i != self.index {
            return Err(VSSError::DealWrongIndex);
        }

        let t = d.t;

        let sid = session_id(
            &self.suite,
            &self.dealer,
            &self.verifiers,
            &d.commitments,
            t,
        )?;

        let mut r = Response {
            session_id: sid,
            index: self.index as u32,
            status: STATUS_APPROVAL,
            ..Default::default()
        };
        match self.verify_deal(&d, true) {
            Ok(_) => (),
            Err(e) => {
                r.status = STATUS_COMPLAINT;
                if let VSSError::DealAlreadyProcessed = e {
                    return Err(e);
                }
            }
        }

        r.signature = schnorr::sign(
            &self.suite,
            &self.longterm.clone(),
            r.hash(&self.suite)?.as_slice(),
        )?;

        self.aggregator.as_mut().unwrap().add_response(&r)?;
        Ok(r)
    }

    pub fn decrypt_deal(&self, e: &EncryptedDeal<SUITE::POINT>) -> Result<Deal<SUITE>, VSSError> {
        let eph_buff = e.dhkey.marshal_binary()?;
        // verify signature
        schnorr::verify(
            self.suite,
            &self.dealer.clone(),
            eph_buff.as_slice(),
            &e.signature,
        )?;

        // compute shared key and AES526-GCM cipher
        let pre = SUITE::dh_exchange(self.suite, self.longterm.clone(), e.dhkey.clone());
        let gcm = AEAD::<SUITE>::new(pre, &self.hkdf_context)?;
        let decrypted = gcm.open(
            None,
            e.nonce.as_slice().try_into().unwrap(),
            &e.cipher,
            Some(self.hkdf_context.as_slice()),
        )?;
        Deal::decode(&decrypted)
    }

    /// [`process_response()`] analyzes the given [`Response`]. If it's a valid complaint, the
    /// verifier should expect to see a [`Justification`] from the [`Dealer`]. It returns an
    /// [`Error`](VSSError) if it's not a valid response.
    /// Call [`v.deal_certified()`] to check if the whole protocol is finished.
    pub fn process_response(&mut self, resp: &Response) -> Result<(), VSSError> {
        match &mut self.aggregator {
            Some(aggregator) => aggregator.verify_response(resp),
            None => Err(VSSError::NoAggregatorForVerifier),
        }
    }

    /// [`commits()`] returns the commitments of the coefficients of the polynomial
    /// contained in the [`Deal`] received. It is public information. The private
    /// information in the deal must be retrieved through [`deal()`].
    pub fn commits(&self) -> Option<Vec<SUITE::POINT>> {
        self.deal.as_ref().map(|d| d.commitments.clone())
    }

    /// [`deal()`] returns the [`Deal`] that this [`Verifier`] has received. It returns
    /// `None` if the deal is not certified or there is not enough approvals.
    pub fn deal(&self) -> Option<Deal<SUITE>> {
        if !self.deal_certified() {
            return None;
        }
        self.deal.clone()
    }

    /// [`process_justification()`] takes a Dealer Response and returns an [`Error`](VSSError) if
    /// something went wrong during the verification. If it is the case, that
    /// probably means the Dealer is acting maliciously. In order to be sure, call
    /// [`v.deal_certified()`].
    pub fn process_justification(&mut self, dr: &Justification<SUITE>) -> Result<(), VSSError> {
        match &mut self.aggregator {
            Some(a) => a.verify_justification(dr),
            None => Err(VSSError::MissingAggregator),
        }
    }

    /// [`key()`] returns the `longterm` key pair this verifier is using during this protocol
    /// run.
    pub fn key(self) -> (<SUITE::POINT as Point>::SCALAR, SUITE::POINT) {
        (self.longterm, self.pubb)
    }

    /// [`index()`] returns the`index of the verifier in the list of participants used
    /// during this run of the protocol.
    pub fn index(&self) -> usize {
        self.index
    }

    /// [`session_id()`] returns the session id generated by the Dealer. WARNING: it returns
    /// an nil slice if the verifier has not received the Deal yet !
    pub fn session_id(&self) -> Vec<u8> {
        self.sid.clone()
    }

    /// [`set_timeout()`] marks the end of the protocol. The caller is expected to call this
    /// after a long timeout so each verifier can still deem its share valid if
    /// enough deals were approved. One should call [`deal_certified()`] after this
    /// method in order to know if the deal is valid or the protocol should abort.
    pub fn set_timeout(&mut self) {
        if let Some(a) = self.aggregator.as_mut() {
            a.timeout = true;
        }
    }

    /// [`unsafe_set_response_dkg()`] is an UNSAFE bypass method to allow DKG to use VSS
    /// that works on basis of approval only.
    #[allow(unused_must_use)]
    pub fn unsafe_set_response_dkg(&mut self, idx: u32, approval: bool) {
        let r = Response {
            session_id: self.sid.clone(),
            index: idx,
            status: approval,
            signature: vec![],
        };

        self.add_response(&r);
    }
}

/// [`recover_secret()`] recovers the secret shared by a [`Dealer`] by gathering at least `t`
/// [`Deals`](Deal) from the verifiers. It returns an [`Error`](VSSError) if there is not enough Deals or
/// if all Deals don't have the same `session_id`.
pub fn recover_secret<SUITE: Suite>(
    suite: SUITE,
    deals: Vec<Deal<SUITE>>,
    n: usize,
    t: usize,
) -> Result<<SUITE::POINT as Point>::SCALAR, VSSError> {
    let mut shares = Vec::with_capacity(deals.len());
    for deal in &deals {
        // all sids the same
        if deal.session_id == deals[0].session_id {
            shares.push(Some(deal.sec_share.clone()));
        } else {
            return Err(VSSError::DealsSameID);
        }
    }
    Ok(share::poly::recover_secret(suite, &shares, t, n)?)
}

/// [`Aggregator`] is used to collect all [`deals`](Deal), and responses for one protocol run.
/// It brings common functionalities for both [`Dealer`] and [`Verifier`] structs.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Aggregator<SUITE: Suite> {
    pub suite: SUITE,
    pub dealer: SUITE::POINT,
    pub verifiers: Vec<SUITE::POINT>,
    commits: Vec<SUITE::POINT>,

    pub(crate) responses: HashMap<u32, Response>,
    pub(crate) sid: Vec<u8>,
    pub(crate) deal: Option<Deal<SUITE>>,
    pub(crate) t: usize,
    pub(crate) bad_dealer: bool,
    pub(crate) timeout: bool,
}

impl<SUITE: Suite> Display for Aggregator<SUITE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "Aggregator ( suite: {},  dealer: {},",
            self.suite, self.dealer,
        )?;

        write!(f, " verifiers: [")?;
        let verifiers = self
            .verifiers
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(",");
        write!(f, "{}],", verifiers)?;

        write!(f, " commits: [")?;
        let commits = self
            .commits
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(",");
        write!(f, "{}],", commits)?;

        write!(f, " responses: [")?;
        let responses = self
            .responses
            .iter()
            .map(|c| "(".to_string() + &c.0.to_string() + ", " + &c.1.to_string() + ")")
            .collect::<Vec<_>>()
            .join(", ");
        write!(f, "{}],", responses)?;

        write!(f, " session_id: 0x{},", hex::encode(&self.sid))?;

        write!(f, " deal: ")?;
        match self.deal {
            Some(ref d) => write!(f, "Some({}),", d),
            None => write!(f, "None,"),
        }?;

        write!(
            f,
            " threshold: {}, bad_dealer: {}, timeout: {} )",
            self.t, self.bad_dealer, self.timeout
        )
    }
}

fn new_aggregator<SUITE: Suite>(
    suite: &SUITE,
    dealer: &SUITE::POINT,
    verifiers: &[SUITE::POINT],
    commitments: &[SUITE::POINT],
    t: usize,
    sid: &[u8],
) -> Aggregator<SUITE> {
    Aggregator {
        suite: *suite,
        dealer: dealer.clone(),
        verifiers: verifiers.to_vec(),
        commits: commitments.to_vec(),
        t,
        sid: sid.to_vec(),
        responses: HashMap::new(),
        deal: None,
        bad_dealer: false,
        timeout: false,
    }
}

/// [`new_empty_aggregator()`] returns a structure capable of storing [`Responses`](Response) about a
/// [`Deal`] and check if the deal is certified or not.
pub fn new_empty_aggregator<SUITE: Suite>(
    suite: SUITE,
    verifiers: &[SUITE::POINT],
) -> Aggregator<SUITE> {
    Aggregator {
        suite,
        verifiers: verifiers.to_vec(),
        responses: HashMap::new(),
        ..Default::default()
    }
}

impl<SUITE: Suite> Aggregator<SUITE>
where
    <SUITE::POINT as Point>::SCALAR: ScalarCanCheckCanonical,
    SUITE::POINT: PointCanCheckCanonicalAndSmallOrder,
{
    /// [`verify_deal()`] analyzes the deal and returns an [`Error`](VSSError) if it's incorrect. If
    /// inclusion is `true`, it also returns an [`Error`](VSSError::DealAlreadyProcessed) if it is the second time this struct
    /// analyzes a [`Deal`].
    pub fn verify_deal(&mut self, d: &Deal<SUITE>, inclusion: bool) -> Result<(), VSSError> {
        if self.deal.is_some() && inclusion {
            return Err(VSSError::DealAlreadyProcessed);
        }
        if self.deal.is_none() {
            self.commits = d.commitments.clone();
            self.sid = d.session_id.clone();
            self.deal = Some(d.clone());
            self.t = d.t;
        }

        if !valid_t(d.t, &self.verifiers) {
            return Err(VSSError::DealInvalidThreshold);
        }

        if d.t != self.t {
            return Err(VSSError::DealIncompatibleThreshold);
        }

        if self.sid != d.session_id {
            return Err(VSSError::DealInvalidSessionId);
        }

        let fi = &d.sec_share;
        if fi.i >= self.verifiers.len() {
            return Err(VSSError::DealIndexOutOfBounds);
        }
        // compute fi * G
        let fig = self.suite.point().base().mul(&fi.v, None);

        let commit_poly = share::poly::PubPoly::new(&self.suite, None, &d.commitments);

        let pub_share = commit_poly.eval(fi.i);
        if !fig.eq(&pub_share.v) {
            return Err(VSSError::DealDoesNotVerify);
        }
        Ok(())
    }

    /// [`set_threshold()`] is used to specify the expected threshold *before* the verifier
    /// receives anything. Sometimes, a verifier knows the treshold in advance and
    /// should make sure the one it receives from the dealer is consistent. If this
    /// method is not called, the first threshold received is considered as the
    /// "truth".
    pub fn set_threshold(&mut self, t: usize) {
        self.t = t
    }

    /// [`process_response()`] verifies the validity of the given response and stores it
    /// internally. It is the public version of [`verify_response()`] created this way to
    /// allow higher-level package to use these functionalities.
    pub fn process_response(&mut self, r: Response) -> Result<(), VSSError> {
        self.verify_response(&r)
    }

    pub(crate) fn verify_response(&mut self, r: &Response) -> Result<(), VSSError> {
        if !self.sid.is_empty() && r.session_id != self.sid {
            return Err(VSSError::ResponseInconsistentSessionId);
        }

        let public = find_pub(&self.verifiers, r.index as usize);
        if public.is_none() {
            return Err(VSSError::ResponseIndexOutOfBounds);
        }

        let msg = r.hash(&self.suite)?;

        schnorr::verify(self.suite, &public.unwrap(), &msg, &r.signature)?;

        self.add_response(r)
    }

    fn verify_justification(&mut self, j: &Justification<SUITE>) -> Result<(), VSSError> {
        let pubb = find_pub(&self.verifiers, j.index as usize);
        if pubb.is_none() {
            return Err(VSSError::JustificationIndexOutOfBounds);
        }

        if !self.responses.contains_key(&j.index) {
            return Err(VSSError::JustificationNoComplaints);
        }

        // clone the resp here
        let mut r = self.responses[&j.index].clone();

        if r.status != STATUS_COMPLAINT {
            return Err(VSSError::JustificationForApproval);
        }

        match self.verify_deal(&j.deal, false) {
            Ok(_) => r.status = STATUS_APPROVAL,
            Err(err) => {
                // if one justification is bad, then flag the dealer as malicious
                self.bad_dealer = true;
                return Err(err);
            }
        }
        Ok(())
    }

    pub fn add_response(&mut self, r: &Response) -> Result<(), VSSError> {
        if find_pub(&self.verifiers, r.index as usize).is_none() {
            return Err(VSSError::ComplaintIndexOutOfBounds);
        }
        if self.responses.get(&r.index).is_some() {
            return Err(VSSError::ResponseAlreadyExisting);
        }
        self.responses.insert(r.index, r.clone());
        Ok(())
    }

    /// [`responses()`] returns the list of [`responses`](Response) received and processed by this
    /// [`Aggregator`]
    pub fn responses(&self) -> &HashMap<u32, Response> {
        &self.responses
    }

    /// [`deal_certified()`] returns `true` if the [`Deal`] is certified.
    /// For a deal to be certified, it needs to comply to the following
    /// conditions in two different cases, since we are not working with the
    /// synchrony assumptions from Feldman's VSS:
    /// Before the timeout (i.e. before the "period" ends):
    /// 1. there is at least `t` approvals
    /// 2. all complaints must be `justified` (a complaint becomes an approval when
    /// justified) -> no complaints
    /// 3. there must not be absent [`responses`](Response)
    /// After the timeout, when the "period" ended, we replace the third condition:
    /// 3. there must not be more than `n-t` missing responses (otherwise it is not
    /// possible to retrieve the secret).
    /// If the caller previously called [`set_timeout()`] and [`deal_certified()`] returns
    /// `false`, the protocol MUST abort as the `deal` is not and never will be validated.
    pub fn deal_certified(&self) -> bool {
        let mut absent_verifiers = 0usize;
        let mut approvals = 0usize;
        let mut is_complaint = false;

        for (i, _) in self.verifiers.iter().enumerate() {
            if !self.responses.contains_key(&(i as u32)) {
                absent_verifiers += 1;
            } else {
                match self.responses.get(&(i as u32)).unwrap().status {
                    STATUS_COMPLAINT => is_complaint = true,
                    STATUS_APPROVAL => approvals += 1,
                }
            }
        }
        let enough_approvals = approvals >= self.t;
        let too_much_absents = absent_verifiers > self.verifiers.len() - self.t;
        let base_condition = !self.bad_dealer && enough_approvals && !is_complaint;
        if self.timeout {
            return base_condition && !too_much_absents;
        }
        base_condition && absent_verifiers == 0
    }

    /// [`missing_responses()`] returns the indexes of the expected but missing [`responses`](Response).
    pub fn missing_responses(&self) -> Vec<usize> {
        let mut absents = Vec::new();
        for (i, _) in self.verifiers.iter().enumerate() {
            if !self.responses.contains_key(&(i as u32)) {
                absents.push(i);
            }
        }
        absents
    }
}

/// [`minimum_t()`] returns the minimum safe `T` that is proven to be secure with this
/// protocol. It expects `n`, the total number of participants.
/// WARNING: Setting a lower `T` could make
/// the whole protocol insecure. Setting a higher `T` only makes it harder to
/// reconstruct the secret.
pub fn minimum_t(n: usize) -> usize {
    (n + 1) / 2
}

fn valid_t<POINT: Point>(t: usize, verifiers: &[POINT]) -> bool {
    t >= 2 && t <= verifiers.len() && (t as u32) as i64 == t as i64
}

pub fn derive_h<SUITE: Suite>(suite: SUITE, verifiers: &[SUITE::POINT]) -> SUITE::POINT {
    let mut b = vec![];
    for v in verifiers {
        v.marshal_to(&mut b).unwrap();
    }
    let base = suite.point().pick(&mut suite.xof(Some(&b)));
    base
}

pub(crate) fn find_pub<POINT: Point>(verifiers: &[POINT], idx: usize) -> Option<POINT> {
    verifiers.get(idx).cloned()
}

pub(crate) fn session_id<SUITE: Suite>(
    suite: &SUITE,
    dealer: &SUITE::POINT,
    verifiers: &[SUITE::POINT],
    commitments: &[SUITE::POINT],
    t: usize,
) -> Result<Vec<u8>, VSSError> {
    let mut h = suite.hash();
    dealer.marshal_to(&mut h)?;

    for v in verifiers {
        v.marshal_to(&mut h)?;
    }

    for c in commitments {
        c.marshal_to(&mut h)?;
    }

    h.write_u32::<LittleEndian>(t as u32)?;

    Ok(h.finalize().to_vec())
}

/// [`context()`] returns the context slice to be used when encrypting a share
pub fn context<SUITE: Suite>(
    suite: SUITE,
    dealer: &SUITE::POINT,
    verifiers: &[SUITE::POINT],
) -> Vec<u8> {
    let mut h = suite.hash();
    h.write_all("vss-dealer".as_bytes()).unwrap();
    dealer.marshal_to(&mut h).unwrap();
    h.write_all("vss-verifiers".as_bytes()).unwrap();
    for v in verifiers {
        v.marshal_to(&mut h).unwrap();
    }
    h.finalize().to_vec()
}