-
Notifications
You must be signed in to change notification settings - Fork 298
/
payload_builder.rs
2434 lines (2256 loc) · 95.5 KB
/
payload_builder.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
//! This module implements the ECDSA payload builder.
#![allow(clippy::too_many_arguments)]
#![allow(clippy::enum_variant_names)]
#![allow(clippy::result_large_err)]
use super::pre_signer::{EcdsaTranscriptBuilder, EcdsaTranscriptBuilderImpl};
use super::signer::{EcdsaSignatureBuilder, EcdsaSignatureBuilderImpl};
use super::utils::{block_chain_reader, get_ecdsa_config_if_enabled, InvalidChainCacheError};
use crate::consensus::metrics::{EcdsaPayloadMetrics, CRITICAL_ERROR_ECDSA_KEY_TRANSCRIPT_MISSING};
pub(super) use errors::EcdsaPayloadError;
use errors::MembershipError;
use ic_consensus_utils::crypto::ConsensusCrypto;
use ic_consensus_utils::pool_reader::PoolReader;
use ic_crypto::retrieve_mega_public_key_from_registry;
use ic_interfaces::ecdsa::EcdsaPool;
use ic_interfaces_registry::RegistryClient;
use ic_interfaces_state_manager::StateManager;
use ic_logger::{error, info, warn, ReplicaLogger};
use ic_management_canister_types::EcdsaKeyId;
use ic_registry_client_helpers::subnet::SubnetRegistry;
use ic_registry_subnet_features::EcdsaConfig;
use ic_replicated_state::{metadata_state::subnet_call_context_manager::*, ReplicatedState};
use ic_types::{
batch::ValidationContext,
consensus::{
idkg::{self, EcdsaBlockReader, HasEcdsaKeyId, TranscriptAttributes},
Block, HasHeight,
},
crypto::canister_threshold_sig::idkg::InitialIDkgDealings,
messages::CallbackId,
Height, NodeId, RegistryVersion, SubnetId, Time,
};
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Deref;
use std::sync::{Arc, RwLock};
use std::time::Duration;
mod errors;
mod key_transcript;
mod quadruples;
pub(super) mod resharing;
pub(super) mod signatures;
/// Builds the very first ecdsa summary block. This would trigger the subsequent
/// data blocks to create the initial key transcript.
pub(crate) fn make_bootstrap_summary(
subnet_id: SubnetId,
key_id: EcdsaKeyId,
height: Height,
) -> idkg::Summary {
Some(idkg::EcdsaPayload {
signature_agreements: BTreeMap::new(),
deprecated_ongoing_signatures: BTreeMap::new(),
available_quadruples: BTreeMap::new(),
quadruples_in_creation: BTreeMap::new(),
uid_generator: idkg::EcdsaUIDGenerator::new(subnet_id, height),
idkg_transcripts: BTreeMap::new(),
ongoing_xnet_reshares: BTreeMap::new(),
xnet_reshare_agreements: BTreeMap::new(),
key_transcript: idkg::EcdsaKeyTranscript {
current: None,
next_in_creation: idkg::KeyTranscriptCreation::Begin,
key_id,
master_key_id: None,
},
})
}
/// Builds the very first ecdsa summary block. This would trigger the subsequent
/// data blocks to create the initial key transcript.
pub(crate) fn make_bootstrap_summary_with_initial_dealings(
subnet_id: SubnetId,
key_id: EcdsaKeyId,
height: Height,
initial_dealings: InitialIDkgDealings,
log: &ReplicaLogger,
) -> Result<idkg::Summary, EcdsaPayloadError> {
let mut summary_payload = idkg::EcdsaPayload {
signature_agreements: BTreeMap::new(),
deprecated_ongoing_signatures: BTreeMap::new(),
available_quadruples: BTreeMap::new(),
quadruples_in_creation: BTreeMap::new(),
uid_generator: idkg::EcdsaUIDGenerator::new(subnet_id, height),
idkg_transcripts: BTreeMap::new(),
ongoing_xnet_reshares: BTreeMap::new(),
xnet_reshare_agreements: BTreeMap::new(),
key_transcript: idkg::EcdsaKeyTranscript {
current: None,
next_in_creation: idkg::KeyTranscriptCreation::Begin,
key_id,
master_key_id: None,
},
};
match idkg::unpack_reshare_of_unmasked_params(height, initial_dealings.params()) {
Some((params, transcript)) => {
summary_payload
.idkg_transcripts
.insert(transcript.transcript_id, transcript);
summary_payload.key_transcript.next_in_creation =
idkg::KeyTranscriptCreation::XnetReshareOfUnmaskedParams((
Box::new(initial_dealings),
params,
));
info!(
log,
"make_ecdsa_genesis_summary(): height = {}, key_transcript = [{}]",
height,
summary_payload.key_transcript
);
}
None => {
// Leave the feature disabled if the initial dealings are incorrect.
warn!(
log,
"make_ecdsa_genesis_summary(): failed to unpack initial dealings"
);
return Err(EcdsaPayloadError::InitialIDkgDealingsNotUnmaskedParams(
Box::new(initial_dealings),
));
}
}
Ok(Some(summary_payload))
}
/// Creates a threshold ECDSA summary payload.
pub(crate) fn create_summary_payload(
subnet_id: SubnetId,
registry_client: &dyn RegistryClient,
pool_reader: &PoolReader<'_>,
context: &ValidationContext,
parent_block: &Block,
ecdsa_payload_metrics: Option<&EcdsaPayloadMetrics>,
log: &ReplicaLogger,
) -> Result<idkg::Summary, EcdsaPayloadError> {
let height = parent_block.height().increment();
let prev_summary_block = pool_reader
.dkg_summary_block(parent_block)
.ok_or_else(|| EcdsaPayloadError::ConsensusSummaryBlockNotFound(parent_block.height()))?;
// For this interval: context.registry_version from prev summary block
// which is the same as calling pool_reader.registry_version(height).
// which is the same as summary.dkg.registry_version (to be created).
let curr_interval_registry_version = prev_summary_block.context.registry_version;
// For next interval: context.registry_version from the new summary block
let next_interval_registry_version = context.registry_version;
// Get ecdsa_config from registry if it exists
let Some(ecdsa_config) = get_ecdsa_config_if_enabled(
subnet_id,
curr_interval_registry_version,
registry_client,
log,
)?
else {
return Ok(None);
};
// Get ecdsa_payload from parent block if it exists
let Some(ecdsa_payload) = parent_block.payload.as_ref().as_data().ecdsa.as_ref() else {
// Parent block doesn't have ECDSA payload and feature is enabled.
// Create the bootstrap summary block, and create a new key for the given key_id.
//
// This is safe because registry's do_update_subnet already ensures that only
// fresh key_id can be assigned to an existing subnet.
//
// Keys already held by existing subnets can only be re-shared when creating
// a new subnet, which means the genesis summary ECDSA payload is not empty
// and we won't reach here.
let key_id = ecdsa_config.key_ids[0].clone();
info!(
log,
"Start to create ECDSA key {} on subnet {} at height {}", key_id, subnet_id, height
);
return Ok(make_bootstrap_summary(subnet_id, key_id, height));
};
let block_reader = block_chain_reader(
pool_reader,
&prev_summary_block,
parent_block,
ecdsa_payload_metrics,
log,
)?;
create_summary_payload_helper(
subnet_id,
registry_client,
&block_reader,
height,
curr_interval_registry_version,
next_interval_registry_version,
ecdsa_payload,
ecdsa_payload_metrics,
log,
)
}
fn create_summary_payload_helper(
subnet_id: SubnetId,
registry_client: &dyn RegistryClient,
block_reader: &dyn EcdsaBlockReader,
height: Height,
curr_interval_registry_version: RegistryVersion,
next_interval_registry_version: RegistryVersion,
ecdsa_payload: &idkg::EcdsaPayload,
ecdsa_payload_metrics: Option<&EcdsaPayloadMetrics>,
log: &ReplicaLogger,
) -> Result<idkg::Summary, EcdsaPayloadError> {
let current_key_transcript = ecdsa_payload.key_transcript.current.as_ref();
let created_key_transcript =
key_transcript::get_created_key_transcript(&ecdsa_payload.key_transcript, block_reader)?;
// Registry version as recorded in the (new) current key transcript if it exists.
// Otherwise use curr_interval_registry_version.
let curr_key_registry_version = created_key_transcript
.as_ref()
.map(idkg::UnmaskedTranscriptWithAttributes::registry_version)
.or_else(|| {
current_key_transcript.map(idkg::UnmaskedTranscriptWithAttributes::registry_version)
})
.unwrap_or(curr_interval_registry_version);
if created_key_transcript.is_none() {
if let Some(metrics) = ecdsa_payload_metrics {
metrics.critical_error_ecdsa_key_transcript_missing.inc();
}
error!(
log,
"{}: Key not created in previous interval, \
keep trying in next interval(height = {}), key_transcript = {}",
CRITICAL_ERROR_ECDSA_KEY_TRANSCRIPT_MISSING,
height,
ecdsa_payload.key_transcript
);
}
let is_new_key_transcript = created_key_transcript.as_ref().is_some_and(|transcript| {
Some(transcript.transcript_id())
!= current_key_transcript.map(idkg::UnmaskedTranscriptWithAttributes::transcript_id)
});
// Check for membership change, start next key creation only when both of the following are
// satisfied:
// 1. Time to reshare key transcript (either due to membership change, or node key change)
// 2. We don't have a key transcript creation in progress.
let next_in_creation = if is_time_to_reshare_key_transcript(
registry_client,
curr_key_registry_version,
next_interval_registry_version,
subnet_id,
)? && created_key_transcript.is_some()
{
info!(
log,
"Noticed subnet membership or mega encryption key change, \
will start key_transcript_creation: height = {} \
current_version = {}, next_version = {}",
height,
curr_key_registry_version,
next_interval_registry_version
);
idkg::KeyTranscriptCreation::Begin
} else {
// No change, just carry forward the next_in_creation transcript
ecdsa_payload.key_transcript.next_in_creation.clone()
};
let key_transcript = idkg::EcdsaKeyTranscript {
// Keep using previous key transcript if the next hasn't been created
current: created_key_transcript.or_else(|| current_key_transcript.cloned()),
next_in_creation,
key_id: ecdsa_payload.key_transcript.key_id.clone(),
master_key_id: None,
};
let mut ecdsa_summary = if is_new_key_transcript {
idkg::EcdsaPayload {
signature_agreements: ecdsa_payload.signature_agreements.clone(),
deprecated_ongoing_signatures: BTreeMap::new(),
// We keep available quadruples for now, even if the key transcript
// changed, as we don't know if they are part of ongoing signature
// requests. Instead we will purge them once the certified state
// height catches up with the height of this summary block.
available_quadruples: ecdsa_payload.available_quadruples.clone(),
quadruples_in_creation: BTreeMap::new(),
uid_generator: ecdsa_payload.uid_generator.clone(),
// This will clear the current ongoing reshares, and
// the execution requests will be restarted with the
// new key and different transcript IDs.
ongoing_xnet_reshares: BTreeMap::new(),
xnet_reshare_agreements: ecdsa_payload.xnet_reshare_agreements.clone(),
idkg_transcripts: BTreeMap::new(),
key_transcript,
}
} else {
idkg::EcdsaPayload {
signature_agreements: ecdsa_payload.signature_agreements.clone(),
deprecated_ongoing_signatures: BTreeMap::new(),
available_quadruples: ecdsa_payload.available_quadruples.clone(),
quadruples_in_creation: ecdsa_payload.quadruples_in_creation.clone(),
uid_generator: ecdsa_payload.uid_generator.clone(),
ongoing_xnet_reshares: ecdsa_payload.ongoing_xnet_reshares.clone(),
xnet_reshare_agreements: ecdsa_payload.xnet_reshare_agreements.clone(),
idkg_transcripts: BTreeMap::new(),
key_transcript,
}
};
ecdsa_summary.uid_generator.update_height(height)?;
update_summary_refs(height, &mut ecdsa_summary, block_reader)?;
Ok(Some(ecdsa_summary))
}
fn update_summary_refs(
height: Height,
summary: &mut idkg::EcdsaPayload,
block_reader: &dyn EcdsaBlockReader,
) -> Result<(), EcdsaPayloadError> {
// Gather the refs and update them to point to the new
// summary block height.
let prev_refs = summary.active_transcripts();
summary.update_refs(height);
// Resolve the transcript refs pointing into the parent chain,
// copy the resolved transcripts into the summary block.
summary.idkg_transcripts.clear();
for transcript_ref in prev_refs {
let transcript = block_reader.transcript(&transcript_ref)?;
summary
.idkg_transcripts
.insert(transcript_ref.transcript_id, transcript);
}
Ok(())
}
fn get_subnet_nodes(
registry_client: &dyn RegistryClient,
registry_version: RegistryVersion,
subnet_id: SubnetId,
) -> Result<Vec<NodeId>, MembershipError> {
// TODO: shuffle the nodes using random beacon?
registry_client
.get_node_ids_on_subnet(subnet_id, registry_version)
.map_err(MembershipError::RegistryClientError)?
.ok_or(MembershipError::SubnetWithNoNodes(
subnet_id,
registry_version,
))
}
// Like `get_subnet_nodes`, but return empty Vec instead of SubnetWithNoNodes error.
// This is used to avoid throwing error, for example, when we do subnet recovery
// the old registry version may not have the new subnet members.
fn get_subnet_nodes_(
registry_client: &dyn RegistryClient,
registry_version: RegistryVersion,
subnet_id: SubnetId,
) -> Result<Vec<NodeId>, MembershipError> {
Ok(registry_client
.get_node_ids_on_subnet(subnet_id, registry_version)
.map_err(MembershipError::RegistryClientError)?
.unwrap_or_default())
}
fn is_time_to_reshare_key_transcript(
registry_client: &dyn RegistryClient,
curr_registry_version: RegistryVersion,
next_registry_version: RegistryVersion,
subnet_id: SubnetId,
) -> Result<bool, MembershipError> {
// Shortcut the case where registry version didn't change
if curr_registry_version == next_registry_version {
return Ok(false);
}
let current_nodes = get_subnet_nodes_(registry_client, curr_registry_version, subnet_id)?
.into_iter()
.collect::<BTreeSet<_>>();
let next_nodes = get_subnet_nodes(registry_client, next_registry_version, subnet_id)?
.into_iter()
.collect::<BTreeSet<_>>();
if current_nodes != next_nodes {
return Ok(true);
}
// Check if node's key has changed, which should also trigger key transcript resharing.
for node in current_nodes {
let curr_key =
retrieve_mega_public_key_from_registry(&node, registry_client, curr_registry_version)
.map_err(MembershipError::MegaKeyFromRegistryError)?;
let next_key =
retrieve_mega_public_key_from_registry(&node, registry_client, next_registry_version)
.map_err(MembershipError::MegaKeyFromRegistryError)?;
if curr_key != next_key {
return Ok(true);
}
}
Ok(false)
}
/// Creates a threshold ECDSA batch payload.
pub(crate) fn create_data_payload(
subnet_id: SubnetId,
registry_client: &dyn RegistryClient,
crypto: &dyn ConsensusCrypto,
pool_reader: &PoolReader<'_>,
ecdsa_pool: Arc<RwLock<dyn EcdsaPool>>,
state_manager: &dyn StateManager<State = ReplicatedState>,
context: &ValidationContext,
parent_block: &Block,
ecdsa_payload_metrics: &EcdsaPayloadMetrics,
log: &ReplicaLogger,
) -> Result<idkg::Payload, EcdsaPayloadError> {
// Return None if parent block does not have ECDSA payload.
if parent_block.payload.as_ref().as_ecdsa().is_none() {
return Ok(None);
};
let summary_block = pool_reader
.dkg_summary_block(parent_block)
.ok_or_else(|| EcdsaPayloadError::ConsensusSummaryBlockNotFound(parent_block.height()))?;
// The notarized tip(parent) may be ahead of the finalized tip, and
// the last few blocks may have references to heights after the finalized
// tip. So use the chain ending at the parent to resolve refs, rather than the
// finalized chain.
let block_reader = block_chain_reader(
pool_reader,
&summary_block,
parent_block,
Some(ecdsa_payload_metrics),
log,
)?;
let ecdsa_pool = ecdsa_pool.read().unwrap();
let signature_builder = EcdsaSignatureBuilderImpl::new(
&block_reader,
crypto,
ecdsa_pool.deref(),
ecdsa_payload_metrics,
log.clone(),
);
let transcript_builder = EcdsaTranscriptBuilderImpl::new(
&block_reader,
crypto,
ecdsa_pool.deref(),
ecdsa_payload_metrics,
log.clone(),
);
let new_payload = create_data_payload_helper(
subnet_id,
context,
parent_block,
&summary_block,
&block_reader,
&transcript_builder,
&signature_builder,
state_manager,
registry_client,
Some(ecdsa_payload_metrics),
log,
)?;
if let Some(ecdsa_payload) = &new_payload {
let is_key_transcript_created = |payload: &idkg::EcdsaPayload| {
matches!(
payload.key_transcript.next_in_creation,
idkg::KeyTranscriptCreation::Created(_)
)
};
if is_key_transcript_created(ecdsa_payload)
&& !parent_block
.payload
.as_ref()
.as_ecdsa()
.is_some_and(is_key_transcript_created)
{
ecdsa_payload_metrics.payload_metrics_inc(
"key_transcripts_created",
Some(ecdsa_payload.key_transcript.key_id()),
);
}
ecdsa_payload_metrics.report(ecdsa_payload);
};
Ok(new_payload)
}
pub(crate) enum CertifiedHeight {
ReachedSummaryHeight,
BelowSummaryHeight,
}
pub(crate) fn create_data_payload_helper(
subnet_id: SubnetId,
context: &ValidationContext,
parent_block: &Block,
summary_block: &Block,
block_reader: &dyn EcdsaBlockReader,
transcript_builder: &dyn EcdsaTranscriptBuilder,
signature_builder: &dyn EcdsaSignatureBuilder,
state_manager: &dyn StateManager<State = ReplicatedState>,
registry_client: &dyn RegistryClient,
ecdsa_payload_metrics: Option<&EcdsaPayloadMetrics>,
log: &ReplicaLogger,
) -> Result<Option<idkg::EcdsaPayload>, EcdsaPayloadError> {
let height = parent_block.height().increment();
let summary = summary_block.payload.as_ref().as_summary();
// For this interval: context.registry_version from last summary block,
// which is the same as calling pool_reader.registry_version(height).
// which is the same as summary.dkg.registry_version,
let curr_interval_registry_version = summary.dkg.registry_version;
// For next interval: context.registry_version from the new summary block
let next_interval_registry_version = summary_block.context.registry_version;
let Some(ecdsa_config) = get_ecdsa_config_if_enabled(
subnet_id,
curr_interval_registry_version,
registry_client,
log,
)?
else {
return Ok(None);
};
let valid_keys: BTreeSet<_> = ecdsa_config.key_ids.iter().cloned().collect();
let mut ecdsa_payload = if let Some(prev_payload) = parent_block.payload.as_ref().as_ecdsa() {
prev_payload.clone()
} else {
return Ok(None);
};
let receivers = get_subnet_nodes(registry_client, next_interval_registry_version, subnet_id)?;
let state = state_manager.get_state_at(context.certified_height)?;
let all_signing_requests = &state
.get_ref()
.metadata
.subnet_call_context_manager
.sign_with_ecdsa_contexts;
let ecdsa_dealings_contexts = &state
.get_ref()
.metadata
.subnet_call_context_manager
.ecdsa_dealings_contexts;
let certified_height = if context.certified_height >= summary_block.height() {
CertifiedHeight::ReachedSummaryHeight
} else {
CertifiedHeight::BelowSummaryHeight
};
create_data_payload_helper_2(
&mut ecdsa_payload,
height,
context.time,
&ecdsa_config,
&valid_keys,
next_interval_registry_version,
certified_height,
&receivers,
all_signing_requests,
ecdsa_dealings_contexts,
block_reader,
transcript_builder,
signature_builder,
ecdsa_payload_metrics,
log,
)?;
Ok(Some(ecdsa_payload))
}
pub(crate) fn create_data_payload_helper_2(
ecdsa_payload: &mut idkg::EcdsaPayload,
height: Height,
context_time: Time,
ecdsa_config: &EcdsaConfig,
valid_keys: &BTreeSet<EcdsaKeyId>,
next_interval_registry_version: RegistryVersion,
certified_height: CertifiedHeight,
receivers: &[NodeId],
all_signing_requests: &BTreeMap<CallbackId, SignWithEcdsaContext>,
ecdsa_dealings_contexts: &BTreeMap<CallbackId, EcdsaDealingsContext>,
block_reader: &dyn EcdsaBlockReader,
transcript_builder: &dyn EcdsaTranscriptBuilder,
signature_builder: &dyn EcdsaSignatureBuilder,
ecdsa_payload_metrics: Option<&EcdsaPayloadMetrics>,
log: &ReplicaLogger,
) -> Result<(), EcdsaPayloadError> {
// Check if we are creating a new key, if so, start using it immediately.
if ecdsa_payload.key_transcript.current.is_none() {
ecdsa_payload.key_transcript.current = key_transcript::get_created_key_transcript(
&ecdsa_payload.key_transcript,
block_reader,
)?;
}
ecdsa_payload.uid_generator.update_height(height)?;
let request_expiry_time = ecdsa_config
.signature_request_timeout_ns
.and_then(|timeout| context_time.checked_sub(Duration::from_nanos(timeout)));
signatures::update_signature_agreements(
all_signing_requests,
signature_builder,
request_expiry_time,
ecdsa_payload,
valid_keys,
ecdsa_payload_metrics,
);
if matches!(certified_height, CertifiedHeight::ReachedSummaryHeight) {
quadruples::purge_old_key_quadruples(ecdsa_payload, all_signing_requests);
}
// We count the number of quadruples in the payload that were already matched,
// such that they can be replenished.
let matched_quadruples = all_signing_requests
.values()
.filter_map(|context| context.matched_quadruple.as_ref())
.filter(|(qid, _)| ecdsa_payload.available_quadruples.contains_key(qid))
.count();
quadruples::make_new_quadruples_if_needed(ecdsa_config, ecdsa_payload, matched_quadruples);
let mut new_transcripts =
quadruples::update_quadruples_in_creation(ecdsa_payload, transcript_builder, height, log)?;
if let Some(new_transcript) = key_transcript::update_next_key_transcript(
receivers,
next_interval_registry_version,
ecdsa_payload,
transcript_builder,
height,
log,
)? {
new_transcripts.push(new_transcript);
};
// Drop transcripts from last round and keep only the
// ones created in this round.
ecdsa_payload.idkg_transcripts.clear();
for transcript in new_transcripts {
ecdsa_payload
.idkg_transcripts
.insert(transcript.transcript_id, transcript);
}
resharing::update_completed_reshare_requests(
ecdsa_payload,
ecdsa_dealings_contexts,
block_reader,
transcript_builder,
log,
);
resharing::initiate_reshare_requests(
ecdsa_payload,
resharing::get_reshare_requests(ecdsa_dealings_contexts),
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::consensus::batch_delivery::generate_responses_to_sign_with_ecdsa_calls;
use crate::ecdsa::payload_builder::quadruples::test_utils::create_available_quadruple;
use crate::ecdsa::payload_builder::quadruples::test_utils::create_new_quadruple_in_creation;
use crate::ecdsa::test_utils::*;
use crate::ecdsa::utils::block_chain_reader;
use crate::ecdsa::utils::get_context_request_id;
use assert_matches::assert_matches;
use ic_consensus_mocks::{dependencies, Dependencies};
use ic_crypto_test_utils_canister_threshold_sigs::dummy_values::dummy_initial_idkg_dealing_for_tests;
use ic_crypto_test_utils_canister_threshold_sigs::generate_tecdsa_protocol_inputs;
use ic_crypto_test_utils_canister_threshold_sigs::{
CanisterThresholdSigTestEnvironment, IDkgParticipants,
};
use ic_crypto_test_utils_reproducible_rng::{reproducible_rng, ReproducibleRng};
use ic_interfaces_registry::RegistryValue;
use ic_logger::replica_logger::no_op_logger;
use ic_metrics::MetricsRegistry;
use ic_protobuf::types::v1 as pb;
use ic_test_artifact_pool::consensus_pool::TestConsensusPool;
use ic_test_utilities_consensus::fake::{Fake, FakeContentSigner};
use ic_test_utilities_registry::{add_subnet_record, SubnetRecordBuilder};
use ic_test_utilities_types::ids::{node_test_id, subnet_test_id, user_test_id};
use ic_types::batch::BatchPayload;
use ic_types::consensus::dkg::{Dealings, Summary};
use ic_types::consensus::idkg::EcdsaPayload;
use ic_types::consensus::idkg::QuadrupleId;
use ic_types::consensus::idkg::ReshareOfUnmaskedParams;
use ic_types::consensus::idkg::TranscriptRef;
use ic_types::consensus::idkg::UnmaskedTranscript;
use ic_types::consensus::idkg::UnmaskedTranscriptWithAttributes;
use ic_types::consensus::{
BlockPayload, BlockProposal, DataPayload, HashedBlock, Payload, Rank, SummaryPayload,
};
use ic_types::crypto::canister_threshold_sig::idkg::IDkgTranscript;
use ic_types::crypto::canister_threshold_sig::ExtendedDerivationPath;
use ic_types::crypto::canister_threshold_sig::ThresholdEcdsaCombinedSignature;
use ic_types::crypto::AlgorithmId;
use ic_types::crypto::{CryptoHash, CryptoHashOf};
use ic_types::time::UNIX_EPOCH;
use ic_types::Randomness;
use ic_types::{messages::CallbackId, Height, RegistryVersion};
use std::collections::BTreeSet;
use std::convert::TryInto;
use std::str::FromStr;
fn empty_ecdsa_summary_payload(
subnet_id: SubnetId,
current_key_transcript: (idkg::UnmaskedTranscript, IDkgTranscript),
) -> idkg::EcdsaPayload {
let mut ret = empty_ecdsa_payload(subnet_id);
ret.key_transcript.current = Some(idkg::UnmaskedTranscriptWithAttributes::new(
current_key_transcript.1.to_attributes(),
current_key_transcript.0,
));
ret
}
fn empty_ecdsa_data_payload(subnet_id: SubnetId) -> idkg::EcdsaPayload {
empty_ecdsa_payload(subnet_id)
}
fn create_summary_block_with_transcripts(
subnet_id: SubnetId,
height: Height,
current_key_transcript: (idkg::UnmaskedTranscript, IDkgTranscript),
transcripts: Vec<BTreeMap<idkg::TranscriptRef, IDkgTranscript>>,
) -> BlockPayload {
let mut ecdsa_summary =
empty_ecdsa_summary_payload(subnet_id, current_key_transcript.clone());
ecdsa_summary.idkg_transcripts.insert(
current_key_transcript.0.as_ref().transcript_id,
current_key_transcript.1,
);
for idkg_transcripts in transcripts {
for (transcript_ref, transcript) in idkg_transcripts {
ecdsa_summary
.idkg_transcripts
.insert(transcript_ref.transcript_id, transcript);
}
}
BlockPayload::Summary(SummaryPayload {
dkg: Summary::new(
vec![],
BTreeMap::new(),
BTreeMap::new(),
Vec::new(),
RegistryVersion::from(0),
Height::from(100),
Height::from(100),
height,
BTreeMap::new(),
),
ecdsa: Some(ecdsa_summary),
})
}
fn create_payload_block_with_transcripts(
subnet_id: SubnetId,
dkg_interval_start_height: Height,
transcripts: Vec<BTreeMap<idkg::TranscriptRef, IDkgTranscript>>,
) -> BlockPayload {
let mut ecdsa_payload = empty_ecdsa_data_payload(subnet_id);
for idkg_transcripts in transcripts {
for (transcript_ref, transcript) in idkg_transcripts {
ecdsa_payload
.idkg_transcripts
.insert(transcript_ref.transcript_id, transcript);
}
}
BlockPayload::Data(DataPayload {
batch: BatchPayload::default(),
dealings: Dealings::new_empty(dkg_interval_start_height),
ecdsa: Some(ecdsa_payload),
})
}
fn add_block(
block_payload: BlockPayload,
advance_by: u64,
pool: &mut TestConsensusPool,
) -> Block {
pool.advance_round_normal_operation_n(advance_by - 1);
let mut block_proposal = pool.make_next_block();
let block = block_proposal.content.as_mut();
block.payload = Payload::new(ic_types::crypto::crypto_hash, block_payload);
block_proposal.content = HashedBlock::new(ic_types::crypto::crypto_hash, block.clone());
pool.advance_round_with_block(&block_proposal);
block_proposal.content.as_ref().clone()
}
fn set_up_ecdsa_payload_with_keys(
key_ids: Vec<EcdsaKeyId>,
) -> (EcdsaPayload, CanisterThresholdSigTestEnvironment) {
let mut rng = reproducible_rng();
let (ecdsa_payload, env, _block_reader) = set_up_ecdsa_payload(
&mut rng,
subnet_test_id(1),
/*nodes_count=*/ 4,
key_ids,
/*should_create_key_transcript=*/ true,
);
(ecdsa_payload, env)
}
fn set_up_sign_with_ecdsa_contexts(
parameters: Vec<(EcdsaKeyId, u8, Time, Option<QuadrupleId>)>,
) -> BTreeMap<CallbackId, SignWithEcdsaContext> {
let mut contexts = BTreeMap::new();
for (key_id, id, batch_time, quadruple) in parameters {
let (callback_id, mut context) =
fake_sign_with_ecdsa_context_with_quadruple(id, key_id, quadruple);
context.batch_time = batch_time;
contexts.insert(callback_id, context);
}
contexts
}
#[test]
fn test_quadruple_recreation() {
let valid_key_id = EcdsaKeyId::from_str("Secp256k1:valid_key").unwrap();
let disabled_key_id = EcdsaKeyId::from_str("Secp256k1:disabled_key").unwrap();
let valid_keys = BTreeSet::from([valid_key_id.clone()]);
let (mut ecdsa_payload, _env) = set_up_ecdsa_payload_with_keys(vec![valid_key_id.clone()]);
// Add two quadruples
let quadruple_for_valid_key =
create_available_quadruple(&mut ecdsa_payload, valid_key_id.clone(), 10);
let quadruple_for_disabled_key =
create_available_quadruple(&mut ecdsa_payload, disabled_key_id.clone(), 11);
let non_existant_quadruple_for_valid_key = ecdsa_payload.uid_generator.next_quadruple_id();
let contexts = set_up_sign_with_ecdsa_contexts(vec![
// Two request contexts without quadruple
(valid_key_id.clone(), 0, UNIX_EPOCH, None),
(disabled_key_id.clone(), 1, UNIX_EPOCH, None),
// One valid context with matched quadruple
(
valid_key_id.clone(),
2,
UNIX_EPOCH,
Some(quadruple_for_valid_key),
),
// One invalid context with matched quadruple
(
disabled_key_id.clone(),
3,
UNIX_EPOCH,
Some(quadruple_for_disabled_key),
),
// One valid context matched to non-existant quadruple
(
valid_key_id.clone(),
4,
UNIX_EPOCH,
Some(non_existant_quadruple_for_valid_key),
),
]);
let ecdsa_config = EcdsaConfig {
quadruples_to_create_in_advance: 5,
key_ids: vec![valid_key_id.clone()],
..EcdsaConfig::default()
};
assert_eq!(ecdsa_payload.quadruples_in_creation.len(), 0);
assert_eq!(ecdsa_payload.available_quadruples.len(), 2);
create_data_payload_helper_2(
&mut ecdsa_payload,
Height::from(5),
UNIX_EPOCH,
&ecdsa_config,
&valid_keys,
RegistryVersion::from(9),
CertifiedHeight::ReachedSummaryHeight,
&[node_test_id(0)],
&contexts,
&BTreeMap::default(),
&TestEcdsaBlockReader::new(),
&TestEcdsaTranscriptBuilder::new(),
&TestEcdsaSignatureBuilder::new(),
/*ecdsa_payload_metrics*/ None,
&ic_logger::replica_logger::no_op_logger(),
)
.unwrap();
let num_quadruples_in_creation = ecdsa_payload.quadruples_in_creation.len() as u32;
let num_available_quadruples = ecdsa_payload.available_quadruples.len() as u32;
// The two matched quadruples remain
// in available_quadruples.
assert_eq!(num_available_quadruples, 2);
// Usually, matched quadruples are replenished, but since one
// of them was matched to a disabled key id whose request context
// is rejected, the quadruple is "reused" and not replenished.
assert_eq!(
num_quadruples_in_creation,
ecdsa_config.quadruples_to_create_in_advance
);
}
#[test]
fn test_ecdsa_signing_request_timeout() {
let key_id = EcdsaKeyId::from_str("Secp256k1:some_key").unwrap();
let expired_time = UNIX_EPOCH + Duration::from_secs(10);
let expiry_time = UNIX_EPOCH + Duration::from_secs(11);
let non_expired_time = UNIX_EPOCH + Duration::from_secs(12);
let (mut ecdsa_payload, _env) = set_up_ecdsa_payload_with_keys(vec![key_id.clone()]);
// Add quadruples
let discarded_quadruple_id =
create_available_quadruple(&mut ecdsa_payload, key_id.clone(), 10);
let matched_quadruple_id =
create_available_quadruple(&mut ecdsa_payload, key_id.clone(), 11);
let contexts = set_up_sign_with_ecdsa_contexts(vec![
// One expired context without quadruple
(key_id.clone(), 0, expired_time, None),
// One expired context with matched quadruple
(
key_id.clone(),
1,
expired_time,
Some(discarded_quadruple_id),
),
// One non-expired context with matched quadruple
(
key_id.clone(),
2,
non_expired_time,
Some(matched_quadruple_id.clone()),
),
]);
assert_eq!(ecdsa_payload.signature_agreements.len(), 0);
assert_eq!(ecdsa_payload.available_quadruples.len(), 2);
let signature_builder = TestEcdsaSignatureBuilder::new();
signatures::update_signature_agreements(
&contexts,
&signature_builder,
Some(expiry_time),
&mut ecdsa_payload,
&BTreeSet::from([key_id]),
None,
);
// Only the expired context with matched quadruple should receive a reject response
assert_eq!(ecdsa_payload.signature_agreements.len(), 1);
let Some(idkg::CompletedSignature::Unreported(response)) =
ecdsa_payload.signature_agreements.get(&[1; 32])
else {
panic!("Request 1 should have a response");
};
assert_matches!(
&response.payload,
ic_types::messages::Payload::Reject(context)
if context.message().contains("request expired")
);
// The quadruple matched with the expired context should be deleted
assert_eq!(ecdsa_payload.available_quadruples.len(), 1);
assert_eq!(
ecdsa_payload.available_quadruples.keys().next().unwrap(),
&matched_quadruple_id
);
}
#[test]
fn test_ecdsa_request_with_invalid_key() {
let valid_key_id = EcdsaKeyId::from_str("Secp256k1:some_key").unwrap();
let invalid_key_id = EcdsaKeyId::from_str("Secp256k1:some_invalid_key").unwrap();
let (mut ecdsa_payload, _env) = set_up_ecdsa_payload_with_keys(vec![valid_key_id.clone()]);
// Add quadruples
let quadruple_id1 = create_available_quadruple(&mut ecdsa_payload, valid_key_id.clone(), 1);
let quadruple_id2 =
create_available_quadruple(&mut ecdsa_payload, invalid_key_id.clone(), 2);
let contexts = set_up_sign_with_ecdsa_contexts(vec![
// One matched context with valid key
(valid_key_id.clone(), 1, UNIX_EPOCH, Some(quadruple_id1)),
// One matched context with invalid key
(
invalid_key_id.clone(),
2,
UNIX_EPOCH,
Some(quadruple_id2.clone()),
),
// One unmatched context with invalid key
(invalid_key_id.clone(), 3, UNIX_EPOCH, None),