-
Notifications
You must be signed in to change notification settings - Fork 316
/
dkg.rs
2203 lines (2048 loc) · 92 KB
/
dkg.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 defines an embedding of the dkg algorithm provided by the crypto
//! component into the consensus algorithm that is implemented within this
//! crate.
use crate::{
consensus::{check_protocol_version, dkg_key_manager::DkgKeyManager},
idkg::{
make_bootstrap_summary,
payload_builder::make_bootstrap_summary_with_initial_dealings,
utils::{get_chain_key_config_if_enabled, inspect_chain_key_initializations},
},
};
use ic_consensus_utils::crypto::ConsensusCrypto;
use ic_interfaces::{
consensus_pool::ConsensusPoolCache,
crypto::ErrorReproducibility,
dkg::{ChangeAction, DkgPool, Mutations},
p2p::consensus::{Bouncer, BouncerFactory, BouncerValue, PoolMutationsProducer},
};
use ic_interfaces_registry::RegistryClient;
use ic_logger::{error, info, warn, ReplicaLogger};
use ic_metrics::buckets::{decimal_buckets, linear_buckets};
use ic_protobuf::registry::subnet::v1::CatchUpPackageContents;
use ic_registry_client_helpers::subnet::SubnetRegistry;
use ic_types::{
batch::ValidationContext,
consensus::{
dkg::{DealingContent, DkgMessageId, Message},
idkg, Block, BlockPayload, CatchUpContent, CatchUpPackage, HashedBlock, HashedRandomBeacon,
Payload, RandomBeaconContent, Rank, SummaryPayload,
},
crypto::{
crypto_hash,
threshold_sig::ni_dkg::{config::NiDkgConfig, NiDkgId, NiDkgTag, NiDkgTargetSubnet},
CombinedThresholdSig, CombinedThresholdSigOf, CryptoHash, Signed,
},
signature::ThresholdSignature,
Height, NodeId, RegistryVersion, SubnetId, Time,
};
pub(crate) use payload_validator::{DkgPayloadValidationFailure, InvalidDkgPayloadReason};
use phantom_newtype::Id;
use prometheus::Histogram;
use rayon::prelude::*;
use std::{
collections::BTreeMap,
sync::{Arc, Mutex},
};
pub(crate) mod payload_builder;
pub(crate) mod payload_validator;
#[cfg(test)]
mod test_utils;
mod utils;
pub use payload_builder::{create_payload, make_genesis_summary, PayloadCreationError};
// The maximal number of DKGs for other subnets we want to run in one interval.
const MAX_REMOTE_DKGS_PER_INTERVAL: usize = 1;
// The maximum number of intervals during which an initial DKG request is
// attempted.
const MAX_REMOTE_DKG_ATTEMPTS: u32 = 5;
// Generic error string for failed remote DKG requests.
const REMOTE_DKG_REPEATED_FAILURE_ERROR: &str = "Attempts to run this DKG repeatedly failed";
// Currently we assume that we run DKGs for all of these tags.
const TAGS: [NiDkgTag; 2] = [NiDkgTag::LowThreshold, NiDkgTag::HighThreshold];
struct Metrics {
on_state_change_duration: Histogram,
on_state_change_processed: Histogram,
}
/// `DkgImpl` is responsible for holding DKG dependencies and for responding to
/// changes in the consensus and DKG pool.
pub struct DkgImpl {
node_id: NodeId,
crypto: Arc<dyn ConsensusCrypto>,
consensus_cache: Arc<dyn ConsensusPoolCache>,
dkg_key_manager: Arc<Mutex<DkgKeyManager>>,
logger: ReplicaLogger,
metrics: Metrics,
}
impl DkgImpl {
/// Build a new DKG component
pub fn new(
node_id: NodeId,
crypto: Arc<dyn ConsensusCrypto>,
consensus_cache: Arc<dyn ConsensusPoolCache>,
dkg_key_manager: Arc<Mutex<DkgKeyManager>>,
metrics_registry: ic_metrics::MetricsRegistry,
logger: ReplicaLogger,
) -> Self {
Self {
crypto,
consensus_cache,
node_id,
dkg_key_manager,
logger,
metrics: Metrics {
on_state_change_duration: metrics_registry.histogram(
"consensus_dkg_on_state_change_duration_seconds",
"The time it took to execute on_state_change(), in seconds",
// 0.1ms, 0.2ms, 0.5ms, 1ms, 2ms, 5ms, 10ms, 20ms, 50ms, 100ms, 200ms, 500ms,
// 1s, 2s, 5s, 10s, 20s, 50s, 100s, 200s, 500s
decimal_buckets(-4, 2),
),
on_state_change_processed: metrics_registry.histogram(
"consensus_dkg_on_state_change_processed",
"Number of entries processed by on_state_change()",
// 0 - 100
linear_buckets(0.0, 1.0, 100),
),
},
}
}
// Create a dealing for the given DKG config if necessary. That is, if this
// replica is a dealer for the config and hasn't yet created a dealing, it will
// return a change action to add a dealing.
fn create_dealing(&self, dkg_pool: &dyn DkgPool, config: &NiDkgConfig) -> Option<ChangeAction> {
// Do not produce any dealings if the dealers list does not contain the id of
// the current replica, or the current replica has already produced dealings.
if !config.dealers().get().contains(&self.node_id)
|| contains_dkg_messages(dkg_pool, config, self.node_id)
{
return None;
}
// If the transcript is being loaded at the moment, we return early.
// The transcript will be available at a later point in time.
if let Some(transcript) = config.resharing_transcript() {
if !self
.dkg_key_manager
.lock()
.unwrap()
.is_transcript_loaded(&transcript.dkg_id)
{
return None;
}
}
let content =
match ic_interfaces::crypto::NiDkgAlgorithm::create_dealing(&*self.crypto, config) {
Ok(dealing) => DealingContent::new(dealing, config.dkg_id()),
Err(err) => {
match config.dkg_id().target_subnet {
NiDkgTargetSubnet::Local => error!(
self.logger,
"Couldn't create a DKG dealing at height {:?}: {:?}",
config.dkg_id().start_block_height,
err
),
// NOTE: In rare cases, we might hit this case.
NiDkgTargetSubnet::Remote(_) => info!(
self.logger,
"Waiting for Remote DKG dealing at height {:?}: {:?}",
config.dkg_id().start_block_height,
err
),
};
return None;
}
};
match self
.crypto
.sign(&content, self.node_id, config.registry_version())
{
Ok(signature) => Some(ChangeAction::AddToValidated(Signed { content, signature })),
Err(err) => {
error!(self.logger, "Couldn't sign a DKG dealing: {:?}", err);
None
}
}
}
// Validates the DKG messages against the provided config.
//
// Invalidates the message if:
// - no DKG config among onging DKGs was found,
// - the dealer is not on the list of dealers wrt. DKG config,
// - the dealing signature is invalid,
// - the dealing is invalid.
//
// We simply remove the message from the pool if we already have a dealing
// from the dealer of the the message, because it is possible for honest
// dealers to provide multiple, non-identical dealings in certain
// situations. We skip the validation if an error occurs during the
// signature or dealing verification.
fn validate_dealings_for_dealer(
&self,
dkg_pool: &dyn DkgPool,
configs: &BTreeMap<NiDkgId, NiDkgConfig>,
dkg_start_height: Height,
messages: Vec<&Message>,
) -> Mutations {
// Because dealing generation is not entirely deterministic, it is
// actually possible to receive multiple dealings from an honest dealer.
// As such, we simply try validating the first message in the list, and
// get a result for that message. Other messages will be dealt with by
// subsequent calls to this function.
let message = if let Some(message) = messages.first() {
message
} else {
return Mutations::new();
};
if check_protocol_version(&message.content.version).is_err() {
return Mutations::from(ChangeAction::RemoveFromUnvalidated((*message).clone()));
}
let message_dkg_id = message.content.dkg_id;
// If the dealing refers to a DKG interval starting at a different height,
// we skip it.
if message_dkg_id.start_block_height != dkg_start_height {
return Mutations::new();
}
// If the dealing refers a config which is not among the ongoing DKGs,
// we reject it.
let config = match configs.get(&message_dkg_id) {
Some(config) => config,
None => {
return get_handle_invalid_change_action(
message,
format!(
"No DKG configuration for Id={:?} was found.",
message_dkg_id
),
)
.into()
}
};
let dealer_id = &message.signature.signer;
// If the validated pool already contains this exact message, we skip it.
if dkg_pool.get_validated().any(|item| item.eq(message)) {
return Mutations::new();
}
// If the dealing comes from a non-dealer, reject it.
if !config.dealers().get().contains(dealer_id) {
return get_handle_invalid_change_action(
message,
format!("Replica with Id={:?} is not a dealer.", dealer_id),
)
.into();
}
// If we already have a dealing from this dealer, we simply remove the
// message from the pool. Multiple distinguishable valid dealings can be
// created by an honest node because dkg dealings are not deterministic,
// and in the case of a restart it is possible it might forget that it
// has already sent out a dealing. See
// https://dfinity.atlassian.net/browse/CON-534 for more details.
if contains_dkg_messages(dkg_pool, config, *dealer_id) {
return Mutations::from(ChangeAction::RemoveFromUnvalidated((*message).clone()));
}
// Verify the signature and reject if it's invalid, or skip, if there was an error.
match self.crypto.verify(message, config.registry_version()) {
Ok(()) => (),
Err(err) if err.is_reproducible() => {
return get_handle_invalid_change_action(
message,
format!("Invalid signature: {}", err),
)
.into()
}
Err(err) => {
error!(
self.logger,
"Couldn't verify the signature of a DKG dealing: {}", err
);
return Mutations::new();
}
}
// Verify the dealing and move to validated if it was successful,
// reject, if it was rejected, or skip, if there was an error.
match ic_interfaces::crypto::NiDkgAlgorithm::verify_dealing(
&*self.crypto,
config,
*dealer_id,
&message.content.dealing,
) {
Ok(()) => ChangeAction::MoveToValidated((*message).clone()).into(),
Err(err) if err.is_reproducible() => get_handle_invalid_change_action(
message,
format!("Dealing verification failed: {}", err),
)
.into(),
Err(err) => {
error!(self.logger, "Couldn't verify a DKG dealing: {}", err);
Mutations::new()
}
}
}
}
fn contains_dkg_messages(dkg_pool: &dyn DkgPool, config: &NiDkgConfig, replica_id: NodeId) -> bool {
dkg_pool.get_validated().any(|message| {
message.content.dkg_id == config.dkg_id() && message.signature.signer == replica_id
})
}
fn get_handle_invalid_change_action<T: AsRef<str>>(message: &Message, reason: T) -> ChangeAction {
ChangeAction::HandleInvalid(DkgMessageId::from(message), reason.as_ref().to_string())
}
impl<T: DkgPool> PoolMutationsProducer<T> for DkgImpl {
type Mutations = Mutations;
fn on_state_change(&self, dkg_pool: &T) -> Mutations {
// This timer will make an entry in the metrics histogram automatically, when
// it's dropped.
let _timer = self.metrics.on_state_change_duration.start_timer();
let dkg_summary_block = self.consensus_cache.summary_block();
let dkg_summary = &dkg_summary_block.payload.as_ref().as_summary().dkg;
let start_height = dkg_summary_block.height;
if start_height > dkg_pool.get_current_start_height() {
return ChangeAction::Purge(start_height).into();
}
let change_set: Mutations = dkg_summary
.configs
.par_iter()
.filter_map(|(_id, config)| self.create_dealing(dkg_pool, config))
.collect();
if !change_set.is_empty() {
return change_set;
}
let mut processed = 0;
let dealings: Vec<Vec<&Message>> = dkg_pool
.get_unvalidated()
// Group all unvalidated dealings by dealer.
.fold(BTreeMap::new(), |mut map, dealing| {
let key = (dealing.signature.signer, dealing.content.dkg_id);
let dealings: &mut Vec<_> = map.entry(key).or_default();
dealings.push(dealing);
processed += 1;
map
})
// Get the dealings sorted by dealers
.values()
.cloned()
.collect();
let changeset = dealings
.par_iter()
.map(|dealings| {
self.validate_dealings_for_dealer(
dkg_pool,
&dkg_summary.configs,
start_height,
dealings.to_vec(),
)
})
.collect::<Vec<Mutations>>()
.into_iter()
.flatten()
.collect::<Mutations>();
self.metrics
.on_state_change_processed
.observe(processed as f64);
changeset
}
}
/// `DkgBouncer` is a placeholder for gossip related DKG interfaces.
pub struct DkgBouncer;
// The NiDKG component does not implement custom `get_filter` function
// because it doesn't require artifact retransmission. Nodes participating
// in NiDKG would create artifacts depending on their own consensus state.
// If a node happens to disconnect, it would send out dealings based on
// its previous state after it reconnects, regardless of whether it has sent
// them before.
impl<Pool: DkgPool> BouncerFactory<DkgMessageId, Pool> for DkgBouncer {
fn new_bouncer(&self, dkg_pool: &Pool) -> Bouncer<DkgMessageId> {
let start_height = dkg_pool.get_current_start_height();
Box::new(move |id| {
use std::cmp::Ordering;
match id.height.cmp(&start_height) {
Ordering::Equal => BouncerValue::Wants,
Ordering::Greater => BouncerValue::MaybeWantsLater,
Ordering::Less => BouncerValue::Unwanted,
}
})
}
fn refresh_period(&self) -> std::time::Duration {
std::time::Duration::from_secs(3)
}
}
/// Constructs a genesis/recovery CUP from the CUP contents associated with the
/// given subnet
pub fn make_registry_cup(
registry: &dyn RegistryClient,
subnet_id: SubnetId,
logger: &ReplicaLogger,
) -> Option<CatchUpPackage> {
let versioned_record = match registry.get_cup_contents(subnet_id, registry.get_latest_version())
{
Ok(versioned_record) => versioned_record,
Err(e) => {
warn!(
logger,
"Failed to retrieve versioned record from the registry {:?}", e,
);
return None;
}
};
let cup_contents = versioned_record.value.expect("Missing CUP contents");
make_registry_cup_from_cup_contents(
registry,
subnet_id,
cup_contents,
versioned_record.version,
logger,
)
}
/// Constructs a genesis/recovery CUP from the CUP contents associated with the
/// given subnet from the provided CUP contents
pub fn make_registry_cup_from_cup_contents(
registry: &dyn RegistryClient,
subnet_id: SubnetId,
cup_contents: CatchUpPackageContents,
registry_version: RegistryVersion,
logger: &ReplicaLogger,
) -> Option<CatchUpPackage> {
let replica_version = match registry.get_replica_version(subnet_id, registry_version) {
Ok(Some(replica_version)) => replica_version,
err => {
warn!(
logger,
"Failed to retrieve subnet replica version at registry version {:?}: {:?}",
registry_version,
err
);
return None;
}
};
let dkg_summary = payload_builder::get_dkg_summary_from_cup_contents(
cup_contents.clone(),
subnet_id,
registry,
registry_version,
);
let cup_height = Height::new(cup_contents.height);
let idkg_summary = match bootstrap_idkg_summary(
&cup_contents,
subnet_id,
registry_version,
registry,
logger,
) {
Ok(summary) => summary,
Err(err) => {
warn!(
logger,
"Failed constructing IDKG summary block from CUP contents: {}", err
);
None
}
};
let low_dkg_id = dkg_summary
.current_transcript(&NiDkgTag::LowThreshold)
.dkg_id;
let high_dkg_id = dkg_summary
.current_transcript(&NiDkgTag::HighThreshold)
.dkg_id;
// In a NNS subnet recovery case the block validation context needs to reference a registry
// version of the NNS to be recovered. Otherwise the validation context points to a registry
// version without the NNS subnet record.
let block_registry_version = cup_contents
.registry_store_uri
.as_ref()
.map(|v| RegistryVersion::from(v.registry_version))
.unwrap_or(registry_version);
let block = Block {
version: replica_version.clone(),
parent: Id::from(CryptoHash(Vec::new())),
payload: Payload::new(
crypto_hash,
BlockPayload::Summary(SummaryPayload {
dkg: dkg_summary,
idkg: idkg_summary,
}),
),
height: cup_height,
rank: Rank(0),
context: ValidationContext {
certified_height: cup_height,
registry_version: block_registry_version,
time: Time::from_nanos_since_unix_epoch(cup_contents.time),
},
};
let random_beacon = Signed {
content: RandomBeaconContent {
version: replica_version,
height: cup_height,
parent: Id::from(CryptoHash(Vec::new())),
},
signature: ThresholdSignature {
signer: low_dkg_id,
signature: CombinedThresholdSigOf::new(CombinedThresholdSig(vec![])),
},
};
Some(CatchUpPackage {
content: CatchUpContent::new(
HashedBlock::new(crypto_hash, block),
HashedRandomBeacon::new(crypto_hash, random_beacon),
Id::from(CryptoHash(cup_contents.state_hash)),
/* oldest_registry_version_in_use_by_replicated_state */ None,
),
signature: ThresholdSignature {
signer: high_dkg_id,
signature: CombinedThresholdSigOf::new(CombinedThresholdSig(vec![])),
},
})
}
fn bootstrap_idkg_summary_from_cup_contents(
cup_contents: &CatchUpPackageContents,
subnet_id: SubnetId,
logger: &ReplicaLogger,
) -> Result<idkg::Summary, String> {
let initial_dealings = inspect_chain_key_initializations(
&cup_contents.ecdsa_initializations,
&cup_contents.chain_key_initializations,
)?;
if initial_dealings.is_empty() {
return Ok(None);
};
make_bootstrap_summary_with_initial_dealings(
subnet_id,
Height::new(cup_contents.height),
initial_dealings,
logger,
)
.map_err(|err| format!("Failed to create IDKG summary block: {:?}", err))
}
fn bootstrap_idkg_summary(
cup_contents: &CatchUpPackageContents,
subnet_id: SubnetId,
registry_version: RegistryVersion,
registry_client: &dyn RegistryClient,
logger: &ReplicaLogger,
) -> Result<idkg::Summary, String> {
if let Some(summary) =
bootstrap_idkg_summary_from_cup_contents(cup_contents, subnet_id, logger)?
{
return Ok(Some(summary));
}
match get_chain_key_config_if_enabled(subnet_id, registry_version, registry_client)
.map_err(|err| format!("Failed getting the chain key config: {:?}", err))?
{
Some(chain_key_config) => Ok(make_bootstrap_summary(
subnet_id,
chain_key_config
.key_configs
.iter()
.map(|key_config| key_config.key_id.clone())
.collect(),
Height::new(cup_contents.height),
)),
None => Ok(None),
}
}
#[cfg(test)]
mod tests {
use super::{test_utils::complement_state_manager_with_remote_dkg_requests, *};
use ic_artifact_pool::dkg_pool::DkgPoolImpl;
use ic_consensus_mocks::{
dependencies, dependencies_with_subnet_params,
dependencies_with_subnet_records_with_raw_state_manager, Dependencies,
};
use ic_consensus_utils::pool_reader::PoolReader;
use ic_crypto_test_utils_ni_dkg::dummy_initial_dkg_transcript;
use ic_interfaces::{
consensus_pool::ConsensusPool,
p2p::consensus::{MutablePool, UnvalidatedArtifact},
};
use ic_interfaces_registry::RegistryVersionedRecord;
use ic_logger::replica_logger::no_op_logger;
use ic_metrics::MetricsRegistry;
use ic_protobuf::registry::subnet::v1::{CatchUpPackageContents, SubnetRecord};
use ic_test_artifact_pool::consensus_pool::TestConsensusPool;
use ic_test_utilities::crypto::CryptoReturningOk;
use ic_test_utilities_logger::with_test_replica_logger;
use ic_test_utilities_registry::{add_subnet_record, SubnetRecordBuilder};
use ic_test_utilities_types::ids::{node_test_id, subnet_test_id};
use ic_types::{
consensus::HasVersion,
crypto::threshold_sig::ni_dkg::{
NiDkgDealing, NiDkgId, NiDkgTag, NiDkgTargetId, NiDkgTargetSubnet,
},
registry::RegistryClientError,
time::UNIX_EPOCH,
PrincipalId, RegistryVersion, ReplicaVersion,
};
use std::{collections::BTreeSet, convert::TryFrom};
#[test]
// In this test we test the creation of dealing payloads.
fn test_create_dealings_payload() {
ic_test_utilities::artifact_pool_config::with_test_pool_config(|pool_config| {
with_test_replica_logger(|logger| {
let nodes: Vec<_> = (0..3).map(node_test_id).collect();
let dkg_interval_len = 30;
let subnet_id = subnet_test_id(222);
let initial_registry_version = 112;
let Dependencies {
crypto,
mut pool,
dkg_pool,
..
} = dependencies_with_subnet_params(
pool_config,
subnet_id,
vec![(
initial_registry_version,
SubnetRecordBuilder::from(&nodes)
.with_dkg_interval_length(dkg_interval_len)
.build(),
)],
);
// Now we instantiate the DKG component for node Id = 1, who is a dealer.
let replica_1 = node_test_id(1);
let dkg_key_manager =
new_dkg_key_manager(crypto.clone(), logger.clone(), &PoolReader::new(&pool));
let dkg = DkgImpl::new(
replica_1,
crypto.clone(),
pool.get_cache(),
dkg_key_manager.clone(),
MetricsRegistry::new(),
logger.clone(),
);
// Creates two dealings for both thresholds and add them to the pool.
sync_dkg_key_manager(&dkg_key_manager, &pool);
let change_set = dkg.on_state_change(&*dkg_pool.read().unwrap());
assert_eq!(change_set.len(), 2);
dkg_pool.write().unwrap().apply(change_set);
// Advance the consensus pool for one round and make sure both dealings made it
// into the block.
pool.advance_round_normal_operation();
let block = pool.get_cache().finalized_block();
let dealings = &block.payload.as_ref().as_data().dealings;
if dealings.start_height != Height::from(0) {
panic!(
"Expected start height in dealings {:?}, but found {:?}",
Height::from(0),
dealings.start_height
)
}
assert_eq!(dealings.messages.len(), 2);
for tag in &TAGS {
assert!(dealings.messages.iter().any(
|m| m.signature.signer == replica_1 && m.content.dkg_id.dkg_tag == *tag
));
}
// Now make sure, the dealing from the same dealer will not be included in a new
// block anymore.
pool.advance_round_normal_operation();
let block = pool.get_cache().finalized_block();
let dealings = &block.payload.as_ref().as_data().dealings;
assert_eq!(dealings.messages.len(), 0);
// Now we empty the dkg pool, add new dealings from this dealer and make sure
// they are still not included.
assert_eq!(dkg_pool.read().unwrap().get_validated().count(), 2);
dkg_pool
.write()
.unwrap()
.apply(vec![ChangeAction::Purge(block.height)]);
// Check that the dkg pool is really empty.
assert_eq!(dkg_pool.read().unwrap().get_validated().count(), 0);
// Create new dealings; this works, because we cleaned the pool before.
let change_set = dkg.on_state_change(&*dkg_pool.read().unwrap());
assert_eq!(change_set.len(), 2);
dkg_pool.write().unwrap().apply(change_set);
// Make sure the new dealings are in the pool.
assert_eq!(dkg_pool.read().unwrap().get_validated().count(), 2);
// Advance the pool and make sure the dealing are not included.
pool.advance_round_normal_operation();
let block = pool.get_cache().finalized_block();
let dealings = &block.payload.as_ref().as_data().dealings;
assert_eq!(dealings.messages.len(), 0);
// Create another dealer and add his dealings into the unvalidated pool of
// replica 1.
let replica_2 = node_test_id(2);
let dkg_key_manager_2 =
new_dkg_key_manager(crypto.clone(), logger.clone(), &PoolReader::new(&pool));
let dkg_2 = DkgImpl::new(
replica_2,
crypto,
pool.get_cache(),
dkg_key_manager_2.clone(),
MetricsRegistry::new(),
logger.clone(),
);
let dkg_pool_2 = DkgPoolImpl::new(MetricsRegistry::new(), logger);
sync_dkg_key_manager(&dkg_key_manager_2, &pool);
match &dkg_2.on_state_change(&dkg_pool_2).as_slice() {
&[ChangeAction::AddToValidated(message), ChangeAction::AddToValidated(message2)] =>
{
dkg_pool.write().unwrap().insert(UnvalidatedArtifact {
message: message.clone(),
peer_id: replica_1,
timestamp: UNIX_EPOCH,
});
dkg_pool.write().unwrap().insert(UnvalidatedArtifact {
message: message2.clone(),
peer_id: replica_1,
timestamp: UNIX_EPOCH,
});
}
val => panic!("Unexpected change set: {:?}", val),
};
// Now we validate these dealings on replica 1 and move them to the validated
// pool.
let change_set = dkg.on_state_change(&*dkg_pool.read().unwrap());
match &change_set.as_slice() {
&[ChangeAction::MoveToValidated(_), ChangeAction::MoveToValidated(_)] => {}
val => panic!("Unexpected change set: {:?}", val),
};
dkg_pool.write().unwrap().apply(change_set);
assert_eq!(dkg_pool.read().unwrap().get_validated().count(), 4);
// Now we create a new block and make sure, the dealings made into the payload.
pool.advance_round_normal_operation();
let block = pool.get_cache().finalized_block();
let dealings = &block.payload.as_ref().as_data().dealings;
if dealings.start_height != Height::from(0) {
panic!(
"Expected start height in dealings {:?}, but found {:?}",
Height::from(0),
dealings.start_height
)
}
assert_eq!(dealings.messages.len(), 2);
for tag in &TAGS {
assert!(dealings.messages.iter().any(
|m| m.signature.signer == replica_2 && m.content.dkg_id.dkg_tag == *tag
));
}
});
});
}
#[test]
fn test_create_dealing_works() {
ic_test_utilities::artifact_pool_config::with_test_pool_config(|pool_config| {
with_test_replica_logger(|logger| {
let Dependencies {
mut pool, crypto, ..
} = dependencies(pool_config.clone(), 2);
let mut dkg_pool = DkgPoolImpl::new(MetricsRegistry::new(), logger.clone());
// Let's check that replica 3, who's not a dealer, does not produce dealings.
let dkg_key_manager =
new_dkg_key_manager(crypto.clone(), logger.clone(), &PoolReader::new(&pool));
let dkg = DkgImpl::new(
node_test_id(3),
crypto.clone(),
pool.get_cache(),
dkg_key_manager,
MetricsRegistry::new(),
logger.clone(),
);
assert!(dkg.on_state_change(&dkg_pool).is_empty());
// Now we instantiate the DKG component for node Id = 1, who is a dealer.
let dkg_key_manager =
new_dkg_key_manager(crypto.clone(), logger.clone(), &PoolReader::new(&pool));
let dkg = DkgImpl::new(
node_test_id(1),
crypto,
pool.get_cache(),
dkg_key_manager.clone(),
MetricsRegistry::new(),
logger,
);
// Make sure the replica creates two dealings for both thresholds.
sync_dkg_key_manager(&dkg_key_manager, &pool);
let change_set = dkg.on_state_change(&dkg_pool);
match &change_set.as_slice() {
&[ChangeAction::AddToValidated(_), ChangeAction::AddToValidated(_)] => {}
val => panic!("Unexpected change set: {:?}", val),
};
// Apply the changes and make sure, we do not produce any dealings anymore.
dkg_pool.apply(change_set);
assert!(dkg.on_state_change(&dkg_pool).is_empty());
// Mimic consensus progress and make sure we still do not
// generate new dealings because the DKG summary didn't change.
pool.advance_round_normal_operation_n(5);
assert!(dkg.on_state_change(&dkg_pool).is_empty());
// Skip till the new DKG summary and make sure we generate dealings
// again.
let default_interval_length = 60;
pool.advance_round_normal_operation_n(default_interval_length);
// First we expect a new purge.
let change_set = dkg.on_state_change(&dkg_pool);
match &change_set.as_slice() {
&[ChangeAction::Purge(purge_height)]
if *purge_height == Height::from(default_interval_length) => {}
val => panic!("Unexpected change set: {:?}", val),
};
dkg_pool.apply(change_set);
// And then we validate...
let change_set = dkg.on_state_change(&dkg_pool);
match &change_set.as_slice() {
&[ChangeAction::AddToValidated(_), ChangeAction::AddToValidated(_)] => {}
val => panic!("Unexpected change set: {:?}", val),
};
// Just check again, we do not reproduce a dealing once changes are applied.
dkg_pool.apply(change_set);
assert!(dkg.on_state_change(&dkg_pool).is_empty());
});
});
}
#[test]
fn test_create_dealing_works_for_remote_dkg() {
ic_test_utilities::artifact_pool_config::with_test_pool_config(|pool_config| {
use ic_types::crypto::threshold_sig::ni_dkg::*;
with_test_replica_logger(|logger| {
let node_ids = vec![node_test_id(0), node_test_id(1)];
let dkg_interval_length = 99;
let subnet_id = subnet_test_id(0);
let Dependencies {
mut pool,
crypto,
registry,
state_manager,
..
} = dependencies_with_subnet_records_with_raw_state_manager(
pool_config,
subnet_id,
vec![(
10,
SubnetRecordBuilder::from(&node_ids)
.with_dkg_interval_length(dkg_interval_length)
.build(),
)],
);
let target_id = NiDkgTargetId::new([0u8; 32]);
complement_state_manager_with_remote_dkg_requests(
state_manager,
registry.get_latest_version(),
vec![10, 11, 12],
None,
Some(target_id),
);
// Now we instantiate the DKG component for node Id = 1, who is a dealer.
let dkg_key_manager =
new_dkg_key_manager(crypto.clone(), logger.clone(), &PoolReader::new(&pool));
let dkg = DkgImpl::new(
node_test_id(1),
crypto,
pool.get_cache(),
dkg_key_manager.clone(),
MetricsRegistry::new(),
logger.clone(),
);
// We did not advance the consensus pool yet. The configs for remote transcripts
// are not added to a summary block yet. That's why we see two dealings for
// local thresholds.
let mut dkg_pool = DkgPoolImpl::new(MetricsRegistry::new(), logger);
sync_dkg_key_manager(&dkg_key_manager, &pool);
let change_set = dkg.on_state_change(&dkg_pool);
match &change_set.as_slice() {
&[ChangeAction::AddToValidated(a), ChangeAction::AddToValidated(b)] => {
assert_eq!(a.content.dkg_id.target_subnet, NiDkgTargetSubnet::Local);
assert_eq!(b.content.dkg_id.target_subnet, NiDkgTargetSubnet::Local);
}
val => panic!("Unexpected change set: {:?}", val),
};
// Apply the changes and make sure, we do not produce any dealings anymore.
dkg_pool.apply(change_set);
assert!(dkg.on_state_change(&dkg_pool).is_empty());
// Advance _past_ the new summary to make sure the configs for remote
// transcripts are added into the summary.
pool.advance_round_normal_operation_n(dkg_interval_length + 1);
// First we expect a new purge.
let change_set = dkg.on_state_change(&dkg_pool);
match &change_set.as_slice() {
&[ChangeAction::Purge(purge_height)]
if *purge_height == Height::from(dkg_interval_length + 1) => {}
val => panic!("Unexpected change set: {:?}", val),
};
dkg_pool.apply(change_set);
// And then we validate two local and two remote dealings.
let change_set = dkg.on_state_change(&dkg_pool);
match &change_set.as_slice() {
&[ChangeAction::AddToValidated(a), ChangeAction::AddToValidated(b), ChangeAction::AddToValidated(c), ChangeAction::AddToValidated(d)] =>
{
assert_eq!(
[a, b, c, d]
.iter()
.filter(|msg| msg.content.dkg_id.target_subnet
== NiDkgTargetSubnet::Remote(target_id))
.count(),
2
);
assert_eq!(
[a, b, c, d]
.iter()
.filter(|msg| msg.content.dkg_id.target_subnet
== NiDkgTargetSubnet::Local)
.count(),
2
);
}
val => panic!("Unexpected change set: {:?}", val),
};
// Just check again, we do not reproduce a dealing once changes are applied.
dkg_pool.apply(change_set);
assert!(dkg.on_state_change(&dkg_pool).is_empty());
});
});
}
#[test]
fn test_config_generation_failures_are_added_to_the_summary() {
ic_test_utilities::artifact_pool_config::with_test_pool_config(|pool_config| {
use ic_types::crypto::threshold_sig::ni_dkg::*;
let node_ids = vec![node_test_id(0), node_test_id(1)];
let dkg_interval_length = 99;
let subnet_id = subnet_test_id(0);
let Dependencies {
mut pool,
registry,
state_manager,
..
} = dependencies_with_subnet_records_with_raw_state_manager(
pool_config,
subnet_id,
vec![(
10,
SubnetRecordBuilder::from(&node_ids)
.with_dkg_interval_length(dkg_interval_length)
.build(),
)],
);
let target_id = NiDkgTargetId::new([0u8; 32]);
complement_state_manager_with_remote_dkg_requests(
state_manager,
registry.get_latest_version(),
vec![], // an erroneous request with no nodes.
None,
Some(target_id),
);
// Advance _past_ the new summary to make sure the replicas attempt to create
// the configs for remote transcripts.
pool.advance_round_normal_operation_n(dkg_interval_length + 1);
// Verify that the first summary block contains only two local configs and the