-
Notifications
You must be signed in to change notification settings - Fork 296
/
payload_builder.rs
3267 lines (3060 loc) · 131 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, get_enabled_signing_keys,
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_error_types::RejectCode;
use ic_ic00_types::EcdsaKeyId;
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_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::{
ecdsa,
ecdsa::{EcdsaBlockReader, TranscriptAttributes},
Block, HasHeight,
},
crypto::{
canister_threshold_sig::idkg::{IDkgTranscript, InitialIDkgDealings},
AlgorithmId,
},
messages::{CallbackId, RejectContext},
Height, NodeId, RegistryVersion, SubnetId, Time,
};
use std::collections::{BTreeMap, BTreeSet};
use std::convert::TryFrom;
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 fn make_bootstrap_summary(
subnet_id: SubnetId,
key_id: EcdsaKeyId,
height: Height,
) -> ecdsa::Summary {
Some(ecdsa::EcdsaPayload {
signature_agreements: BTreeMap::new(),
ongoing_signatures: BTreeMap::new(),
available_quadruples: BTreeMap::new(),
quadruples_in_creation: BTreeMap::new(),
uid_generator: ecdsa::EcdsaUIDGenerator::new(subnet_id, height),
idkg_transcripts: BTreeMap::new(),
ongoing_xnet_reshares: BTreeMap::new(),
xnet_reshare_agreements: BTreeMap::new(),
key_transcript: ecdsa::EcdsaKeyTranscript {
current: None,
next_in_creation: ecdsa::KeyTranscriptCreation::Begin,
key_id,
},
})
}
/// Builds the very first ecdsa summary block. This would trigger the subsequent
/// data blocks to create the initial key transcript.
pub fn make_bootstrap_summary_with_initial_dealings(
subnet_id: SubnetId,
key_id: EcdsaKeyId,
height: Height,
initial_dealings: InitialIDkgDealings,
log: &ReplicaLogger,
) -> Result<ecdsa::Summary, EcdsaPayloadError> {
let mut summary_payload = ecdsa::EcdsaPayload {
signature_agreements: BTreeMap::new(),
ongoing_signatures: BTreeMap::new(),
available_quadruples: BTreeMap::new(),
quadruples_in_creation: BTreeMap::new(),
uid_generator: ecdsa::EcdsaUIDGenerator::new(subnet_id, height),
idkg_transcripts: BTreeMap::new(),
ongoing_xnet_reshares: BTreeMap::new(),
xnet_reshare_agreements: BTreeMap::new(),
key_transcript: ecdsa::EcdsaKeyTranscript {
current: None,
next_in_creation: ecdsa::KeyTranscriptCreation::Begin,
key_id,
},
};
match ecdsa::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 =
ecdsa::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<ecdsa::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: &ecdsa::EcdsaPayload,
ecdsa_payload_metrics: Option<&EcdsaPayloadMetrics>,
log: &ReplicaLogger,
) -> Result<ecdsa::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(ecdsa::UnmaskedTranscriptWithAttributes::registry_version)
.or_else(|| {
current_key_transcript.map(ecdsa::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(ecdsa::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
);
ecdsa::KeyTranscriptCreation::Begin
} else {
// No change, just carry forward the next_in_creation transcript
ecdsa_payload.key_transcript.next_in_creation.clone()
};
let key_transcript = ecdsa::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(),
};
let mut ecdsa_summary = if is_new_key_transcript {
ecdsa::EcdsaPayload {
signature_agreements: ecdsa_payload.signature_agreements.clone(),
ongoing_signatures: ecdsa_payload.ongoing_signatures.clone(),
available_quadruples: BTreeMap::new(),
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 {
ecdsa::EcdsaPayload {
signature_agreements: ecdsa_payload.signature_agreements.clone(),
ongoing_signatures: ecdsa_payload.ongoing_signatures.clone(),
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 ecdsa::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<ecdsa::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: &ecdsa::EcdsaPayload| {
matches!(
payload.key_transcript.next_in_creation,
ecdsa::KeyTranscriptCreation::Created(_)
)
};
if is_key_transcript_created(ecdsa_payload)
&& parent_block
.payload
.as_ref()
.as_ecdsa()
.map(is_key_transcript_created)
.unwrap_or(false)
{
ecdsa_payload_metrics.payload_metrics_inc("key_transcripts_created");
}
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<ecdsa::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 enabled_signing_keys = get_enabled_signing_keys(
subnet_id,
curr_interval_registry_version,
registry_client,
&ecdsa_config,
)?;
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,
&enabled_signing_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 ecdsa::EcdsaPayload,
height: Height,
context_time: Time,
ecdsa_config: &EcdsaConfig,
enabled_signing_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(Duration::from_nanos(timeout)));
signatures::update_signature_agreements(all_signing_requests, signature_builder, ecdsa_payload);
let new_signing_requests = get_signing_requests(
height,
request_expiry_time,
ecdsa_payload,
all_signing_requests,
enabled_signing_keys,
ecdsa_payload_metrics,
);
signatures::update_ongoing_signatures(
new_signing_requests,
ecdsa_config.quadruples_to_create_in_advance,
ecdsa_payload,
log,
)?;
if matches!(certified_height, CertifiedHeight::ReachedSummaryHeight) {
quadruples::purge_old_key_quadruples(ecdsa_payload, all_signing_requests);
}
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) = 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,
&resharing::make_reshare_dealings_response(ecdsa_dealings_contexts),
block_reader,
transcript_builder,
log,
);
resharing::initiate_reshare_requests(
ecdsa_payload,
resharing::get_reshare_requests(ecdsa_dealings_contexts),
);
Ok(())
}
/// Return the set of new signing requests by assigning them a RequestId. The
/// logic enforces the requirements set forth in Section A.5 of the ECDSA
/// design doc. Suppose we have signing requests SR_1, SR_2, ... and
/// quadruples Q_1, Q_2, ... .
///
/// The SR_i's are ordered in the order the requests were made by execution,
/// which is determined by the corresponding callback_id, which is defined in
/// the SubnetCallContextManager struct (see
/// rs/replicated_state/src/metadata_state/subnet_call_context_manager.rs).
/// callback_id's are obtained from a counter that gets incremented as requests
/// get made.
///
/// The Q_i's are ordered in the order in which their construction was
/// initiated, which is determined by QuadrupleId. QuadrupleId's are obtained
/// from a counter that gets incremented as new quadruples are initiated.
///
/// The basic idea is that SR_i gets paired with Q_i. These pairings are
/// reflected in the RequestId struct, which consists of a QuadrupleId and a
/// the pseudo_random_id of the signing request. A pseudo_random_id is the
/// random string generated from the random tape when the signing request is
/// made, as per Section A.5 of the ECDSA design doc. While pseudo_random_id
/// is ultimately used in the crypto layer as the nonce from which the
/// re-randomization value delta is derived, it is also used in consensus as an
/// ID for signing requests.
///
/// The logic here works as follows.
///
/// 1. let known_random_ids = the pseudo_random_id's of all signing requests
/// that are either ongoing or agreed upon.
///
/// 2. let unassigned_quadruple_ids be the list of all QuadrupleIds for
/// quadruples that are currently (a) either in creation or available, but (b)
/// are not paired with any signing requests that are either ongoing or agreed
/// upon.
///
/// 3. Now we build the list of RequestId's by iterating through the signing
/// request contexts in order of callback_id. This is done implicitly by virtue
/// of the fact that sign_with_ecdsa_contexts is a BTreeMap mapping CallBackId
/// to SignWithEcdsaContext and the semantics of the BTreeMap.values method.
/// So for each context considered in the given order, we ignore it if it
/// corresponds to an ongoing or agreed upon signing request (using the value
/// known_random_ids), and otherwise take the next unassigned quadruple from
/// unassigned_quadruple_ids and pair that with this signing request.
///
/// The main caller of this function is create_data_payload, who uses the
/// result to determine which signing-request/quadruple pairs will be moved to
/// the ongoing signatures state. This is done via the function
/// update_ongoing_signatures, which moves such a pair to ongoing signatures
/// if the quadruple is available.
///
/// For example, say in one round we could have SR_1, SR_2, SR_3, SR_4 in the
/// signing request contexts, none of which are yet ongoing, and Q_1, Q_2, Q_3
/// in the unassigned_quadruple_ids list. So the return value of the function
/// would be ((SR_1,Q_1), (SR_2,Q_2), (SR_3,Q_3)). In this same round, the
/// calling function, create_data_payload, could move, say, (SR_2,Q_2) to the
/// ongoing signatures state if Q2 were available. In the next round, we have
/// SR_1, SR_3, SR_4 in the signing requests contexts, with SR_2 now removed
/// because it is in the ongoing signatures state. We would also have
/// unassigned_quadruple_ids Q_1, Q_3, Q_4. The return value of the function
/// would be ((SR_1,Q_1), (SR_3,Q_3)). In this same round, we could move, say,
/// (SR_1,Q_1) to the ongoing signatures state if Q1 were available.
///
/// The above logic ensures that the pairing of SR_i with Q_i is deterministic,
/// and cannot be manipulated by the adversary, as discussed in Section A.5 of
/// the ECDSA design doc. However, as discussed in Section A.5.1 of the ECDSA
/// design doc, it is allowed to essentially dispose of Q_i and replace it with
/// a fresh quadruple Q'_i. In the implementation, this may happen at a
/// summary block. The logic in create_summary_payload will ensure that all
/// quadruples that are either in creation or available or disposed of
/// (currently, if a key reshare occurs) or retained (currently, if a key
/// reshare does not occur). This logic of either either disposing of or
/// retaining all quadruples that are either in creation or available
/// guarantees that the invariants in Section A.5.1 of the ECDSA design doc are
/// maintained. However, the following logic would also be acceptable: if we
/// dispose of a quadruple Q_i that is in creation or available, then we must
/// dispose of all quadruples Q_j for j > i that are in creation or available.
/// This logic may be useful if and when we implement pro-active resharing of
/// the signing key without subnet membership changes. In this case, in
/// creat_summary_payload, if Q_i is the first quadruple that is in creation,
/// we can retain Q_1, ..., Q_{i-1} and dispose of all quadruples Q_j for j >=
/// i that are in creation or available. This logic will allow us to continue
/// using at least some (and typically most) of the quadruples that were
/// already available when we pro-actively reshare the signing key.
pub(crate) fn get_signing_requests<'a>(
height: Height,
request_expiry_time: Option<Time>,
ecdsa_payload: &mut ecdsa::EcdsaPayload,
sign_with_ecdsa_contexts: &'a BTreeMap<CallbackId, SignWithEcdsaContext>,
valid_keys: &BTreeSet<EcdsaKeyId>,
ecdsa_payload_metrics: Option<&EcdsaPayloadMetrics>,
) -> BTreeMap<ecdsa::RequestId, &'a SignWithEcdsaContext> {
let mut known_random_ids_completed = ecdsa_payload
.signature_agreements
.keys()
.cloned()
.collect::<BTreeSet<_>>();
let known_random_ids_ongoing = ecdsa_payload
.ongoing_signatures
.keys()
.map(|id| (id.pseudo_random_id, id.clone()))
.collect::<BTreeMap<_, _>>();
let mut unassigned_quadruple_ids = ecdsa_payload.unassigned_quadruple_ids().collect::<Vec<_>>();
// sort in reverse order (bigger to smaller).
unassigned_quadruple_ids.sort_by(|a, b| b.cmp(a));
let mut new_requests = BTreeMap::new();
// We first go through all requests and check if their key_ids are valid.
// All *new* requests with invalid key ids will be rejected.
for (callback_id, context) in sign_with_ecdsa_contexts {
// Skip known completed and ongoing requests.
if known_random_ids_completed.contains(&context.pseudo_random_id)
|| known_random_ids_ongoing.contains_key(&context.pseudo_random_id)
{
continue;
}
if !valid_keys.contains(&context.key_id) {
// Reject new requests with unknown key Ids.
// Note that no quadruples are consumed at this stage.
let response = ic_types::messages::Response {
originator: context.request.sender,
respondent: ic_types::CanisterId::ic_00(),
originator_reply_callback: *callback_id,
refund: context.request.payment,
response_payload: ic_types::messages::Payload::Reject(RejectContext::new(
RejectCode::CanisterReject,
format!(
"Invalid or disabled key_id in signature request: {:?}",
context.key_id
),
)),
};
ecdsa_payload.signature_agreements.insert(
context.pseudo_random_id,
ecdsa::CompletedSignature::Unreported(response),
);
// Remember this is already responded to.
known_random_ids_completed.insert(context.pseudo_random_id);
if let Some(metrics) = ecdsa_payload_metrics {
metrics.payload_errors_inc("invalid_keyid_requests");
}
}
}
// The following iteration goes through contexts in the order
// of their keys, which is the callback_id. Therefore we are
// traversing the requests in the order they were created.
for (callback_id, context) in sign_with_ecdsa_contexts {
// Skip known completed requests.
if known_random_ids_completed.contains(&context.pseudo_random_id) {
continue;
}
// A request_id may already exist for this signing request.
// If not, we create one by pairing the pseudo_random_id with a quadruple id
// if there are still unassigned quadruples.
let known_request_id = known_random_ids_ongoing.get(&context.pseudo_random_id);
let request_id = known_request_id.cloned().or_else(|| {
unassigned_quadruple_ids
.pop()
.map(|quadruple_id| ecdsa::RequestId {
height,
quadruple_id,
pseudo_random_id: context.pseudo_random_id,
})
});
// Reject requests that timed out.
//
// Note that we only reach this stage when a request gets paired with a quadruple id.
// If we assume all requests eventually are paired with quadruple ids, expired ones
// will eventually all be rejected.
//
// This assumption holds because we start to make new quadruples whenever there is space.
// If an ongoing quadruple does not make progress, it will be purged eventually due to
// the expiry of its corresponding request. This leads to the creation of a new quadruple.
if let Some(expiry) = request_expiry_time {
if context.batch_time < expiry {
let response = ic_types::messages::Response {
originator: context.request.sender,
respondent: ic_types::CanisterId::ic_00(),
originator_reply_callback: *callback_id,
refund: context.request.payment,
response_payload: ic_types::messages::Payload::Reject(RejectContext::new(
RejectCode::CanisterError,
"Signature request expired",
)),
};
ecdsa_payload.signature_agreements.insert(
context.pseudo_random_id,
ecdsa::CompletedSignature::Unreported(response),
);
if let Some(metrics) = ecdsa_payload_metrics {
metrics.payload_errors_inc("expired_requests");
}
// Remove from other structures if request id exists
if let Some(request_id) = request_id {
ecdsa_payload.ongoing_signatures.remove(&request_id);
ecdsa_payload
.quadruples_in_creation
.remove(&request_id.quadruple_id);
ecdsa_payload
.available_quadruples
.remove(&request_id.quadruple_id);
}
continue;
}
}
// If a request is not known and not expired and request id exists, it is a new request.
if known_request_id.is_none() {
if let Some(request_id) = request_id {
new_requests.insert(request_id, context);
}
}
}
new_requests
}
/// Update configuration and data about the next ECDSA key transcript.
/// Returns the newly created transcript, if any.
///
/// Note that when creating next key transcript we must use the registry version
/// that is going to be put into the next DKG summary.
fn update_next_key_transcript(
receivers: &[NodeId],
registry_version: RegistryVersion,
ecdsa_payload: &mut ecdsa::EcdsaPayload,
transcript_cache: &dyn EcdsaTranscriptBuilder,
height: Height,
log: &ReplicaLogger,
) -> Result<Option<IDkgTranscript>, EcdsaPayloadError> {
let mut new_transcript = None;
match (
&ecdsa_payload.key_transcript.current,
&ecdsa_payload.key_transcript.next_in_creation,
) {
(Some(transcript), ecdsa::KeyTranscriptCreation::Begin) => {
// We have an existing key transcript, need to reshare it to create next
// Create a new reshare config when there is none
let dealers = transcript.receivers();
let receivers_set = receivers.iter().copied().collect::<BTreeSet<_>>();
info!(
log,
"Reshare ECDSA key transcript from dealers {:?} to receivers {:?}, height = {}",
dealers,
receivers,
height,
);
ecdsa_payload.key_transcript.next_in_creation =
ecdsa::KeyTranscriptCreation::ReshareOfUnmaskedParams(
ecdsa::ReshareOfUnmaskedParams::new(
ecdsa_payload.uid_generator.next_transcript_id(),
receivers_set,
registry_version,
transcript,
transcript.unmasked_transcript(),
),
);
}
(Some(_), ecdsa::KeyTranscriptCreation::ReshareOfUnmaskedParams(config)) => {
// check if the next key transcript has been made
if let Some(transcript) =
transcript_cache.get_completed_transcript(config.as_ref().transcript_id)
{
info!(
log,
"ECDSA key transcript created from ReshareOfUnmasked {:?} \
registry_version {} height = {}",
config.as_ref().transcript_id,
transcript.registry_version,
height,
);
let transcript_ref = ecdsa::UnmaskedTranscript::try_from((height, &transcript))?;
ecdsa_payload.key_transcript.next_in_creation =
ecdsa::KeyTranscriptCreation::Created(transcript_ref);
new_transcript = Some(transcript);
}
}
(None, ecdsa::KeyTranscriptCreation::Begin) => {
// The first ECDSA key transcript has to be created, starting from a random
// config. Here receivers and dealers are the same set.
let transcript_id = ecdsa_payload.uid_generator.next_transcript_id();
let receivers_set = receivers.iter().copied().collect::<BTreeSet<_>>();
let dealers_set = receivers_set.clone();
ecdsa_payload.key_transcript.next_in_creation =
ecdsa::KeyTranscriptCreation::RandomTranscriptParams(
ecdsa::RandomTranscriptParams::new(
transcript_id,
dealers_set,
receivers_set,
registry_version,
AlgorithmId::ThresholdEcdsaSecp256k1,
),
);
}
(None, ecdsa::KeyTranscriptCreation::RandomTranscriptParams(config)) => {
// Check if the random transcript has been created
if let Some(transcript) =
transcript_cache.get_completed_transcript(config.as_ref().transcript_id)
{
let receivers_set = receivers.iter().copied().collect::<BTreeSet<_>>();
let transcript_ref = ecdsa::MaskedTranscript::try_from((height, &transcript))?;
ecdsa_payload.key_transcript.next_in_creation =
ecdsa::KeyTranscriptCreation::ReshareOfMaskedParams(
ecdsa::ReshareOfMaskedParams::new(
ecdsa_payload.uid_generator.next_transcript_id(),
receivers_set,
registry_version,
&transcript,
transcript_ref,
),
);
new_transcript = Some(transcript);
}
}
(None, ecdsa::KeyTranscriptCreation::ReshareOfMaskedParams(config)) => {
// Check if the unmasked transcript has been created