/
execution_environment.rs
2493 lines (2348 loc) · 101 KB
/
execution_environment.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 crate::{
canister_manager::{
CanisterManager, CanisterManagerError, CanisterMgrConfig, DtsInstallCodeResult,
InstallCodeContext, PausedInstallCodeExecution, StopCanisterResult,
},
canister_settings::CanisterSettings,
execution::{
inspect_message, nonreplicated_query::execute_non_replicated_query,
replicated_query::execute_replicated_query, response::execute_response,
system_task::execute_canister_task, update::execute_update,
},
execution_environment_metrics::{
ExecutionEnvironmentMetrics, SUBMITTED_OUTCOME_LABEL, SUCCESS_STATUS_LABEL,
},
hypervisor::Hypervisor,
util::candid_error_to_user_error,
NonReplicatedQueryKind,
};
use candid::Encode;
use ic_base_types::PrincipalId;
use ic_config::execution_environment::Config as ExecutionConfig;
use ic_config::flag_status::FlagStatus;
use ic_constants::{LOG_CANISTER_OPERATION_CYCLES_THRESHOLD, SMALL_APP_SUBNET_MAX_SIZE};
use ic_crypto_tecdsa::derive_tecdsa_public_key;
use ic_cycles_account_manager::{CyclesAccountManager, IngressInductionCost};
use ic_error_types::{ErrorCode, RejectCode, UserError};
use ic_ic00_types::{
CanisterHttpRequestArgs, CanisterIdRecord, CanisterSettingsArgs,
ComputeInitialEcdsaDealingsArgs, CreateCanisterArgs, ECDSAPublicKeyArgs,
ECDSAPublicKeyResponse, EcdsaKeyId, EmptyBlob, InstallCodeArgs, Method as Ic00Method,
Payload as Ic00Payload, ProvisionalCreateCanisterWithCyclesArgs, ProvisionalTopUpCanisterArgs,
SetControllerArgs, SetupInitialDKGArgs, SignWithECDSAArgs, UpdateSettingsArgs, IC_00,
};
use ic_interfaces::{
execution_environment::{
ExecutionMode, IngressHistoryWriter, RegistryExecutionSettings, SubnetAvailableMemory,
},
messages::{CanisterCall, CanisterMessage, CanisterMessageOrTask, CanisterTask},
};
use ic_logger::{error, info, warn, ReplicaLogger};
use ic_metrics::{MetricsRegistry, Timer};
use ic_registry_provisional_whitelist::ProvisionalWhitelist;
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::canister_state::NextExecution;
use ic_replicated_state::ExecutionTask;
use ic_replicated_state::{
canister_state::system_state::PausedExecutionId,
metadata_state::subnet_call_context_manager::SubnetCallContext,
};
use ic_replicated_state::{
metadata_state::subnet_call_context_manager::{
EcdsaDealingsContext, SetupInitialDkgContext, SignWithEcdsaContext,
},
CanisterState, NetworkTopology, ReplicatedState,
};
use ic_system_api::{ExecutionParameters, InstructionLimits};
use ic_types::{
canister_http::CanisterHttpRequestContext,
crypto::canister_threshold_sig::{ExtendedDerivationPath, MasterEcdsaPublicKey},
crypto::threshold_sig::ni_dkg::NiDkgTargetId,
ingress::{IngressState, IngressStatus, WasmResult},
messages::{
extract_effective_canister_id, AnonymousQuery, Payload, RejectContext, Request, Response,
SignedIngressContent, StopCanisterContext,
},
nominal_cycles::NominalCycles,
CanisterId, Cycles, LongExecutionMode, NumBytes, NumInstructions, SubnetId, Time,
};
use ic_types::{messages::MessageId, methods::WasmMethod};
use ic_wasm_types::WasmHash;
use lazy_static::lazy_static;
use phantom_newtype::AmountOf;
use prometheus::IntCounter;
use rand::RngCore;
use std::collections::{BTreeMap, HashMap};
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::{convert::Into, convert::TryFrom, sync::Arc};
use strum::ParseError;
#[cfg(test)]
mod tests;
lazy_static! {
/// Track how many system task errors have been encountered
/// so that we can restrict logging to a sample of them.
static ref SYSTEM_TASK_ERROR_COUNT: AtomicU64 = AtomicU64::new(0);
}
/// How often system task errors should be logged to avoid overloading the logs.
const LOG_ONE_SYSTEM_TASK_OUT_OF: u64 = 100;
/// How many first system task messages to log unconditionally.
const LOG_FIRST_N_SYSTEM_TASKS: u64 = 50;
/// The response of the executed message created by the `ic0.msg_reply()`
/// or `ic0.msg_reject()` System API functions.
/// If the execution failed or did not call these System API functions,
/// then the response is empty.
#[derive(Debug)]
pub enum ExecutionResponse {
Ingress((MessageId, IngressStatus)),
Request(Response),
Empty,
}
/// The data structure returned by
/// `ExecutionEnvironment.execute_canister_message()`.
#[derive(Debug)]
pub enum ExecuteMessageResult {
Finished {
/// The new state of the canister after execution.
canister: CanisterState,
/// The response of the executed message. The caller needs to either push it
/// to the output queue of the canister or update the ingress status.
response: ExecutionResponse,
/// The number of instructions used by the message execution.
instructions_used: NumInstructions,
/// The size of the heap delta the canister produced
heap_delta: NumBytes,
},
Paused {
/// The old state of the canister before execution
/// with some changes necessary for DTS.
canister: CanisterState,
/// The paused execution that the caller can either resume or abort.
paused_execution: Box<dyn PausedExecution>,
/// If the original message was an ingress message, then this field
/// contains an ingress status with the state `Processing`.
ingress_status: Option<(MessageId, IngressStatus)>,
},
}
/// Contains round-specific context necessary for resuming a paused execution.
#[derive(Clone)]
pub struct RoundContext<'a> {
pub network_topology: &'a NetworkTopology,
pub hypervisor: &'a Hypervisor,
pub cycles_account_manager: &'a CyclesAccountManager,
pub execution_refund_error_counter: &'a IntCounter,
pub log: &'a ReplicaLogger,
pub time: Time,
}
/// Keeps track of instruction remaining in the current execution round.
/// This type is useful for deterministic time slicing because it allows
/// to distinguish a round instructions from a message instructions.
///
/// Another motivation for this type is that `NumInstructions` is backed
/// by an unsigned integer and loses information below zero whereas this
/// type is signed and works well if Wasm execution overshoots the limit
/// making the remaining instructions negative.
pub struct RoundInstructionsTag;
pub type RoundInstructions = AmountOf<RoundInstructionsTag, i64>;
/// Orphan rules prevent defining `From` / `Into` helpers, so we have to define
/// standalone helpers.
pub fn as_round_instructions(n: NumInstructions) -> RoundInstructions {
RoundInstructions::from(i64::try_from(n.get()).unwrap_or(i64::MAX))
}
pub fn as_num_instructions(a: RoundInstructions) -> NumInstructions {
NumInstructions::from(u64::try_from(a.get()).unwrap_or(0))
}
/// Contains limits (or budget) for various resources that affect duration of
/// a round such as
/// - executed instructions,
/// - produced heap delta,
/// - allocated bytes,
/// - etc.
///
/// This struct is passed by a mutable reference throughout the entire
/// execution layer:
/// - the scheduler initializes the limits at the start of each round.
/// - high-level execution functions pass the reference through.
/// - low-level execution functions decrease the limits based on the data returned
/// by the Wasm executor.
///
/// A recommended pattern for adding a new limit:
/// - the limit is represented as a signed integer to avoid losing information when
/// a Wasm execution overshoots the limit.
/// - the round stops when the limit reaches zero.
/// - the scheduler (and any other high-level caller) can compute consumption of
/// some function `foo()` as follows:
/// ```text
/// let limit_before = round_limits.$limit;
/// foo(..., &mut round_limits);
/// let consumption = limit_before - round_limits.$limit;
/// ```
///
/// Note that other entry-points of the execution layer such as the query handler,
/// inspect message, benchmarks, tests also have to initialize the round limits.
/// In such cases the "round" should be considered as a trivial round consisting
/// of a single message.
#[derive(Debug, Default)]
pub struct RoundLimits {
/// Keeps track of remaining instructions in this execution round.
pub instructions: RoundInstructions,
/// Keeps track of the available storage memory. It decreases if
/// - Wasm execution grows the Wasm/stable memory.
/// - Wasm execution pushes a new request to the output queue.
pub subnet_available_memory: SubnetAvailableMemory,
// TODO would be nice to change that to available, but this requires
// a lot of changes since available allocation sits in CanisterManager config
pub compute_allocation_used: u64,
}
/// Represent a paused execution that can be resumed or aborted.
pub trait PausedExecution: std::fmt::Debug + Send {
/// Resumes a paused execution.
/// It takes:
/// - the canister state,
/// - system parameters that can change while the execution is in progress,
/// - helpers.
///
/// If the execution finishes, then it returns the new canister state and
/// the result of the execution.
fn resume(
self: Box<Self>,
canister: CanisterState,
round_context: RoundContext,
round_limits: &mut RoundLimits,
subnet_size: usize,
) -> ExecuteMessageResult;
/// Aborts the paused execution.
/// Returns the original message and the cycles prepaid for execution.
fn abort(self: Box<Self>, log: &ReplicaLogger) -> (CanisterMessageOrTask, Cycles);
}
/// Stores all paused executions keyed by their ids.
#[derive(Default)]
struct PausedExecutionRegistry {
// A counter that increases monotonically until it wraps around.
// Wrapping around is not a problem because all paused executions
// are aborted before the next checkpoint and there cannot be
// more than 2^64 paused executions between two checkpoints.
next_id: u64,
// Paused executions of ordinary canister messages.
paused_execution: HashMap<PausedExecutionId, Box<dyn PausedExecution>>,
// Paused executions of `install_code` subnet messages.
paused_install_code: HashMap<PausedExecutionId, Box<dyn PausedInstallCodeExecution>>,
}
/// ExecutionEnvironment is the component responsible for executing messages
/// on the IC.
pub struct ExecutionEnvironment {
log: ReplicaLogger,
hypervisor: Arc<Hypervisor>,
canister_manager: CanisterManager,
ingress_history_writer: Arc<dyn IngressHistoryWriter<State = ReplicatedState>>,
metrics: ExecutionEnvironmentMetrics,
config: ExecutionConfig,
cycles_account_manager: Arc<CyclesAccountManager>,
own_subnet_id: SubnetId,
own_subnet_type: SubnetType,
paused_execution_registry: Arc<Mutex<PausedExecutionRegistry>>,
}
/// This is a helper enum that indicates whether the current DTS execution of
/// install_code is the first execution or not.
pub enum DtsInstallCodeStatus {
StartingFirstExecution,
ResumingPausedOrAbortedExecution,
}
impl ExecutionEnvironment {
#[allow(clippy::too_many_arguments)]
pub fn new(
log: ReplicaLogger,
hypervisor: Arc<Hypervisor>,
ingress_history_writer: Arc<dyn IngressHistoryWriter<State = ReplicatedState>>,
metrics_registry: &MetricsRegistry,
own_subnet_id: SubnetId,
own_subnet_type: SubnetType,
compute_capacity: usize,
config: ExecutionConfig,
cycles_account_manager: Arc<CyclesAccountManager>,
) -> Self {
// Assert the flag implication: DTS => sandboxing.
assert!(
config.deterministic_time_slicing == FlagStatus::Disabled
|| config.canister_sandboxing_flag == FlagStatus::Enabled,
"Deterministic time slicing works only with canister sandboxing."
);
let canister_manager_config: CanisterMgrConfig = CanisterMgrConfig::new(
config.subnet_memory_capacity,
config.default_provisional_cycles_balance,
config.default_freeze_threshold,
own_subnet_id,
own_subnet_type,
config.max_controllers,
compute_capacity,
config.rate_limiting_of_instructions,
config.allocatable_compute_capacity_in_percent,
);
let canister_manager = CanisterManager::new(
Arc::clone(&hypervisor),
log.clone(),
canister_manager_config,
Arc::clone(&cycles_account_manager),
Arc::clone(&ingress_history_writer),
);
Self {
log,
hypervisor,
canister_manager,
ingress_history_writer,
metrics: ExecutionEnvironmentMetrics::new(metrics_registry),
config,
cycles_account_manager,
own_subnet_id,
own_subnet_type,
paused_execution_registry: Default::default(),
}
}
/// Look up the current amount of memory available on the subnet.
pub fn subnet_available_memory(&self, state: &ReplicatedState) -> SubnetAvailableMemory {
let (memory_taken, message_memory_taken) = state.total_and_message_memory_taken();
SubnetAvailableMemory::new(
self.config.subnet_memory_capacity.get() as i64 - memory_taken.get() as i64,
self.config.subnet_message_memory_capacity.get() as i64
- message_memory_taken.get() as i64,
)
}
fn verify_sender_id(req: &Request, state: &ReplicatedState) -> Result<(), UserError> {
match state.find_subnet_id(req.sender.into()) {
Ok(sender_subnet_id) => {
if sender_subnet_id == state.metadata.network_topology.nns_subnet_id
|| sender_subnet_id == state.metadata.own_subnet_id
{
Ok(())
} else {
Err(UserError::new(
ErrorCode::CanisterContractViolation,
format!("Incorrect sender subnet id: {sender_subnet_id}. Sender should be on the same subnet or on the NNS subnet."),
))
}
}
Err(err) => Err(err),
}
}
/// Executes a replicated message sent to a subnet.
/// Returns the new replicated state and the number of left instructions.
#[allow(clippy::cognitive_complexity)]
#[allow(clippy::too_many_arguments)]
pub fn execute_subnet_message(
&self,
msg: CanisterMessage,
mut state: ReplicatedState,
instruction_limits: InstructionLimits,
rng: &mut dyn RngCore,
ecdsa_subnet_public_keys: &BTreeMap<EcdsaKeyId, MasterEcdsaPublicKey>,
registry_settings: &RegistryExecutionSettings,
round_limits: &mut RoundLimits,
) -> (ReplicatedState, Option<NumInstructions>) {
let timer = Timer::start(); // Start logging execution time.
let mut msg = match msg {
CanisterMessage::Response(response) => {
let context = state
.metadata
.subnet_call_context_manager
.retrieve_context(response.originator_reply_callback, &self.log);
return match context {
None => (state, Some(NumInstructions::from(0))),
Some(context) => {
let time_elapsed = state.time() - context.get_time();
let request = context.get_request();
self.metrics.observe_subnet_message(
&request.method_name,
time_elapsed.as_secs_f64(),
&match &response.response_payload {
Payload::Data(_) => Ok(()),
Payload::Reject(_) => Err(ErrorCode::CanisterRejectedMessage),
},
);
if matches!(
(&context, &response.response_payload),
(&SubnetCallContext::SignWithEcsda(_), &Payload::Data(_))
) {
state.metadata.subnet_metrics.ecdsa_signature_agreements += 1;
}
state.push_subnet_output_response(
Response {
originator: request.sender,
respondent: CanisterId::from(self.own_subnet_id),
originator_reply_callback: request.sender_reply_callback,
refund: request.payment,
response_payload: response.response_payload.clone(),
}
.into(),
);
(state, Some(NumInstructions::from(0)))
}
};
}
CanisterMessage::Ingress(msg) => CanisterCall::Ingress(msg),
CanisterMessage::Request(msg) => CanisterCall::Request(msg),
};
let method = Ic00Method::from_str(msg.method_name());
let payload = msg.method_payload();
let result = match method {
Ok(Ic00Method::InstallCode) => {
// Tail call is needed for deterministic time slicing here to
// properly handle the case of a paused execution.
return self.execute_install_code(
msg,
None,
DtsInstallCodeStatus::StartingFirstExecution,
state,
instruction_limits,
round_limits,
registry_settings.subnet_size,
);
}
Ok(Ic00Method::SignWithECDSA) => match &msg {
CanisterCall::Request(request) => {
let reject_message = if payload.is_empty() {
"An empty message cannot be signed".to_string()
} else {
String::new()
};
if !reject_message.is_empty() {
use ic_types::messages;
state.push_subnet_output_response(
Response {
originator: request.sender,
respondent: CanisterId::from(self.own_subnet_id),
originator_reply_callback: request.sender_reply_callback,
refund: request.payment,
response_payload: messages::Payload::Reject(
messages::RejectContext {
code: ic_error_types::RejectCode::CanisterReject,
message: reject_message,
},
),
}
.into(),
);
return (state, Some(NumInstructions::from(0)));
}
match SignWithECDSAArgs::decode(payload) {
Err(err) => Some((Err(candid_error_to_user_error(err)), msg.take_cycles())),
Ok(args) => {
match get_master_ecdsa_public_key(
ecdsa_subnet_public_keys,
self.own_subnet_id,
&args.key_id,
) {
Err(err) => Some((Err(err), msg.take_cycles())),
Ok(_) => self
.sign_with_ecdsa(
(**request).clone(),
args.message_hash,
args.derivation_path,
args.key_id,
registry_settings.max_ecdsa_queue_size,
&mut state,
rng,
registry_settings.subnet_size,
)
.map_or_else(
|err| Some((Err(err), msg.take_cycles())),
|()| None,
),
}
}
}
}
CanisterCall::Ingress(_) => {
self.reject_unexpected_ingress(Ic00Method::SignWithECDSA)
}
},
Ok(Ic00Method::CreateCanister) => {
match &mut msg {
CanisterCall::Ingress(_) =>
Some((Err(UserError::new(
ErrorCode::CanisterMethodNotFound,
"create_canister can only be called by other canisters, not via ingress messages.")),
Cycles::zero(),
)),
CanisterCall::Request(req) => {
match Self::verify_sender_id(req, &state) {
Err(err) => Some((Err(err), msg.take_cycles())),
Ok(_) => {
let cycles = Arc::make_mut(req).take_cycles();
match CreateCanisterArgs::decode(req.method_payload()) {
Err(err) => Some((Err(err), cycles)),
Ok(args) => {
// Start logging execution time for `create_canister`.
let timer = Timer::start();
let settings = match args.settings {
None => CanisterSettingsArgs::default(),
Some(settings) => settings,
};
let result = match CanisterSettings::try_from(settings) {
Err(err) => Some((Err(err.into()), cycles)),
Ok(settings) =>
Some(self.create_canister(*msg.sender(), cycles, settings, registry_settings.max_number_of_canisters, &mut state, registry_settings.subnet_size, round_limits))
};
info!(
self.log,
"Finished executing create_canister message after {:?} with result: {:?}",
timer.elapsed(),
result
);
result
}
}
}
}
}
}
}
Ok(Ic00Method::UninstallCode) => {
let res = match CanisterIdRecord::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => self
.canister_manager
.uninstall_code(args.get_canister_id(), *msg.sender(), &mut state)
.map(|()| EmptyBlob.encode())
.map_err(|err| err.into()),
};
Some((res, msg.take_cycles()))
}
Ok(Ic00Method::UpdateSettings) => {
let res = match UpdateSettingsArgs::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => {
// Start logging execution time for `update_settings`.
let timer = Timer::start();
let canister_id = args.get_canister_id();
let result = match CanisterSettings::try_from(args.settings) {
Err(err) => Err(err.into()),
Ok(settings) => self.update_settings(
*msg.sender(),
settings,
canister_id,
&mut state,
round_limits,
),
};
// The induction cost of `UpdateSettings` is charged
// after applying the new settings to allow users to
// decrease the freezing threshold if it was set too
// high that topping up the canister is not feasible.
if let CanisterCall::Ingress(ingress) = &msg {
if let Ok(canister) = get_canister_mut(canister_id, &mut state) {
let bytes_to_charge =
ingress.method_payload.len() + ingress.method_name.len();
let induction_cost = self
.cycles_account_manager
.ingress_induction_cost_from_bytes(
NumBytes::from(bytes_to_charge as u64),
registry_settings.subnet_size,
);
let memory_usage = canister.memory_usage(self.own_subnet_type);
// This call may fail with `CanisterOutOfCyclesError`,
// which is not actionable at this point.
let _ignore_error = self.cycles_account_manager.consume_cycles(
&mut canister.system_state,
memory_usage,
canister.scheduler_state.compute_allocation,
induction_cost,
registry_settings.subnet_size,
);
}
}
info!(
self.log,
"Finished executing update_settings message on canister {:?} after {:?} with result: {:?}",
canister_id,
timer.elapsed(),
result
);
result
}
};
Some((res, msg.take_cycles()))
}
// This API is deprecated and should not be used in new code.
Ok(Ic00Method::SetController) => {
let res = match SetControllerArgs::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => self
.canister_manager
.set_controller(
*msg.sender(),
args.get_canister_id(),
args.get_new_controller(),
&mut state,
round_limits,
)
.map(|()| EmptyBlob.encode())
.map_err(|err| err.into()),
};
Some((res, msg.take_cycles()))
}
Ok(Ic00Method::CanisterStatus) => {
let res = match CanisterIdRecord::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => self.get_canister_status(
*msg.sender(),
args.get_canister_id(),
&mut state,
registry_settings.subnet_size,
),
};
Some((res, msg.take_cycles()))
}
Ok(Ic00Method::StartCanister) => {
let res = match CanisterIdRecord::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => {
self.start_canister(args.get_canister_id(), *msg.sender(), &mut state)
}
};
Some((res, msg.take_cycles()))
}
Ok(Ic00Method::StopCanister) => match CanisterIdRecord::decode(payload) {
Err(err) => Some((Err(candid_error_to_user_error(err)), msg.take_cycles())),
Ok(args) => self.stop_canister(args.get_canister_id(), &msg, &mut state),
},
Ok(Ic00Method::DeleteCanister) => {
let res = match CanisterIdRecord::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => {
// Start logging execution time for `delete_canister`.
let timer = Timer::start();
let result = self
.canister_manager
.delete_canister(*msg.sender(), args.get_canister_id(), &mut state)
.map(|()| EmptyBlob.encode())
.map_err(|err| err.into());
info!(
self.log,
"Finished executing delete_canister message on canister {:?} after {:?} with result: {:?}",
args.get_canister_id(),
timer.elapsed(),
result
);
result
}
};
Some((res, msg.take_cycles()))
}
Ok(Ic00Method::RawRand) => match &msg {
CanisterCall::Ingress(_) => Some((
Err(UserError::new(
ErrorCode::CanisterMethodNotFound,
"raw_rand can only be called by other canisters, not via ingress messages.",
)),
Cycles::zero(),
)),
CanisterCall::Request(req) => match Self::verify_sender_id(req, &state) {
Err(err) => Some((Err(err), msg.take_cycles())),
Ok(_) => {
let res = match EmptyBlob::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(EmptyBlob) => {
let mut buffer = vec![0u8; 32];
rng.fill_bytes(&mut buffer);
Ok(Encode!(&buffer).unwrap())
}
};
Some((res, msg.take_cycles()))
}
},
},
Ok(Ic00Method::DepositCycles) => match CanisterIdRecord::decode(payload) {
Err(err) => Some((Err(candid_error_to_user_error(err)), msg.take_cycles())),
Ok(args) => Some(self.deposit_cycles(args.get_canister_id(), &mut msg, &mut state)),
},
Ok(Ic00Method::HttpRequest) => match state.metadata.own_subnet_features.http_requests {
true => match &msg {
CanisterCall::Request(request) => {
match Self::verify_sender_id(request, &state) {
Err(err) => Some((Err(err), msg.take_cycles())),
Ok(_) => match CanisterHttpRequestArgs::decode(payload) {
Err(err) => {
Some((Err(candid_error_to_user_error(err)), msg.take_cycles()))
}
Ok(args) => match CanisterHttpRequestContext::try_from((
state.time(),
request.as_ref(),
args,
)) {
Err(err) => Some((Err(err.into()), msg.take_cycles())),
Ok(mut canister_http_request_context) => {
let http_request_fee =
self.cycles_account_manager.http_request_fee(
canister_http_request_context.variable_parts_size(),
canister_http_request_context.max_response_bytes,
registry_settings.subnet_size,
);
if request.payment < http_request_fee {
let err = Err(UserError::new(
ErrorCode::CanisterRejectedMessage,
format!(
"http_request request sent with {} cycles, but {} cycles are required.",
request.payment, http_request_fee
),
));
Some((err, msg.take_cycles()))
} else {
canister_http_request_context.request.payment -=
http_request_fee;
state
.metadata
.subnet_metrics
.consumed_cycles_http_outcalls +=
NominalCycles::from(http_request_fee);
state
.metadata
.subnet_call_context_manager
.push_http_request(canister_http_request_context);
self.metrics.observe_message_with_label(
&request.method_name,
timer.elapsed(),
SUBMITTED_OUTCOME_LABEL.into(),
SUCCESS_STATUS_LABEL.into(),
);
None
}
}
},
},
}
}
CanisterCall::Ingress(_) => {
self.reject_unexpected_ingress(Ic00Method::HttpRequest)
}
},
false => {
let err = Err(UserError::new(
ErrorCode::CanisterContractViolation,
"This API is not enabled on this subnet".to_string(),
));
Some((err, msg.take_cycles()))
}
},
Ok(Ic00Method::SetupInitialDKG) => match &msg {
CanisterCall::Request(request) => match SetupInitialDKGArgs::decode(payload) {
Err(err) => Some((Err(candid_error_to_user_error(err)), msg.take_cycles())),
Ok(args) => self
.setup_initial_dkg(*msg.sender(), &args, request, &mut state, rng)
.map_or_else(|err| Some((Err(err), msg.take_cycles())), |()| None),
},
CanisterCall::Ingress(_) => {
self.reject_unexpected_ingress(Ic00Method::SetupInitialDKG)
}
},
Ok(Ic00Method::ECDSAPublicKey) => {
let cycles = msg.take_cycles();
match &msg {
CanisterCall::Request(request) => {
let res = match ECDSAPublicKeyArgs::decode(request.method_payload()) {
Err(err) => Some(Err(candid_error_to_user_error(err))),
Ok(args) => match get_master_ecdsa_public_key(
ecdsa_subnet_public_keys,
self.own_subnet_id,
&args.key_id,
) {
Err(err) => Some(Err(err)),
Ok(pubkey) => {
let canister_id = match args.canister_id {
Some(id) => id.into(),
None => *msg.sender(),
};
Some(
self.get_ecdsa_public_key(
pubkey,
canister_id,
args.derivation_path,
&args.key_id,
)
.map(|res| res.encode()),
)
}
},
};
res.map(|res| (res, cycles))
}
CanisterCall::Ingress(_) => {
self.reject_unexpected_ingress(Ic00Method::ECDSAPublicKey)
}
}
}
Ok(Ic00Method::ComputeInitialEcdsaDealings) => {
let cycles = msg.take_cycles();
match &msg {
CanisterCall::Request(request) => {
let res =
match ComputeInitialEcdsaDealingsArgs::decode(request.method_payload())
{
Err(err) => Some(candid_error_to_user_error(err)),
Ok(args) => match get_master_ecdsa_public_key(
ecdsa_subnet_public_keys,
self.own_subnet_id,
&args.key_id,
) {
Err(err) => Some(err),
Ok(_) => self
.compute_initial_ecdsa_dealings(
&mut state,
msg.sender(),
args,
request,
)
.map_or_else(Some, |()| None),
},
};
res.map(|err| (Err(err), cycles))
}
CanisterCall::Ingress(_) => {
self.reject_unexpected_ingress(Ic00Method::ComputeInitialEcdsaDealings)
}
}
}
Ok(Ic00Method::ProvisionalCreateCanisterWithCycles) => {
let res = match ProvisionalCreateCanisterWithCyclesArgs::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => {
let cycles_amount = args.to_u128();
match CanisterSettings::try_from(args.settings) {
Ok(settings) => self
.canister_manager
.create_canister_with_cycles(
*msg.sender(),
cycles_amount,
settings,
args.specified_id,
&mut state,
®istry_settings.provisional_whitelist,
registry_settings.max_number_of_canisters,
round_limits,
)
.map(|canister_id| CanisterIdRecord::from(canister_id).encode())
.map_err(|err| err.into()),
Err(err) => Err(err.into()),
}
}
};
Some((res, msg.take_cycles()))
}
Ok(Ic00Method::ProvisionalTopUpCanister) => {
let res = match ProvisionalTopUpCanisterArgs::decode(payload) {
Err(err) => Err(candid_error_to_user_error(err)),
Ok(args) => self.add_cycles(
*msg.sender(),
args.get_canister_id(),
args.to_u128(),
&mut state,
®istry_settings.provisional_whitelist,
),
};
Some((res, msg.take_cycles()))
}
Ok(Ic00Method::BitcoinGetBalance) => {
let cycles = msg.take_cycles();
let res = crate::bitcoin::get_balance(msg.method_payload(), &mut state, cycles);
Some(res)
}
Ok(Ic00Method::BitcoinGetUtxos) => {
let cycles = msg.take_cycles();
let res = crate::bitcoin::get_utxos(msg.method_payload(), &mut state, cycles);
Some(res)
}
Ok(Ic00Method::BitcoinGetCurrentFeePercentiles) => {
let cycles = msg.take_cycles();
let res = crate::bitcoin::get_current_fee_percentiles(
msg.method_payload(),
&mut state,
cycles,
);
Some(res)
}
Ok(Ic00Method::BitcoinSendTransaction) => {
let cycles = msg.take_cycles();
let res =
crate::bitcoin::send_transaction(msg.method_payload(), &mut state, cycles);
Some(res)
}
Ok(Ic00Method::BitcoinSendTransactionInternal) => match &msg {
CanisterCall::Request(request) => {
match crate::bitcoin::send_transaction_internal(
&self.config.bitcoin.privileged_access,
request,
&mut state,
) {
Ok(Some(payload)) => Some(Ok(payload)),
Ok(None) => None,
Err(err) => Some(Err(err)),
}
}
CanisterCall::Ingress(_) => self
.reject_unexpected_ingress(Ic00Method::BitcoinGetSuccessors)
.map(|(payload, _)| payload),
}
.map(|payload| (payload, msg.take_cycles())),
Ok(Ic00Method::BitcoinGetSuccessors) => match &msg {
CanisterCall::Request(request) => {
match crate::bitcoin::get_successors(
&self.config.bitcoin.privileged_access,
request,
&mut state,
) {
Ok(Some(payload)) => Some(Ok(payload)),
Ok(None) => None,
Err(err) => Some(Err(err)),
}
}
CanisterCall::Ingress(_) => self
.reject_unexpected_ingress(Ic00Method::BitcoinGetSuccessors)
.map(|(payload, _)| payload),
}
.map(|payload| (payload, msg.take_cycles())),
Err(ParseError::VariantNotFound) => {
let res = Err(UserError::new(
ErrorCode::CanisterMethodNotFound,
format!("Management canister has no method '{}'", msg.method_name()),
));
Some((res, msg.take_cycles()))
}
};
// Note that some branches above like `InstallCode` and `SignWithECDSA`
// have early returns. If you modify code below, please also update
// these cases.
let state = match result {
Some((res, refund)) => {
self.finish_subnet_message_execution(state, msg, res, refund, timer)
}
None => {
// This scenario happens when calling ic00::stop_canister on a
// canister that is already stopping. In this scenario, the
// request is not responded to until the canister has fully
// stopped. At the moment, requests for these metrics are not
// observed since it's not feasible with the current
// architecture to time the request all the way until it is
// responded to (which currently happens in the scheduler).
//
// This scenario also happens in the case of
// Ic00Method::SetupInitialDKG, Ic00Method::HttpRequest, and
// Ic00Method::SignWithECDSA. The request is saved and the
// response from consensus is handled separately.
state
}
};
(state, Some(NumInstructions::from(0)))
}