-
Notifications
You must be signed in to change notification settings - Fork 330
/
Copy pathlib.rs
3963 lines (3634 loc) · 144 KB
/
lib.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
use candid::Decode;
use core::sync::atomic::Ordering;
use ic_artifact_pool::canister_http_pool::CanisterHttpPoolImpl;
use ic_btc_adapter_client::setup_bitcoin_adapter_clients;
use ic_btc_consensus::BitcoinPayloadBuilder;
use ic_config::{
adapters::AdaptersConfig,
bitcoin_payload_builder_config::Config as BitcoinPayloadBuilderConfig,
execution_environment::Config as HypervisorConfig, state_manager::LsmtConfig,
subnet_config::SubnetConfig,
};
use ic_consensus::{
consensus::payload_builder::PayloadBuilderImpl, make_registry_cup,
make_registry_cup_from_cup_contents,
};
use ic_consensus_utils::crypto::SignVerify;
use ic_crypto_test_utils_ni_dkg::{
dummy_initial_dkg_transcript_with_master_key, sign_message, SecretKeyBytes,
};
use ic_crypto_tree_hash::{sparse_labeled_tree_from_paths, Label, Path as LabeledTreePath};
use ic_crypto_utils_threshold_sig_der::threshold_sig_public_key_to_der;
use ic_cycles_account_manager::CyclesAccountManager;
pub use ic_error_types::{ErrorCode, UserError};
use ic_execution_environment::{ExecutionServices, IngressHistoryReaderImpl};
use ic_http_endpoints_public::{metrics::HttpHandlerMetrics, IngressWatcher, IngressWatcherHandle};
use ic_https_outcalls_consensus::payload_builder::CanisterHttpPayloadBuilderImpl;
use ic_ingress_manager::{IngressManager, RandomStateKind};
use ic_interfaces::{
batch_payload::{BatchPayloadBuilder, IntoMessages, PastPayload, ProposalContext},
canister_http::{CanisterHttpChangeAction, CanisterHttpPool},
certification::{Verifier, VerifierError},
consensus::{PayloadBuilder as ConsensusPayloadBuilder, PayloadValidationError},
consensus_pool::ConsensusTime,
execution_environment::{IngressFilterService, IngressHistoryReader, QueryExecutionService},
ingress_pool::{
IngressPool, IngressPoolObject, PoolSection, UnvalidatedIngressArtifact,
ValidatedIngressArtifact,
},
p2p::consensus::MutablePool,
validation::ValidationResult,
};
use ic_interfaces_certified_stream_store::{CertifiedStreamStore, EncodeStreamError};
use ic_interfaces_registry::RegistryClient;
use ic_interfaces_state_manager::{CertificationScope, StateHashError, StateManager, StateReader};
use ic_limits::{MAX_INGRESS_TTL, PERMITTED_DRIFT, SMALL_APP_SUBNET_MAX_SIZE};
use ic_logger::replica_logger::no_op_logger;
use ic_logger::{error, ReplicaLogger};
use ic_management_canister_types::{
self as ic00, CanisterIdRecord, InstallCodeArgs, MasterPublicKeyId, Method, Payload,
};
use ic_management_canister_types::{
CanisterHttpResponsePayload, CanisterInstallMode, CanisterSettingsArgs,
CanisterSnapshotResponse, CanisterStatusResultV2, ClearChunkStoreArgs, EcdsaCurve, EcdsaKeyId,
InstallChunkedCodeArgs, LoadCanisterSnapshotArgs, SchnorrAlgorithm, SignWithECDSAReply,
SignWithSchnorrReply, TakeCanisterSnapshotArgs, UpdateSettingsArgs, UploadChunkArgs,
UploadChunkReply,
};
use ic_messaging::SyncMessageRouting;
use ic_metrics::MetricsRegistry;
use ic_protobuf::{
registry::{
crypto::v1::{ChainKeySigningSubnetList, PublicKey as PublicKeyProto, X509PublicKeyCert},
node::v1::{ConnectionEndpoint, NodeRecord},
provisional_whitelist::v1::ProvisionalWhitelist as PbProvisionalWhitelist,
replica_version::v1::{BlessedReplicaVersions, ReplicaVersionRecord},
routing_table::v1::{
CanisterMigrations as PbCanisterMigrations, RoutingTable as PbRoutingTable,
},
subnet::v1::CatchUpPackageContents,
},
types::{
v1 as pb,
v1::{PrincipalId as PrincipalIdIdProto, SubnetId as SubnetIdProto},
},
};
use ic_registry_client_fake::FakeRegistryClient;
use ic_registry_client_helpers::{
provisional_whitelist::ProvisionalWhitelistRegistry,
subnet::{SubnetListRegistry, SubnetRegistry},
};
use ic_registry_keys::{
make_blessed_replica_versions_key, make_canister_migrations_record_key,
make_catch_up_package_contents_key, make_chain_key_signing_subnet_list_key,
make_crypto_node_key, make_crypto_tls_cert_key, make_node_record_key,
make_provisional_whitelist_record_key, make_replica_version_key, make_routing_table_record_key,
ROOT_SUBNET_ID_KEY,
};
use ic_registry_proto_data_provider::{ProtoRegistryDataProvider, INITIAL_REGISTRY_VERSION};
use ic_registry_provisional_whitelist::ProvisionalWhitelist;
use ic_registry_routing_table::{
routing_table_insert_subnet, CanisterIdRange, CanisterIdRanges, RoutingTable,
};
use ic_registry_subnet_features::{
ChainKeyConfig, KeyConfig, SubnetFeatures, DEFAULT_ECDSA_MAX_QUEUE_SIZE,
};
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::{
canister_state::{system_state::CyclesUseCase, NumWasmPages, WASM_PAGE_SIZE_IN_BYTES},
metadata_state::subnet_call_context_manager::{SignWithThresholdContext, ThresholdArguments},
page_map::Buffer,
CheckpointLoadingMetrics, Memory, PageMap, ReplicatedState,
};
use ic_state_layout::{CheckpointLayout, ReadOnly};
use ic_state_manager::StateManagerImpl;
use ic_test_utilities::crypto::CryptoReturningOk;
use ic_test_utilities_consensus::FakeConsensusPoolCache;
use ic_test_utilities_metrics::{
fetch_counter_vec, fetch_histogram_stats, fetch_int_counter, fetch_int_gauge,
fetch_int_gauge_vec, Labels,
};
use ic_test_utilities_registry::{
add_single_subnet_record, add_subnet_key_record, add_subnet_list_record, SubnetRecordBuilder,
};
use ic_test_utilities_time::FastForwardTimeSource;
pub use ic_types::ingress::WasmResult;
use ic_types::{
artifact::IngressMessageId,
batch::{
Batch, BatchMessages, BatchSummary, BlockmakerMetrics, ConsensusResponse,
QueryStatsPayload, SelfValidatingPayload, TotalQueryStats, ValidationContext, XNetPayload,
},
canister_http::{CanisterHttpResponse, CanisterHttpResponseContent},
consensus::{
block_maker::SubnetRecords,
certification::{Certification, CertificationContent},
CatchUpPackage,
},
crypto::{
canister_threshold_sig::MasterPublicKey,
threshold_sig::ni_dkg::{NiDkgId, NiDkgTag, NiDkgTargetSubnet, NiDkgTranscript},
AlgorithmId, CombinedThresholdSig, CombinedThresholdSigOf, KeyPurpose, Signable, Signed,
},
malicious_flags::MaliciousFlags,
messages::{
Blob, Certificate, CertificateDelegation, HttpCallContent, HttpCanisterUpdate,
HttpRequestEnvelope, Payload as MsgPayload, Query, QuerySource, RejectContext,
SignedIngress, EXPECTED_MESSAGE_ID_LENGTH,
},
signature::ThresholdSignature,
time::GENESIS,
xnet::{CertifiedStreamSlice, StreamIndex},
CanisterLog, CountBytes, CryptoHashOfPartialState, Height, NodeId, Randomness, RegistryVersion,
ReplicaVersion,
};
use ic_types::{
canister_http::{
CanisterHttpRequestContext, CanisterHttpRequestId, CanisterHttpResponseMetadata,
},
crypto::threshold_sig::ThresholdSigPublicKey,
ingress::{IngressState, IngressStatus},
messages::{CallbackId, MessageId},
time::Time,
CanisterId, CryptoHashOfState, Cycles, NumBytes, PrincipalId, SubnetId, UserId,
};
use ic_xnet_payload_builder::{
certified_slice_pool::CertifiedSlicePool, refill_stream_slice_indices, RefillTaskHandle,
XNetPayloadBuilderImpl, XNetPayloadBuilderMetrics, XNetSlicePoolImpl,
};
use rcgen::{CertificateParams, KeyPair};
use serde::Deserialize;
use ic_error_types::RejectCode;
use maplit::btreemap;
use rand::{rngs::StdRng, Rng, SeedableRng};
use serde::Serialize;
use slog::Level;
use std::{
collections::{BTreeMap, BTreeSet},
convert::TryFrom,
fmt,
io::{self, stderr},
net::Ipv6Addr,
path::{Path, PathBuf},
str::FromStr,
string::ToString,
sync::{atomic::AtomicU64, Arc, Mutex, RwLock},
time::{Duration, Instant, SystemTime},
};
use tempfile::TempDir;
use tokio::{
runtime::Runtime,
sync::{mpsc, watch},
};
use tower::ServiceExt;
/// The size of the channel used to communicate between the [`IngressWatcher`] and
/// execution. Mirrors the size used in production defined in `setup_ic_stack.rs`
const COMPLETED_EXECUTION_MESSAGES_BUFFER_SIZE: usize = 10_000;
#[cfg(test)]
mod tests;
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Deserialize, Serialize)]
pub enum SubmitIngressError {
HttpError(String),
UserError(UserError),
}
struct FakeVerifier;
impl Verifier for FakeVerifier {
fn validate(
&self,
_: SubnetId,
_: &Certification,
_: RegistryVersion,
) -> ValidationResult<VerifierError> {
Ok(())
}
}
/// Adds root subnet ID, routing table, subnet list,
/// and provisional whitelist to the registry.
pub fn finalize_registry(
nns_subnet_id: SubnetId,
routing_table: RoutingTable,
subnet_list: Vec<SubnetId>,
registry_data_provider: Arc<ProtoRegistryDataProvider>,
) {
let registry_version = INITIAL_REGISTRY_VERSION;
let root_subnet_id_proto = SubnetIdProto {
principal_id: Some(PrincipalIdIdProto {
raw: nns_subnet_id.get_ref().to_vec(),
}),
};
registry_data_provider
.add(
ROOT_SUBNET_ID_KEY,
registry_version,
Some(root_subnet_id_proto),
)
.unwrap();
let pb_routing_table = PbRoutingTable::from(routing_table.clone());
registry_data_provider
.add(
&make_routing_table_record_key(),
registry_version,
Some(pb_routing_table),
)
.unwrap();
add_subnet_list_record(®istry_data_provider, registry_version.get(), subnet_list);
let pb_whitelist = PbProvisionalWhitelist::from(ProvisionalWhitelist::All);
registry_data_provider
.add(
&make_provisional_whitelist_record_key(),
registry_version,
Some(pb_whitelist),
)
.unwrap();
let replica_version = ReplicaVersion::default();
let blessed_replica_version = BlessedReplicaVersions {
blessed_version_ids: vec![replica_version.clone().into()],
};
registry_data_provider
.add(
&make_blessed_replica_versions_key(),
registry_version,
Some(blessed_replica_version),
)
.unwrap();
let replica_version_record = ReplicaVersionRecord {
release_package_sha256_hex: "".to_string(),
release_package_urls: vec![],
guest_launch_measurement_sha256_hex: None,
};
registry_data_provider
.add(
&make_replica_version_key(replica_version),
registry_version,
Some(replica_version_record),
)
.unwrap();
}
/// Adds subnet-related records to registry.
/// Note: `finalize_registry` must be called with `routing_table` containing `subnet_id`
/// before any other public method of the `StateMachine` (except for `get_subnet_id`) is invoked.
fn make_nodes_registry(
subnet_id: SubnetId,
subnet_type: SubnetType,
chain_keys_enabled_status: &BTreeMap<MasterPublicKeyId, bool>,
features: SubnetFeatures,
registry_data_provider: Arc<ProtoRegistryDataProvider>,
nodes: &Vec<StateMachineNode>,
is_root_subnet: bool,
public_key: ThresholdSigPublicKey,
ni_dkg_transcript: NiDkgTranscript,
) -> FakeRegistryClient {
let registry_version = if registry_data_provider.is_empty() {
INITIAL_REGISTRY_VERSION
} else {
let latest_registry_version = registry_data_provider.latest_version();
RegistryVersion::from(latest_registry_version.get() + 1)
};
// subnet_id must be different from nns_subnet_id, otherwise
// the IC00 call won't be charged.
let subnet_id_proto = SubnetIdProto {
principal_id: Some(PrincipalIdIdProto {
raw: subnet_id.get_ref().to_vec(),
}),
};
for (key_id, is_enabled) in chain_keys_enabled_status {
if !*is_enabled {
continue;
}
registry_data_provider
.add(
&make_chain_key_signing_subnet_list_key(key_id),
registry_version,
Some(ChainKeySigningSubnetList {
subnets: vec![subnet_id_proto.clone()],
}),
)
.unwrap();
}
for node in nodes {
let node_record = NodeRecord {
node_operator_id: vec![0],
xnet: Some(ConnectionEndpoint {
ip_addr: node.xnet_ip_addr.to_string(),
port: 2497,
}),
http: Some(ConnectionEndpoint {
ip_addr: node.http_ip_addr.to_string(),
port: 8080,
}),
hostos_version_id: None,
chip_id: None,
public_ipv4_config: None,
domain: None,
node_reward_type: None,
};
registry_data_provider
.add(
&make_node_record_key(node.node_id),
registry_version,
Some(node_record),
)
.unwrap();
for (key, key_purpose) in [
(node.node_signing_key.clone(), KeyPurpose::NodeSigning),
(
node.committee_signing_key.clone(),
KeyPurpose::CommitteeSigning,
),
(
node.dkg_dealing_encryption_key.clone(),
KeyPurpose::DkgDealingEncryption,
),
(
node.idkg_mega_encryption_key.clone(),
KeyPurpose::IDkgMEGaEncryption,
),
] {
let node_pk_proto = PublicKeyProto {
algorithm: AlgorithmId::Ed25519 as i32,
key_value: key.public_key().serialize_raw().to_vec(),
version: 0,
proof_data: None,
timestamp: None,
};
registry_data_provider
.add(
&make_crypto_node_key(node.node_id, key_purpose),
registry_version,
Some(node_pk_proto.clone()),
)
.unwrap();
}
let root_key_pair = KeyPair::generate().unwrap();
let root_cert = CertificateParams::new(vec![node.node_id.to_string()])
.unwrap()
.self_signed(&root_key_pair)
.unwrap();
let tls_cert = X509PublicKeyCert {
certificate_der: root_cert.der().to_vec(),
};
registry_data_provider
.add(
&make_crypto_tls_cert_key(node.node_id),
registry_version,
Some(tls_cert),
)
.unwrap();
}
// The following constants were derived from the mainnet config
// using `ic-admin --nns-url https://icp0.io get-topology`.
// Note: The value of the constant `max_ingress_bytes_per_message`
// does not match the corresponding values for the SNS and Bitcoin
// subnets on the IC mainnet. This is because the input parameters
// to this method do not allow to distinguish those two subnets.
let max_ingress_bytes_per_message = match subnet_type {
SubnetType::Application => 2 * 1024 * 1024,
SubnetType::VerifiedApplication => 2 * 1024 * 1024,
SubnetType::System => 3 * 1024 * 1024 + 512 * 1024,
};
let max_ingress_messages_per_block = if is_root_subnet { 400 } else { 1000 };
let max_block_payload_size = 4 * 1024 * 1024;
let node_ids: Vec<_> = nodes.iter().map(|n| n.node_id).collect();
let record = SubnetRecordBuilder::from(&node_ids)
.with_subnet_type(subnet_type)
.with_max_ingress_bytes_per_message(max_ingress_bytes_per_message)
.with_max_ingress_messages_per_block(max_ingress_messages_per_block)
.with_max_block_payload_size(max_block_payload_size)
.with_dkg_interval_length(u64::MAX / 2) // use the genesis CUP throughout the test
.with_chain_key_config(ChainKeyConfig {
key_configs: chain_keys_enabled_status
.iter()
.map(|(key_id, _)| KeyConfig {
key_id: key_id.clone(),
pre_signatures_to_create_in_advance: 1,
max_queue_size: DEFAULT_ECDSA_MAX_QUEUE_SIZE,
})
.collect(),
signature_request_timeout_ns: None,
idkg_key_rotation_period_ms: None,
})
.with_features(features)
.build();
// Insert initial DKG transcripts
let mut high_threshold_transcript = ni_dkg_transcript.clone();
high_threshold_transcript.dkg_id.dkg_tag = NiDkgTag::HighThreshold;
let mut low_threshold_transcript = ni_dkg_transcript;
low_threshold_transcript.dkg_id.dkg_tag = NiDkgTag::LowThreshold;
let cup_contents = CatchUpPackageContents {
initial_ni_dkg_transcript_high_threshold: Some(high_threshold_transcript.into()),
initial_ni_dkg_transcript_low_threshold: Some(low_threshold_transcript.into()),
..Default::default()
};
registry_data_provider
.add(
&make_catch_up_package_contents_key(subnet_id),
registry_version,
Some(cup_contents),
)
.expect("Failed to add subnet record.");
add_single_subnet_record(
®istry_data_provider,
registry_version.get(),
subnet_id,
record,
);
add_subnet_key_record(
®istry_data_provider,
registry_version.get(),
subnet_id,
public_key,
);
let registry_client = FakeRegistryClient::new(Arc::clone(®istry_data_provider) as _);
registry_client.update_to_latest_version();
registry_client
}
/// Convert an object into CBOR binary.
fn into_cbor<R: Serialize>(r: &R) -> Vec<u8> {
let mut ser = serde_cbor::Serializer::new(Vec::new());
ser.self_describe().expect("Could not write magic tag.");
r.serialize(&mut ser).expect("Serialization failed.");
ser.into_inner()
}
fn replica_logger(log_level: Option<Level>) -> ReplicaLogger {
use slog::Drain;
if let Some(log_level) = std::env::var("RUST_LOG")
.ok()
.and_then(|level| Level::from_str(&level).ok())
.or(log_level)
{
let writer: Box<dyn io::Write + Sync + Send> = if std::env::var("LOG_TO_STDERR").is_ok() {
Box::new(stderr())
} else {
Box::new(slog_term::TestStdoutWriter)
};
let decorator = slog_term::PlainSyncDecorator::new(writer);
let drain = slog_term::FullFormat::new(decorator)
.build()
.filter_level(log_level)
.fuse();
let logger = slog::Logger::root(drain, slog::o!());
logger.into()
} else {
no_op_logger()
}
}
/// Bundles the configuration of a `StateMachine`.
#[derive(Clone)]
pub struct StateMachineConfig {
subnet_config: SubnetConfig,
hypervisor_config: HypervisorConfig,
}
impl StateMachineConfig {
pub fn new(subnet_config: SubnetConfig, hypervisor_config: HypervisorConfig) -> Self {
Self {
subnet_config,
hypervisor_config,
}
}
}
/// Struct mocking consensus time required for instantiating `IngressManager`
/// in `StateMachine`.
struct PocketConsensusTime {
t: RwLock<Time>,
}
impl PocketConsensusTime {
fn new(t: Time) -> Self {
Self { t: RwLock::new(t) }
}
/// We need to override the consensus time if the time in `StateMachine` changes.
fn set(&self, t: Time) {
*self.t.write().unwrap() = t;
}
}
impl ConsensusTime for PocketConsensusTime {
fn consensus_time(&self) -> Option<Time> {
Some(*self.t.read().unwrap())
}
}
/// Struct mocking the pool of received ingress messages required for
/// instantiating `IngressManager` in `StateMachine`.
struct PocketIngressPool {
validated: BTreeMap<IngressMessageId, ValidatedIngressArtifact>,
}
impl IngressPool for PocketIngressPool {
fn validated(&self) -> &dyn PoolSection<ValidatedIngressArtifact> {
self
}
fn unvalidated(&self) -> &dyn PoolSection<UnvalidatedIngressArtifact> {
unimplemented!("PocketIngressPool has no unvalidated pool")
}
fn exceeds_limit(&self, _peer_id: &NodeId) -> bool {
false
}
}
impl PoolSection<ValidatedIngressArtifact> for PocketIngressPool {
fn get(&self, message_id: &IngressMessageId) -> Option<&ValidatedIngressArtifact> {
self.validated.get(message_id)
}
fn get_all_by_expiry_range<'a>(
&self,
range: std::ops::RangeInclusive<Time>,
) -> Box<dyn Iterator<Item = &ValidatedIngressArtifact> + '_> {
let (start, end) = range.into_inner();
if end < start {
return Box::new(std::iter::empty());
}
let min_bytes = [0; EXPECTED_MESSAGE_ID_LENGTH];
let max_bytes = [0xff; EXPECTED_MESSAGE_ID_LENGTH];
let range = std::ops::RangeInclusive::new(
IngressMessageId::new(start, MessageId::from(min_bytes)),
IngressMessageId::new(end, MessageId::from(max_bytes)),
);
Box::new(self.validated.range(range).map(|(_, v)| v))
}
fn get_timestamp(&self, message_id: &IngressMessageId) -> Option<Time> {
self.validated.get(message_id).map(|x| x.timestamp)
}
fn size(&self) -> usize {
self.validated.len()
}
}
impl PocketIngressPool {
fn new() -> Self {
Self {
validated: btreemap![],
}
}
/// Pushes a received ingress message into the pool.
fn push(&mut self, m: SignedIngress, timestamp: Time, peer_id: NodeId) {
self.validated.insert(
IngressMessageId::new(m.expiry_time(), m.id()),
ValidatedIngressArtifact {
msg: IngressPoolObject::new(peer_id, m),
timestamp,
},
);
}
}
pub trait Subnets: Send + Sync {
fn insert(&self, state_machine: Arc<StateMachine>);
fn get(&self, subnet_id: SubnetId) -> Option<Arc<StateMachine>>;
}
/// Struct mocking the XNet layer.
struct PocketXNetImpl {
/// Pool of `StateMachine`s from which XNet messages are fetched.
subnets: Arc<dyn Subnets>,
/// The certified slice pool of the `StateMachine` for which the XNet layer is mocked.
pool: Arc<Mutex<CertifiedSlicePool>>,
/// The subnet ID of the `StateMachine` for which the XNet layer is mocked.
own_subnet_id: SubnetId,
}
impl PocketXNetImpl {
fn new(
subnets: Arc<dyn Subnets>,
pool: Arc<Mutex<CertifiedSlicePool>>,
own_subnet_id: SubnetId,
) -> Self {
Self {
subnets,
pool,
own_subnet_id,
}
}
fn refill(&self, registry_version: RegistryVersion, log: ReplicaLogger) {
let refill_stream_slice_indices =
refill_stream_slice_indices(self.pool.clone(), self.own_subnet_id);
for (subnet_id, indices) in refill_stream_slice_indices {
let sm = self.subnets.get(subnet_id).unwrap();
match sm.generate_certified_stream_slice(
self.own_subnet_id,
Some(indices.witness_begin),
Some(indices.msg_begin),
None,
Some(indices.byte_limit),
) {
Ok(slice) => {
if indices.witness_begin != indices.msg_begin {
// Pulled a stream suffix, append to pooled slice.
self.pool
.lock()
.unwrap()
.append(subnet_id, slice, registry_version, log.clone())
.unwrap();
} else {
// Pulled a complete stream, replace pooled slice (if any).
self.pool
.lock()
.unwrap()
.put(subnet_id, slice, registry_version, log.clone())
.unwrap();
}
}
Err(EncodeStreamError::NoStreamForSubnet(_)) => (),
Err(err) => panic!("Unexpected XNetClient error: {}", err),
}
}
}
}
/// A custom `QueryStatsPayloadBuilderImpl` that uses a single
/// `QueryStatsPayloadBuilderImpl` to retrieve total query stats
/// and turns them into a collection of fractional query stats
/// for each node of the corresponding subnet.
/// Those fractional query stats are stored in the field `pending_payloads`
/// until they become part of a block and get `purge`d.
struct PocketQueryStatsPayloadBuilderImpl {
query_stats_payload_builder: Box<dyn BatchPayloadBuilder>,
node_ids: Vec<NodeId>,
pending_payloads: RwLock<Vec<QueryStatsPayload>>,
}
impl PocketQueryStatsPayloadBuilderImpl {
pub(crate) fn new(
query_stats_payload_builder: Box<dyn BatchPayloadBuilder>,
node_ids: Vec<NodeId>,
) -> Self {
Self {
query_stats_payload_builder,
node_ids,
pending_payloads: RwLock::new(Vec::new()),
}
}
pub(crate) fn purge(&self, payload: &QueryStatsPayload) {
assert!(self.pending_payloads.read().unwrap().contains(payload));
self.pending_payloads
.write()
.unwrap()
.retain(|p| p != payload);
}
}
impl BatchPayloadBuilder for PocketQueryStatsPayloadBuilderImpl {
fn build_payload(
&self,
height: Height,
max_size: NumBytes,
past_payloads: &[PastPayload],
context: &ValidationContext,
) -> Vec<u8> {
if let Some(payload) = self.pending_payloads.read().unwrap().iter().next() {
return payload.serialize_with_limit(max_size);
}
let serialized_payload = self.query_stats_payload_builder.build_payload(
height,
max_size,
past_payloads,
context,
);
let num_nodes = self.node_ids.len();
if let Some(payload) = QueryStatsPayload::deserialize(&serialized_payload).unwrap() {
assert!(self.node_ids.contains(&payload.proposer));
*self.pending_payloads.write().unwrap() = self
.node_ids
.iter()
.map(|node_id| {
let mut payload = payload.clone();
payload.proposer = *node_id;
// scale down the stats by the number of nodes
// since they'll be aggregated across all nodes
payload.stats = payload
.stats
.into_iter()
.map(|mut s| {
s.stats.num_calls /= num_nodes as u32;
s.stats.num_instructions /= num_nodes as u64;
s.stats.ingress_payload_size /= num_nodes as u64;
s.stats.egress_payload_size /= num_nodes as u64;
s
})
.collect();
payload
})
.collect();
}
if let Some(payload) = self.pending_payloads.read().unwrap().iter().next() {
payload.serialize_with_limit(max_size)
} else {
vec![]
}
}
fn validate_payload(
&self,
_height: Height,
_proposal_context: &ProposalContext,
_payload: &[u8],
_past_payloads: &[PastPayload],
) -> Result<(), PayloadValidationError> {
Ok(())
}
}
/// A replica node of the subnet with the corresponding `StateMachine`.
pub struct StateMachineNode {
pub node_id: NodeId,
pub node_signing_key: ic_crypto_ed25519::PrivateKey,
pub committee_signing_key: ic_crypto_ed25519::PrivateKey,
pub dkg_dealing_encryption_key: ic_crypto_ed25519::PrivateKey,
pub idkg_mega_encryption_key: ic_crypto_ed25519::PrivateKey,
pub http_ip_addr: Ipv6Addr,
pub xnet_ip_addr: Ipv6Addr,
}
impl StateMachineNode {
fn new(rng: &mut StdRng) -> Self {
let node_signing_key = ic_crypto_ed25519::PrivateKey::deserialize_raw_32(&rng.gen());
let committee_signing_key = ic_crypto_ed25519::PrivateKey::deserialize_raw_32(&rng.gen());
let dkg_dealing_encryption_key =
ic_crypto_ed25519::PrivateKey::deserialize_raw_32(&rng.gen());
let idkg_mega_encryption_key =
ic_crypto_ed25519::PrivateKey::deserialize_raw_32(&rng.gen());
let mut http_ip_addr_bytes = rng.gen::<[u8; 16]>();
http_ip_addr_bytes[0] = 0xe0; // make sure the ipv6 address has no special form
let http_ip_addr = Ipv6Addr::from(http_ip_addr_bytes);
let mut xnet_ip_addr_bytes = rng.gen::<[u8; 16]>();
xnet_ip_addr_bytes[0] = 0xe0; // make sure the ipv6 address has no special form
let xnet_ip_addr = Ipv6Addr::from(xnet_ip_addr_bytes);
Self {
node_id: PrincipalId::new_self_authenticating(
&node_signing_key.public_key().serialize_rfc8410_der(),
)
.into(),
node_signing_key,
committee_signing_key,
dkg_dealing_encryption_key,
idkg_mega_encryption_key,
http_ip_addr,
xnet_ip_addr,
}
}
}
#[allow(clippy::large_enum_variant)]
enum SignatureSecretKey {
EcdsaSecp256k1(ic_crypto_secp256k1::PrivateKey),
SchnorrBip340(ic_crypto_secp256k1::PrivateKey),
Ed25519(ic_crypto_ed25519::DerivedPrivateKey),
}
/// Represents a replicated state machine detached from the network layer that
/// can be used to test this part of the stack in isolation.
pub struct StateMachine {
subnet_id: SubnetId,
subnet_type: SubnetType,
public_key: ThresholdSigPublicKey,
public_key_der: Vec<u8>,
secret_key: SecretKeyBytes,
is_ecdsa_signing_enabled: bool,
is_schnorr_signing_enabled: bool,
registry_data_provider: Arc<ProtoRegistryDataProvider>,
pub registry_client: Arc<FakeRegistryClient>,
pub state_manager: Arc<StateManagerImpl>,
consensus_time: Arc<PocketConsensusTime>,
ingress_pool: Arc<RwLock<PocketIngressPool>>,
ingress_manager: Arc<IngressManager>,
pub ingress_filter: Arc<Mutex<IngressFilterService>>,
pocket_xnet: Arc<RwLock<Option<PocketXNetImpl>>>,
payload_builder: Arc<RwLock<Option<PayloadBuilderImpl>>>,
message_routing: SyncMessageRouting,
pub metrics_registry: MetricsRegistry,
ingress_history_reader: Box<dyn IngressHistoryReader>,
pub query_handler: Arc<Mutex<QueryExecutionService>>,
pub runtime: Arc<Runtime>,
// The atomicity is required for internal mutability and sending across threads.
checkpoint_interval_length: AtomicU64,
nonce: AtomicU64,
// the time used to derive the time of the next round that is:
// - equal to `time` + 1ns if `time` = `time_of_last_round`;
// - equal to `time` otherwise.
time: AtomicU64,
// the time of the last round
// (equal to `time` when this `StateMachine` is initialized)
time_of_last_round: RwLock<Time>,
chain_key_subnet_public_keys: BTreeMap<MasterPublicKeyId, MasterPublicKey>,
chain_key_subnet_secret_keys: BTreeMap<MasterPublicKeyId, SignatureSecretKey>,
pub replica_logger: ReplicaLogger,
pub log_level: Option<Level>,
pub nodes: Vec<StateMachineNode>,
pub batch_summary: Option<BatchSummary>,
time_source: Arc<FastForwardTimeSource>,
consensus_pool_cache: Arc<FakeConsensusPoolCache>,
canister_http_pool: Arc<RwLock<CanisterHttpPoolImpl>>,
canister_http_payload_builder: Arc<CanisterHttpPayloadBuilderImpl>,
certified_height_tx: watch::Sender<Height>,
pub ingress_watcher_handle: IngressWatcherHandle,
/// A drop guard to gracefully cancel the ingress watcher task.
_ingress_watcher_drop_guard: tokio_util::sync::DropGuard,
query_stats_payload_builder: Arc<PocketQueryStatsPayloadBuilderImpl>,
remove_old_states: bool,
// This field must be the last one so that the temporary directory is deleted at the very end.
state_dir: Box<dyn StateMachineStateDir>,
// DO NOT PUT ANY FIELDS AFTER `state_dir`!!!
}
impl Default for StateMachine {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for StateMachine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StateMachine")
.field("state_dir", &self.state_dir.path().display())
.field("nonce", &self.nonce.load(Ordering::Relaxed))
.finish()
}
}
/// A state directory for a `StateMachine` in which
/// the `StateMachine` maintains its state.
pub trait StateMachineStateDir: Send + Sync {
fn path(&self) -> PathBuf;
}
/// A state directory based on a `TempDir` which
/// gets deleted once the `StateMachine` is dropped.
impl StateMachineStateDir for TempDir {
fn path(&self) -> PathBuf {
self.path().to_path_buf()
}
}
/// A state directory based on a `PathBuf` which
/// is persisted once the `StateMachine` is dropped.
/// To reuse the state in another `StateMachine`,
/// you need to run `state_machine.checkpointed_tick()`
/// followed by `state_machine.await_state_hash()`
/// before dropping the `StateMachine`.
impl StateMachineStateDir for PathBuf {
fn path(&self) -> PathBuf {
self.clone()
}
}
pub struct StateMachineBuilder {
state_dir: Box<dyn StateMachineStateDir>,
nonce: u64,
time: Time,
config: Option<StateMachineConfig>,
// The default value `None` is to use 199/499 for system/app subnets.
checkpoint_interval_length: Option<u64>,
subnet_type: SubnetType,
subnet_size: usize,
nns_subnet_id: Option<SubnetId>,
subnet_id: Option<SubnetId>,
routing_table: RoutingTable,
chain_keys_enabled_status: BTreeMap<MasterPublicKeyId, bool>,
ecdsa_signature_fee: Option<Cycles>,
schnorr_signature_fee: Option<Cycles>,
is_ecdsa_signing_enabled: bool,
is_schnorr_signing_enabled: bool,
features: SubnetFeatures,
runtime: Option<Arc<Runtime>>,
registry_data_provider: Arc<ProtoRegistryDataProvider>,
lsmt_override: Option<LsmtConfig>,
is_root_subnet: bool,
seed: [u8; 32],
with_extra_canister_range: Option<std::ops::RangeInclusive<CanisterId>>,
log_level: Option<Level>,
bitcoin_testnet_uds_path: Option<PathBuf>,
remove_old_states: bool,
}
impl StateMachineBuilder {
pub fn new() -> Self {
Self {
state_dir: Box::new(TempDir::new().expect("failed to create a temporary directory")),
nonce: 0,
time: GENESIS,
config: None,
checkpoint_interval_length: None,
subnet_type: SubnetType::System,
subnet_size: SMALL_APP_SUBNET_MAX_SIZE,
nns_subnet_id: None,
subnet_id: None,
routing_table: RoutingTable::new(),
chain_keys_enabled_status: Default::default(),
ecdsa_signature_fee: None,
schnorr_signature_fee: None,
is_ecdsa_signing_enabled: true,
is_schnorr_signing_enabled: true,
features: SubnetFeatures {
http_requests: true,
..SubnetFeatures::default()
},
runtime: None,
registry_data_provider: Arc::new(ProtoRegistryDataProvider::new()),
lsmt_override: None,
is_root_subnet: false,
seed: [42; 32],
with_extra_canister_range: None,
log_level: Some(Level::Warning),
bitcoin_testnet_uds_path: None,
remove_old_states: true,
}
}
pub fn with_lsmt_override(self, lsmt_override: Option<LsmtConfig>) -> Self {
Self {
lsmt_override,
..self
}
}
pub fn with_state_machine_state_dir(self, state_dir: Box<dyn StateMachineStateDir>) -> Self {
Self { state_dir, ..self }
}
fn with_nonce(self, nonce: u64) -> Self {
Self { nonce, ..self }
}
pub fn with_time(self, time: Time) -> Self {
Self { time, ..self }
}
pub fn with_config(self, config: Option<StateMachineConfig>) -> Self {
Self { config, ..self }
}
pub fn with_checkpoints_enabled(self, checkpoints_enabled: bool) -> Self {
let checkpoint_interval_length = if checkpoints_enabled { 0 } else { u64::MAX };
Self {
checkpoint_interval_length: Some(checkpoint_interval_length),
..self
}
}
pub fn with_checkpoint_interval_length(self, checkpoint_interval_length: u64) -> Self {
Self {
checkpoint_interval_length: Some(checkpoint_interval_length),
..self
}