-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfrost.rs
2457 lines (2169 loc) · 94.5 KB
/
frost.rs
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
//! FROST implementation.
//!
//! This follows the v14 draft specification: [draft-irtf-cfrg-frost-14]
//!
//! FROST is a threshold Schnorr signature scheme: the group private key
//! is split into individual signer shares. If enough signers (with a
//! configurable threshold) collaborate, then they can conjointly
//! generate a signature on a given message. The individual signers do
//! not have to trust each other (the protocol is resilient to actively
//! malicious signers, who may at worst prevent the generation of a valid
//! signature). Output signatures are "plain" Schnorr signatures,
//! verifiable against the group public key. When the ciphersuite is
//! FROST(Ed25519, SHA-512), the generated signatures can also be
//! successfully verified with a plain Ed25519 verifier (as per RFC
//! 8032); the same applies to FROST(Ed448, SHAKE256) relatively to Ed448
//! verifiers (also as defined in RFC 8032).
//!
//! Single-signer usage is also supported: message signatures can be
//! generated from the group private key itself. In distributed signature
//! usage, _nobody_ knows the group private key itself once it has been
//! split into individual signer key shares.
//!
//! Sub-modules are defined for several ciphersuites:
//!
//! - `ed25519`: FROST(Ed25519, SHA-512)
//! - `ristretto255`: FROST(ristretto255, SHA-512)
//! - `ed448`: FROST(Ed448, SHAKE256)
//! - `p256`: FROST(P-256, SHA-256)
//! - `secp256k1`: FROST(secp256k1, SHA-256)
//!
//! All sub-modules implement the same API, with the following types:
//!
//! - `GroupPrivateKey`: a group private key
//! - `GroupPublicKey`: a group public key
//! - `SignerPrivateKeyShare`: an individual signer's private key share
//! - `SignerPublicKey`: an individual signer's public key
//! - `KeySplitter`: tagging structure for the trusted dealer, who
//! splits the group private key into individual key shares
//! - `VSSElement`: an element of the VSS commitment produced by the trusted
//! dealer (the VSS commitment allows individual signers to validate that
//! their private key share was properly generated)
//! - `Coordinator`: the permanent state of a coordinator, who organizes
//! the signature generation and assembles the signature shares (that
//! state consists of the signature threshold and the group public key)
//! - `Nonce`: a per-signature nonce produced by an individual signer
//! - `Commitment`: a per-signature commitment produced by an individual signer
//! - `SignatureShare`: a signature share, produced by an individual signer
//! - `Signature`: a generated FROST signature
//!
//! All the types that are meant to be either transmitted or stored on a
//! non-volatile medium have encoding and decoding functions; the encoding
//! functions return a fixed-size array of bytes (the size is published as
//! the `ENC_LEN` constant in the structure) while the decoding function
//! takes as input a slice of bytes and returns an `Option` type.
//!
//! Sample code using the FROST API is available in [frost-sample.rs].
//!
//! The implementation of all operations involving secret values is
//! constant-time.
//!
//! [draft-irtf-cfrg-frost-14]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-frost-14
//! [frost-sample.rs]: https://github.com/pornin/crrl/extra/frost-sample.rs
#![allow(non_snake_case)]
#![allow(unused_macros)]
/// Most functions are generic, provided that the relevant Point and
/// Scalar types are in scope, and a few constants defined. This macro
/// generates the generic functions. The caller is supposed to invoke it
/// in an appropriate module with Point and Scalar already defined.
macro_rules! define_frost_core { () => {
use crate::{CryptoRng, RngCore};
use crate::Vec;
use core::cmp::Ordering;
/// A group private key.
///
/// In normal FROST usage, the group private key is not supposed to be
/// kept anywhere once the private key shares have been computed. In
/// single-signer usage, the group private key is handled like a
/// normal cryptographic private key.
#[derive(Clone, Copy, Debug)]
pub struct GroupPrivateKey {
sk: Scalar,
pk: Point,
pk_enc: [u8; NE], // keep cached copy of the encoded public key
}
/// A group public key.
#[derive(Clone, Copy, Debug)]
pub struct GroupPublicKey {
pk: Point,
pk_enc: [u8; NE], // keep cached copy of the encoded public key
}
/// A tagging structure for functions related to key splitting; it
/// does not contain any state.
#[derive(Clone, Copy, Debug)]
pub struct KeySplitter { }
/// A private key share.
///
/// This structure contains the private key share of a given signer.
/// It includes the signer's identifier, private key (a scalar),
/// corresponding public key (a point), and group public key. The
/// signer's public key is recomputed from the signer's private key
/// when decoding, so it always matches the signers private key.
#[derive(Clone, Copy, Debug)]
pub struct SignerPrivateKeyShare {
/// Signer identifier
pub ident: Scalar,
sk: Scalar,
pk: Point,
group_pk: GroupPublicKey,
}
/// A signer's public key.
///
/// This structure contains the public key of a given signer. It
/// includes the signer's identifier. It does NOT include the group
/// public key.
#[derive(Clone, Copy, Debug)]
pub struct SignerPublicKey {
/// Signer identifier
pub ident: Scalar,
pk: Point,
}
/// A VSS element.
///
/// The key split process yields, along with the private key shares,
/// a sequence of public VSS elements which can be used by individual
/// signers to verify that their share was properly computed, and
/// also to derive the group information (all signers' public keys,
/// and the group public key).
#[derive(Clone, Copy, Debug)]
pub struct VSSElement(Point);
/// A signer's nonce.
///
/// A nonce and a commitment are generated by a signer when starting
/// the computation of a new signature. The signer must remember them
/// for the second round of the signature generation protocol. The
/// nonce is secret; the commitment is public and must be sent to the
/// coordinator.
#[derive(Clone, Copy, Debug)]
pub struct Nonce {
ident: Scalar,
hiding: Scalar,
binding: Scalar,
}
/// A signer's commitment.
///
/// A nonce and a commitment are generated by a signer when starting
/// the computation of a new signature. The signer must remember them
/// for the second round of the signature generation protocol. The
/// nonce is secret; the commitment is public and must be sent to the
/// coordinator.
#[derive(Clone, Copy, Debug)]
pub struct Commitment {
/// Signer identifier
pub ident: Scalar,
hiding: Point,
binding: Point,
}
/// A signature share.
///
/// A signature share is computed by an individual signer, and sent
/// to the coordinator for assembly of the complete group signature.
#[derive(Clone, Copy, Debug)]
pub struct SignatureShare {
/// Signer identifier
pub ident: Scalar,
zi: Scalar,
}
/// A FROST signature.
#[derive(Clone, Copy, Debug)]
pub struct Signature {
R: Point,
z: Scalar,
}
/// A coordinator's permanent state.
///
/// The coordinator knows the signature threshold and the group
/// public key.
#[derive(Clone, Copy, Debug)]
pub struct Coordinator {
min_signers: usize,
group_pk: GroupPublicKey,
}
impl GroupPrivateKey {
/// Encoded private key length (in bytes).
pub const ENC_LEN: usize = NS;
/// Generates a new (group) private key.
///
/// A private key is a randomly selected non-zero scalar.
pub fn generate<T: CryptoRng + RngCore>(rng: &mut T) -> Self {
let mut sk = random_scalar(rng);
sk.set_cond(&Scalar::ONE, sk.iszero());
let pk = Point::mulgen(&sk);
let pk_enc = point_encode(pk);
Self { sk, pk, pk_enc }
}
/// Gets the public key corresponding to this private key.
pub fn get_public_key(self) -> GroupPublicKey {
GroupPublicKey { pk: self.pk, pk_enc: self.pk_enc }
}
/// Encodes this private key into bytes.
///
/// In normal FROST usage, group private keys are only transient
/// in-memory object discarded at the end of the key split process.
/// Private key encoding is meant to support single-signer FROST
/// usage.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
scalar_encode(self.sk)
}
/// Decodes this private key from bytes.
///
/// This function may fail (i.e. return `None`) if the source does
/// not have the length of an encoded private key, or if the
/// provided bytes are not a proper canonical encoding for a
/// non-zero scalar.
pub fn decode(buf: &[u8]) -> Option<Self> {
let sk = scalar_decode(buf)?;
if sk.iszero() != 0 {
return None;
}
let pk = Point::mulgen(&sk);
let pk_enc = point_encode(pk);
Some(Self { sk, pk, pk_enc })
}
/// Generates a signature (single-signer version).
///
/// This function uses the (group) private key to sign the
/// provided message. The signature is randomized, though it also
/// uses a derandomization process internally so that safety is
/// maintained even if the provided random generator has poor
/// quality.
pub fn sign<T: CryptoRng + RngCore>(self, rng: &mut T, msg: &[u8])
-> Signature
{
let mut seed = [0u8; 32];
rng.fill_bytes(&mut seed);
self.sign_seeded(&seed, msg)
}
/// Generates a signature (single-signer version, seeded).
///
/// This function uses the (group) private key to sign the
/// provided message. The signature uses an internal derandomization
/// process to compute the per-signature nonce; an additional seed
/// can be provided, which is integrated in that process. If that
/// extra seed is fixed (e.g. it is empty), then the signature
/// is deterministic (but still safe).
pub fn sign_seeded(self, seed: &[u8], msg: &[u8]) -> Signature {
// Per-signature nonce is obtained with hash function H6(),
// over the public key, private key, seed, and message. The
// seed length is included before the seed to make the hashing
// unambiguous; we append that length to the encoded private
// key since we statically know its length.
let mut esksl = [0u8; NS + 8];
esksl[0..NS].copy_from_slice(&scalar_encode(self.sk));
esksl[NS..NS + 8].copy_from_slice(
&(seed.len() as u64).to_le_bytes());
let k = H6(&self.pk_enc, &esksl, seed, msg);
let R = Point::mulgen(&k);
let challenge = compute_challenge(R, &self.pk_enc, msg);
let z = k + challenge * self.sk;
Signature { R, z }
}
}
impl GroupPublicKey {
/// Encoded public key length (in bytes).
pub const ENC_LEN: usize = NE;
/// Encodes this public key into bytes.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
self.pk_enc
}
/// Decodes this public key from bytes.
///
/// This function may fail (i.e. return `None`) if the source does
/// not have the length of an encoded public key, or if the
/// provided bytes are not a proper canonical encoding for a
/// non-neutral group element.
pub fn decode(buf: &[u8]) -> Option<Self> {
// If the source bytes decode properly then we can use them
// as the cached encoded public key.
let pk = point_decode(buf)?;
let mut pk_enc = [0u8; NE];
pk_enc[..].copy_from_slice(buf);
Some(Self { pk, pk_enc })
}
/// Verifies a FROST signature.
///
/// The provided signature (`sig`) is verified against this
/// public key, for the given message (`msg`). FROST is nominally
/// a distributed signature scheme, but this function also works
/// with singler-signer signatures.
pub fn verify(self, sig: Signature, msg: &[u8]) -> bool {
// Compute the challenge.
let challenge = compute_challenge(sig.R, &self.pk_enc, msg);
// Verify the equation.
self.pk.verify_helper_vartime(&sig.R, &sig.z, &challenge)
}
/// Verifies a FROST signature.
///
/// This function decodes the signature from its encoded format
/// (`esig`), then calls `self.verify()`. If the signature cannot
/// be decoded, or if the signature is syntactically correct but
/// the verification algorithm fails, then `false` is returned.
pub fn verify_esig(self, esig: &[u8], msg: &[u8]) -> bool {
match Signature::decode(esig) {
Some(sig) => self.verify(sig, msg),
None => false,
}
}
}
impl KeySplitter {
/// FROST specification, in appendix D, mandates that the
/// key generation process with a trusted dealers does not generate
/// more than 65535 shares. This is an arbitrary limit that may
/// change in the future (it was historically related to the
/// encoding of share identifiers over two bytes in older draft
/// specifications, but the encoding has changed and no longer has
/// this limitation).
pub const MAX_MAX_SIGNERS: usize = 65535;
/// Split a group private key into shares.
///
/// This function corresponds to the `trusted_dealer_keygen`
/// function in the FROST specification.
///
/// `group_sk` is the group private key.
/// `min_signers` is the signing threshold; it must be at least 2.
/// `max_signers` is the number of shares; it must not be lower than
/// `min_signers`, and must not exceed `MAX_MAX_SIGNERS`.
///
/// Returned values are:
/// - a vector of `max_signers` signing shares;
/// - a vector os `min_signers` VSS elements, that allow
/// individual signers to verify that their respective shares
/// were correctly generated.
pub fn trusted_split<T: CryptoRng + RngCore>(rng: &mut T,
group_sk: GroupPrivateKey, min_signers: usize, max_signers: usize)
-> (Vec<SignerPrivateKeyShare>, Vec<VSSElement>)
{
assert!(min_signers >= 2);
assert!(min_signers <= max_signers);
assert!(max_signers <= Self::MAX_MAX_SIGNERS);
let group_pk = GroupPublicKey {
pk: group_sk.pk,
pk_enc: group_sk.pk_enc,
};
let mut coefficients: Vec<Scalar> = Vec::new();
let mut vsscomm: Vec<VSSElement> = Vec::new();
coefficients.push(group_sk.sk);
vsscomm.push(VSSElement(group_pk.pk));
for _ in 1..min_signers {
let coef = random_scalar(rng);
coefficients.push(coef);
vsscomm.push(VSSElement(Point::mulgen(&coef)));
}
let mut shares: Vec<SignerPrivateKeyShare> = Vec::new();
for i in 0..max_signers {
let x = Scalar::from_u64((i as u64) + 1);
let mut y = coefficients[min_signers - 1];
for j in (0..(min_signers - 1)).rev() {
y = (y * x) + coefficients[j];
}
let pk = Point::mulgen(&y);
shares.push(SignerPrivateKeyShare {
ident: x,
sk: y,
pk: pk,
group_pk: group_pk,
});
}
(shares, vsscomm)
}
/// Derives the group information (individual signer public keys, and
/// group public key) from the key sharing output.
///
/// `max_signers` is the total number of signers (computed key shares).
/// `vsscomm` is the VSS commitment from the sharing step; it contains
/// exactly `min_signers` points (where `min_signers` is the signing
/// threshold).
///
/// This function assumes that the provided parameters are correct,
/// i.e. that the VSS commitment has been duly verified.
pub fn derive_group_info(max_signers: usize, vsscomm: Vec<VSSElement>)
-> (Vec<SignerPublicKey>, GroupPublicKey)
{
assert!(vsscomm.len() >= 2);
assert!(max_signers >= vsscomm.len());
assert!(max_signers <= Self::MAX_MAX_SIGNERS);
let group_pk = GroupPublicKey {
pk: vsscomm[0].0,
pk_enc: point_encode(vsscomm[0].0),
};
let min_signers = vsscomm.len();
let mut signer_pk_list: Vec<SignerPublicKey> = Vec::new();
for i in 1..=max_signers {
let mut Q = group_pk.pk;
let k = Scalar::from_u64(i as u64);
let mut z = k;
for j in 1..min_signers {
Q += vsscomm[j].0 * z;
z *= k;
}
signer_pk_list.push(SignerPublicKey {
ident: Scalar::from_u64(i as u64),
pk: Q,
});
}
(signer_pk_list, group_pk)
}
}
impl SignerPrivateKeyShare {
/// Private key share encoded length (in bytes).
pub const ENC_LEN: usize = NS + NS + NE;
/// Encodes this private key share into bytes.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
let mut buf = [0u8; Self::ENC_LEN];
buf[0..NS].copy_from_slice(&scalar_encode(self.ident));
buf[NS..NS + NS].copy_from_slice(&scalar_encode(self.sk));
buf[NS + NS..NS + NS + NE].copy_from_slice(&self.group_pk.pk_enc);
buf
}
/// Decodes this share from bytes.
///
/// The process fails (i.e. returns `None`) if the source slice
/// does not have a proper length or does not contain properly
/// canonical encodings of the share identifier, share of the
/// private key, or group public key.
pub fn decode(buf: &[u8]) -> Option<Self> {
if buf.len() != Self::ENC_LEN {
return None;
}
let ident = scalar_decode(&buf[0..NS])?;
if ident.iszero() != 0 {
// Share identifiers are not allowed to be zero.
return None;
}
let sk = scalar_decode(&buf[NS..NS + NS])?;
if sk.iszero() != 0 {
// We explicitly reject a zero scalar here because:
// - We don't want to get a neutral point as public
// key, since that is not supported in most ciphersuites,
// and that would make some later encoding/decoding fail.
// - Zero private keys are just plain abnormal. They may
// theoretically happen with a negligible probability;
// in practice, if a zero is obtained, then it is almost
// surely because of a bug, an attack, or a hardware
// failure.
return None;
}
let group_pk = GroupPublicKey::decode(&buf[NS + NS..NS + NS + NE])?;
Some(Self {
ident: ident,
sk: sk,
pk: Point::mulgen(&sk),
group_pk: group_pk,
})
}
/// Get the public key for this signer.
pub fn get_public_key(self) -> SignerPublicKey {
SignerPublicKey {
ident: self.ident,
pk: self.pk,
}
}
/// Verifies that this share was properly computed, given the VSS
/// commitments.
///
/// This function is called `vss_verify` in the FROST specification.
pub fn verify_split(self, vsscomm: &[VSSElement]) -> bool {
// We don't need to check that the private key is not zero, or
// that the public key matches it, because this was already
// verified when decoding.
let mut Q = vsscomm[0].0;
let k = self.ident;
let mut z = k;
for j in 1..vsscomm.len() {
Q += vsscomm[j].0 * z;
z *= k;
}
self.pk.equals(Q) != 0
}
/// Internal generation of a new nonce.
///
/// As per the specification, the nonce is obtained by hashing the
/// concatenation of 32 random bytes and the private key.
fn nonce_generate<T: CryptoRng + RngCore>(self, rng: &mut T) -> Scalar {
let mut buf = [0u8; 32 + NS];
rng.fill_bytes(&mut buf[0..32]);
buf[32..32 + NS].copy_from_slice(&scalar_encode(self.sk));
H3(&buf)
}
/// Generates nonces and commitments for a new signature generation.
///
/// The returned `Nonce` and `Commitment` should be remembered by the
/// signer for round 2. The `Commitment` should be sent to the
/// coordinator (`Nonce` is secret and MUST NOT be revealed to
/// anybody).
pub fn commit<T: CryptoRng + RngCore>(self, rng: &mut T)
-> (Nonce, Commitment)
{
let ident = self.ident;
let hiding = self.nonce_generate(rng);
let binding = self.nonce_generate(rng);
let nonce = Nonce { ident, hiding, binding };
(nonce, nonce.get_commitment())
}
/// Computes a signature share.
///
/// The nonce and commitment (previously generated with a `commit()`
/// call, the commitment was sent to the coordinator) is combined with
/// the message and list of signer commitments selected by the
/// coordinator.
///
/// This function may fail if the list of commitments is too short
/// (less than two commitments), or not in the expected order
/// (by ascending signer identifier), or contains duplicates (two
/// commitments with the same identifier), or does not contain this
/// signer's identifier, or contains this signer's identifier but
/// with a different commitment. In all failure cases, `None` is
/// returned.
///
/// The signer's own nonce (`nonce`) and commitment (`comm`) MUST
/// match each other.
pub fn sign(self, nonce: Nonce, comm: Commitment,
msg: &[u8], commitment_list: &[Commitment])
-> Option<SignatureShare>
{
// Verify that the commitment list is ordered with no duplicate,
// that we are part of the list of signers, and that our commitment
// indeed appears there.
if commitment_list.len() < 2 {
return None;
}
for i in 0..(commitment_list.len() - 1) {
if scalar_cmp_vartime(commitment_list[i].ident,
commitment_list[i + 1].ident) != Ordering::Less
{
return None;
}
}
let mut ff = false;
for i in 0..commitment_list.len() {
if commitment_list[i].ident.equals(self.ident) != 0 {
ff = true;
if commitment_list[i].hiding.equals(comm.hiding) == 0
|| commitment_list[i].binding.equals(comm.binding) == 0
{
return None;
}
}
}
if !ff {
return None;
}
// The caller should remember both the nonce and the commitment;
// thus, a mismatch here is a programming bug, not a case of
// incoming malicious data.
assert!(nonce.ident.equals(comm.ident) != 0);
// Compute the binding factors. Since we verified that our
// commitment is in the provided list,
// binding_factor_for_participant() cannot fail.
let binding_factor_list = compute_binding_factors(
self.group_pk, commitment_list, msg);
let binding_factor = binding_factor_for_participant(
&binding_factor_list, self.ident).unwrap();
// Compute the group commitment.
let group_commitment = compute_group_commitment(
commitment_list, &binding_factor_list);
// Compute the Lagrange coefficient.
let participant_list = participants_from_commitment_list(
commitment_list);
let lambda = derive_interpolating_value(
self.ident, &participant_list);
// Compute the per-message challenge.
let challenge = compute_challenge(
group_commitment, &self.group_pk.pk_enc, msg);
// Compute the signature share.
let sig_share = nonce.hiding + nonce.binding * binding_factor
+ lambda * self.sk * challenge;
Some(SignatureShare {
ident: self.ident,
zi: sig_share,
})
}
}
impl SignerPublicKey {
/// Signer's public key encoded length (in bytes).
pub const ENC_LEN: usize = NS + NE;
/// Encodes this public key into bytes.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
let mut buf = [0u8; Self::ENC_LEN];
buf[0..NS].copy_from_slice(&scalar_encode(self.ident));
buf[NS..NS + NE].copy_from_slice(&point_encode(self.pk));
buf
}
/// Decodes this public key from bytes.
///
/// The process fails (i.e. returns `None`) if the source slice
/// does not have a proper length or does not contain properly
/// canonical encodings of the share identifier and signer's
/// public key.
pub fn decode(buf: &[u8]) -> Option<Self> {
if buf.len() != Self::ENC_LEN {
return None;
}
let ident = scalar_decode(&buf[0..NS])?;
if ident.iszero() != 0 {
return None;
}
let pk = point_decode(&buf[NS..NS + NE])?;
Some(Self { ident, pk })
}
/// Verifies a signature share relatively to this signer's public key,
/// for a given signature generation process.
///
/// This function can be used by the coordinator to check that the
/// signer computed its signature share properly. It is implictly
/// called by `Coordinator::assemble_signature()`.
pub fn verify_signature_share(self, sig_share: SignatureShare,
commitment_list: &[Commitment], group_pk: GroupPublicKey,
msg: &[u8]) -> bool
{
let binding_factor_list = compute_binding_factors(
group_pk, commitment_list, msg);
let group_commitment = compute_group_commitment(
commitment_list, &binding_factor_list);
let challenge = compute_challenge(
group_commitment, &group_pk.pk_enc, msg);
self.inner_verify_signature_share(sig_share, commitment_list,
&binding_factor_list, challenge)
}
/// Verifies a signature share relatively to this signer's public key,
/// for a given signature generation process (inner function).
fn inner_verify_signature_share(self, sig_share: SignatureShare,
commitment_list: &[Commitment],
binding_factor_list: &[BindingFactor], challenge: Scalar) -> bool
{
// Verify that the share is really ours.
if sig_share.ident.equals(self.ident) == 0 {
return false;
}
// Find our commitment in the list.
let mut comm = Commitment::INVALID;
for c in commitment_list.iter() {
if c.ident.equals(self.ident) != 0 {
comm = *c;
break;
}
}
if comm.is_invalid() {
return false;
}
// Get the correct binding factor.
let binding_factor = binding_factor_for_participant(
binding_factor_list, self.ident).unwrap();
// Compute the commitment share.
let comm_share = comm.hiding + binding_factor * comm.binding;
// Compute the Lagrange coefficient.
let participant_list = participants_from_commitment_list(
commitment_list);
let lambda = derive_interpolating_value(
self.ident, &participant_list);
// Compute relation values.
// We want to verify that P1 = P2, with:
// P1 = sig_share*G
// P2 = comm_share + (challenge * lambda)*Q
// (with Q = public key)
// Everything here is public so we can use verify_helper_vartime().
self.pk.verify_helper_vartime(
&comm_share, &sig_share.zi, &(challenge * lambda))
}
}
impl VSSElement {
/// Encodes a VSS commitment (list of VSS elements) into bytes.
pub fn encode_list(vss: &[VSSElement]) -> Vec<u8> {
let mut r: Vec<u8> = Vec::with_capacity(NE * vss.len());
for v in vss.iter() {
r.extend_from_slice(&point_encode(v.0));
}
r
}
/// Decodes a VSS commitment (list of VSS elements) from bytes.
///
/// This function returns `None` if the source slice does not split
/// evenly into at least two encoded points (with no trailing garbage),
/// or if any of the encodings is not a valid point encoding, or if any
/// of the points is the neutral.
pub fn decode_list(buf: &[u8]) -> Option<Vec<VSSElement>> {
if buf.len() % NE != 0 {
return None;
}
let n = buf.len() / NE;
if n < 2 {
return None;
}
let mut r: Vec<VSSElement> = Vec::with_capacity(n);
for i in 0..n {
r.push(VSSElement(point_decode(&buf[NE * i .. NE * (i + 1)])?));
}
Some(r)
}
}
impl Nonce {
/// Encoded nonce length (in bytes).
pub const ENC_LEN: usize = 3 * NS;
/// Encodes this nonce into bytes.
///
/// In normal FROST usage, nonces are transient, remembered only
/// by the individual signer who generated them, and not transmitted.
/// Encoding nonces into bytes is possible to allow long-latency
/// scenarios in which the signer cannot reliably maintain the nonce
/// in RAM only between the two rounds.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
let mut buf = [0u8; Self::ENC_LEN];
buf[0..NS].copy_from_slice(&scalar_encode(self.ident));
buf[NS..2 * NS].copy_from_slice(&scalar_encode(self.hiding));
buf[2 * NS..3 * NS].copy_from_slice(&scalar_encode(self.binding));
buf
}
/// Decodes this nonce from bytes.
pub fn decode(buf: &[u8]) -> Option<Self> {
if buf.len() != Self::ENC_LEN {
return None;
}
let ident = scalar_decode(&buf[0..NS])?;
if ident.iszero() != 0 {
return None;
}
let hiding = scalar_decode(&buf[NS..2 * NS])?;
let binding = scalar_decode(&buf[2 * NS..3 * NS])?;
Some(Self { ident, hiding, binding })
}
/// (Re)computes the commitment corresponding to this nonce.
pub fn get_commitment(self) -> Commitment {
Commitment {
ident: self.ident,
hiding: Point::mulgen(&self.hiding),
binding: Point::mulgen(&self.binding),
}
}
}
impl Commitment {
/// Invalid commitment value, used as a placeholder.
const INVALID: Commitment = Self {
ident: Scalar::ZERO,
hiding: Point::NEUTRAL,
binding: Point::NEUTRAL,
};
/// Encoded length (in bytes).
pub const ENC_LEN: usize = NS + 2 * NE;
fn is_invalid(self) -> bool {
self.ident.iszero() != 0
}
/// Encodes this commitment into bytes.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
let mut buf = [0u8; Self::ENC_LEN];
buf[0..NS].copy_from_slice(&scalar_encode(self.ident));
buf[NS..NS + NE].copy_from_slice(&point_encode(self.hiding));
buf[NS + NE..NS + 2 * NE].copy_from_slice(
&point_encode(self.binding));
buf
}
/// Decodes this commitment from bytes.
///
/// The process fails (i.e. returns `None`) if the source slice
/// does not have a proper length or does not contain properly
/// canonical encodings of the signer identifier and commitment.
pub fn decode(buf: &[u8]) -> Option<Self> {
if buf.len() != Self::ENC_LEN {
return None;
}
let ident = scalar_decode(&buf[0..NS])?;
if ident.iszero() != 0 {
return None;
}
let hiding = point_decode(&buf[NS..NS + NE])?;
let binding = point_decode(&buf[NS + NE..NS + 2 * NE])?;
Some(Self { ident, hiding, binding })
}
/// Encodes a commitment list into bytes.
pub fn encode_list(commitment_list: &[Commitment]) -> Vec<u8> {
// This is encode_group_commitment_list() from the FROST spec.
let mut r: Vec<u8> = Vec::with_capacity(
Commitment::ENC_LEN * commitment_list.len());
for c in commitment_list.iter() {
r.extend_from_slice(&c.encode());
}
r
}
/// Decodes a commitment list from bytes.
///
/// This function verifies that there are at least two commitments, that
/// the source slice does not have any trailing unused bytes, that all
/// commitments are syntactically correct (in particular that the
/// identifiers are canonically-encoded non-zero scalars and the
/// commitment points are canonically encoded), and that the list
/// is properly ordered in ascending order of identifiers with no
/// duplicate. If any of these verification fails, then this function
/// returns `None`.
pub fn decode_list(buf: &[u8]) -> Option<Vec<Commitment>> {
if buf.len() % Commitment::ENC_LEN != 0 {
return None;
}
let n = buf.len() / Commitment::ENC_LEN;
if n < 2 {
return None;
}
let mut cc: Vec<Commitment> = Vec::with_capacity(n);
for i in 0..n {
let c = Commitment::decode(&buf[i * Commitment::ENC_LEN
.. (i + 1) * Commitment::ENC_LEN])?;
if i > 0 {
if scalar_cmp_vartime(cc[i - 1].ident, c.ident)
!= Ordering::Less
{
return None;
}
}
cc.push(c);
}
Some(cc)
}
}
impl SignatureShare {
/// Encoded length (in bytes) of a signature share.
pub const ENC_LEN: usize = NS + NS;
/// Encode a signature share into bytes.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
let mut buf = [0u8; Self::ENC_LEN];
buf[0..NS].copy_from_slice(&scalar_encode(self.ident));
buf[NS..NS + NS].copy_from_slice(&scalar_encode(self.zi));
buf
}
/// Decode a signature share from bytes.
pub fn decode(buf: &[u8]) -> Option<Self> {
if buf.len() != Self::ENC_LEN {
return None;
}
let ident = scalar_decode(&buf[0..NS])?;
if ident.iszero() != 0 {
return None;
}
let zi = scalar_decode(&buf[NS..NS + NS])?;
Some(Self { ident, zi })
}
}
impl Signature {
/// Encoded length (in bytes) of a signature.
pub const ENC_LEN: usize = NE + NS;
/// Encode a signature into bytes.
pub fn encode(self) -> [u8; Self::ENC_LEN] {
let mut buf = [0u8; Self::ENC_LEN];
buf[0..NE].copy_from_slice(&point_encode(self.R));
buf[NE..NE + NS].copy_from_slice(&scalar_encode(self.z));
buf
}
/// Decode a signature from bytes.
///
/// `None` is returned if the source bytes do not have the proper
/// length for a signature, or if the signature is syntactically
/// incorrect.
pub fn decode(buf: &[u8]) -> Option<Self> {
if buf.len() != Self::ENC_LEN {
return None;
}
let R = point_decode(&buf[0..NE])?;
let z = scalar_decode(&buf[NE..NE + NS])?;
Some(Signature { R, z })
}
}
impl Coordinator {
/// Create an instance over the provided group public key and
/// signature threshold.
///
/// If the threshold is invalid (less than 2), then this function
/// returns `None`.
pub fn new(min_signers: usize, group_pk: GroupPublicKey)
-> Option<Self>
{
if min_signers < 2 {
return None;
}
Some(Self { min_signers, group_pk })
}
/// Choose the signers from a list of commitments.
///
/// If there are enough commitments (given the group threshold),
/// then this function chooses `min_signers` of them and returns
/// the corresponding ordered list of commitments. The list must
/// be sent to all chosen participants.
pub fn choose(self, comms: &[Commitment]) -> Option<Vec<Commitment>> {
// TODO: maybe do a better sort? This is an insertion sort, with
// a cost quadratic min_signers. Normally, min_signers is rather
// small, so this does not matter much.
let mut r: Vec<Commitment> = Vec::with_capacity(self.min_signers);
for i in 0..comms.len() {
let c = comms[i];
let mut ff = false;
for j in 0..r.len() {
let cv = scalar_cmp_vartime(r[j].ident, c.ident);
if cv != Ordering::Less {
if cv == Ordering::Greater {
r.insert(j, c);
}
ff = true;
break;
}
}
if !ff {
r.push(c);
}
if r.len() >= self.min_signers {
// We got enough distinct commitments, and they are
// already sorted.
return Some(r);