-
Notifications
You must be signed in to change notification settings - Fork 296
/
lib.rs
1138 lines (1059 loc) · 40.4 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
//! # PocketIC: A Canister Testing Platform
//!
//! PocketIC is the local canister smart contract testing platform for the [Internet Computer](https://internetcomputer.org/).
//!
//! It consists of the PocketIC-server, which can run many independent IC instances, and a client library (this crate), which provides an interface to your IC instances.
//!
//! With PocketIC, testing canisters is as simple as calling rust functions. Here is a minimal example:
//!
//! ```rust
//! use candid;
//! use pocket_ic;
//!
//! #[test]
//! fn test_counter_canister() {
//! let pic = PocketIc::new();
//! // Create an empty canister as the anonymous principal.
//! let canister_id = pic.create_canister(None);
//! let wasm_bytes = load_counter_wasm(...);
//! pic.install_canister(canister_id, wasm_bytes, vec![], None);
//! // 'inc' is a counter canister method.
//! call_counter_canister(&pic, canister_id, "inc");
//! // Check if it had the desired effect.
//! let reply = call_counter_canister(&pic, canister_id, "read");
//! assert_eq!(reply, WasmResult::Reply(vec![0, 0, 0, 1]));
//! }
//!
//! fn call_counter_canister(pic: &PocketIc, canister_id: CanisterId, method: &str) -> WasmResult {
//! pic.update_call(canister_id, Principal::anonymous(), method, encode_one(()).unwrap())
//! .expect("Failed to call counter canister")
//! }
//! ```
//! For more information, see the [README](https://crates.io/crates/pocket-ic).
//!
use crate::common::rest::{
ApiResponse, BlobCompression, BlobId, CreateInstanceResponse, InstanceId, RawAddCycles,
RawCanisterCall, RawCanisterId, RawCanisterResult, RawCycles, RawSetStableMemory,
RawStableMemory, RawTime, RawWasmResult,
};
use candid::{
decode_args, encode_args,
utils::{ArgumentDecoder, ArgumentEncoder},
CandidType, Principal,
};
use common::rest::{
RawEffectivePrincipal, RawSubnetId, RawVerifyCanisterSigArg, SubnetConfigSet, SubnetId,
Topology,
};
use ic_cdk::api::management_canister::{
main::{CanisterInstallMode, CreateCanisterArgument, InstallCodeArgument},
provisional::{CanisterId, CanisterIdRecord, CanisterSettings},
};
use reqwest::Url;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{
path::{Path, PathBuf},
process::Command,
time::{Duration, Instant, SystemTime},
};
use tracing::{debug, instrument};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter;
pub mod common;
const PROCESSING_TIME_HEADER: &str = "processing-timeout-ms";
const PROCESSING_TIME_VALUE_MS: u64 = 300_000;
const LOCALHOST: &str = "127.0.0.1";
const LOG_DIR_PATH_ENV_NAME: &str = "POCKET_IC_LOG_DIR";
const LOG_DIR_LEVELS_ENV_NAME: &str = "POCKET_IC_LOG_DIR_LEVELS";
pub struct PocketIcBuilder {
pub config: SubnetConfigSet,
}
#[allow(clippy::new_without_default)]
impl PocketIcBuilder {
pub fn new() -> Self {
Self {
config: SubnetConfigSet::default(),
}
}
pub fn build(self) -> PocketIc {
PocketIc::from_config(self.config)
}
pub fn with_nns_subnet(self) -> Self {
Self {
config: SubnetConfigSet {
nns: true,
..self.config
},
}
}
pub fn with_sns_subnet(self) -> Self {
Self {
config: SubnetConfigSet {
sns: true,
..self.config
},
}
}
pub fn with_ii_subnet(self) -> Self {
Self {
config: SubnetConfigSet {
ii: true,
..self.config
},
}
}
pub fn with_fiduciary_subnet(self) -> Self {
Self {
config: SubnetConfigSet {
fiduciary: true,
..self.config
},
}
}
pub fn with_bitcoin_subnet(self) -> Self {
Self {
config: SubnetConfigSet {
bitcoin: true,
..self.config
},
}
}
pub fn with_system_subnet(self) -> Self {
Self {
config: SubnetConfigSet {
system: self.config.system + 1,
..self.config
},
}
}
pub fn with_application_subnet(self) -> Self {
Self {
config: SubnetConfigSet {
application: self.config.application + 1,
..self.config
},
}
}
}
/// Main entry point for interacting with PocketIC.
pub struct PocketIc {
/// The unique ID of this PocketIC instance.
pub instance_id: InstanceId,
topology: Topology,
server_url: Url,
reqwest_client: reqwest::blocking::Client,
_log_guard: Option<WorkerGuard>,
}
impl PocketIc {
/// Creates a new PocketIC instance with a single application subnet on the server.
/// The server is started if it's not already running.
pub fn new() -> Self {
PocketIcBuilder::new().with_application_subnet().build()
}
/// Creates a new PocketIC instance with the specified subnet config.
/// The server is started if it's not already running.
pub fn from_config(config: SubnetConfigSet) -> Self {
config.validate().unwrap();
let parent_pid = std::os::unix::process::parent_id();
let log_guard = setup_tracing(parent_pid);
let server_url = crate::start_or_reuse_server();
let reqwest_client = reqwest::blocking::Client::new();
let (instance_id, topology) = match reqwest_client
.post(server_url.join("instances").unwrap())
.json(&config)
.send()
.expect("Failed to get result")
.json::<CreateInstanceResponse>()
.expect("Could not parse response for create instance request")
{
CreateInstanceResponse::Created {
instance_id,
topology,
} => (instance_id, topology),
CreateInstanceResponse::Error { message } => panic!("{}", message),
};
debug!("instance_id={} New instance created.", instance_id);
Self {
instance_id,
topology,
server_url,
reqwest_client,
_log_guard: log_guard,
}
}
/// Returns the topology of the different subnets of this PocketIC instance.
pub fn topology(&self) -> Topology {
self.topology.clone()
}
/// Upload and store a binary blob to the PocketIC server.
#[instrument(ret(Display), skip(self, blob), fields(instance_id=self.instance_id, blob_len = %blob.len(), compression = ?compression))]
pub fn upload_blob(&self, blob: Vec<u8>, compression: BlobCompression) -> BlobId {
let mut request = self
.reqwest_client
.post(self.server_url.join("blobstore/").unwrap())
.body(blob);
if compression == BlobCompression::Gzip {
request = request.header(reqwest::header::CONTENT_ENCODING, "gzip");
}
let blob_id = request
.send()
.expect("Failed to get response")
.text()
.expect("Failed to get text");
let hash_vec = hex::decode(blob_id).expect("Failed to decode hex");
BlobId(hash_vec)
}
/// Set stable memory of a canister. Optional GZIP compression can be used for reduced
/// data traffic.
#[instrument(skip(self, data), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), data_len = %data.len(), compression = ?compression))]
pub fn set_stable_memory(
&self,
canister_id: CanisterId,
data: Vec<u8>,
compression: BlobCompression,
) {
let blob_id = self.upload_blob(data, compression);
let endpoint = "update/set_stable_memory";
self.post::<(), _>(
endpoint,
RawSetStableMemory {
canister_id: canister_id.as_slice().to_vec(),
blob_id,
},
);
}
/// Get stable memory of a canister.
#[instrument(skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string()))]
pub fn get_stable_memory(&self, canister_id: CanisterId) -> Vec<u8> {
let endpoint = "read/get_stable_memory";
let RawStableMemory { blob } = self.post(
endpoint,
RawCanisterId {
canister_id: canister_id.as_slice().to_vec(),
},
);
blob
}
/// List all instances and their status.
#[instrument(ret)]
pub fn list_instances() -> Vec<String> {
let url = crate::start_or_reuse_server().join("instances").unwrap();
let instances: Vec<String> = reqwest::blocking::Client::new()
.get(url)
.send()
.expect("Failed to get result")
.json()
.expect("Failed to get json");
instances
}
/// Verify a canister signature.
#[instrument(skip_all, fields(instance_id=self.instance_id))]
pub fn verify_canister_signature(
&self,
msg: Vec<u8>,
sig: Vec<u8>,
pubkey: Vec<u8>,
root_pubkey: Vec<u8>,
) -> Result<(), String> {
let url = self.server_url.join("verify_signature").unwrap();
reqwest::blocking::Client::new()
.post(url)
.json(&RawVerifyCanisterSigArg {
msg,
sig,
pubkey,
root_pubkey,
})
.send()
.expect("Failed to get result")
.json()
.expect("Failed to get json")
}
/// Make the IC produce and progress by one block.
#[instrument(skip(self), fields(instance_id=self.instance_id))]
pub fn tick(&self) {
let endpoint = "update/tick";
self.post::<(), _>(endpoint, "");
}
/// Get the root key of this IC instance. Returns `None` if the IC has no NNS subnet.
#[instrument(skip(self), fields(instance_id=self.instance_id))]
pub fn root_key(&self) -> Option<Vec<u8>> {
let subnet_id = self.topology.get_nns()?;
let subnet_id: RawSubnetId = subnet_id.into();
let endpoint = "read/pub_key";
let res = self.post::<Vec<u8>, _>(endpoint, subnet_id);
Some(res)
}
/// Get the current time of the IC.
#[instrument(ret, skip(self), fields(instance_id=self.instance_id))]
pub fn get_time(&self) -> SystemTime {
let endpoint = "read/get_time";
let result: RawTime = self.get(endpoint);
SystemTime::UNIX_EPOCH + Duration::from_nanos(result.nanos_since_epoch)
}
/// Set the current time of the IC, on all subnets.
#[instrument(skip(self), fields(instance_id=self.instance_id, time = ?time))]
pub fn set_time(&self, time: SystemTime) {
let endpoint = "update/set_time";
self.post::<(), _>(
endpoint,
RawTime {
nanos_since_epoch: time
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Time went backwards")
.as_nanos() as u64,
},
);
}
/// Advance the time on the IC on all subnets by some nanoseconds.
#[instrument(skip(self), fields(instance_id=self.instance_id, duration = ?duration))]
pub fn advance_time(&self, duration: Duration) {
let now = self.get_time();
self.set_time(now + duration);
}
/// Get the current cycles balance of a canister.
#[instrument(ret, skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string()))]
pub fn cycle_balance(&self, canister_id: CanisterId) -> u128 {
let endpoint = "read/get_cycles";
let result: RawCycles = self.post(
endpoint,
RawCanisterId {
canister_id: canister_id.as_slice().to_vec(),
},
);
result.cycles
}
/// Add cycles to a canister. Returns the new balance.
#[instrument(ret, skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), amount = %amount))]
pub fn add_cycles(&self, canister_id: CanisterId, amount: u128) -> u128 {
let endpoint = "update/add_cycles";
let result: RawCycles = self.post(
endpoint,
RawAddCycles {
canister_id: canister_id.as_slice().to_vec(),
amount,
},
);
result.cycles
}
/// Execute an update call on a canister.
#[instrument(skip(self, payload), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), sender = %sender.to_string(), method = %method, payload_len = %payload.len()))]
pub fn update_call(
&self,
canister_id: CanisterId,
sender: Principal,
method: &str,
payload: Vec<u8>,
) -> Result<WasmResult, UserError> {
let endpoint = "update/execute_ingress_message";
self.canister_call(
endpoint,
RawEffectivePrincipal::None,
canister_id,
sender,
method,
payload,
)
}
/// Execute a query call on a canister.
#[instrument(skip(self, payload), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), sender = %sender.to_string(), method = %method, payload_len = %payload.len()))]
pub fn query_call(
&self,
canister_id: CanisterId,
sender: Principal,
method: &str,
payload: Vec<u8>,
) -> Result<WasmResult, UserError> {
let endpoint = "read/query";
self.canister_call(
endpoint,
RawEffectivePrincipal::None,
canister_id,
sender,
method,
payload,
)
}
/// Create a canister with default settings as the anonymous principal.
#[instrument(ret(Display), skip(self), fields(instance_id=self.instance_id))]
pub fn create_canister(&self) -> CanisterId {
let CanisterIdRecord { canister_id } = call_candid_as(
self,
Principal::management_canister(),
RawEffectivePrincipal::None,
Principal::anonymous(),
"provisional_create_canister_with_cycles",
(CreateCanisterArgument { settings: None },),
)
.map(|(x,)| x)
.unwrap();
canister_id
}
/// Create a canister with optional custom settings and a sender.
#[instrument(ret(Display), skip(self), fields(instance_id=self.instance_id, settings = ?settings, sender = %sender.unwrap_or(Principal::anonymous()).to_string()))]
pub fn create_canister_with_settings(
&self,
sender: Option<Principal>,
settings: Option<CanisterSettings>,
) -> CanisterId {
let CanisterIdRecord { canister_id } = call_candid_as(
self,
Principal::management_canister(),
RawEffectivePrincipal::None,
sender.unwrap_or(Principal::anonymous()),
"provisional_create_canister_with_cycles",
(CreateCanisterArgument { settings },),
)
.map(|(x,)| x)
.unwrap();
canister_id
}
/// Creates a canister with a specific canister ID and optional custom settings.
/// Returns an error if the canister ID is already in use.
/// Panics if the canister ID is not contained in any of the subnets.
///
/// The canister ID must be contained in the Bitcoin, Fiduciary, II, SNS or NNS
/// subnet range, it is not intended to be used on regular app or system subnets,
/// where it can lead to conflicts on which the function panics.
#[instrument(ret, skip(self), fields(instance_id=self.instance_id, sender = %sender.unwrap_or(Principal::anonymous()).to_string(), settings = ?settings, canister_id = %canister_id.to_string()))]
pub fn create_canister_with_id(
&self,
sender: Option<Principal>,
settings: Option<CanisterSettings>,
canister_id: CanisterId,
) -> Result<CanisterId, String> {
let res = call_candid_as(
self,
Principal::management_canister(),
RawEffectivePrincipal::CanisterId(canister_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"provisional_create_canister_with_cycles",
(ProvisionalCreateCanisterArgument {
settings,
specified_id: Some(canister_id),
},),
)
.map(|(x,)| x);
match res {
Ok(CanisterIdRecord {
canister_id: actual_canister_id,
}) => Ok(actual_canister_id),
Err(e) => Err(format!("{:?}", e)),
}
}
/// Create a canister on a specific subnet with optional custom settings.
#[instrument(ret(Display), skip(self), fields(instance_id=self.instance_id, sender = %sender.unwrap_or(Principal::anonymous()).to_string(), settings = ?settings, subnet_id = %subnet_id.to_string()))]
pub fn create_canister_on_subnet(
&self,
sender: Option<Principal>,
settings: Option<CanisterSettings>,
subnet_id: SubnetId,
) -> CanisterId {
let CanisterIdRecord { canister_id } = call_candid_as(
self,
Principal::management_canister(),
RawEffectivePrincipal::SubnetId(subnet_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"provisional_create_canister_with_cycles",
(CreateCanisterArgument { settings },),
)
.map(|(x,)| x)
.unwrap();
canister_id
}
/// Install a WASM module on an existing canister.
#[instrument(skip(self, wasm_module, arg), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), wasm_module_len = %wasm_module.len(), arg_len = %arg.len(), sender = %sender.unwrap_or(Principal::anonymous()).to_string()))]
pub fn install_canister(
&self,
canister_id: CanisterId,
wasm_module: Vec<u8>,
arg: Vec<u8>,
sender: Option<Principal>,
) {
call_candid_as::<(InstallCodeArgument,), ()>(
self,
Principal::management_canister(),
RawEffectivePrincipal::CanisterId(canister_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"install_code",
(InstallCodeArgument {
mode: CanisterInstallMode::Install,
canister_id,
wasm_module,
arg,
},),
)
.unwrap();
}
/// Upgrade a canister with a new WASM module.
#[instrument(skip(self, wasm_module, arg), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), wasm_module_len = %wasm_module.len(), arg_len = %arg.len(), sender = %sender.unwrap_or(Principal::anonymous()).to_string()))]
pub fn upgrade_canister(
&self,
canister_id: CanisterId,
wasm_module: Vec<u8>,
arg: Vec<u8>,
sender: Option<Principal>,
) -> Result<(), CallError> {
call_candid_as::<(InstallCodeArgument,), ()>(
self,
Principal::management_canister(),
RawEffectivePrincipal::CanisterId(canister_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"install_code",
(InstallCodeArgument {
mode: CanisterInstallMode::Upgrade,
canister_id,
wasm_module,
arg,
},),
)
}
/// Reinstall a canister WASM module.
#[instrument(skip(self, wasm_module, arg), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), wasm_module_len = %wasm_module.len(), arg_len = %arg.len(), sender = %sender.unwrap_or(Principal::anonymous()).to_string()))]
pub fn reinstall_canister(
&self,
canister_id: CanisterId,
wasm_module: Vec<u8>,
arg: Vec<u8>,
sender: Option<Principal>,
) -> Result<(), CallError> {
call_candid_as::<(InstallCodeArgument,), ()>(
self,
Principal::management_canister(),
RawEffectivePrincipal::CanisterId(canister_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"install_code",
(InstallCodeArgument {
mode: CanisterInstallMode::Reinstall,
canister_id,
wasm_module,
arg,
},),
)
}
/// Start a canister.
#[instrument(skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), sender = %sender.unwrap_or(Principal::anonymous()).to_string()))]
pub fn start_canister(
&self,
canister_id: CanisterId,
sender: Option<Principal>,
) -> Result<(), CallError> {
call_candid_as::<(CanisterIdRecord,), ()>(
self,
Principal::management_canister(),
RawEffectivePrincipal::CanisterId(canister_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"start_canister",
(CanisterIdRecord { canister_id },),
)
}
/// Stop a canister.
#[instrument(skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), sender = %sender.unwrap_or(Principal::anonymous()).to_string()))]
pub fn stop_canister(
&self,
canister_id: CanisterId,
sender: Option<Principal>,
) -> Result<(), CallError> {
call_candid_as::<(CanisterIdRecord,), ()>(
self,
Principal::management_canister(),
RawEffectivePrincipal::CanisterId(canister_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"stop_canister",
(CanisterIdRecord { canister_id },),
)
}
/// Delete a canister.
#[instrument(skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string(), sender = %sender.unwrap_or(Principal::anonymous()).to_string()))]
pub fn delete_canister(
&self,
canister_id: CanisterId,
sender: Option<Principal>,
) -> Result<(), CallError> {
call_candid_as::<(CanisterIdRecord,), ()>(
self,
Principal::management_canister(),
RawEffectivePrincipal::CanisterId(canister_id.as_slice().to_vec()),
sender.unwrap_or(Principal::anonymous()),
"delete_canister",
(CanisterIdRecord { canister_id },),
)
}
/// Checks whether the provided canister exists.
#[instrument(ret(Display), skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string()))]
pub fn canister_exists(&self, canister_id: CanisterId) -> bool {
self.get_subnet(canister_id).is_some()
}
/// Returns the subnet ID of the canister if the canister exists.
#[instrument(ret, skip(self), fields(instance_id=self.instance_id, canister_id = %canister_id.to_string()))]
pub fn get_subnet(&self, canister_id: CanisterId) -> Option<SubnetId> {
let endpoint = "read/get_subnet";
let result: Option<RawSubnetId> = self.post(
endpoint,
RawCanisterId {
canister_id: canister_id.as_slice().to_vec(),
},
);
result.map(|RawSubnetId { subnet_id }| SubnetId::from_slice(&subnet_id))
}
fn instance_url(&self) -> Url {
self.server_url
.join("/instances/")
.unwrap()
.join(&format!("{}/", self.instance_id))
.unwrap()
}
fn get<T: DeserializeOwned>(&self, endpoint: &str) -> T {
let result = self
.reqwest_client
.get(self.instance_url().join(endpoint).unwrap())
.header(PROCESSING_TIME_HEADER, PROCESSING_TIME_VALUE_MS)
.send()
.expect("HTTP failure");
Self::check_response(result)
}
fn post<T: DeserializeOwned, B: Serialize>(&self, endpoint: &str, body: B) -> T {
let result = self
.reqwest_client
.post(self.instance_url().join(endpoint).unwrap())
.header(PROCESSING_TIME_HEADER, PROCESSING_TIME_VALUE_MS)
.json(&body)
.send()
.expect("HTTP failure");
Self::check_response(result)
}
fn check_response<T: DeserializeOwned>(result: reqwest::blocking::Response) -> T {
match result.into() {
ApiResponse::Success(t) => t,
ApiResponse::Error { message } => panic!("{}", message),
ApiResponse::Busy { state_label, op_id } => {
panic!("Busy: state_label: {}, op_id: {}", state_label, op_id)
}
ApiResponse::Started { state_label, op_id } => {
panic!("Started: state_label: {}, op_id: {}", state_label, op_id)
}
}
}
fn canister_call(
&self,
endpoint: &str,
effective_principal: RawEffectivePrincipal,
canister_id: CanisterId,
sender: Principal,
method: &str,
payload: Vec<u8>,
) -> Result<WasmResult, UserError> {
let raw_canister_call = RawCanisterCall {
sender: sender.as_slice().to_vec(),
canister_id: canister_id.as_slice().to_vec(),
method: method.to_string(),
payload,
effective_principal,
};
let result: RawCanisterResult = self.post(endpoint, raw_canister_call);
match result {
RawCanisterResult::Ok(raw_wasm_result) => match raw_wasm_result {
RawWasmResult::Reply(data) => Ok(WasmResult::Reply(data)),
RawWasmResult::Reject(text) => Ok(WasmResult::Reject(text)),
},
RawCanisterResult::Err(user_error) => Err(user_error),
}
}
fn update_call_with_effective_principal(
&self,
canister_id: CanisterId,
effective_principal: RawEffectivePrincipal,
sender: Principal,
method: &str,
payload: Vec<u8>,
) -> Result<WasmResult, UserError> {
let endpoint = "update/execute_ingress_message";
self.canister_call(
endpoint,
effective_principal,
canister_id,
sender,
method,
payload,
)
}
}
impl Default for PocketIc {
fn default() -> Self {
Self::new()
}
}
impl Drop for PocketIc {
fn drop(&mut self) {
self.reqwest_client
.delete(self.instance_url())
.send()
.expect("Failed to send delete request");
}
}
/// Call a canister candid method, authenticated. The sender can be impersonated (i.e., the
/// signature is not verified).
/// PocketIC executes update calls synchronously, so there is no need to poll for the result.
pub fn call_candid_as<Input, Output>(
env: &PocketIc,
canister_id: CanisterId,
effective_principal: RawEffectivePrincipal,
sender: Principal,
method: &str,
input: Input,
) -> Result<Output, CallError>
where
Input: ArgumentEncoder,
Output: for<'a> ArgumentDecoder<'a>,
{
with_candid(input, |payload| {
env.update_call_with_effective_principal(
canister_id,
effective_principal,
sender,
method,
payload,
)
})
}
/// Call a canister candid method, anonymous.
/// PocketIC executes update calls synchronously, so there is no need to poll for the result.
pub fn call_candid<Input, Output>(
env: &PocketIc,
canister_id: CanisterId,
effective_principal: RawEffectivePrincipal,
method: &str,
input: Input,
) -> Result<Output, CallError>
where
Input: ArgumentEncoder,
Output: for<'a> ArgumentDecoder<'a>,
{
call_candid_as(
env,
canister_id,
effective_principal,
Principal::anonymous(),
method,
input,
)
}
/// Call a canister candid query method, anonymous.
pub fn query_candid<Input, Output>(
env: &PocketIc,
canister_id: CanisterId,
method: &str,
input: Input,
) -> Result<Output, CallError>
where
Input: ArgumentEncoder,
Output: for<'a> ArgumentDecoder<'a>,
{
query_candid_as(env, canister_id, Principal::anonymous(), method, input)
}
/// Call a canister candid query method, authenticated. The sender can be impersonated (i.e., the
/// signature is not verified).
pub fn query_candid_as<Input, Output>(
env: &PocketIc,
canister_id: CanisterId,
sender: Principal,
method: &str,
input: Input,
) -> Result<Output, CallError>
where
Input: ArgumentEncoder,
Output: for<'a> ArgumentDecoder<'a>,
{
with_candid(input, |bytes| {
env.query_call(canister_id, sender, method, bytes)
})
}
/// Call a canister candid update method, anonymous.
pub fn update_candid<Input, Output>(
env: &PocketIc,
canister_id: CanisterId,
method: &str,
input: Input,
) -> Result<Output, CallError>
where
Input: ArgumentEncoder,
Output: for<'a> ArgumentDecoder<'a>,
{
update_candid_as(env, canister_id, Principal::anonymous(), method, input)
}
/// Call a canister candid update method, authenticated. The sender can be impersonated (i.e., the
/// signature is not verified).
pub fn update_candid_as<Input, Output>(
env: &PocketIc,
canister_id: CanisterId,
sender: Principal,
method: &str,
input: Input,
) -> Result<Output, CallError>
where
Input: ArgumentEncoder,
Output: for<'a> ArgumentDecoder<'a>,
{
with_candid(input, |bytes| {
env.update_call(canister_id, sender, method, bytes)
})
}
/// A helper function that we use to implement both [`call_candid`] and
/// [`query_candid`].
pub fn with_candid<Input, Output>(
input: Input,
f: impl FnOnce(Vec<u8>) -> Result<WasmResult, UserError>,
) -> Result<Output, CallError>
where
Input: ArgumentEncoder,
Output: for<'a> ArgumentDecoder<'a>,
{
let in_bytes = encode_args(input).expect("failed to encode args");
match f(in_bytes) {
Ok(WasmResult::Reply(out_bytes)) => Ok(decode_args(&out_bytes).unwrap_or_else(|e| {
panic!(
"Failed to decode response as candid type {}:\nerror: {}\nbytes: {:?}\nutf8: {}",
std::any::type_name::<Output>(),
e,
out_bytes,
String::from_utf8_lossy(&out_bytes),
)
})),
Ok(WasmResult::Reject(message)) => Err(CallError::Reject(message)),
Err(user_error) => Err(CallError::UserError(user_error)),
}
}
fn setup_tracing(pid: u32) -> Option<WorkerGuard> {
use tracing_subscriber::prelude::*;
match std::env::var(LOG_DIR_PATH_ENV_NAME).map(std::path::PathBuf::from) {
Ok(p) => {
std::fs::create_dir_all(&p).expect("Could not create directory");
let file_name = format!("pocket_ic_client_{pid}.log");
let appender = tracing_appender::rolling::never(&p, file_name);
let (non_blocking_appender, guard) = tracing_appender::non_blocking(appender);
let log_dir_filter: EnvFilter =
tracing_subscriber::EnvFilter::try_from_env(LOG_DIR_LEVELS_ENV_NAME)
.unwrap_or_else(|_| "trace".parse().unwrap());
let layers = vec![tracing_subscriber::fmt::layer()
.with_writer(non_blocking_appender)
// disable color escape codes in files
.with_ansi(false)
.with_filter(log_dir_filter)
.boxed()];
let _ = tracing_subscriber::registry().with(layers).try_init();
Some(guard)
}
_ => None,
}
}
#[derive(
CandidType, Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default,
)]
struct ProvisionalCreateCanisterArgument {
pub settings: Option<CanisterSettings>,
pub specified_id: Option<Principal>,
}
/// Error type for [`TryFrom<u64>`].
#[derive(Clone, Copy, Debug)]
pub enum TryFromError {
ValueOutOfRange(u64),
}
/// User-facing error codes.
///
/// The error codes are currently assigned using an HTTP-like
/// convention: the most significant digit is the corresponding reject
/// code and the rest is just a sequentially assigned two-digit
/// number.
#[derive(PartialOrd, Ord, Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ErrorCode {
SubnetOversubscribed = 101,
MaxNumberOfCanistersReached = 102,
CanisterQueueFull = 201,
IngressMessageTimeout = 202,
CanisterQueueNotEmpty = 203,
IngressHistoryFull = 204,
CanisterIdAlreadyExists = 205,
CanisterNotFound = 301,
CanisterMethodNotFound = 302,
CanisterAlreadyInstalled = 303,
CanisterWasmModuleNotFound = 304,
InsufficientMemoryAllocation = 402,
InsufficientCyclesForCreateCanister = 403,
SubnetNotFound = 404,
CanisterNotHostedBySubnet = 405,
CanisterOutOfCycles = 501,
CanisterTrapped = 502,
CanisterCalledTrap = 503,
CanisterContractViolation = 504,
CanisterInvalidWasm = 505,
CanisterDidNotReply = 506,
CanisterOutOfMemory = 507,
CanisterStopped = 508,
CanisterStopping = 509,
CanisterNotStopped = 510,
CanisterStoppingCancelled = 511,
CanisterInvalidController = 512,
CanisterFunctionNotFound = 513,
CanisterNonEmpty = 514,
CertifiedStateUnavailable = 515,
CanisterRejectedMessage = 516,
QueryCallGraphLoopDetected = 517,
UnknownManagementMessage = 518,
InvalidManagementPayload = 519,
InsufficientCyclesInCall = 520,
CanisterWasmEngineError = 521,
CanisterInstructionLimitExceeded = 522,
CanisterInstallCodeRateLimited = 523,
CanisterMemoryAccessLimitExceeded = 524,
QueryCallGraphTooDeep = 525,
QueryCallGraphTotalInstructionLimitExceeded = 526,
CompositeQueryCalledInReplicatedMode = 527,
QueryTimeLimitExceeded = 528,
QueryCallGraphInternal = 529,
InsufficientCyclesInComputeAllocation = 530,
InsufficientCyclesInMemoryAllocation = 531,
InsufficientCyclesInMemoryGrow = 532,
ReservedCyclesLimitExceededInMemoryAllocation = 533,
ReservedCyclesLimitExceededInMemoryGrow = 534,
InsufficientCyclesInMessageMemoryGrow = 535,
}
impl TryFrom<u64> for ErrorCode {
type Error = TryFromError;
fn try_from(err: u64) -> Result<ErrorCode, Self::Error> {
match err {
101 => Ok(ErrorCode::SubnetOversubscribed),
102 => Ok(ErrorCode::MaxNumberOfCanistersReached),
201 => Ok(ErrorCode::CanisterQueueFull),
202 => Ok(ErrorCode::IngressMessageTimeout),
203 => Ok(ErrorCode::CanisterQueueNotEmpty),
204 => Ok(ErrorCode::IngressHistoryFull),
205 => Ok(ErrorCode::CanisterIdAlreadyExists),
301 => Ok(ErrorCode::CanisterNotFound),
302 => Ok(ErrorCode::CanisterMethodNotFound),