-
Notifications
You must be signed in to change notification settings - Fork 296
/
test_utils.rs
1174 lines (1022 loc) · 38.4 KB
/
test_utils.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
#![allow(dead_code)]
use assert_matches::assert_matches;
use ic_crypto_internal_threshold_sig_ecdsa::*;
use ic_types::crypto::canister_threshold_sig::MasterEcdsaPublicKey;
use ic_types::crypto::AlgorithmId;
use ic_types::{NumberOfNodes, Randomness};
use rand::{seq::IteratorRandom, Rng};
use std::collections::BTreeMap;
#[derive(Copy, Clone, Debug)]
pub struct TestConfig {
signature_curve: EccCurveType,
key_curve: EccCurveType,
}
impl TestConfig {
pub fn all() -> Vec<Self> {
vec![
Self::new(EccCurveType::K256),
Self::new(EccCurveType::P256),
Self::new_mixed(EccCurveType::P256, EccCurveType::K256),
]
}
pub fn new(curve: EccCurveType) -> Self {
Self::new_mixed(curve, curve)
}
pub fn new_mixed(signature_curve: EccCurveType, key_curve: EccCurveType) -> Self {
Self {
signature_curve,
key_curve,
}
}
pub fn signature_curve(&self) -> EccCurveType {
self.signature_curve
}
pub fn key_curve(&self) -> EccCurveType {
self.key_curve
}
}
fn verify_ecdsa_signature_using_third_party(
alg: AlgorithmId,
pk: &[u8],
sig: &[u8],
msg: &[u8],
) -> bool {
match alg {
AlgorithmId::ThresholdEcdsaSecp256k1 => {
use k256::ecdsa::signature::Verifier;
let vk =
k256::ecdsa::VerifyingKey::from_sec1_bytes(pk).expect("Failed to parse public key");
let sig = k256::ecdsa::Signature::try_from(sig).expect("Failed to parse signature");
vk.verify(msg, &sig).is_ok()
}
AlgorithmId::ThresholdEcdsaSecp256r1 => {
use p256::ecdsa::signature::Verifier;
let vk =
p256::ecdsa::VerifyingKey::from_sec1_bytes(pk).expect("Failed to parse public key");
let sig = p256::ecdsa::Signature::try_from(sig).expect("Failed to parse signature");
vk.verify(msg, &sig).is_ok()
}
_ => panic!("Unexpected algorithm ID for checking ECDSA signature"),
}
}
pub fn verify_bip340_signature_using_third_party(pk: &[u8], sig: &[u8], msg: &[u8]) -> bool {
use k256::ecdsa::signature::hazmat::PrehashVerifier;
assert_eq!(pk.len(), 32);
assert_eq!(sig.len(), 64);
let vk = k256::schnorr::VerifyingKey::from_bytes(pk).unwrap();
let sig = k256::schnorr::Signature::try_from(sig).unwrap();
vk.verify_prehash(msg, &sig).is_ok()
}
#[derive(Debug, Clone)]
pub struct ProtocolSetup {
alg: AlgorithmId,
cfg: TestConfig,
threshold: NumberOfNodes,
receivers: usize,
ad: Vec<u8>,
pk: Vec<MEGaPublicKey>,
sk: Vec<MEGaPrivateKey>,
seed: Seed,
protocol_round: std::cell::Cell<usize>,
}
impl ProtocolSetup {
pub fn new(
cfg: TestConfig,
receivers: usize,
threshold: usize,
seed: Seed,
) -> Result<Self, ThresholdEcdsaError> {
let alg = match cfg.signature_curve() {
EccCurveType::K256 => AlgorithmId::ThresholdEcdsaSecp256k1,
EccCurveType::P256 => AlgorithmId::ThresholdEcdsaSecp256r1,
};
let rng = &mut seed.into_rng();
let ad = rng.gen::<[u8; 32]>().to_vec();
let mut sk = Vec::with_capacity(receivers);
let mut pk = Vec::with_capacity(receivers);
for _i in 0..receivers {
let k = MEGaPrivateKey::generate(cfg.key_curve(), rng);
pk.push(k.public_key());
sk.push(k);
}
let threshold = NumberOfNodes::from(threshold as u32);
Ok(Self {
alg,
cfg,
threshold,
receivers,
ad,
pk,
sk,
seed: Seed::from_rng(rng),
protocol_round: std::cell::Cell::new(0),
})
}
pub fn signature_curve(&self) -> EccCurveType {
self.cfg.signature_curve()
}
pub fn key_curve(&self) -> EccCurveType {
self.cfg.key_curve()
}
pub fn next_dealing_seed(&self) -> Seed {
let round = self.protocol_round.get();
let seed = self
.seed
.derive(&format!("ic-crypto-tecdsa-round-{}", round));
self.protocol_round.set(round + 1);
seed
}
pub fn remove_nodes(&mut self, removing: usize) {
assert!(self.receivers >= removing);
self.receivers -= removing;
while self.pk.len() != self.receivers {
self.pk.pop();
}
while self.sk.len() != self.receivers {
self.sk.pop();
}
}
pub fn modify_threshold(&mut self, threshold: usize) {
self.threshold = NumberOfNodes::from(threshold as u32);
}
pub fn receiver_info(&self) -> Vec<(MEGaPrivateKey, MEGaPublicKey, NodeIndex)> {
let mut info = Vec::with_capacity(self.receivers);
for i in 0..self.receivers {
info.push((self.sk[i].clone(), self.pk[i].clone(), i as NodeIndex));
}
info
}
}
#[derive(Debug, Clone)]
pub struct ProtocolRound {
pub commitment: PolynomialCommitment,
pub transcript: IDkgTranscriptInternal,
pub openings: Vec<CommitmentOpening>,
pub dealings: BTreeMap<NodeIndex, IDkgDealingInternal>,
pub mode: IDkgTranscriptOperationInternal,
}
impl ProtocolRound {
// Internal constructor
pub fn new(
setup: &ProtocolSetup,
dealings: BTreeMap<NodeIndex, IDkgDealingInternal>,
transcript: IDkgTranscriptInternal,
mode: IDkgTranscriptOperationInternal,
) -> Self {
let openings = Self::open_dealings(setup, &dealings, &transcript);
let commitment = transcript.combined_commitment.commitment().clone();
assert!(Self::verify_commitment_openings(&commitment, &openings).is_ok());
Self {
commitment,
transcript,
openings,
dealings,
mode,
}
}
/// Runs a `ProtocolRound` for a `Random` transcript with `number_of_dealers` many
/// distinct dealers.
///
/// If `number_of_dealings_corrupted` is > 0 then some number of the dealings
/// will be randomly corrupted.
pub fn random(
setup: &ProtocolSetup,
number_of_dealers: usize,
number_of_dealings_corrupted: usize,
) -> ThresholdEcdsaResult<Self> {
let shares = vec![SecretShares::Random; number_of_dealers];
let mode = IDkgTranscriptOperationInternal::Random;
let dealings = Self::create_dealings(
setup,
&shares,
number_of_dealers,
number_of_dealings_corrupted,
&mode,
setup.next_dealing_seed(),
);
let transcript = Self::create_transcript(setup, &dealings, &mode)?;
match transcript.combined_commitment {
CombinedCommitment::BySummation(PolynomialCommitment::Pedersen(_)) => {}
_ => panic!("Unexpected transcript commitment type"),
}
Ok(Self::new(setup, dealings, transcript, mode))
}
/// Runs a `ProtocolRound` for a `RandomUnmasked` transcript with
/// `number_of_dealers` many distinct dealers.
///
/// If `number_of_dealings_corrupted` is > 0 then some number of the dealings
/// will be randomly corrupted.
pub fn random_unmasked(
setup: &ProtocolSetup,
number_of_dealers: usize,
number_of_dealings_corrupted: usize,
) -> ThresholdEcdsaResult<Self> {
let shares = vec![SecretShares::RandomUnmasked; number_of_dealers];
let mode = IDkgTranscriptOperationInternal::RandomUnmasked;
let dealings = Self::create_dealings(
setup,
&shares,
number_of_dealers,
number_of_dealings_corrupted,
&mode,
setup.next_dealing_seed(),
);
let transcript = Self::create_transcript(setup, &dealings, &mode)?;
match transcript.combined_commitment {
CombinedCommitment::BySummation(PolynomialCommitment::Simple(_)) => {}
_ => panic!("Unexpected transcript commitment type"),
}
Ok(Self::new(setup, dealings, transcript, mode))
}
/// Runs a `ProtocolRound` for a `ReshareOfMasked` transcript with `number_of_dealers`
/// many distinct dealers.
///
/// If `number_of_dealings_corrupted` is > 0 then some number of the dealings
/// will be randomly corrupted.
pub fn reshare_of_masked(
setup: &ProtocolSetup,
masked: &ProtocolRound,
number_of_dealers: usize,
number_of_dealings_corrupted: usize,
) -> ThresholdEcdsaResult<Self> {
let mut shares = Vec::with_capacity(masked.openings.len());
for opening in &masked.openings {
match opening {
CommitmentOpening::Pedersen(v, m) => {
shares.push(SecretShares::ReshareOfMasked(v.clone(), m.clone()));
}
_ => panic!("Unexpected opening type"),
}
}
let mode = IDkgTranscriptOperationInternal::ReshareOfMasked(masked.commitment.clone());
let dealings = Self::create_dealings(
setup,
&shares,
number_of_dealers,
number_of_dealings_corrupted,
&mode,
setup.next_dealing_seed(),
);
let transcript = Self::create_transcript(setup, &dealings, &mode)?;
match transcript.combined_commitment {
CombinedCommitment::ByInterpolation(PolynomialCommitment::Simple(_)) => {}
_ => panic!("Unexpected transcript commitment type"),
}
Ok(Self::new(setup, dealings, transcript, mode))
}
/// Runs a `ProtocolRound` for a `ReshareOfUnmasked` transcript with
/// `number_of_dealers` many distinct dealers.
///
/// If `number_of_dealings_corrupted` is > 0 then some number of the dealings
/// will be randomly corrupted.
pub fn reshare_of_unmasked(
setup: &ProtocolSetup,
unmasked: &ProtocolRound,
number_of_dealers: usize,
number_of_dealings_corrupted: usize,
) -> ThresholdEcdsaResult<Self> {
let mut shares = Vec::with_capacity(unmasked.openings.len());
for opening in &unmasked.openings {
match opening {
CommitmentOpening::Simple(v) => {
shares.push(SecretShares::ReshareOfUnmasked(v.clone()));
}
_ => panic!("Unexpected opening type"),
}
}
let mode = IDkgTranscriptOperationInternal::ReshareOfUnmasked(unmasked.commitment.clone());
let dealings = Self::create_dealings(
setup,
&shares,
number_of_dealers,
number_of_dealings_corrupted,
&mode,
setup.next_dealing_seed(),
);
let transcript = Self::create_transcript(setup, &dealings, &mode)?;
match transcript.combined_commitment {
CombinedCommitment::ByInterpolation(PolynomialCommitment::Simple(_)) => {}
_ => panic!("Unexpected transcript commitment type"),
}
// The two commitments are both simple, so we can verify shared value
assert_eq!(
transcript.combined_commitment.commitment().constant_term(),
unmasked.constant_term()
);
Ok(Self::new(setup, dealings, transcript, mode))
}
/// Runs a `ProtocolRound` for a `UnmaskedTimesMasked` transcript with
/// `number_of_dealers` many distinct dealers.
///
/// If `number_of_dealings_corrupted` is > 0 then some number of the dealings
/// will be randomly corrupted.
pub fn multiply(
setup: &ProtocolSetup,
masked: &ProtocolRound,
unmasked: &ProtocolRound,
number_of_dealers: usize,
number_of_dealings_corrupted: usize,
) -> ThresholdEcdsaResult<Self> {
let mut shares = Vec::with_capacity(unmasked.openings.len());
for opening in unmasked.openings.iter().zip(masked.openings.iter()) {
match opening {
(CommitmentOpening::Simple(lhs_v), CommitmentOpening::Pedersen(rhs_v, rhs_m)) => {
shares.push(SecretShares::UnmaskedTimesMasked(
lhs_v.clone(),
(rhs_v.clone(), rhs_m.clone()),
))
}
_ => panic!("Unexpected opening type"),
}
}
let mode = IDkgTranscriptOperationInternal::UnmaskedTimesMasked(
unmasked.commitment.clone(),
masked.commitment.clone(),
);
let dealings = Self::create_dealings(
setup,
&shares,
number_of_dealers,
number_of_dealings_corrupted,
&mode,
setup.next_dealing_seed(),
);
let transcript = Self::create_transcript(setup, &dealings, &mode)?;
match transcript.combined_commitment {
CombinedCommitment::ByInterpolation(PolynomialCommitment::Pedersen(_)) => {}
_ => panic!("Unexpected transcript commitment type"),
}
Ok(Self::new(setup, dealings, transcript, mode))
}
/// Verified that parties holding secret `openings` can reconstruct the
/// opening of the constant term of `commitment`.
fn verify_commitment_openings(
commitment: &PolynomialCommitment,
openings: &[CommitmentOpening],
) -> ThresholdEcdsaResult<()> {
let constant_term = commitment.constant_term();
let curve_type = constant_term.curve_type();
match commitment {
PolynomialCommitment::Simple(_) => {
let mut indexes = Vec::with_capacity(openings.len());
let mut g_openings = Vec::with_capacity(openings.len());
for (idx, opening) in openings.iter().enumerate() {
if let CommitmentOpening::Simple(value) = opening {
indexes.push(idx as NodeIndex);
g_openings.push(value.clone());
} else {
panic!("Unexpected opening type");
}
}
let coefficients = LagrangeCoefficients::at_zero(curve_type, &indexes)?;
let dlog = coefficients.interpolate_scalar(&g_openings)?;
let pt = EccPoint::mul_by_g(&dlog);
assert_eq!(pt, constant_term);
}
PolynomialCommitment::Pedersen(_) => {
let mut indexes = Vec::with_capacity(openings.len());
let mut g_openings = Vec::with_capacity(openings.len());
let mut h_openings = Vec::with_capacity(openings.len());
for (idx, opening) in openings.iter().enumerate() {
if let CommitmentOpening::Pedersen(value, mask) = opening {
indexes.push(idx as NodeIndex);
g_openings.push(value.clone());
h_openings.push(mask.clone());
} else {
panic!("Unexpected opening type");
}
}
let coefficients = LagrangeCoefficients::at_zero(curve_type, &indexes)?;
let dlog_g = coefficients.interpolate_scalar(&g_openings)?;
let dlog_h = coefficients.interpolate_scalar(&h_openings)?;
let pt = EccPoint::pedersen(&dlog_g, &dlog_h)?;
assert_eq!(pt, constant_term);
}
}
Ok(())
}
/// Reconstruct the secret shares for all receivers in a given transcript.
fn open_dealings(
setup: &ProtocolSetup,
dealings: &BTreeMap<NodeIndex, IDkgDealingInternal>,
transcript: &IDkgTranscriptInternal,
) -> Vec<CommitmentOpening> {
let mut openings = Vec::with_capacity(setup.receivers);
let reconstruction_threshold = setup.threshold.get() as usize;
let seed = Seed::from_bytes(&transcript.combined_commitment.serialize().unwrap());
let rng = &mut seed.derive("rng").into_rng();
// Ensure every receiver can open
for receiver in 0..setup.receivers {
let opening = compute_secret_shares(
dealings,
transcript,
&setup.ad,
receiver as NodeIndex,
&setup.sk[receiver],
&setup.pk[receiver],
);
if let Ok(opening) = opening {
openings.push(opening);
} else {
// Generate a complaint:
let complaints = generate_complaints(
dealings,
&setup.ad,
receiver as NodeIndex,
&setup.sk[receiver],
&setup.pk[receiver],
seed.derive(&format!("complaint-{}", receiver)),
)
.expect("Unable to generate complaints");
let mut provided_openings = BTreeMap::new();
for (dealer_index, complaint) in &complaints {
let dealing = dealings.get(dealer_index).unwrap();
// the complaints must be valid
assert!(complaint
.verify(
dealing,
*dealer_index,
receiver as NodeIndex, /* complainer index */
&setup.pk[receiver],
&setup.ad
)
.is_ok());
let mut openings_for_this_dealing = BTreeMap::new();
// create openings in response to the complaints
for (private_key, public_key, opener) in setup.receiver_info() {
if opener == receiver as NodeIndex {
continue;
}
// we can't open, if we ourselves got an invalid dealing
if privately_verify_dealing(
setup.alg,
dealing,
&private_key,
&public_key,
&setup.ad,
*dealer_index,
opener,
)
.is_err()
{
continue;
}
let dopening = open_dealing(
dealing,
&setup.ad,
*dealer_index,
opener as NodeIndex,
&setup.sk[opener as usize],
&setup.pk[opener as usize],
)
.expect("Unable to open dealing");
// The openings must be valid:
assert!(
verify_dealing_opening(dealing, opener as NodeIndex, &dopening).is_ok()
);
openings_for_this_dealing.insert(opener as NodeIndex, dopening);
}
// drop all but the required # of openings
while openings_for_this_dealing.len() > reconstruction_threshold {
let index = *openings_for_this_dealing.keys().choose(rng).unwrap();
openings_for_this_dealing.remove(&index);
}
provided_openings.insert(*dealer_index, openings_for_this_dealing);
}
let opening = compute_secret_shares_with_openings(
dealings,
&provided_openings,
transcript,
&setup.ad,
receiver as NodeIndex,
&setup.sk[receiver],
&setup.pk[receiver],
)
.expect("Unable to open dealing using provided openings");
openings.push(opening);
}
}
assert_eq!(
openings.len(),
setup.receivers,
"Expected number of openings"
);
openings
}
fn create_transcript(
setup: &ProtocolSetup,
dealings: &BTreeMap<NodeIndex, IDkgDealingInternal>,
mode: &IDkgTranscriptOperationInternal,
) -> ThresholdEcdsaResult<IDkgTranscriptInternal> {
match create_transcript(setup.alg, setup.threshold, dealings, mode) {
Ok(t) => {
assert!(verify_transcript(&t, setup.alg, setup.threshold, dealings, mode).is_ok());
Ok(t)
}
Err(IDkgCreateTranscriptInternalError::InsufficientDealings) => {
Err(ThresholdEcdsaError::InsufficientDealings)
}
Err(IDkgCreateTranscriptInternalError::InconsistentCommitments) => {
Err(ThresholdEcdsaError::InvalidCommitment)
}
Err(_) => panic!("Unexpected error from create_transcript"),
}
}
pub fn verify_transcript(
&self,
setup: &ProtocolSetup,
dealings: &BTreeMap<NodeIndex, IDkgDealingInternal>,
) -> Result<(), IDkgVerifyTranscriptInternalError> {
verify_transcript(
&self.transcript,
setup.alg,
setup.threshold,
dealings,
&self.mode,
)
}
/// Create dealings generated by `number_of_dealers` random dealers.
fn create_dealings(
setup: &ProtocolSetup,
shares: &[SecretShares],
number_of_dealers: usize,
number_of_dealings_corrupted: usize,
transcript_type: &IDkgTranscriptOperationInternal,
seed: Seed,
) -> BTreeMap<NodeIndex, IDkgDealingInternal> {
assert!(number_of_dealers <= shares.len());
assert!(number_of_dealings_corrupted <= number_of_dealers);
let rng = &mut seed.into_rng();
let mut dealings = BTreeMap::new();
for (dealer_index, share) in shares.iter().enumerate() {
let dealer_index = dealer_index as u32;
let dealing = create_dealing(
setup.alg,
&setup.ad,
dealer_index,
setup.threshold,
&setup.pk,
share,
Seed::from_rng(rng),
)
.expect("failed to create dealing");
Self::test_public_dealing_verification(setup, &dealing, transcript_type, dealer_index);
for (private_key, public_key, recipient_index) in setup.receiver_info() {
let is_locally_valid = privately_verify_dealing(
setup.alg,
&dealing,
&private_key,
&public_key,
&setup.ad,
dealer_index,
recipient_index,
)
.is_ok();
assert!(is_locally_valid, "Created a locally invalid dealing");
}
dealings.insert(dealer_index, dealing);
}
// Discard some of the dealings at random
while dealings.len() > number_of_dealers {
let index = *dealings.keys().choose(rng).unwrap();
dealings.remove(&index);
}
let dealings_to_damage = dealings
.iter_mut()
.choose_multiple(rng, number_of_dealings_corrupted);
for (dealer_index, dealing) in dealings_to_damage {
let max_corruptions = setup.threshold.get() as usize;
let number_of_corruptions = rng.gen_range(1..=max_corruptions);
let corrupted_recip =
(0..setup.receivers as NodeIndex).choose_multiple(rng, number_of_corruptions);
let bad_dealing =
test_utils::corrupt_dealing(dealing, &corrupted_recip, Seed::from_rng(rng))
.unwrap();
// Privately invalid iff we were corrupted
for (private_key, public_key, recipient_index) in setup.receiver_info() {
let was_corrupted = corrupted_recip.contains(&recipient_index);
let locally_invalid = privately_verify_dealing(
setup.alg,
&bad_dealing,
&private_key,
&public_key,
&setup.ad,
*dealer_index,
recipient_index,
)
.is_err();
if locally_invalid {
assert!(was_corrupted);
} else {
assert!(!was_corrupted);
}
}
// replace the dealing with a corrupted one
*dealing = bad_dealing;
}
dealings
}
fn test_public_dealing_verification(
setup: &ProtocolSetup,
dealing: &IDkgDealingInternal,
transcript_type: &IDkgTranscriptOperationInternal,
dealer_index: NodeIndex,
) {
let number_of_receivers = NumberOfNodes::from(setup.receivers as u32);
dealing
.publicly_verify(
setup.key_curve(),
setup.signature_curve(),
transcript_type,
setup.threshold,
dealer_index,
number_of_receivers,
&setup.ad,
)
.expect("Dealing should pass public verification");
// wrong dealer index -> invalid
assert_eq!(
dealing.publicly_verify(
setup.key_curve(),
setup.signature_curve(),
transcript_type,
setup.threshold,
dealer_index + 1,
number_of_receivers,
&setup.ad,
),
Err(ThresholdEcdsaError::InvalidProof)
);
// wrong number of receivers -> invalid
assert_eq!(
dealing.publicly_verify(
setup.key_curve(),
setup.signature_curve(),
transcript_type,
setup.threshold,
dealer_index,
NumberOfNodes::from(1 + setup.receivers as u32),
&setup.ad,
),
Err(ThresholdEcdsaError::InvalidRecipients)
);
// wrong associated data -> invalid
assert_eq!(
dealing.publicly_verify(
setup.key_curve(),
setup.signature_curve(),
transcript_type,
setup.threshold,
dealer_index,
number_of_receivers,
"wrong ad".as_bytes(),
),
Err(ThresholdEcdsaError::InvalidProof)
);
/*
* This function assumes the MEGa keys are secp256k1 (CRP-2236)
*
* So for setup.key_curve() == K256 we expect success, and other
* curves should fail.
*/
let top_level_dealing_verify_result = publicly_verify_dealing(
setup.alg,
dealing,
transcript_type,
setup.threshold,
dealer_index,
number_of_receivers,
&setup.ad,
);
if setup.key_curve() == EccCurveType::K256 {
assert!(top_level_dealing_verify_result.is_ok());
} else {
assert_matches!(
top_level_dealing_verify_result.unwrap_err(),
IDkgVerifyDealingInternalError::InternalError(_)
);
}
}
pub fn constant_term(&self) -> EccPoint {
self.commitment.constant_term()
}
}
#[derive(Clone, Debug)]
pub struct EcdsaSignatureProtocolSetup {
setup: ProtocolSetup,
pub key: ProtocolRound,
pub kappa: ProtocolRound,
pub lambda: ProtocolRound,
pub key_times_lambda: ProtocolRound,
pub kappa_times_lambda: ProtocolRound,
}
impl EcdsaSignatureProtocolSetup {
/// Create a key plus a quadruple for performing an ECDSA signature
///
/// Generates a new key and a quadruple (kappa, lambda, kappa*lambda, key*lambda)
///
/// If use_masked_kappa is true then kappa is generated by first generating
/// a masked random transcript, then resharing it. Otherwise (false), kappa is
/// created directly by a unmasked random transcript.
pub fn new(
cfg: TestConfig,
number_of_dealers: usize,
threshold: usize,
number_of_dealings_corrupted: usize,
seed: Seed,
use_masked_kappa: bool,
) -> ThresholdEcdsaResult<Self> {
let setup = ProtocolSetup::new(cfg, number_of_dealers, threshold, seed)?;
let key = ProtocolRound::random(&setup, number_of_dealers, number_of_dealings_corrupted)?;
/*
Regarding kappa the code here is a little contorted due to wanting to use the same
order of protocol rounds as was done in the initial version of the code, to avoid
having to change the stability tests (in serialization.rs)
*/
let kappa = if use_masked_kappa {
ProtocolRound::random(&setup, number_of_dealers, number_of_dealings_corrupted)?
} else {
ProtocolRound::random_unmasked(&setup, number_of_dealers, number_of_dealings_corrupted)?
};
let lambda =
ProtocolRound::random(&setup, number_of_dealers, number_of_dealings_corrupted)?;
let key = ProtocolRound::reshare_of_masked(
&setup,
&key,
number_of_dealers,
number_of_dealings_corrupted,
)?;
let kappa = if use_masked_kappa {
ProtocolRound::reshare_of_masked(
&setup,
&kappa,
number_of_dealers,
number_of_dealings_corrupted,
)?
} else {
kappa
};
let key_times_lambda = ProtocolRound::multiply(
&setup,
&lambda,
&key,
number_of_dealers,
number_of_dealings_corrupted,
)?;
let kappa_times_lambda = ProtocolRound::multiply(
&setup,
&lambda,
&kappa,
number_of_dealers,
number_of_dealings_corrupted,
)?;
Ok(Self {
setup,
key,
kappa,
lambda,
key_times_lambda,
kappa_times_lambda,
})
}
pub fn public_key(&self, path: &DerivationPath) -> Result<EcdsaPublicKey, ThresholdEcdsaError> {
let mpk_alg = match self.setup.alg {
AlgorithmId::ThresholdEcdsaSecp256r1 => AlgorithmId::EcdsaP256,
AlgorithmId::ThresholdEcdsaSecp256k1 => AlgorithmId::EcdsaSecp256k1,
_ => panic!("Unknown algorithm in ProtocolSetup"),
};
let master_public_key = MasterEcdsaPublicKey {
algorithm_id: mpk_alg,
public_key: self.key.transcript.constant_term().serialize(),
};
ic_crypto_internal_threshold_sig_ecdsa::derive_ecdsa_public_key(&master_public_key, path)
.map_err(|e| ThresholdEcdsaError::InvalidArguments(format!("{:?}", e)))
}
pub fn alg(&self) -> AlgorithmId {
self.setup.alg
}
}
#[derive(Clone, Debug)]
pub struct EcdsaSignatureProtocolExecution {
setup: EcdsaSignatureProtocolSetup,
signed_message: Vec<u8>,
hashed_message: Vec<u8>,
random_beacon: Randomness,
derivation_path: DerivationPath,
}
impl EcdsaSignatureProtocolExecution {
pub fn new(
setup: EcdsaSignatureProtocolSetup,
signed_message: Vec<u8>,
random_beacon: Randomness,
derivation_path: DerivationPath,
) -> Self {
let hashed_message = ic_crypto_sha2::Sha256::hash(&signed_message).to_vec();
Self {
setup,
signed_message,
hashed_message,
random_beacon,
derivation_path,
}
}
pub fn generate_shares(
&self,
) -> ThresholdEcdsaResult<BTreeMap<u32, ThresholdEcdsaSigShareInternal>> {
let mut shares = BTreeMap::new();
for node_index in 0..self.setup.setup.receivers {
let share = create_ecdsa_signature_share(
&self.derivation_path,
&self.hashed_message,
self.random_beacon,
&self.setup.key.transcript,
&self.setup.kappa.transcript,
&self.setup.lambda.openings[node_index],
&self.setup.kappa_times_lambda.openings[node_index],
&self.setup.key_times_lambda.openings[node_index],
self.setup.setup.alg,
)
.expect("Failed to create sig share");
verify_ecdsa_signature_share(
&share,
&self.derivation_path,
&self.hashed_message,
self.random_beacon,
node_index as u32,
&self.setup.key.transcript,
&self.setup.kappa.transcript,
&self.setup.lambda.transcript,
&self.setup.kappa_times_lambda.transcript,
&self.setup.key_times_lambda.transcript,
self.setup.setup.alg,
)
.expect("Signature share verification failed");
shares.insert(node_index as NodeIndex, share);
}
Ok(shares)
}
pub fn generate_signature(
&self,
shares: &BTreeMap<NodeIndex, ThresholdEcdsaSigShareInternal>,
) -> Result<ThresholdEcdsaCombinedSigInternal, ThresholdEcdsaCombineSigSharesInternalError>
{
combine_ecdsa_signature_shares(
&self.derivation_path,
&self.hashed_message,
self.random_beacon,
&self.setup.key.transcript,
&self.setup.kappa.transcript,
self.setup.setup.threshold,
shares,
self.setup.setup.alg,