-
Notifications
You must be signed in to change notification settings - Fork 390
Expand file tree
/
Copy pathlib.rs
More file actions
3336 lines (3061 loc) · 127 KB
/
lib.rs
File metadata and controls
3336 lines (3061 loc) · 127 KB
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 ic_base_types::{NumBytes, NumSeconds, PrincipalId, SubnetId};
use ic_config::embedders::{MeteringType, StableMemoryPageLimit};
use ic_config::{
embedders::{Config as EmbeddersConfig, WASM_MAX_SIZE},
execution_environment::Config,
flag_status::FlagStatus,
subnet_config::SchedulerConfig,
subnet_config::SubnetConfig,
};
use ic_crypto_test_utils_reproducible_rng::ReproducibleRng;
use ic_cycles_account_manager::{CyclesAccountManager, ResourceSaturation};
use ic_embedders::{
WasmtimeEmbedder,
wasm_utils::{compile, decoding::decode_wasm},
wasmtime_embedder::system_api::InstructionLimits,
};
use ic_error_types::{ErrorCode, RejectCode, UserError};
pub use ic_execution_environment::ExecutionResponse;
use ic_execution_environment::Ic00MethodPermissions;
use ic_execution_environment::{
CompilationCostHandling, DataCertificateWithDelegationMetadata, ExecuteMessageResult,
ExecuteSubnetMessageResultType, ExecutionEnvironment, ExecutionServicesForTesting, Hypervisor,
IngressFilterMetrics, InternalHttpQueryHandler, RoundInstructions, RoundLimits, WasmSource,
abort_all_paused_executions, execute_canister, wasm_execution_mode,
};
use ic_interfaces::execution_environment::{
ChainKeySettings, ExecutionMode, IngressHistoryWriter, RegistryExecutionSettings,
SubnetAvailableMemory,
};
use ic_interfaces_state_manager::Labeled;
use ic_limits::SMALL_APP_SUBNET_MAX_SIZE;
use ic_logger::{
ReplicaLogger,
replica_logger::{no_op_logger, test_logger},
};
use ic_management_canister_types_private::{
CanisterIdRecord, CanisterInstallMode, CanisterInstallModeV2, CanisterSettingsArgs,
CanisterSettingsArgsBuilder, CanisterStatusResultV2, CanisterStatusType,
CanisterUpgradeOptions, EmptyBlob, InstallChunkedCodeArgs, InstallCodeArgs, InstallCodeArgsV2,
LoadCanisterSnapshotArgs, LogVisibilityV2, MasterPublicKeyId, Method, Payload,
ProvisionalCreateCanisterWithCyclesArgs, SchnorrAlgorithm, UpdateSettingsArgs,
};
use ic_metrics::MetricsRegistry;
use ic_registry_provisional_whitelist::ProvisionalWhitelist;
use ic_registry_resource_limits::ResourceLimits;
use ic_registry_routing_table::{
CANISTER_IDS_PER_SUBNET, CanisterIdRange, RoutingTable, WellFormedError,
};
use ic_registry_subnet_features::SubnetFeatures;
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::{
CallContext, CanisterState, ExecutionState, ExecutionTask, InputQueueType, NetworkTopology,
PageIndex, ReplicatedState, SubnetTopology,
canister_state::{
NextExecution, execution_state::SandboxMemory, execution_state::WasmExecutionMode,
},
metadata_state::testing::NetworkTopologyTesting,
page_map::{
PAGE_SIZE, PageMap, TestPageAllocatorFileDescriptorImpl,
test_utils::base_only_storage_layout,
},
testing::{CanisterQueuesTesting, ReplicatedStateTesting},
};
use ic_test_utilities::state_manager::FakeStateManager;
use ic_test_utilities_types::messages::{IngressBuilder, RequestBuilder, SignedIngressBuilder};
use ic_types::batch::ChainKeyData;
use ic_types::crypto::threshold_sig::ni_dkg::{
NiDkgId, NiDkgMasterPublicKeyId, NiDkgTag, NiDkgTargetSubnet,
};
use ic_types::messages::{Blob, RawSignedSenderInfo, SignedIngressContent, SignedSenderInfo};
use ic_types::{
CanisterId, Height, NumInstructions, QueryStatsEpoch, Time, UserId,
batch::QueryStats,
crypto::{AlgorithmId, canister_threshold_sig::MasterPublicKey},
ingress::{IngressState, IngressStatus, WasmResult},
messages::{
CallbackId, CanisterCall, CanisterMessage, CanisterTask, CertificateDelegationMetadata,
MAX_INTER_CANISTER_PAYLOAD_IN_BYTES, MessageId, Payload as ResponsePayload, Query,
QuerySource, RequestOrResponse, Response, SenderInfo, SubnetMessage,
extract_effective_canister_id,
},
time::UNIX_EPOCH,
};
use ic_types::{ExecutionRound, RegistryVersion, ReplicaVersion};
use ic_types_cycles::{
CanisterCreation, CanisterCyclesCostSchedule, CompoundCycles, Cycles, CyclesUseCase,
HTTPOutcalls, Instructions, NominalCycles, RequestAndResponseTransmission,
};
use ic_types_test_utils::ids::{node_test_id, subnet_test_id, user_test_id};
use ic_universal_canister::{UNIVERSAL_CANISTER_SERIALIZED_MODULE, UNIVERSAL_CANISTER_WASM};
use ic_wasm_types::{BinaryEncodedWasm, CanisterModule, WasmHash};
use maplit::{btreemap, btreeset};
use num_traits::ops::saturating::SaturatingAdd;
use prometheus::IntCounter;
use slog::Level;
use std::{
collections::{BTreeMap, BTreeSet, HashMap},
convert::TryFrom,
os::unix::prelude::FileExt,
str::FromStr,
sync::Arc,
time::Duration,
};
use tempfile::NamedTempFile;
mod wat_canister;
pub use wat_canister::{WatCanisterBuilder, WatFnCode, wat_canister, wat_fn};
const INITIAL_CANISTER_CYCLES: Cycles = Cycles::new(2_500_000_000_000);
// These are well formed example public keys.
// We need to have well formed keys for the "*_public_key" tests, otherwise crypto will
// return an error and we can't test the happy path.
const ECDSA_PUB_KEY: [u8; 33] = [
2, 249, 172, 52, 95, 107, 230, 219, 81, 225, 197, 97, 44, 221, 181, 158, 114, 195, 208, 212,
147, 201, 148, 209, 32, 53, 207, 19, 37, 126, 59, 31, 167,
];
const SCHNORR_BIP340_PUB_KEY: [u8; 33] = [
3, 122, 101, 26, 46, 94, 243, 209, 239, 99, 232, 76, 76, 76, 170, 2, 159, 164, 164, 58, 52,
122, 145, 228, 216, 74, 142, 132, 104, 83, 213, 27, 225,
];
const SCHNORR_ED29915_PUB_KEY: [u8; 32] = [
108, 8, 36, 190, 179, 118, 33, 188, 202, 110, 236, 194, 55, 237, 27, 196, 230, 76, 156, 89,
220, 184, 83, 68, 170, 127, 156, 200, 39, 142, 227, 31,
];
const VETKD_PUB_KEY: [u8; 96] = [
173, 134, 232, 255, 132, 89, 18, 240, 34, 160, 131, 138, 80, 45, 118, 63, 222, 165, 71, 201,
148, 143, 140, 178, 14, 167, 115, 141, 213, 44, 28, 56, 220, 180, 198, 202, 154, 194, 159, 154,
198, 144, 252, 90, 215, 104, 28, 180, 25, 34, 184, 223, 251, 214, 93, 148, 191, 241, 65, 245,
251, 91, 102, 36, 236, 204, 3, 191, 133, 15, 34, 32, 82, 223, 136, 140, 249, 177, 228, 114, 3,
85, 109, 117, 34, 39, 28, 187, 135, 155, 46, 244, 184, 194, 191, 177,
];
/// A helper to create subnets.
pub fn generate_subnets(
subnet_ids: Vec<SubnetId>,
nns_subnet_id: SubnetId,
root_key: Option<Vec<u8>>,
own_subnet_id: SubnetId,
own_subnet_type: SubnetType,
own_subnet_size: usize,
own_subnet_cost_schedule: CanisterCyclesCostSchedule,
own_subnet_admins: BTreeSet<PrincipalId>,
) -> BTreeMap<SubnetId, SubnetTopology> {
let mut result: BTreeMap<SubnetId, SubnetTopology> = Default::default();
for subnet_id in subnet_ids {
let mut subnet_type = SubnetType::System;
let mut nodes = btreeset! {};
let mut cost_schedule = CanisterCyclesCostSchedule::Normal;
let mut subnet_admins = BTreeSet::new();
if subnet_id == own_subnet_id {
subnet_type = own_subnet_type;
cost_schedule = own_subnet_cost_schedule;
// Populate network_topology of own_subnet with fake nodes to simulate subnet_size.
for i in 0..own_subnet_size {
nodes.insert(node_test_id(i as u64));
}
subnet_admins = own_subnet_admins.clone();
}
let public_key = if subnet_id == nns_subnet_id {
root_key.clone().unwrap_or(vec![1, 2, 3, 4])
} else {
vec![1, 2, 3, 4]
};
result.insert(
subnet_id,
SubnetTopology {
public_key,
nodes,
subnet_type,
subnet_features: SubnetFeatures::default(),
chain_keys_held: BTreeSet::new(),
cost_schedule,
subnet_admins,
},
);
}
result
}
pub fn generate_network_topology(
subnet_size: usize,
own_subnet_id: SubnetId,
nns_subnet_id: SubnetId,
own_subnet_type: SubnetType,
subnets: Vec<SubnetId>,
routing_table: Option<RoutingTable>,
own_subnet_cost_schedule: CanisterCyclesCostSchedule,
own_subnet_admins: BTreeSet<PrincipalId>,
) -> NetworkTopology {
let mut topo = NetworkTopology::default();
topo.nns_subnet_id = nns_subnet_id;
topo.set_subnets(generate_subnets(
subnets,
nns_subnet_id,
None,
own_subnet_id,
own_subnet_type,
subnet_size,
own_subnet_cost_schedule,
own_subnet_admins,
));
match routing_table {
Some(rt) => topo.set_routing_table(rt),
None => {
topo.routing_table_mut()
.insert(
CanisterIdRange {
start: CanisterId::from(0),
end: CanisterId::from(CANISTER_IDS_PER_SUBNET - 1),
},
own_subnet_id,
)
.unwrap();
}
}
topo
}
pub fn test_registry_settings() -> RegistryExecutionSettings {
RegistryExecutionSettings {
max_number_of_canisters: 0x2000,
provisional_whitelist: ProvisionalWhitelist::Set(BTreeSet::new()),
chain_key_settings: BTreeMap::new(),
subnet_size: SMALL_APP_SUBNET_MAX_SIZE,
node_ids: (0..SMALL_APP_SUBNET_MAX_SIZE)
.map(|i| node_test_id(i as u64))
.collect(),
registry_version: RegistryVersion::default(),
}
}
/// When a universal canister is installed, but the serialized module has been
/// cached, the test setup thinks the canister was only charged for the reduced
/// compilation cost amount, when it was really charged for the full amount
/// (because it uses the change in round limits instead of what the canister was
/// actually charged). This function returns the amount needed to correct for
/// that difference.
pub fn universal_canister_compilation_cost_correction() -> NumInstructions {
let cost = wasm_compilation_cost(&UNIVERSAL_CANISTER_WASM);
cost - CompilationCostHandling::CountReducedAmount.adjusted_compilation_cost(cost)
}
/// Helper function to test that cycles are reserved for both
/// application and verified application subnets.
///
/// Expects a test function that takes a `SubnetType` as an argument
/// so it can be tested over the desired subnet types.
pub fn cycles_reserved_for_app_and_verified_app_subnets<T: Fn(SubnetType)>(test: T) {
for subnet_type in [SubnetType::Application, SubnetType::VerifiedApplication] {
test(subnet_type);
}
}
struct PausedSubnetMessage {
message: SubnetMessage,
/// cycles for instructions used so far before starting execution of the message
cycles_used_before: NominalCycles,
/// instructions executed by a paused message since the message started execution;
/// the value is reset when the execution gets aborted
instructions: NumInstructions,
}
/// A helper for execution tests.
///
/// Example usage:
/// ```no_run
/// use ic_test_utilities_execution_environment::{*};
/// let mut test = ExecutionTestBuilder::new().build();
/// let wat = r#"(module (func (export "canister_query query")))"#;
/// let canister_id = test.canister_from_wat(wat).unwrap();
/// let result = test.ingress(canister_id, "query", vec![]);
/// expect_canister_did_not_reply(result);
/// ```
pub struct ExecutionTest {
// Mutable fields that change after message execution.
// The current replicated state. The option type allows taking the state for
// execution and then putting it back afterwards.
state: Option<ReplicatedState>,
// Monotonically increasing ingress message id.
message_id: u64,
// The memory available in the subnet.
subnet_available_memory: SubnetAvailableMemory,
// The memory reserved for executing response handlers.
subnet_memory_reservation: NumBytes,
// The pool of callbacks available on the subnet.
subnet_available_callbacks: i64,
// The number of instructions executed so far per canister.
executed_instructions: HashMap<CanisterId, NumInstructions>,
// The total cost of execution so far per canister.
execution_cost: HashMap<CanisterId, CompoundCycles<Instructions>>,
// Tracks paused subnet message executions per canister.
// The value is reset when the execution finishes.
paused_subnet_messages: HashMap<CanisterId, PausedSubnetMessage>,
// Messages to canisters on other subnets.
xnet_messages: Vec<RequestOrResponse>,
// Messages that couldn't be delivered to other canisters
// due to an error in `push_input()`.
lost_messages: Vec<RequestOrResponse>,
// Mutable parameters of execution.
time: Time,
user_id: UserId,
sender_info: Option<SenderInfo>,
current_round: ExecutionRound,
// Read-only fields.
dirty_heap_page_overhead: u64,
instruction_limits: InstructionLimits,
install_code_instruction_limits: InstructionLimits,
instruction_limit_per_query_message: NumInstructions,
initial_canister_cycles: Cycles,
ingress_memory_capacity: NumBytes,
registry_settings: RegistryExecutionSettings,
manual_execution: bool,
caller_canister_id: Option<CanisterId>,
chain_key_data: ChainKeyData,
replica_version: ReplicaVersion,
canister_snapshot_baseline_instructions: NumInstructions,
execution_config: Config,
resource_limits: ResourceLimits,
// The actual implementation.
exec_env: Arc<ExecutionEnvironment>,
query_handler: InternalHttpQueryHandler,
cycles_account_manager: Arc<CyclesAccountManager>,
metrics_registry: MetricsRegistry,
ingress_history_writer: Arc<dyn IngressHistoryWriter<State = ReplicatedState>>,
log: ReplicaLogger,
// Temporary files created to fake checkpoints. They are only stored so that
// they can be properly cleaned up on test completion.
checkpoint_files: Vec<NamedTempFile>,
}
impl ExecutionTest {
pub fn hypervisor_deprecated(&self) -> &Hypervisor {
self.exec_env.hypervisor_for_testing()
}
pub fn execution_environment(&self) -> Arc<ExecutionEnvironment> {
Arc::clone(&self.exec_env)
}
pub fn dirty_heap_page_overhead(&self) -> u64 {
self.dirty_heap_page_overhead
}
pub fn user_id(&self) -> UserId {
self.user_id
}
pub fn set_user_id(&mut self, user_id: UserId) {
self.user_id = user_id
}
pub fn set_sender_info(&mut self, sender_info: SenderInfo) {
self.sender_info = Some(sender_info);
}
pub fn clear_sender_info(&mut self) {
self.sender_info = None;
}
pub fn state(&self) -> &ReplicatedState {
self.state.as_ref().unwrap()
}
pub fn state_mut(&mut self) -> &mut ReplicatedState {
self.state.as_mut().unwrap()
}
pub fn canister_state(&self, canister_id: CanisterId) -> &CanisterState {
self.state().canister_state(&canister_id).unwrap()
}
pub fn install_code_instructions_limit(&self) -> NumInstructions {
self.install_code_instruction_limits.message()
}
pub fn canister_state_mut(&mut self, canister_id: CanisterId) -> &mut CanisterState {
self.state_mut()
.canister_state_make_mut(&canister_id)
.unwrap()
}
pub fn execution_state(&self, canister_id: CanisterId) -> &ExecutionState {
self.canister_state(canister_id)
.execution_state
.as_ref()
.unwrap()
}
pub fn max_instructions_per_message(&self) -> NumInstructions {
self.instruction_limits.message()
}
pub fn canister_wasm_execution_mode(&self, canister_id: CanisterId) -> WasmExecutionMode {
// In case of any error or missing state, default to Wasm32.
if let Some(state) = self.state.as_ref()
&& let Some(canister) = state.canister_state(&canister_id).as_ref()
&& let Some(execution_state) = canister.execution_state.as_ref()
{
return execution_state.wasm_execution_mode;
}
WasmExecutionMode::Wasm32
}
pub fn xnet_messages(&self) -> &Vec<RequestOrResponse> {
&self.xnet_messages
}
pub fn get_xnet_response(&self, index: usize) -> &Arc<Response> {
match &self.xnet_messages[index] {
RequestOrResponse::Request(request) => {
panic!("Expected the xnet message to be a Response, but got a Request: {request:?}")
}
RequestOrResponse::Response(response) => response,
}
}
pub fn lost_messages(&self) -> &Vec<RequestOrResponse> {
&self.lost_messages
}
pub fn subnet_size(&self) -> usize {
self.registry_settings.subnet_size
}
pub fn cost_schedule(&self) -> CanisterCyclesCostSchedule {
self.state.as_ref().unwrap().get_own_cost_schedule()
}
pub fn executed_instructions(&self) -> NumInstructions {
self.executed_instructions.values().sum()
}
pub fn ingress_memory_capacity(&self) -> NumBytes {
self.ingress_memory_capacity
}
pub fn canister_executed_instructions(&self, canister_id: CanisterId) -> NumInstructions {
*self
.executed_instructions
.get(&canister_id)
.unwrap_or(&NumInstructions::new(0))
}
pub fn canister_snapshot_cost(&self, canister_id: CanisterId) -> Cycles {
let canister = self.canister_state(canister_id);
let new_snapshot_size = canister.snapshot_size_bytes();
let instructions = self
.canister_snapshot_baseline_instructions
.saturating_add(&new_snapshot_size.get().into());
self.cycles_account_manager
.management_canister_cost(instructions, self.subnet_size(), self.cost_schedule())
.real()
}
pub fn canister_execution_cost(&self, canister_id: CanisterId) -> CompoundCycles<Instructions> {
*self
.execution_cost
.get(&canister_id)
.unwrap_or(&CompoundCycles::new(Cycles::new(0), self.cost_schedule()))
}
pub fn idle_cycles_burned_per_day(&self, canister_id: CanisterId) -> Cycles {
let memory_usage = self.canister_state(canister_id).memory_usage();
self.idle_cycles_burned_per_day_for_memory_usage(canister_id, memory_usage)
}
pub fn idle_cycles_burned_per_day_for_memory_usage(
&self,
canister_id: CanisterId,
memory_usage: NumBytes,
) -> Cycles {
let memory_allocation = self
.canister_state(canister_id)
.system_state
.memory_allocation;
let compute_allocation = self.canister_state(canister_id).compute_allocation();
let message_memory_usage = self.canister_state(canister_id).message_memory_usage();
self.cycles_account_manager.idle_cycles_burned_rate(
memory_allocation,
memory_usage,
message_memory_usage,
compute_allocation,
self.subnet_size(),
self.cost_schedule(),
)
}
pub fn freezing_threshold(&self, canister_id: CanisterId) -> Cycles {
let canister = self.canister_state(canister_id);
let memory_usage = canister.memory_usage();
let message_memory_usage = canister.message_memory_usage();
let memory_allocation = canister.system_state.memory_allocation;
let compute_allocation = canister.compute_allocation();
let freeze_threshold = canister.system_state.freeze_threshold;
self.cycles_account_manager.freeze_threshold_cycles(
freeze_threshold,
memory_allocation,
memory_usage,
message_memory_usage,
compute_allocation,
self.subnet_size(),
self.cost_schedule(),
canister.system_state.reserved_balance(),
)
}
pub fn call_fee<S: ToString>(
&self,
method_name: S,
payload: &[u8],
) -> CompoundCycles<RequestAndResponseTransmission> {
self.cycles_account_manager
.xnet_call_performed_fee(self.subnet_size(), self.cost_schedule())
+ self.cycles_account_manager.xnet_call_bytes_transmitted_fee(
NumBytes::from((payload.len() + method_name.to_string().len()) as u64),
self.subnet_size(),
self.cost_schedule(),
)
}
pub fn max_response_fee(&self) -> CompoundCycles<RequestAndResponseTransmission> {
self.cycles_account_manager.xnet_call_bytes_transmitted_fee(
MAX_INTER_CANISTER_PAYLOAD_IN_BYTES,
self.subnet_size(),
self.cost_schedule(),
)
}
pub fn reply_fee(&self, payload: &[u8]) -> CompoundCycles<RequestAndResponseTransmission> {
self.cycles_account_manager.xnet_call_bytes_transmitted_fee(
NumBytes::from(payload.len() as u64),
self.subnet_size(),
self.cost_schedule(),
)
}
pub fn reject_fee<S: ToString>(
&self,
reject_message: S,
) -> CompoundCycles<RequestAndResponseTransmission> {
let bytes = reject_message.to_string().len() + std::mem::size_of::<RejectCode>();
self.cycles_account_manager.xnet_call_bytes_transmitted_fee(
NumBytes::from(bytes as u64),
self.subnet_size(),
self.cost_schedule(),
)
}
pub fn canister_creation_fee(&self) -> CompoundCycles<CanisterCreation> {
self.cycles_account_manager
.canister_creation_fee(self.subnet_size(), self.cost_schedule())
}
pub fn http_request_fee(
&self,
request_size: NumBytes,
response_size_limit: Option<NumBytes>,
) -> CompoundCycles<HTTPOutcalls> {
self.cycles_account_manager.http_request_fee(
request_size,
response_size_limit,
self.subnet_size(),
self.cost_schedule(),
)
}
pub fn reduced_wasm_compilation_fee(&self, wasm: &[u8]) -> Cycles {
let cost = wasm_compilation_cost(wasm);
self.convert_instructions_to_cycles(
cost - CompilationCostHandling::CountReducedAmount.adjusted_compilation_cost(cost),
WasmExecutionMode::Wasm32, // In this case it does not matter if it is a Wasm64 or Wasm32 canister.
)
}
pub fn convert_instructions_to_cycles(
&self,
instructions: NumInstructions,
mode: WasmExecutionMode,
) -> Cycles {
self.cycles_account_manager()
.convert_instructions_to_cycles(instructions, mode)
}
pub fn install_code_reserved_execution_cycles(&self) -> Cycles {
let num_instructions = self.install_code_instruction_limits.message();
self.cycles_account_manager
.execution_cost(
num_instructions,
self.subnet_size(),
self.cost_schedule(),
WasmExecutionMode::Wasm32, // For this test, we can assume a Wasm32 execution.
)
.real()
}
pub fn subnet_available_memory(&self) -> SubnetAvailableMemory {
self.subnet_available_memory
}
pub fn set_available_execution_memory(&mut self, execution_memory: i64) {
self.subnet_available_memory = SubnetAvailableMemory::new_for_testing(
execution_memory,
self.subnet_available_memory
.get_guaranteed_response_message_memory(),
self.subnet_available_memory
.get_wasm_custom_sections_memory(),
);
}
fn set_available_guaranteed_response_message_memory(
&mut self,
guaranteed_response_message_memory: i64,
) {
self.subnet_available_memory = SubnetAvailableMemory::new_for_testing(
self.subnet_available_memory.get_execution_memory(),
guaranteed_response_message_memory,
self.subnet_available_memory
.get_wasm_custom_sections_memory(),
);
}
pub fn subnet_available_callbacks(&self) -> i64 {
self.subnet_available_callbacks
}
pub fn set_subnet_available_callbacks(&mut self, callbacks: i64) {
self.subnet_available_callbacks = callbacks
}
pub fn metrics_registry(&self) -> &MetricsRegistry {
&self.metrics_registry
}
pub fn cycles_account_manager(&self) -> &CyclesAccountManager {
&self.cycles_account_manager
}
pub fn time(&self) -> Time {
self.time
}
pub fn advance_time(&mut self, duration: std::time::Duration) {
self.time += duration;
}
pub fn ingress_status(&self, message_id: &MessageId) -> IngressStatus {
self.state().get_ingress_status(message_id).clone()
}
pub fn ingress_result(&self, message_id: &MessageId) -> Result<WasmResult, UserError> {
match self.ingress_state(message_id) {
IngressState::Completed(res) => Ok(res),
IngressState::Failed(err) => Err(err),
status => panic!("Unexpected ingress status: {:?}", status),
}
}
pub fn ingress_state(&self, message_id: &MessageId) -> IngressState {
match self.ingress_status(message_id) {
IngressStatus::Known { state, .. } => state,
IngressStatus::Unknown => unreachable!("Expected a known ingress status."),
}
}
pub fn get_call_context(
&self,
canister_id: CanisterId,
callback_id: CallbackId,
) -> &CallContext {
match self.canister_state(canister_id).status() {
CanisterStatusType::Stopping => {
panic!("Canister status is not running");
}
CanisterStatusType::Running | CanisterStatusType::Stopped => {
let call_context_manager = self
.canister_state(canister_id)
.system_state
.call_context_manager()
.unwrap();
let callback = call_context_manager
.callback(callback_id)
.expect("Unknown callback id.");
call_context_manager
.call_context(callback.call_context_id)
.expect("Unknown call context id.")
}
}
}
/// Sends a `create_canister` message to the IC management canister.
/// Consider using higher-level helpers like `canister_from_wat()`.
pub fn create_canister(&mut self, cycles: Cycles) -> CanisterId {
let args = ProvisionalCreateCanisterWithCyclesArgs::new(Some(cycles.get()), None);
let result =
self.subnet_message(Method::ProvisionalCreateCanisterWithCycles, args.encode());
CanisterIdRecord::decode(&get_reply(result))
.unwrap()
.get_canister_id()
}
/// Deletes the specified canister.
pub fn delete_canister(&mut self, canister_id: CanisterId) -> Result<WasmResult, UserError> {
let payload = CanisterIdRecord::from(canister_id).encode();
self.subnet_message(Method::DeleteCanister, payload)
}
pub fn create_canister_with_allocation(
&mut self,
cycles: Cycles,
compute_allocation: Option<u64>,
memory_allocation: Option<u64>,
) -> Result<CanisterId, UserError> {
self.create_canister_with_settings(
cycles,
CanisterSettingsArgsBuilder::new()
.with_maybe_compute_allocation(compute_allocation)
.with_maybe_memory_allocation(memory_allocation)
.build(),
)
}
pub fn create_canister_with_settings(
&mut self,
cycles: Cycles,
settings: CanisterSettingsArgs,
) -> Result<CanisterId, UserError> {
let mut args = ProvisionalCreateCanisterWithCyclesArgs::new(Some(cycles.get()), None);
args.settings = Some(settings);
let result =
self.subnet_message(Method::ProvisionalCreateCanisterWithCycles, args.encode());
match result {
Ok(WasmResult::Reply(data)) => {
Ok(CanisterIdRecord::decode(&data).unwrap().get_canister_id())
}
Ok(WasmResult::Reject(error)) => {
panic!("Expected reply, got: {error:?}");
}
Err(error) => Err(error),
}
}
/// Updates the compute and memory allocations of the given canister.
pub fn canister_update_allocations_settings(
&mut self,
canister_id: CanisterId,
compute_allocation: Option<u64>,
memory_allocation: Option<u64>,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_maybe_compute_allocation(compute_allocation)
.with_maybe_memory_allocation(memory_allocation)
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
/// Updates the controller of the given canister.
pub fn canister_update_controller(
&mut self,
canister_id: CanisterId,
controllers: Vec<PrincipalId>,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_controllers(controllers)
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
/// Updates the reserved cycles limit of the canister.
pub fn canister_update_reserved_cycles_limit(
&mut self,
canister_id: CanisterId,
reserved_cycles_limit: Cycles,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_reserved_cycles_limit(reserved_cycles_limit.get())
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
pub fn canister_update_wasm_memory_limit(
&mut self,
canister_id: CanisterId,
wasm_memory_limit: NumBytes,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_wasm_memory_limit(wasm_memory_limit.get())
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
pub fn canister_update_wasm_memory_limit_and_wasm_memory_threshold(
&mut self,
canister_id: CanisterId,
wasm_memory_limit: NumBytes,
wasm_memory_threshold: NumBytes,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_wasm_memory_limit(wasm_memory_limit.get())
.with_wasm_memory_threshold(wasm_memory_threshold.get())
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
/// Sends an `install_code` message to the IC management canister.
/// Consider using higher-level helpers like `canister_from_wat()`.
pub fn install_code(&mut self, args: InstallCodeArgs) -> Result<WasmResult, UserError> {
self.subnet_message(Method::InstallCode, args.encode())
}
pub fn install_code_v2(&mut self, args: InstallCodeArgsV2) -> Result<WasmResult, UserError> {
self.subnet_message(Method::InstallCode, args.encode())
}
/// Sends an `install_code` message to the IC management canister with DTS.
/// Similar to `subnet_message()`but does not check the ingress status of
/// the response as the subnet message execution may not finish immediately.
pub fn dts_install_code(&mut self, args: InstallCodeArgs) -> MessageId {
let message_id = self.subnet_message_raw(Method::InstallCode, args.encode());
self.execute_subnet_message();
message_id
}
/// Sends an `uninstall_code` message to the IC management canister.
pub fn uninstall_code(&mut self, canister_id: CanisterId) -> Result<WasmResult, UserError> {
let payload = CanisterIdRecord::from(canister_id).encode();
self.subnet_message(Method::UninstallCode, payload)
}
/// Starts running the given canister.
/// Consider using higher-level helpers like `canister_from_wat()`.
pub fn start_canister(&mut self, canister_id: CanisterId) -> Result<WasmResult, UserError> {
let payload = CanisterIdRecord::from(canister_id).encode();
self.subnet_message(Method::StartCanister, payload)
}
/// Changes the state of the given canister to stopping if it was previously running.
pub fn stop_canister(&mut self, canister_id: CanisterId) -> MessageId {
let payload = CanisterIdRecord::from(canister_id).encode();
let message_id = self.subnet_message_raw(Method::StopCanister, payload);
self.execute_subnet_message();
message_id
}
/// Stops stopping canisters that no longer have open call contexts.
pub fn process_stopping_canisters(&mut self) {
let state = self
.exec_env
.process_stopping_canisters(self.state.take().unwrap());
self.state = Some(state);
}
/// Returns the canister status by canister id.
pub fn canister_status(
&mut self,
canister_id: CanisterId,
) -> Result<CanisterStatusResultV2, UserError> {
let payload = CanisterIdRecord::from(canister_id).encode();
let result = self.subnet_message(Method::CanisterStatus, payload);
match result {
Ok(WasmResult::Reply(bytes)) => Ok(CanisterStatusResultV2::decode(&bytes).unwrap()),
Ok(WasmResult::Reject(err)) => panic!("Unexpected reject: {}", err),
Err(err) => Err(err),
}
}
/// Updates the settings of the given canister.
pub fn update_settings(
&mut self,
canister_id: CanisterId,
settings: CanisterSettingsArgs,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings,
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
/// Updates the freezing threshold of the given canister.
pub fn update_freezing_threshold(
&mut self,
canister_id: CanisterId,
freezing_threshold: NumSeconds,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_freezing_threshold(freezing_threshold.get())
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
/// Sets the controller of the canister to the given principal.
pub fn set_controller(
&mut self,
canister_id: CanisterId,
controller: PrincipalId,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_controllers(vec![controller])
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
/// Sets the log visibility of the canister.
pub fn set_log_visibility(
&mut self,
canister_id: CanisterId,
log_visibility: LogVisibilityV2,
) -> Result<WasmResult, UserError> {
let payload = UpdateSettingsArgs {
canister_id: canister_id.into(),
settings: CanisterSettingsArgsBuilder::new()
.with_log_visibility(log_visibility)
.build(),
sender_canister_version: None,
}
.encode();
self.subnet_message(Method::UpdateSettings, payload)
}
/// Installs the given Wasm binary in the given canister.
pub fn install_canister(
&mut self,
canister_id: CanisterId,
wasm_binary: Vec<u8>,
) -> Result<(), UserError> {
self.install_canister_with_args(canister_id, wasm_binary, vec![])
}
/// Installs the given Wasm binary in the given canister with the given init args.
pub fn install_canister_with_args(
&mut self,
canister_id: CanisterId,
wasm_binary: Vec<u8>,
args: Vec<u8>,
) -> Result<(), UserError> {
let args =
InstallCodeArgs::new(CanisterInstallMode::Install, canister_id, wasm_binary, args);
let result = self.install_code(args)?;
assert_eq!(WasmResult::Reply(EmptyBlob.encode()), result);
Ok(())
}
/// Installs the given Wasm binary in the given canister using `InstallCodeArgsV2`
pub fn install_canister_v2(
&mut self,
canister_id: CanisterId,
wasm_binary: Vec<u8>,
) -> Result<(), UserError> {
let args = InstallCodeArgsV2::new(
CanisterInstallModeV2::Install,
canister_id,
wasm_binary,
vec![],
);
let result = self.install_code_v2(args)?;