-
Notifications
You must be signed in to change notification settings - Fork 295
/
util.rs
1751 lines (1616 loc) · 60 KB
/
util.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_agent::CanisterAgent;
use crate::canister_api::GenericRequest;
use crate::driver::group::{MAX_RUNTIME_BLOCKING_THREADS, MAX_RUNTIME_THREADS};
use crate::driver::test_env_api::*;
use crate::generic_workload_engine::{engine::Engine, metrics::LoadTestMetrics};
use crate::retry_with_msg;
use crate::retry_with_msg_async;
use crate::types::*;
use anyhow::bail;
use candid::{Decode, Encode};
use canister_test::{Canister, RemoteTestRuntime, Runtime, Wasm};
use dfn_protobuf::{protobuf, ProtoBuf};
use futures::future::{join_all, select_all, try_join_all};
use futures::FutureExt;
use ic_agent::export::Principal;
use ic_agent::identity::BasicIdentity;
use ic_agent::{
agent::{http_transport::reqwest_transport::ReqwestTransport, RejectCode, RejectResponse},
Agent, AgentError, Identity, RequestId,
};
use ic_canister_client::{Agent as DeprecatedAgent, Sender};
use ic_config::ConfigOptional;
use ic_constants::MAX_INGRESS_TTL;
use ic_management_canister_types::{CanisterStatusResult, EmptyBlob, Payload};
use ic_message::ForwardParams;
use ic_nervous_system_proto::pb::v1::GlobalTimeOfDay;
use ic_nns_constants::{GOVERNANCE_CANISTER_ID, ROOT_CANISTER_ID};
use ic_nns_governance::pb::v1::{
create_service_nervous_system::SwapParameters, CreateServiceNervousSystem,
};
use ic_nns_test_utils::governance::upgrade_nns_canister_with_args_by_proposal;
use ic_registry_subnet_type::SubnetType;
use ic_rosetta_api::convert::to_arg;
use ic_sns_swap::pb::v1::{NeuronBasketConstructionParameters, Params};
use ic_types::{CanisterId, Cycles, PrincipalId};
use ic_universal_canister::{
call_args, wasm as universal_canister_argument_builder, UNIVERSAL_CANISTER_WASM,
};
use ic_utils::call::AsyncCall;
use ic_utils::interfaces::ManagementCanister;
use icp_ledger::{
tokens_from_proto, AccountBalanceArgs, AccountIdentifier, Memo, SendArgs, Subaccount, Tokens,
DEFAULT_TRANSFER_FEE,
};
use itertools::Itertools;
use on_wire::FromWire;
use slog::{debug, info};
use std::collections::BTreeMap;
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
use std::{
convert::{TryFrom, TryInto},
fmt::Debug,
future::Future,
net::IpAddr,
time::{Duration, Instant},
};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::net::{TcpSocket, TcpStream};
use tokio::runtime::Builder;
use tokio::runtime::Handle as THandle;
use url::Url;
pub mod delegations;
pub const CANISTER_FREEZE_BALANCE_RESERVE: Cycles = Cycles::new(5_000_000_000_000);
pub const CYCLES_LIMIT_PER_CANISTER: Cycles = Cycles::new(100_000_000_000_000);
pub const AGENT_REQUEST_TIMEOUT: Duration = Duration::from_secs(20);
pub const IDENTITY_PEM:&str = "-----BEGIN PRIVATE KEY-----\nMFMCAQEwBQYDK2VwBCIEILhMGpmYuJ0JEhDwocj6pxxOmIpGAXZd40AjkNhuae6q\noSMDIQBeXC6ae2dkJ8QC50bBjlyLqsFQFsMsIThWB21H6t6JRA==\n-----END PRIVATE KEY-----";
/// A short wasm module that is a legal canister binary.
pub(crate) const _EMPTY_WASM: &[u8] = &[0, 97, 115, 109, 1, 0, 0, 0];
/// The following definition is a temporary work-around. Please do not copy!
pub(crate) const MESSAGE_CANISTER_WASM: &[u8] = include_bytes!("message.wasm");
pub(crate) const CFG_TEMPLATE_BYTES: &[u8] =
include_bytes!("../../../ic-os/guestos/rootfs/opt/ic/share/ic.json5.template");
pub fn get_identity() -> ic_agent::identity::BasicIdentity {
ic_agent::identity::BasicIdentity::from_pem(IDENTITY_PEM.as_bytes())
.expect("Invalid secret key.")
}
/// Initializes a testing [Runtime] from a node's url. You should really
/// think of this runtime as a _HTTP Agent_, perhaps one day we should rename
/// it. Anyway, the [Runtime] is used to talk to a node in a caching manner.
///
/// We use the [Runtime] to install and interact with canisters. It might be
/// tempting to pack a [Runtime] and a [Canister<'_>] into the same struct but
/// this can lead to inconsistent data if we install a canister from one node's
/// runtime but delete it from another node's runtime.
pub fn runtime_from_url(url: Url, effective_canister_id: PrincipalId) -> Runtime {
let agent = DeprecatedAgent::new(
url,
Sender::from_keypair(&ic_test_identity::TEST_IDENTITY_KEYPAIR),
);
Runtime::Remote(RemoteTestRuntime {
agent,
effective_canister_id,
})
}
/// Provides an abstraction to the universal canister.
#[derive(Clone)]
pub struct UniversalCanister<'a> {
agent: &'a Agent,
canister_id: Principal,
}
impl<'a> UniversalCanister<'a> {
/// Initializes a [UniversalCanister] using the provided [Agent] and
/// allocates some stable memory at canister installation.
pub async fn new(
agent: &'a Agent,
effective_canister_id: PrincipalId,
) -> UniversalCanister<'a> {
Self::new_with_params(agent, effective_canister_id, None, None, None)
.await
.expect("Could not create universal canister.")
}
pub async fn try_new(
agent: &'a Agent,
effective_canister_id: PrincipalId,
) -> Result<UniversalCanister<'a>, String> {
Self::new_with_params(agent, effective_canister_id, None, None, None).await
}
pub async fn new_with_retries(
agent: &'a Agent,
effective_canister_id: PrincipalId,
log: &slog::Logger,
) -> UniversalCanister<'a> {
retry_with_msg_async!(
format!(
"install UniversalCanister {}",
effective_canister_id.to_string()
),
log,
READY_WAIT_TIMEOUT,
RETRY_BACKOFF,
|| async {
match Self::new_with_params(agent, effective_canister_id, None, None, None).await {
Ok(c) => Ok(c),
Err(e) => anyhow::bail!(e),
}
}
)
.await
.expect("Could not create universal canister.")
}
pub async fn new_with_cycles_with_retries<C: Into<u128>>(
agent: &'a Agent,
effective_canister_id: PrincipalId,
cycles: C,
log: &slog::Logger,
) -> UniversalCanister<'a> {
let c = cycles.into();
retry_with_msg_async!(
format!(
"install UniversalCanister {}",
effective_canister_id.to_string()
),
log,
READY_WAIT_TIMEOUT,
RETRY_BACKOFF,
|| async {
match Self::new_with_cycles(agent, effective_canister_id, c).await {
Ok(c) => Ok(c),
Err(e) => anyhow::bail!(e),
}
}
)
.await
.expect("Could not create universal canister with cycles.")
}
pub async fn new_with_params_with_retries(
agent: &'a Agent,
effective_canister_id: PrincipalId,
compute_allocation: Option<u64>,
cycles: Option<u128>,
pages: Option<u32>,
log: &slog::Logger,
) -> UniversalCanister<'a> {
retry_with_msg_async!(
format!(
"install UniversalCanister {}",
effective_canister_id.to_string()
),
log,
READY_WAIT_TIMEOUT,
RETRY_BACKOFF,
|| async {
match Self::new_with_params(
agent,
effective_canister_id,
compute_allocation,
cycles,
pages,
)
.await
{
Ok(c) => Ok(c),
Err(e) => anyhow::bail!(e),
}
}
)
.await
.expect("Could not create universal canister with params.")
}
pub async fn new_with_params(
agent: &'a Agent,
effective_canister_id: PrincipalId,
compute_allocation: Option<u64>,
cycles: Option<u128>,
pages: Option<u32>,
) -> Result<UniversalCanister<'a>, String> {
let pages = pages.unwrap_or(1);
let payload = universal_canister_argument_builder()
.stable_grow(pages)
.build();
// Create a canister.
let mgr = ManagementCanister::create(agent);
let canister_id = mgr
.create_canister()
.with_optional_compute_allocation(compute_allocation)
.as_provisional_create_with_amount(cycles)
.with_effective_canister_id(effective_canister_id)
.call_and_wait()
.await
.map_err(|err| format!("Couldn't create canister with provisional API: {}", err))?
.0;
// Install the universal canister.
mgr.install_code(&canister_id, UNIVERSAL_CANISTER_WASM)
.with_raw_arg(payload.clone())
.call_and_wait()
.await
.map_err(|err| format!("Couldn't install universal canister: {}", err))?;
Ok(Self { agent, canister_id })
}
pub async fn new_with_cycles<C: Into<u128>>(
agent: &'a Agent,
effective_canister_id: PrincipalId,
cycles: C,
) -> Result<UniversalCanister<'a>, String> {
let payload = universal_canister_argument_builder().stable_grow(1).build();
// Create a canister.
let mgr = ManagementCanister::create(agent);
let canister_id = mgr
.create_canister()
.as_provisional_create_with_amount(Some(cycles.into()))
.with_effective_canister_id(effective_canister_id)
.call_and_wait()
.await
.unwrap_or_else(|err| panic!("Couldn't create canister with provisional API: {}", err))
.0;
// Install the universal canister.
mgr.install_code(&canister_id, UNIVERSAL_CANISTER_WASM)
.with_raw_arg(payload.clone())
.call_and_wait()
.await
.map_err(|err| format!("Couldn't install universal canister: {}", err))?;
Ok(Self { agent, canister_id })
}
pub async fn new_with_64bit_stable_memory(
agent: &'a Agent,
effective_canister_id: PrincipalId,
) -> Result<UniversalCanister<'a>, String> {
let payload = universal_canister_argument_builder()
.stable64_grow(1)
.build();
// Create a canister.
let mgr = ManagementCanister::create(agent);
let canister_id = mgr
.create_canister()
.as_provisional_create_with_amount(None)
.with_effective_canister_id(effective_canister_id)
.call_and_wait()
.await
.map_err(|err| format!("Couldn't create canister with provisional API: {}", err))?
.0;
// Install the universal canister.
mgr.install_code(&canister_id, UNIVERSAL_CANISTER_WASM)
.with_raw_arg(payload.clone())
.call_and_wait()
.await
.map_err(|err| format!("Couldn't install universal canister: {}", err))?;
Ok(Self { agent, canister_id })
}
/// Initializes a universal canister wrapper from a canister id. Does /NOT/
/// perform any installation operation on the runtime.
pub fn from_canister_id(agent: &'a Agent, canister_id: Principal) -> UniversalCanister<'a> {
Self { agent, canister_id }
}
/// Upgrades an NNS canister to universal abilities (by proposal),
/// preserving the Id.
pub async fn upgrade(
runtime: &'a Runtime,
agent: &'a Agent,
nns_canister_id: &CanisterId,
) -> UniversalCanister<'a> {
let can = Canister::new(runtime, *nns_canister_id);
let governance = Canister::new(runtime, GOVERNANCE_CANISTER_ID);
let root = Canister::new(runtime, ROOT_CANISTER_ID);
upgrade_nns_canister_with_args_by_proposal(
&can,
&governance,
&root,
true,
Wasm::from_bytes(UNIVERSAL_CANISTER_WASM.to_vec()),
vec![],
)
.await;
Self::from_canister_id(
agent,
Principal::try_from(nns_canister_id.get().to_vec()).unwrap(),
)
}
pub async fn upgrade_with_args(
runtime: &'a Runtime,
agent: &'a Agent,
nns_canister_id: &CanisterId,
args: Vec<u8>,
) -> UniversalCanister<'a> {
let can = Canister::new(runtime, *nns_canister_id);
let governance = Canister::new(runtime, GOVERNANCE_CANISTER_ID);
let root = Canister::new(runtime, ROOT_CANISTER_ID);
upgrade_nns_canister_with_args_by_proposal(
&can,
&governance,
&root,
true,
Wasm::from_bytes(UNIVERSAL_CANISTER_WASM.to_vec()),
args,
)
.await;
Self::from_canister_id(
agent,
Principal::try_from(nns_canister_id.get().to_vec()).unwrap(),
)
}
/// Builds the arguments to use with stable writer
pub fn stable_writer(offset: u32, msg: &[u8]) -> Vec<u8> {
universal_canister_argument_builder()
.stable_write(offset, msg)
.reply()
.build()
}
/// Try to store `msg` in stable memory starting at `offset` bytes.
pub async fn try_store_to_stable(&self, offset: u32, msg: &[u8]) -> Result<(), AgentError> {
let res = self
.agent
.update(&self.canister_id, "update")
.with_arg(Self::stable_writer(offset, msg))
.call_and_wait()
.await;
match res {
Ok(_) => Ok(()),
Err(err) => Err(err),
}
}
/// Stores `msg` in stable memory starting at `offset` bytes.
pub async fn store_to_stable(&self, offset: u32, msg: &[u8]) {
self.agent
.update(&self.canister_id, "update")
.with_arg(Self::stable_writer(offset, msg))
.call_and_wait()
.await
.unwrap_or_else(|err| panic!("Could not push message to stable: {}", err));
}
/// Tries to read `len` bytes of the stable memory, starting from `offset`.
pub async fn read_stable(&self, offset: u32, len: u32) -> Result<Vec<u8>, AgentError> {
self.agent
.query(&self.canister_id, "query")
.with_arg(
universal_canister_argument_builder()
.stable_read(offset, len)
.reply_data_append()
.reply()
.build(),
)
.call()
.await
}
/// Tries to read `len` bytes of the stable memory, starting from `offset`.
/// Panics if the read could not be performed.
pub async fn try_read_stable(&self, offset: u32, len: u32) -> Vec<u8> {
self.read_stable(offset, len).await.unwrap_or_else(|err| {
panic!("could not read message of len {} from stable: {}", len, err)
})
}
/// Tries to read `len` bytes of the stable memory, starting from `offset`.
/// Panics if the read could not be performed after `max_retries`.
pub async fn try_read_stable_with_retries(
&self,
log: &slog::Logger,
offset: u32,
len: u32,
max_retries: u64,
retry_wait: Duration,
) -> Vec<u8> {
for i in 0..max_retries + 1 {
debug!(log, "Reading from stable memory, attempt {}.", i + 1);
let result = self.read_stable(offset, len).await;
match result {
Ok(message) => return message,
Err(err) => {
debug!(log, "Couldn't read from stable memory, err={}", err);
debug!(log, "Retrying in {} secs ...", retry_wait.as_secs());
tokio::time::sleep(retry_wait).await;
}
}
}
panic!(
"Could not read message from stable memory after {} retries.",
max_retries
);
}
/// Forwards a message to the `receiver` that calls
/// `receiver.method(payload)` along with the specified amount of cycles
/// and returns the result.
pub async fn forward_with_cycles_to(
&self,
receiver: &Principal,
method: &str,
payload: Vec<u8>,
cycles: Cycles,
) -> Result<Vec<u8>, AgentError> {
let universal_canister_payload = universal_canister_argument_builder()
.call_with_cycles(
// The universal canister API expects a `PrincipalId`.
PrincipalId::try_from(receiver.as_slice()).unwrap(),
method,
call_args().other_side(payload).on_reject(
universal_canister_argument_builder()
.reject_message()
.reject(),
),
cycles,
)
.build();
self.agent
.update(&self.canister_id, "update")
.with_arg(universal_canister_payload)
.call_and_wait()
.await
}
/// Forwards a message to the `receiver` that calls
/// `receiver.method(payload)` and returns the result.
pub async fn forward_to(
&self,
receiver: &Principal,
method: &str,
payload: Vec<u8>,
) -> Result<Vec<u8>, AgentError> {
self.forward_with_cycles_to(
receiver,
method,
payload,
Cycles::zero(), /* no cycles */
)
.await
}
pub fn canister_id(&self) -> Principal {
self.canister_id
}
pub async fn query<P: Into<Vec<u8>>>(&self, payload: P) -> Result<Vec<u8>, AgentError> {
self.agent
.query(&self.canister_id, "query")
.with_arg(payload.into())
.call()
.await
}
pub async fn replicated_query<P: Into<Vec<u8>>>(
&self,
payload: P,
) -> Result<Vec<u8>, AgentError> {
self.agent
.update(&self.canister_id, "query")
.with_arg(payload.into())
.call_and_wait()
.await
}
pub async fn composite_query<P: Into<Vec<u8>>>(
&self,
payload: P,
) -> Result<Vec<u8>, AgentError> {
self.agent
.query(&self.canister_id, "composite_query")
.with_arg(payload.into())
.call()
.await
}
pub async fn update<P: Into<Vec<u8>>>(&self, payload: P) -> Result<Vec<u8>, AgentError> {
self.agent
.update(&self.canister_id, "update")
.with_arg(payload.into())
.call_and_wait()
.await
}
}
/// Provides an abstraction to the message canister.
#[derive(Clone)]
pub struct MessageCanister<'a> {
agent: &'a Agent,
canister_id: Principal,
}
impl<'a> MessageCanister<'a> {
/// Initializes a [MessageCanister] using the provided [Agent].
pub async fn new(agent: &'a Agent, effective_canister_id: PrincipalId) -> MessageCanister<'a> {
Self::new_with_params(agent, effective_canister_id, None, None)
.await
.expect("Could not create message canister.")
}
pub async fn try_new(
agent: &'a Agent,
effective_canister_id: PrincipalId,
) -> Result<MessageCanister<'a>, String> {
Self::new_with_params(agent, effective_canister_id, None, None).await
}
pub async fn new_with_retries(
agent: &'a Agent,
effective_canister_id: PrincipalId,
log: &slog::Logger,
timeout: Duration,
backoff: Duration,
) -> MessageCanister<'a> {
retry_with_msg_async!(
format!(
"install UniversalCanister {}",
effective_canister_id.to_string()
),
log,
timeout,
backoff,
|| async {
match Self::new_with_params(agent, effective_canister_id, None, None).await {
Ok(c) => Ok(c),
Err(e) => anyhow::bail!(e),
}
}
)
.await
.expect("Could not create message canister.")
}
pub async fn new_with_params(
agent: &'a Agent,
effective_canister_id: PrincipalId,
compute_allocation: Option<u64>,
cycles: Option<u128>,
) -> Result<MessageCanister<'a>, String> {
// Create a canister.
let mgr = ManagementCanister::create(agent);
let canister_id = mgr
.create_canister()
.with_optional_compute_allocation(compute_allocation)
.as_provisional_create_with_amount(cycles)
.with_effective_canister_id(effective_canister_id)
.call_and_wait()
.await
.map_err(|err| format!("Couldn't create canister with provisional API: {}", err))?
.0;
// Install the universal canister.
mgr.install_code(&canister_id, MESSAGE_CANISTER_WASM)
.call_and_wait()
.await
.map_err(|err| format!("Couldn't install message canister: {}", err))?;
Ok(Self { agent, canister_id })
}
pub async fn new_with_cycles<C: Into<u128>>(
agent: &'a Agent,
effective_canister_id: PrincipalId,
cycles: C,
) -> MessageCanister<'a> {
// Create a canister.
let mgr = ManagementCanister::create(agent);
let canister_id = mgr
.create_canister()
.as_provisional_create_with_amount(Some(cycles.into()))
.with_effective_canister_id(effective_canister_id)
.call_and_wait()
.await
.unwrap_or_else(|err| panic!("Couldn't create canister with provisional API: {}", err))
.0;
// Install the universal canister.
mgr.install_code(&canister_id, MESSAGE_CANISTER_WASM)
.call_and_wait()
.await
.unwrap_or_else(|err| panic!("Couldn't install message canister: {}", err));
Self { agent, canister_id }
}
pub fn canister_id(&self) -> Principal {
self.canister_id
}
/// Initializes a message canister wrapper from a canister id. Does /NOT/
/// perform any installation operation on the runtime.
pub fn from_canister_id(agent: &'a Agent, canister_id: Principal) -> MessageCanister<'a> {
Self { agent, canister_id }
}
/// Forwards a message to the `receiver` that calls
/// `receiver.method(payload)` along with the specified amount of cycles
/// and returns the result.
pub async fn forward_with_cycles_to(
&self,
receiver: &Principal,
method: &str,
payload: Vec<u8>,
cycles: Cycles,
) -> Result<Vec<u8>, AgentError> {
let params = ForwardParams {
receiver: Principal::from_slice(receiver.as_slice()),
method: method.to_string(),
cycles: cycles.get(),
payload,
};
let arg = Encode!(¶ms).unwrap();
self.agent
.update(&self.canister_id, "forward")
.with_arg(arg)
.call_and_wait()
.await
.map(|bytes| Decode!(&bytes, Vec<u8>).unwrap())
}
/// Forwards a message to the `receiver` that calls
/// `receiver.method(payload)` and returns the result.
pub async fn forward_to(
&self,
receiver: &Principal,
method: &str,
payload: Vec<u8>,
) -> Result<Vec<u8>, AgentError> {
self.forward_with_cycles_to(
receiver,
method,
payload,
Cycles::zero(), /* no cycles */
)
.await
}
pub async fn try_store_msg<P: Into<String>>(&self, msg: P) -> Result<(), AgentError> {
self.agent
.update(&self.canister_id, "store")
.with_arg(Encode!(&msg.into()).unwrap())
.call_and_wait()
.await
.map(|_| ())
}
pub async fn store_msg<P: Into<String>>(&self, msg: P) {
self.try_store_msg(msg)
.await
.unwrap_or_else(|err| panic!("Could not store message: {}", err))
}
pub async fn try_read_msg(&self) -> Result<Option<String>, String> {
self.agent
.query(&self.canister_id, "read")
.with_arg(Encode!(&()).unwrap())
.call()
.await
.map_err(|e| e.to_string())
.and_then(|r| Decode!(r.as_slice(), Option<String>).map_err(|e| e.to_string()))
}
pub async fn read_msg(&self) -> Option<String> {
self.try_read_msg()
.await
.unwrap_or_else(|err| panic!("Could not read message: {}", err))
}
}
/// Initializes an `Agent` using the provided URL.
/// The root key is fetched as part of the initialization in order
/// to validate certificates from the replica.
pub async fn assert_create_agent(url: &str) -> Agent {
let start = Instant::now();
while start.elapsed() < READY_WAIT_TIMEOUT {
if let Ok(v) = create_agent(url).await {
return v;
}
tokio::time::sleep(RETRY_BACKOFF).await;
}
create_agent(url)
.await
.unwrap_or_else(|err| panic!("Failed to create agent for {}: {:?}", url, err))
}
/// Initializes an `Agent` using the provided URL and identity.
pub async fn assert_create_agent_with_identity(
url: &str,
identity: impl Identity + Clone + 'static,
) -> Agent {
let start = Instant::now();
while start.elapsed() < READY_WAIT_TIMEOUT {
if let Ok(v) = agent_with_identity(url, identity.clone()).await {
return v;
}
tokio::time::sleep(RETRY_BACKOFF).await;
}
agent_with_identity(url, identity)
.await
.unwrap_or_else(|err| panic!("Failed to create agent for {}: {:?}", url, err))
}
pub async fn create_agent(url: &str) -> Result<Agent, AgentError> {
agent_with_identity(url, get_identity()).await
}
pub async fn create_agent_mapping(url: &str, addr_mapping: IpAddr) -> Result<Agent, AgentError> {
agent_with_identity_mapping(url, Some(addr_mapping), get_identity()).await
}
pub async fn agent_with_identity(
url: &str,
identity: impl Identity + 'static,
) -> Result<Agent, AgentError> {
agent_with_identity_mapping(url, None, identity).await
}
pub async fn agent_with_identity_mapping(
url: &str,
addr_mapping: Option<IpAddr>,
identity: impl Identity + 'static,
) -> Result<Agent, AgentError> {
let builder = reqwest::Client::builder()
.timeout(AGENT_REQUEST_TIMEOUT)
.danger_accept_invalid_certs(true);
let builder = match (
addr_mapping,
reqwest::Url::parse(url).as_ref().map(|u| u.domain()),
) {
(Some(addr_mapping), Ok(Some(domain))) => builder.resolve(domain, (addr_mapping, 0).into()),
_ => builder,
};
let client = builder
.build()
.map_err(|err| AgentError::TransportError(Box::new(err)))?;
agent_with_client_identity(url, client, identity).await
}
pub async fn agent_with_client_identity(
url: &str,
client: reqwest::Client,
identity: impl Identity + 'static,
) -> Result<Agent, AgentError> {
let a = Agent::builder()
.with_transport(ReqwestTransport::create_with_client(url, client)?)
.with_identity(identity)
// Ingresses are created with the system time but are checked against the consensus time.
// Consensus time is the time that is in the last finalized block. Consensus time might lag
// behind, for example when the subnet has many modes and the progress of consensus is
// computaionally heavy for the system to deal with in time. In such cases, the consensus
// time might be 'x', while the system time is x+2sn, for example. When the handlers check
// the validity of ingresses, they expect the expiry time to be between x and
// x+MAX_INGRESS_TTL. If we used MAX_INGRESS_TTL as the expiry delay while creating the
// ingresses as well, we would set the ingresses' expiry_time to x+MAX_INGRESS_TTL+2sn in
// this case. Then, such ingresses would get rejected by the replica as their expiry_time is
// too further in the future, i.e. greater than x+MAX_INGRESS_TTL in this case. To tolerate
// the delays in the progress of consensus, we reduce 30sn from MAX_INGRESS_TTL and set the
// expiry_time of ingresses accordingly.
.with_ingress_expiry(Some(MAX_INGRESS_TTL - std::time::Duration::from_secs(30)))
.build()
.unwrap();
a.fetch_root_key().await?;
Ok(a)
}
// Creates an identity to be used with `Agent`.
pub fn random_ed25519_identity() -> BasicIdentity {
let rng = ring::rand::SystemRandom::new();
let key_pair = ring::signature::Ed25519KeyPair::generate_pkcs8(&rng)
.expect("Could not generate a key pair.");
BasicIdentity::from_key_pair(
ring::signature::Ed25519KeyPair::from_pkcs8(key_pair.as_ref())
.expect("Could not read the key pair."),
)
}
pub fn get_nns_node(topo_snapshot: &TopologySnapshot) -> IcNodeSnapshot {
let nns_node = topo_snapshot.root_subnet().nodes().next().unwrap();
nns_node.await_status_is_healthy().unwrap();
nns_node
}
pub fn get_app_subnet_and_node(
topo_snapshot: &TopologySnapshot,
) -> (SubnetSnapshot, IcNodeSnapshot) {
let app_subnet = topo_snapshot
.subnets()
.find(|subnet| subnet.subnet_type() == SubnetType::Application)
.expect("there is no application subnet");
let app_node = app_subnet
.nodes()
.next()
.expect("there is no application node");
app_node.await_status_is_healthy().unwrap();
(app_subnet, app_node)
}
// This indirectly asserts a non-zero finalization rate of the subnet:
// - We store a string in the memory by sending an `update` message to a canister
// - We retrieve the saved string by sending `query` message to a canister
pub(crate) async fn assert_subnet_can_make_progress(message: &[u8], node: &IcNodeSnapshot) {
let agent = assert_create_agent(node.get_public_url().as_str()).await;
let universal_canister = UniversalCanister::new(&agent, node.effective_canister_id()).await;
universal_canister.store_to_stable(0, message).await;
assert_eq!(
universal_canister
.try_read_stable(0, message.len() as u32)
.await,
message.to_vec()
);
}
pub(crate) fn assert_reject<T: std::fmt::Debug>(res: Result<T, AgentError>, code: RejectCode) {
match res {
Ok(val) => panic!("Expected call to fail but it succeeded with {:?}", val),
Err(agent_error) => match agent_error {
AgentError::UncertifiedReject(RejectResponse {
reject_code,
reject_message,
..
}) => assert_eq!(
code, reject_code,
"Expect code {:?} did not match {:?}. Reject message: {}",
code, reject_code, reject_message
),
AgentError::CertifiedReject(RejectResponse {
reject_code,
reject_message,
..
}) => assert_eq!(
code, reject_code,
"Expect code {:?} did not match {:?}. Reject message: {}",
code, reject_code, reject_message
),
others => panic!(
"Expected call to fail with a replica error but got {:?} instead",
others
),
},
}
}
pub(crate) fn assert_reject_msg<T: std::fmt::Debug>(
res: Result<T, AgentError>,
code: RejectCode,
partial_message: &str,
) {
match res {
Ok(val) => panic!("Expected call to fail but it succeeded with {:?}", val),
Err(agent_error) => match agent_error {
AgentError::CertifiedReject(RejectResponse {
reject_code,
reject_message,
..
}) => {
assert_eq!(
code, reject_code,
"Expect code {:?} did not match {:?}. Reject message: {}",
code, reject_code, reject_message
);
assert!(
reject_message.contains(partial_message),
"Actual reject message: {}",
reject_message
);
}
AgentError::UncertifiedReject(RejectResponse {
reject_code,
reject_message,
..
}) => {
assert_eq!(
code, reject_code,
"Expect code {:?} did not match {:?}. Reject message: {}",
code, reject_code, reject_message
);
assert!(
reject_message.contains(partial_message),
"Actual reject message: {}",
reject_message
);
}
others => panic!(
"Expected call to fail with a replica error but got {:?} instead",
others
),
},
}
}
#[derive(Clone, Copy, Debug)]
pub enum EndpointsStatus {
AllHealthy,
AllUnhealthy,
}
pub(crate) fn assert_nodes_health_statuses(
log: slog::Logger,
nodes: &[IcNodeSnapshot],
status: EndpointsStatus,
) {
let nodes_with_undesired_status = || {
let health_statuses = nodes.iter().map(|n| (n, n.status_is_healthy()));
match status {
EndpointsStatus::AllHealthy => health_statuses
.into_iter()
.filter_map(|(n, s)| s.map_or(Some(n), |f| (!f).then_some(n)))
.collect(),
EndpointsStatus::AllUnhealthy => health_statuses
.into_iter()
.filter_map(|(n, s)| s.map_or(None, |f| f.then_some(n)))
.collect(),
}
};
retry_with_msg!(
format!("check for desired health status {:?}", status),
log,
READY_WAIT_TIMEOUT,
RETRY_BACKOFF,
|| {
let nodes: Vec<&IcNodeSnapshot> = nodes_with_undesired_status();
if nodes.is_empty() {
Ok(())
} else {
let nodes_str = nodes.iter().map(|e|format!("[node_id={}, ip={}]", e.node_id, e.get_ip_addr())).join(",\n");
let msg = format!("The following nodes have not reached the desired health statuses {status:?}:\n{nodes_str}");
bail!(msg);
}
}
).unwrap_or_else(|err| panic!("Retry function failed within the timeout of {} sec, {err}", READY_WAIT_TIMEOUT.as_secs()));
}
/// Asserts that the response from an agent call is rejected by the replica
/// resulting in a [`AgentError::UncertifiedReject`], and an expected [`RejectCode`].
pub(crate) fn assert_http_submit_fails(
result: Result<RequestId, AgentError>,
expected_reject_code: RejectCode,
) {
match result {
Ok(val) => panic!("Expected call to fail but it succeeded with {:?}.", val),
Err(agent_error) => match agent_error {
AgentError::UncertifiedReject(RejectResponse{reject_code, ..}) => assert_eq!(
expected_reject_code, reject_code,
"Unexpected reject_code: `{:?}`.",
reject_code
),
others => panic!(
"Expected agent call to replica to fail with AgentError::UncertifiedReject, but got {:?} instead.",
others
),
},
}
}