-
Notifications
You must be signed in to change notification settings - Fork 296
/
pre_signer.rs
2701 lines (2472 loc) · 116 KB
/
pre_signer.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
//! The pre signature process manager
use crate::consensus::metrics::{timed_call, EcdsaPayloadMetrics, EcdsaPreSignerMetrics};
use crate::ecdsa::complaints::EcdsaTranscriptLoader;
use crate::ecdsa::utils::{load_transcripts, transcript_op_summary, EcdsaBlockReaderImpl};
use ic_consensus_utils::crypto::ConsensusCrypto;
use ic_consensus_utils::RoundRobin;
use ic_interfaces::consensus_pool::ConsensusBlockCache;
use ic_interfaces::crypto::{ErrorReproducibility, IDkgProtocol};
use ic_interfaces::ecdsa::{EcdsaChangeAction, EcdsaChangeSet, EcdsaPool};
use ic_logger::{debug, warn, ReplicaLogger};
use ic_metrics::MetricsRegistry;
use ic_types::artifact::EcdsaMessageId;
use ic_types::consensus::ecdsa::{
dealing_prefix, dealing_support_prefix, EcdsaBlockReader, EcdsaMessage, EcdsaStats,
IDkgTranscriptParamsRef,
};
use ic_types::crypto::canister_threshold_sig::error::IDkgCreateDealingError;
use ic_types::crypto::canister_threshold_sig::idkg::{
BatchSignedIDkgDealing, BatchSignedIDkgDealings, IDkgDealingSupport, IDkgTranscript,
IDkgTranscriptId, IDkgTranscriptOperation, IDkgTranscriptParams, SignedIDkgDealing,
};
use ic_types::crypto::CryptoHashOf;
use ic_types::signature::BasicSignatureBatch;
use ic_types::{Height, NodeId};
use std::cell::RefCell;
use std::collections::{btree_map::Entry, BTreeMap, BTreeSet};
use std::fmt::{self, Debug, Formatter};
use std::sync::Arc;
pub(crate) trait EcdsaPreSigner: Send {
/// The on_state_change() called from the main ECDSA path.
fn on_state_change(
&self,
ecdsa_pool: &dyn EcdsaPool,
transcript_loader: &dyn EcdsaTranscriptLoader,
) -> EcdsaChangeSet;
}
pub(crate) struct EcdsaPreSignerImpl {
pub(crate) node_id: NodeId,
pub(crate) consensus_block_cache: Arc<dyn ConsensusBlockCache>,
pub(crate) crypto: Arc<dyn ConsensusCrypto>,
schedule: RoundRobin,
pub(crate) metrics: EcdsaPreSignerMetrics,
pub(crate) log: ReplicaLogger,
}
impl EcdsaPreSignerImpl {
pub(crate) fn new(
node_id: NodeId,
consensus_block_cache: Arc<dyn ConsensusBlockCache>,
crypto: Arc<dyn ConsensusCrypto>,
metrics_registry: MetricsRegistry,
log: ReplicaLogger,
) -> Self {
Self {
node_id,
consensus_block_cache,
crypto,
schedule: RoundRobin::default(),
metrics: EcdsaPreSignerMetrics::new(metrics_registry),
log,
}
}
/// Starts the transcript generation sequence by issuing the
/// dealing for the transcript. The requests for new transcripts
/// come from the latest finalized block.
fn send_dealings(
&self,
ecdsa_pool: &dyn EcdsaPool,
transcript_loader: &dyn EcdsaTranscriptLoader,
block_reader: &dyn EcdsaBlockReader,
) -> EcdsaChangeSet {
let mut target_subnet_xnet_transcripts = BTreeSet::new();
for transcript_params_ref in block_reader.target_subnet_xnet_transcripts() {
target_subnet_xnet_transcripts.insert(transcript_params_ref.transcript_id);
}
block_reader
.requested_transcripts()
.filter_map(|transcript_params_ref| {
let mut ret = None;
if let Some(transcript_params) =
self.resolve_ref(transcript_params_ref, block_reader, "send_dealings")
{
// Issue a dealing if we are in the dealer list and we haven't
//already issued a dealing for this transcript
if transcript_params.dealers().position(self.node_id).is_some()
&& !self.has_dealer_issued_dealing(
ecdsa_pool,
&transcript_params.transcript_id(),
&self.node_id,
)
{
ret = Some(transcript_params);
}
}
ret
})
.flat_map(|transcript_params| {
if target_subnet_xnet_transcripts.contains(&transcript_params.transcript_id()) {
self.metrics
.pre_sign_errors_inc("create_dealing_for_xnet_transcript");
warn!(
self.log,
"Dealing creation: dealing for target xnet dealing: {:?}",
transcript_params,
);
}
self.crypto_create_dealing(ecdsa_pool, transcript_loader, &transcript_params)
})
.collect()
}
/// Processes the dealings received from peer dealers
fn validate_dealings(
&self,
ecdsa_pool: &dyn EcdsaPool,
block_reader: &dyn EcdsaBlockReader,
) -> EcdsaChangeSet {
// TranscriptId -> TranscriptParamsRef
let transcript_param_map = self.requested_transcripts(block_reader);
let mut target_subnet_xnet_transcripts = BTreeSet::new();
for transcript_params_ref in block_reader.target_subnet_xnet_transcripts() {
target_subnet_xnet_transcripts.insert(transcript_params_ref.transcript_id);
}
let mut validated_dealings = BTreeSet::new();
let mut ret = Vec::new();
for (id, signed_dealing) in ecdsa_pool.unvalidated().signed_dealings() {
let dealing = signed_dealing.idkg_dealing();
// We already accepted a dealing for the same <transcript_id, dealer_id>
// in the current batch, drop the subsequent ones. This scheme does create a
// risk when we get several invalid dealings for the same <transcript_id, dealer_id>
// before we see a good one. In this case, we would spend several cycles
// to just check/discard the invalid ones.
let key = (dealing.transcript_id, signed_dealing.dealer_id());
if validated_dealings.contains(&key) {
self.metrics
.pre_sign_errors_inc("duplicate_dealing_in_batch");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!("Duplicate dealing in unvalidated batch: {}", signed_dealing),
));
continue;
}
// We don't expect dealings for the xnet transcripts on the target subnet
// (as the initial dealings are already built and passed in by the source
// subnet)
if target_subnet_xnet_transcripts.contains(&dealing.transcript_id) {
self.metrics
.pre_sign_errors_inc("unexpected_dealing_xnet_target_subnet");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!(
"Dealing for xnet dealing on target subnet: {}",
signed_dealing
),
));
continue;
}
match Action::action(
block_reader,
&transcript_param_map,
Some(dealing.transcript_id.source_height()),
&dealing.transcript_id,
) {
Action::Process(transcript_params_ref) => {
let transcript_params = match self.resolve_ref(
transcript_params_ref,
block_reader,
"validate_dealings",
) {
Some(transcript_params) => transcript_params,
None => {
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!(
"validate_dealings(): failed to translate transcript_params_ref: {}",
signed_dealing
),
));
continue;
}
};
if transcript_params
.dealers()
.position(signed_dealing.dealer_id())
.is_none()
{
// The node is not in the dealer list for this transcript
self.metrics.pre_sign_errors_inc("unexpected_dealing");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!("Dealing from unexpected node: {}", signed_dealing),
))
} else if self.has_dealer_issued_dealing(
ecdsa_pool,
&dealing.transcript_id,
&signed_dealing.dealer_id(),
) {
// The node already sent a valid dealing for this transcript
self.metrics.pre_sign_errors_inc("duplicate_dealing");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!("Duplicate dealing: {}", signed_dealing),
))
} else {
let action =
self.crypto_verify_dealing(id, &transcript_params, signed_dealing);
if let Some(EcdsaChangeAction::MoveToValidated(_)) = action {
validated_dealings.insert(key);
}
ret.append(&mut action.into_iter().collect());
}
}
Action::Drop => ret.push(EcdsaChangeAction::RemoveUnvalidated(id)),
Action::Defer => {}
}
}
ret
}
/// Does "private" validation of the dealings received from peer dealers and,
/// if successful, sends out the signature share (support message) for it.
fn send_dealing_support(
&self,
ecdsa_pool: &dyn EcdsaPool,
block_reader: &dyn EcdsaBlockReader,
) -> EcdsaChangeSet {
// TranscriptId -> TranscriptParamsRef
let transcript_param_map = self.requested_transcripts(block_reader);
let mut source_subnet_xnet_transcripts = BTreeSet::new();
for transcript_params_ref in block_reader.source_subnet_xnet_transcripts() {
source_subnet_xnet_transcripts.insert(transcript_params_ref.transcript_id);
}
ecdsa_pool
.validated()
.signed_dealings()
.filter(|(id, signed_dealing)| {
id.dealing_hash().map_or_else(
|| {
self.metrics
.pre_sign_errors_inc("create_support_id_dealing_hash");
warn!(
self.log,
"send_dealing_support(): Failed to get dealing hash: {:?}", id
);
false
},
|dealing_hash| {
!self.has_node_issued_dealing_support(
ecdsa_pool,
&signed_dealing.idkg_dealing().transcript_id,
&signed_dealing.dealer_id(),
&self.node_id,
&dealing_hash,
)
},
)
})
.filter_map(|(id, signed_dealing)| {
let dealing = signed_dealing.idkg_dealing();
// Look up the transcript params for the dealing, and check if we
// are a receiver for this dealing
if let Some(transcript_params_ref) =
transcript_param_map.get(&dealing.transcript_id)
{
self.resolve_ref(transcript_params_ref, block_reader, "send_dealing_support")
.and_then(|transcript_params| {
transcript_params
.receivers()
.position(self.node_id)
.map(|_| (id, transcript_params, signed_dealing))
})
} else {
self.metrics
.pre_sign_errors_inc("create_support_missing_transcript_params");
warn!(
self.log,
"Dealing support creation: transcript_param not found: {}", signed_dealing,
);
None
}
})
.flat_map(|(id, transcript_params, signed_dealing)| {
let dealing = signed_dealing.idkg_dealing();
if source_subnet_xnet_transcripts.contains(&dealing.transcript_id) {
self.metrics
.pre_sign_errors_inc("create_support_for_xnet_transcript");
warn!(
self.log,
"Dealing support creation: support for target xnet dealing: {}",
signed_dealing,
);
}
self.crypto_create_dealing_support(&id, &transcript_params, &signed_dealing)
})
.collect()
}
/// Processes the received dealing support messages
fn validate_dealing_support(
&self,
ecdsa_pool: &dyn EcdsaPool,
block_reader: &dyn EcdsaBlockReader,
) -> EcdsaChangeSet {
// TranscriptId -> TranscriptParamsRef
let transcript_param_map = self.requested_transcripts(block_reader);
// Build the map of valid dealings crypto hash -> dealings
let mut valid_dealings = BTreeMap::new();
for (id, signed_dealing) in ecdsa_pool.validated().signed_dealings() {
if let Some(dealing_hash) = id.dealing_hash() {
valid_dealings.insert(dealing_hash, signed_dealing);
} else {
self.metrics
.pre_sign_errors_inc("validate_dealing_support_id_dealing_hash");
warn!(
self.log,
"validate_dealing_support(): Failed to get dealing hash: {:?}", id
)
}
}
let mut source_subnet_xnet_transcripts = BTreeSet::new();
for transcript_params_ref in block_reader.source_subnet_xnet_transcripts() {
source_subnet_xnet_transcripts.insert(transcript_params_ref.transcript_id);
}
let mut target_subnet_xnet_transcripts = BTreeSet::new();
for transcript_params_ref in block_reader.target_subnet_xnet_transcripts() {
target_subnet_xnet_transcripts.insert(transcript_params_ref.transcript_id);
}
let mut validated_dealing_supports = BTreeSet::new();
let mut ret = Vec::new();
for (id, support) in ecdsa_pool.unvalidated().dealing_support() {
// Dedup dealing support by (transcript_id, dealer_id, signer_id)
// Also see has_node_issued_dealing_support().
let key = (
support.transcript_id,
support.dealer_id,
support.sig_share.signer,
);
if validated_dealing_supports.contains(&key) {
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!(
"Duplicate dealing support in unvalidated batch: {}",
support
),
));
continue;
};
// Drop shares for xnet reshare transcripts
if source_subnet_xnet_transcripts.contains(&support.transcript_id) {
self.metrics.pre_sign_errors_inc("xnet_reshare_support");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!("Support for xnet reshare transcript: {}", support),
));
continue;
}
// Disable the height check on target subnet side for the initial transcripts.
// Since the transcript_id.source_height is from the source subnet, the height
// cannot be relied upon. This also lets us process the shares for the initial
// bootstrap with higher urgency, without deferring it.
let msg_height = if target_subnet_xnet_transcripts.contains(&support.transcript_id) {
None
} else {
Some(support.transcript_id.source_height())
};
match Action::action(
block_reader,
&transcript_param_map,
msg_height,
&support.transcript_id,
) {
Action::Process(transcript_params_ref) => {
let transcript_params = match self.resolve_ref(
transcript_params_ref,
block_reader,
"validate_dealing_support",
) {
Some(transcript_params) => transcript_params,
None => {
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!("Failed to translate transcript_params_ref: {}", support),
));
continue;
}
};
if transcript_params
.receivers()
.position(support.sig_share.signer)
.is_none()
{
// The node is not in the receiver list for this transcript,
// support share is not expected from it
self.metrics.pre_sign_errors_inc("unexpected_support");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!("Support from unexpected node: {}", support),
))
} else if let Some(signed_dealing) = valid_dealings.get(&support.dealing_hash) {
let dealing = signed_dealing.idkg_dealing();
if self.has_node_issued_dealing_support(
ecdsa_pool,
&signed_dealing.idkg_dealing().transcript_id,
&signed_dealing.dealer_id(),
&support.sig_share.signer,
&support.dealing_hash,
) {
// The node already sent a valid support for this dealing
self.metrics.pre_sign_errors_inc("duplicate_support");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!("Duplicate support: {}", support),
))
} else if support.transcript_id != dealing.transcript_id
|| support.dealer_id != signed_dealing.dealer_id()
{
// Meta data mismatch
self.metrics
.pre_sign_errors_inc("support_meta_data_mismatch");
ret.push(EcdsaChangeAction::HandleInvalid(
id,
format!(
"Support meta data mismatch: expected = {:?}/{:?}, \
received = {:?}/{:?}",
support.transcript_id,
support.dealer_id,
dealing.transcript_id,
signed_dealing.dealer_id()
),
))
} else {
let action = self.crypto_verify_dealing_support(
id,
&transcript_params,
signed_dealing,
support,
ecdsa_pool.stats(),
);
if let Some(EcdsaChangeAction::MoveToValidated(_)) = action {
validated_dealing_supports.insert(key);
}
ret.append(&mut action.into_iter().collect());
}
} else {
// If the dealer_id in the share is invalid, drop it.
if transcript_params
.dealers()
.position(support.dealer_id)
.is_none()
{
self.metrics
.pre_sign_errors_inc("missing_hash_invalid_dealer");
ret.push(EcdsaChangeAction::RemoveUnvalidated(id));
warn!(
self.log,
"validate_dealing_support(): Missing hash, invalid dealer: {:?}",
support
);
} else {
// If the share points to a different dealing hash than what we
// have for the same <transcript Id, dealer Id>, drop it. This is
// different from the case where we don't have the dealing yet
let mut dealing_hash_mismatch = false;
for signed_dealing in valid_dealings.values() {
if support.transcript_id
== signed_dealing.idkg_dealing().transcript_id
&& support.dealer_id == signed_dealing.dealer_id()
{
dealing_hash_mismatch = true;
break;
}
}
if dealing_hash_mismatch {
self.metrics
.pre_sign_errors_inc("missing_hash_meta_data_mismatch");
ret.push(EcdsaChangeAction::RemoveUnvalidated(id));
warn!(
self.log,
"validate_dealing_support(): Missing hash, meta data mismatch: {:?}",
support
);
}
// Else: Support for a dealing we don't have yet, defer it
}
}
}
Action::Drop => ret.push(EcdsaChangeAction::RemoveUnvalidated(id)),
Action::Defer => {}
}
}
ret
}
/// Purges the entries no longer needed from the artifact pool
fn purge_artifacts(
&self,
ecdsa_pool: &dyn EcdsaPool,
block_reader: &dyn EcdsaBlockReader,
) -> EcdsaChangeSet {
let in_progress = block_reader
.requested_transcripts()
.map(|transcript_params| transcript_params.transcript_id)
.collect::<BTreeSet<_>>();
let mut ret = Vec::new();
let current_height = block_reader.tip_height();
let mut target_subnet_xnet_transcripts = BTreeSet::new();
for transcript_params_ref in block_reader.target_subnet_xnet_transcripts() {
target_subnet_xnet_transcripts.insert(transcript_params_ref.transcript_id);
}
// Unvalidated dealings.
let mut action = ecdsa_pool
.unvalidated()
.signed_dealings()
.filter(|(_, signed_dealing)| {
self.should_purge(
&signed_dealing.idkg_dealing().transcript_id,
current_height,
&in_progress,
&target_subnet_xnet_transcripts,
)
})
.map(|(id, _)| EcdsaChangeAction::RemoveUnvalidated(id))
.collect();
ret.append(&mut action);
// Validated dealings.
let mut action = ecdsa_pool
.validated()
.signed_dealings()
.filter(|(_, signed_dealing)| {
self.should_purge(
&signed_dealing.idkg_dealing().transcript_id,
current_height,
&in_progress,
&target_subnet_xnet_transcripts,
)
})
.map(|(id, _)| EcdsaChangeAction::RemoveValidated(id))
.collect();
ret.append(&mut action);
// Unvalidated dealing support.
let mut action = ecdsa_pool
.unvalidated()
.dealing_support()
.filter(|(_, support)| {
self.should_purge(
&support.transcript_id,
current_height,
&in_progress,
&target_subnet_xnet_transcripts,
)
})
.map(|(id, _)| EcdsaChangeAction::RemoveUnvalidated(id))
.collect();
ret.append(&mut action);
// Validated dealing support.
let mut action = ecdsa_pool
.validated()
.dealing_support()
.filter(|(_, support)| {
self.should_purge(
&support.transcript_id,
current_height,
&in_progress,
&target_subnet_xnet_transcripts,
)
})
.map(|(id, _)| EcdsaChangeAction::RemoveValidated(id))
.collect();
ret.append(&mut action);
ret
}
/// Helper to create dealing
fn crypto_create_dealing(
&self,
ecdsa_pool: &dyn EcdsaPool,
transcript_loader: &dyn EcdsaTranscriptLoader,
transcript_params: &IDkgTranscriptParams,
) -> EcdsaChangeSet {
if let Some(changes) =
self.load_dependencies(ecdsa_pool, transcript_loader, transcript_params)
{
return changes;
}
match IDkgProtocol::create_dealing(&*self.crypto, transcript_params) {
Ok(idkg_dealing) => {
self.metrics.pre_sign_metrics_inc("dealing_created");
self.metrics.pre_sign_metrics_inc("dealing_sent");
vec![EcdsaChangeAction::AddToValidated(
EcdsaMessage::EcdsaSignedDealing(idkg_dealing),
)]
}
Err(IDkgCreateDealingError::SignatureError { internal_error }) => {
warn!(
self.log,
"Failed to sign dealing: transcript_id = {:?}, type = {:?}, error = {:?}",
transcript_params.transcript_id(),
transcript_op_summary(transcript_params.operation_type()),
internal_error
);
self.metrics.pre_sign_errors_inc("sign_dealing");
Default::default()
}
Err(err) => {
// TODO: currently, transcript creation will be retried the next time, which
// will most likely fail again. This should be signaled up so that the bad
// transcript params can be acted on
warn!(
self.log,
"Failed to create dealing: transcript_id = {:?}, type = {:?}, error = {:?}",
transcript_params.transcript_id(),
transcript_op_summary(transcript_params.operation_type()),
err
);
self.metrics.pre_sign_errors_inc("create_dealing");
Default::default()
}
}
}
/// Helper to do public verification of a dealing received for a transcript we are building
fn crypto_verify_dealing(
&self,
id: EcdsaMessageId,
transcript_params: &IDkgTranscriptParams,
signed_dealing: SignedIDkgDealing,
) -> Option<EcdsaChangeAction> {
match IDkgProtocol::verify_dealing_public(&*self.crypto, transcript_params, &signed_dealing)
{
Err(error) if error.is_reproducible() => {
self.metrics.pre_sign_errors_inc("verify_dealing_permanent");
Some(EcdsaChangeAction::HandleInvalid(
id,
format!(
"Dealing validation(permanent error): {}, error = {:?}",
signed_dealing, error
),
))
}
Err(error) => {
// Defer in case of transient errors
debug!(
self.log,
"Dealing validation(transient error): {}, error = {:?}", signed_dealing, error
);
self.metrics.pre_sign_errors_inc("verify_dealing_transient");
None
}
Ok(()) => {
self.metrics.pre_sign_metrics_inc("dealing_received");
Some(EcdsaChangeAction::MoveToValidated(
EcdsaMessage::EcdsaSignedDealing(signed_dealing),
))
}
}
}
/// Helper to do private verification of a dealing and, if successful, issue a support share for it.
/// Assumes we are a receiver for the dealing.
fn crypto_create_dealing_support(
&self,
id: &EcdsaMessageId,
transcript_params: &IDkgTranscriptParams,
signed_dealing: &SignedIDkgDealing,
) -> EcdsaChangeSet {
let dealing = signed_dealing.idkg_dealing();
if let Err(error) =
IDkgProtocol::verify_dealing_private(&*self.crypto, transcript_params, signed_dealing)
{
if error.is_reproducible() {
self.metrics
.pre_sign_errors_inc("verify_dealing_private_permanent");
warn!(
self.log,
"Dealing private verification(permanent error): {}, error = {:?}",
dealing,
error
);
return vec![EcdsaChangeAction::HandleInvalid(
id.clone(),
format!(
"Dealing private verification(permanent error): {}, error = {:?}",
dealing, error
),
)];
} else {
self.metrics
.pre_sign_errors_inc("verify_dealing_private_transient");
debug!(
self.log,
"Dealing private verification(transient error): {}, error = {:?}",
dealing,
error
);
return Default::default();
}
}
// Generate the multi sig share
self.crypto
.sign(
signed_dealing,
self.node_id,
transcript_params.registry_version(),
)
.map_or_else(
|error| {
debug!(
self.log,
"Dealing multi sign failed: {}, error = {:?}", dealing, error
);
self.metrics
.pre_sign_errors_inc("dealing_support_multi_sign");
Default::default()
},
|multi_sig_share| {
let dealing_support = IDkgDealingSupport {
transcript_id: dealing.transcript_id,
dealer_id: signed_dealing.dealer_id(),
dealing_hash: ic_types::crypto::crypto_hash(signed_dealing),
sig_share: multi_sig_share,
};
self.metrics.pre_sign_metrics_inc("dealing_support_sent");
vec![EcdsaChangeAction::AddToValidated(
EcdsaMessage::EcdsaDealingSupport(dealing_support),
)]
},
)
}
/// Helper to verify a support share for a dealing
fn crypto_verify_dealing_support(
&self,
id: EcdsaMessageId,
transcript_params: &IDkgTranscriptParams,
signed_dealing: &SignedIDkgDealing,
support: IDkgDealingSupport,
stats: &dyn EcdsaStats,
) -> Option<EcdsaChangeAction> {
let start = std::time::Instant::now();
let ret = self.crypto.verify_basic_sig(
&support.sig_share.signature,
signed_dealing,
support.sig_share.signer,
transcript_params.registry_version(),
);
stats.record_support_validation(&support, start.elapsed());
match ret {
Err(error) => {
self.metrics.pre_sign_errors_inc("verify_dealing_support");
Some(EcdsaChangeAction::HandleInvalid(
id,
format!(
"Support validation failed: {}, error = {:?}",
support, error
),
))
}
Ok(_) => {
self.metrics
.pre_sign_metrics_inc("dealing_support_received");
Some(EcdsaChangeAction::MoveToValidated(
EcdsaMessage::EcdsaDealingSupport(support),
))
}
}
}
/// Helper to load the transcripts the given transcript config is dependent on.
///
/// Returns None if all the transcripts could be loaded successfully.
/// Otherwise, returns the complaint change set to be added to the pool
fn load_dependencies(
&self,
ecdsa_pool: &dyn EcdsaPool,
transcript_loader: &dyn EcdsaTranscriptLoader,
transcript_params: &IDkgTranscriptParams,
) -> Option<EcdsaChangeSet> {
match &transcript_params.operation_type() {
IDkgTranscriptOperation::Random => None,
IDkgTranscriptOperation::ReshareOfMasked(t) => {
load_transcripts(ecdsa_pool, transcript_loader, &[t])
}
IDkgTranscriptOperation::ReshareOfUnmasked(t) => {
load_transcripts(ecdsa_pool, transcript_loader, &[t])
}
IDkgTranscriptOperation::UnmaskedTimesMasked(t1, t2) => {
load_transcripts(ecdsa_pool, transcript_loader, &[t1, t2])
}
}
}
/// Checks if we have a valid dealing from the dealer for the given
/// transcript
fn has_dealer_issued_dealing(
&self,
ecdsa_pool: &dyn EcdsaPool,
transcript_id: &IDkgTranscriptId,
dealer_id: &NodeId,
) -> bool {
let prefix = dealing_prefix(transcript_id, dealer_id);
ecdsa_pool
.validated()
.signed_dealings_by_prefix(prefix)
.any(|(_, signed_dealing)| {
let dealing = signed_dealing.idkg_dealing();
signed_dealing.dealer_id() == *dealer_id && dealing.transcript_id == *transcript_id
})
}
/// Checks if we have a valid dealing support from the node for the
/// given dealing
fn has_node_issued_dealing_support(
&self,
ecdsa_pool: &dyn EcdsaPool,
transcript_id: &IDkgTranscriptId,
dealer_id: &NodeId,
signer_id: &NodeId,
dealing_hash: &CryptoHashOf<SignedIDkgDealing>,
) -> bool {
let prefix = dealing_support_prefix(transcript_id, dealer_id, signer_id);
ecdsa_pool
.validated()
.dealing_support_by_prefix(prefix)
.any(|(_, support)| {
support.dealing_hash == *dealing_hash && support.sig_share.signer == *signer_id
})
}
/// Checks if the dealing should be purged
fn should_purge(
&self,
transcript_id: &IDkgTranscriptId,
current_height: Height,
in_progress: &BTreeSet<IDkgTranscriptId>,
target_subnet_xnet_transcripts: &BTreeSet<IDkgTranscriptId>,
) -> bool {
// It is possible the ECDSA component runs and tries to purge the initial
// dealings before the finalized tip has the next_key_transcript_creation
// set up. Avoid this by keeping the initial dealings until the initial
// resharing completes.
if target_subnet_xnet_transcripts.contains(transcript_id) {
return false;
}
transcript_id.source_height() <= current_height && !in_progress.contains(transcript_id)
}
/// Resolves the IDkgTranscriptParamsRef -> IDkgTranscriptParams.
pub(crate) fn resolve_ref(
&self,
transcript_params_ref: &IDkgTranscriptParamsRef,
block_reader: &dyn EcdsaBlockReader,
reason: &str,
) -> Option<IDkgTranscriptParams> {
match transcript_params_ref.translate(block_reader) {
Ok(transcript_params) => {
self.metrics.pre_sign_metrics_inc("resolve_transcript_refs");
Some(transcript_params)
}
Err(error) => {
warn!(
self.log,
"Failed to translate transcript ref: reason = {}, \
transcript_params_ref = {:?}, tip = {:?}, error = {:?}",
reason,
transcript_params_ref,
block_reader.tip_height(),
error
);
self.metrics.pre_sign_errors_inc("resolve_transcript_refs");
None
}
}
}
/// Returns the requested transcript map.
fn requested_transcripts<'a>(
&self,
block_reader: &'a dyn EcdsaBlockReader,
) -> BTreeMap<IDkgTranscriptId, &'a IDkgTranscriptParamsRef> {
block_reader
.requested_transcripts()
.map(|transcript_params| (transcript_params.transcript_id, transcript_params))
.collect::<BTreeMap<_, _>>()
}
}
impl EcdsaPreSigner for EcdsaPreSignerImpl {
fn on_state_change(
&self,
ecdsa_pool: &dyn EcdsaPool,
transcript_loader: &dyn EcdsaTranscriptLoader,
) -> EcdsaChangeSet {
let block_reader = EcdsaBlockReaderImpl::new(self.consensus_block_cache.finalized_chain());
let metrics = self.metrics.clone();
ecdsa_pool.stats().update_active_transcripts(&block_reader);
ecdsa_pool.stats().update_active_quadruples(&block_reader);
let send_dealings = || {
timed_call(
"send_dealings",
|| self.send_dealings(ecdsa_pool, transcript_loader, &block_reader),
&metrics.on_state_change_duration,
)
};
let validate_dealings = || {
timed_call(
"validate_dealings",
|| self.validate_dealings(ecdsa_pool, &block_reader),
&metrics.on_state_change_duration,
)
};
let send_dealing_support = || {
timed_call(
"send_dealing_support",
|| self.send_dealing_support(ecdsa_pool, &block_reader),
&metrics.on_state_change_duration,
)
};
let validate_dealing_support = || {
timed_call(
"validate_dealing_support",
|| self.validate_dealing_support(ecdsa_pool, &block_reader),
&metrics.on_state_change_duration,
)
};
let purge_artifacts = || {
timed_call(
"purge_artifacts",
|| self.purge_artifacts(ecdsa_pool, &block_reader),
&metrics.on_state_change_duration,
)
};
let calls: [&'_ dyn Fn() -> EcdsaChangeSet; 5] = [
&send_dealings,
&validate_dealings,
&send_dealing_support,
&validate_dealing_support,
&purge_artifacts,
];
self.schedule.call_next(&calls)
}
}
pub(crate) trait EcdsaTranscriptBuilder {
/// Returns the specified transcript if it can be successfully
/// built from the current entries in the ECDSA pool
fn get_completed_transcript(&self, transcript_id: IDkgTranscriptId) -> Option<IDkgTranscript>;
/// Returns the validated dealings for the given transcript Id from
/// the ECDSA pool
fn get_validated_dealings(&self, transcript_id: IDkgTranscriptId) -> Vec<SignedIDkgDealing>;
}
pub(crate) struct EcdsaTranscriptBuilderImpl<'a> {
block_reader: &'a dyn EcdsaBlockReader,
crypto: &'a dyn ConsensusCrypto,
metrics: &'a EcdsaPayloadMetrics,
ecdsa_pool: &'a dyn EcdsaPool,
cache: RefCell<BTreeMap<IDkgTranscriptId, IDkgTranscript>>,
log: ReplicaLogger,
}
impl<'a> EcdsaTranscriptBuilderImpl<'a> {
pub(crate) fn new(
block_reader: &'a dyn EcdsaBlockReader,
crypto: &'a dyn ConsensusCrypto,
ecdsa_pool: &'a dyn EcdsaPool,
metrics: &'a EcdsaPayloadMetrics,
log: ReplicaLogger,