-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathmod.rs
1858 lines (1710 loc) · 68.3 KB
/
mod.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
//! The main Agent module. Contains the [Agent] type and all associated structures.
pub(crate) mod agent_config;
pub mod agent_error;
pub(crate) mod builder;
pub mod http_transport;
pub(crate) mod nonce;
pub(crate) mod response_authentication;
pub mod status;
pub use agent_config::AgentConfig;
pub use agent_error::AgentError;
use async_lock::Semaphore;
pub use builder::AgentBuilder;
use cached::{Cached, TimedCache};
use ed25519_consensus::{Error as Ed25519Error, Signature, VerificationKey};
#[doc(inline)]
pub use ic_transport_types::{
signed, Envelope, EnvelopeContent, RejectCode, RejectResponse, ReplyResponse,
RequestStatusResponse,
};
pub use nonce::{NonceFactory, NonceGenerator};
use rangemap::{RangeInclusiveMap, RangeInclusiveSet, StepFns};
use time::OffsetDateTime;
#[cfg(test)]
mod agent_test;
use crate::{
agent::response_authentication::{
extract_der, lookup_canister_info, lookup_canister_metadata, lookup_request_status,
lookup_subnet, lookup_subnet_metrics, lookup_time, lookup_value,
},
export::Principal,
identity::Identity,
to_request_id, RequestId,
};
use backoff::{backoff::Backoff, ExponentialBackoffBuilder};
use backoff::{exponential::ExponentialBackoff, SystemClock};
use ic_certification::{Certificate, Delegation, Label};
use ic_transport_types::{
signed::{SignedQuery, SignedRequestStatus, SignedUpdate},
QueryResponse, ReadStateResponse, SubnetMetrics,
};
use serde::Serialize;
use status::Status;
use std::{
borrow::Cow,
collections::HashMap,
convert::TryFrom,
fmt,
future::{Future, IntoFuture},
pin::Pin,
sync::{Arc, Mutex, RwLock},
task::{Context, Poll},
time::Duration,
};
use crate::agent::response_authentication::lookup_api_boundary_nodes;
const IC_STATE_ROOT_DOMAIN_SEPARATOR: &[u8; 14] = b"\x0Dic-state-root";
const IC_ROOT_KEY: &[u8; 133] = b"\x30\x81\x82\x30\x1d\x06\x0d\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x01\x02\x01\x06\x0c\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x02\x01\x03\x61\x00\x81\x4c\x0e\x6e\xc7\x1f\xab\x58\x3b\x08\xbd\x81\x37\x3c\x25\x5c\x3c\x37\x1b\x2e\x84\x86\x3c\x98\xa4\xf1\xe0\x8b\x74\x23\x5d\x14\xfb\x5d\x9c\x0c\xd5\x46\xd9\x68\x5f\x91\x3a\x0c\x0b\x2c\xc5\x34\x15\x83\xbf\x4b\x43\x92\xe4\x67\xdb\x96\xd6\x5b\x9b\xb4\xcb\x71\x71\x12\xf8\x47\x2e\x0d\x5a\x4d\x14\x50\x5f\xfd\x74\x84\xb0\x12\x91\x09\x1c\x5f\x87\xb9\x88\x83\x46\x3f\x98\x09\x1a\x0b\xaa\xae";
#[cfg(not(target_family = "wasm"))]
type AgentFuture<'a, V> = Pin<Box<dyn Future<Output = Result<V, AgentError>> + Send + 'a>>;
#[cfg(target_family = "wasm")]
type AgentFuture<'a, V> = Pin<Box<dyn Future<Output = Result<V, AgentError>> + 'a>>;
/// A facade that connects to a Replica and does requests. These requests can be of any type
/// (does not have to be HTTP). This trait is to inverse the control from the Agent over its
/// connection code, and to resolve any direct dependencies to tokio or HTTP code from this
/// crate.
///
/// An implementation of this trait for HTTP transport is implemented using Reqwest, with the
/// feature flag `reqwest`. This might be deprecated in the future.
///
/// Any error returned by these methods will bubble up to the code that called the [Agent].
pub trait Transport: Send + Sync {
/// Sends an asynchronous request to a replica. The Request ID is non-mutable and
/// depends on the content of the envelope.
///
/// This normally corresponds to the `/api/v2/canister/<effective_canister_id>/call` endpoint.
fn call(
&self,
effective_canister_id: Principal,
envelope: Vec<u8>,
request_id: RequestId,
) -> AgentFuture<()>;
/// Sends a synchronous request to a replica. This call includes the body of the request message
/// itself (envelope).
///
/// This normally corresponds to the `/api/v2/canister/<effective_canister_id>/read_state` endpoint.
fn read_state(
&self,
effective_canister_id: Principal,
envelope: Vec<u8>,
) -> AgentFuture<Vec<u8>>;
/// Sends a synchronous request to a replica. This call includes the body of the request message
/// itself (envelope).
///
/// This normally corresponds to the `/api/v2/subnet/<subnet_id>/read_state` endpoint.
fn read_subnet_state(&self, subnet_id: Principal, envelope: Vec<u8>) -> AgentFuture<Vec<u8>>;
/// Sends a synchronous request to a replica. This call includes the body of the request message
/// itself (envelope).
///
/// This normally corresponds to the `/api/v2/canister/<effective_canister_id>/query` endpoint.
fn query(&self, effective_canister_id: Principal, envelope: Vec<u8>) -> AgentFuture<Vec<u8>>;
/// Sends a status request to the replica, returning whatever the replica returns.
/// In the current spec v2, this is a CBOR encoded status message, but we are not
/// making this API attach semantics to the response.
fn status(&self) -> AgentFuture<Vec<u8>>;
}
impl<I: Transport + ?Sized> Transport for Box<I> {
fn call(
&self,
effective_canister_id: Principal,
envelope: Vec<u8>,
request_id: RequestId,
) -> AgentFuture<()> {
(**self).call(effective_canister_id, envelope, request_id)
}
fn read_state(
&self,
effective_canister_id: Principal,
envelope: Vec<u8>,
) -> AgentFuture<Vec<u8>> {
(**self).read_state(effective_canister_id, envelope)
}
fn query(&self, effective_canister_id: Principal, envelope: Vec<u8>) -> AgentFuture<Vec<u8>> {
(**self).query(effective_canister_id, envelope)
}
fn status(&self) -> AgentFuture<Vec<u8>> {
(**self).status()
}
fn read_subnet_state(&self, subnet_id: Principal, envelope: Vec<u8>) -> AgentFuture<Vec<u8>> {
(**self).read_subnet_state(subnet_id, envelope)
}
}
impl<I: Transport + ?Sized> Transport for Arc<I> {
fn call(
&self,
effective_canister_id: Principal,
envelope: Vec<u8>,
request_id: RequestId,
) -> AgentFuture<()> {
(**self).call(effective_canister_id, envelope, request_id)
}
fn read_state(
&self,
effective_canister_id: Principal,
envelope: Vec<u8>,
) -> AgentFuture<Vec<u8>> {
(**self).read_state(effective_canister_id, envelope)
}
fn query(&self, effective_canister_id: Principal, envelope: Vec<u8>) -> AgentFuture<Vec<u8>> {
(**self).query(effective_canister_id, envelope)
}
fn status(&self) -> AgentFuture<Vec<u8>> {
(**self).status()
}
fn read_subnet_state(&self, subnet_id: Principal, envelope: Vec<u8>) -> AgentFuture<Vec<u8>> {
(**self).read_subnet_state(subnet_id, envelope)
}
}
/// Classification of the result of a request_status_raw (poll) call.
#[derive(Debug)]
pub enum PollResult {
/// The request has been submitted, but we do not know yet if it
/// has been accepted or not.
Submitted,
/// The request has been received and may be processing.
Accepted,
/// The request completed and returned some data.
Completed(Vec<u8>),
}
/// A low level Agent to make calls to a Replica endpoint.
///
/// ```ignore
/// # // This test is ignored because it requires an ic to be running. We run these
/// # // in the ic-ref workflow.
/// use ic_agent::{Agent, export::Principal};
/// use candid::{Encode, Decode, CandidType, Nat};
/// use serde::Deserialize;
///
/// #[derive(CandidType)]
/// struct Argument {
/// amount: Option<Nat>,
/// }
///
/// #[derive(CandidType, Deserialize)]
/// struct CreateCanisterResult {
/// canister_id: Principal,
/// }
///
/// # fn create_identity() -> impl ic_agent::Identity {
/// # let rng = ring::rand::SystemRandom::new();
/// # let key_pair = ring::signature::Ed25519KeyPair::generate_pkcs8(&rng)
/// # .expect("Could not generate a key pair.");
/// #
/// # ic_agent::identity::BasicIdentity::from_key_pair(
/// # ring::signature::Ed25519KeyPair::from_pkcs8(key_pair.as_ref())
/// # .expect("Could not read the key pair."),
/// # )
/// # }
/// #
/// async fn create_a_canister() -> Result<Principal, Box<dyn std::error::Error>> {
/// # let url = format!("http://localhost:{}", option_env!("IC_REF_PORT").unwrap_or("4943"));
/// let agent = Agent::builder()
/// .with_url(url)
/// .with_identity(create_identity())
/// .build()?;
///
/// // Only do the following call when not contacting the IC main net (e.g. a local emulator).
/// // This is important as the main net public key is static and a rogue network could return
/// // a different key.
/// // If you know the root key ahead of time, you can use `agent.set_root_key(root_key);`.
/// agent.fetch_root_key().await?;
/// let management_canister_id = Principal::from_text("aaaaa-aa")?;
///
/// // Create a call to the management canister to create a new canister ID,
/// // and wait for a result.
/// // The effective canister id must belong to the canister ranges of the subnet at which the canister is created.
/// let effective_canister_id = Principal::from_text("rwlgt-iiaaa-aaaaa-aaaaa-cai").unwrap();
/// let response = agent.update(&management_canister_id, "provisional_create_canister_with_cycles")
/// .with_effective_canister_id(effective_canister_id)
/// .with_arg(Encode!(&Argument { amount: None })?)
/// .await?;
///
/// let result = Decode!(response.as_slice(), CreateCanisterResult)?;
/// let canister_id: Principal = Principal::from_text(&result.canister_id.to_text())?;
/// Ok(canister_id)
/// }
///
/// # let mut runtime = tokio::runtime::Runtime::new().unwrap();
/// # runtime.block_on(async {
/// let canister_id = create_a_canister().await.unwrap();
/// eprintln!("{}", canister_id);
/// # });
/// ```
///
/// This agent does not understand Candid, and only acts on byte buffers.
#[derive(Clone)]
pub struct Agent {
nonce_factory: Arc<dyn NonceGenerator>,
identity: Arc<dyn Identity>,
ingress_expiry: Duration,
root_key: Arc<RwLock<Vec<u8>>>,
transport: Arc<dyn Transport>,
subnet_key_cache: Arc<Mutex<SubnetCache>>,
concurrent_requests_semaphore: Arc<Semaphore>,
verify_query_signatures: bool,
}
impl fmt::Debug for Agent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_struct("Agent")
.field("ingress_expiry", &self.ingress_expiry)
.finish_non_exhaustive()
}
}
impl Agent {
/// Create an instance of an [`AgentBuilder`] for building an [`Agent`]. This is simpler than
/// using the [`AgentConfig`] and [`Agent::new()`].
pub fn builder() -> builder::AgentBuilder {
Default::default()
}
/// Create an instance of an [`Agent`].
pub fn new(config: agent_config::AgentConfig) -> Result<Agent, AgentError> {
Ok(Agent {
nonce_factory: config.nonce_factory,
identity: config.identity,
ingress_expiry: config.ingress_expiry.unwrap_or(DEFAULT_INGRESS_EXPIRY),
root_key: Arc::new(RwLock::new(IC_ROOT_KEY.to_vec())),
transport: config
.transport
.ok_or_else(AgentError::MissingReplicaTransport)?,
subnet_key_cache: Arc::new(Mutex::new(SubnetCache::new())),
verify_query_signatures: config.verify_query_signatures,
concurrent_requests_semaphore: Arc::new(Semaphore::new(config.max_concurrent_requests)),
})
}
/// Set the transport of the [`Agent`].
pub fn set_transport<F: 'static + Transport>(&mut self, transport: F) {
self.transport = Arc::new(transport);
}
/// Set the identity provider for signing messages.
///
/// NOTE: if you change the identity while having update calls in
/// flight, you will not be able to [Agent::poll] the status of these
/// messages.
pub fn set_identity<I>(&mut self, identity: I)
where
I: 'static + Identity,
{
self.identity = Arc::new(identity);
}
/// Set the arc identity provider for signing messages.
///
/// NOTE: if you change the identity while having update calls in
/// flight, you will not be able to [Agent::poll] the status of these
/// messages.
pub fn set_arc_identity(&mut self, identity: Arc<dyn Identity>) {
self.identity = identity;
}
/// By default, the agent is configured to talk to the main Internet Computer, and verifies
/// responses using a hard-coded public key.
///
/// This function will instruct the agent to ask the endpoint for its public key, and use
/// that instead. This is required when talking to a local test instance, for example.
///
/// *Only use this when you are _not_ talking to the main Internet Computer, otherwise
/// you are prone to man-in-the-middle attacks! Do not call this function by default.*
pub async fn fetch_root_key(&self) -> Result<(), AgentError> {
if self.read_root_key()[..] != IC_ROOT_KEY[..] {
// already fetched the root key
return Ok(());
}
let status = self.status().await?;
let root_key = match status.root_key {
Some(key) => key,
None => return Err(AgentError::NoRootKeyInStatus(status)),
};
self.set_root_key(root_key);
Ok(())
}
/// By default, the agent is configured to talk to the main Internet Computer, and verifies
/// responses using a hard-coded public key.
///
/// Using this function you can set the root key to a known one if you know if beforehand.
pub fn set_root_key(&self, root_key: Vec<u8>) {
*self.root_key.write().unwrap() = root_key;
}
/// Return the root key currently in use.
pub fn read_root_key(&self) -> Vec<u8> {
self.root_key.read().unwrap().clone()
}
fn get_expiry_date(&self) -> u64 {
let expiry_raw = OffsetDateTime::now_utc() + self.ingress_expiry;
let mut rounded = expiry_raw.replace_nanosecond(0).unwrap();
if self.ingress_expiry.as_secs() > 90 {
rounded = rounded.replace_second(0).unwrap();
}
rounded.unix_timestamp_nanos() as u64
}
/// Return the principal of the identity.
pub fn get_principal(&self) -> Result<Principal, String> {
self.identity.sender()
}
async fn query_endpoint<A>(
&self,
effective_canister_id: Principal,
serialized_bytes: Vec<u8>,
) -> Result<A, AgentError>
where
A: serde::de::DeserializeOwned,
{
let _permit = self.concurrent_requests_semaphore.acquire().await;
let bytes = self
.transport
.query(effective_canister_id, serialized_bytes)
.await?;
serde_cbor::from_slice(&bytes).map_err(AgentError::InvalidCborData)
}
async fn read_state_endpoint<A>(
&self,
effective_canister_id: Principal,
serialized_bytes: Vec<u8>,
) -> Result<A, AgentError>
where
A: serde::de::DeserializeOwned,
{
let _permit = self.concurrent_requests_semaphore.acquire().await;
let bytes = self
.transport
.read_state(effective_canister_id, serialized_bytes)
.await?;
serde_cbor::from_slice(&bytes).map_err(AgentError::InvalidCborData)
}
async fn read_subnet_state_endpoint<A>(
&self,
subnet_id: Principal,
serialized_bytes: Vec<u8>,
) -> Result<A, AgentError>
where
A: serde::de::DeserializeOwned,
{
let _permit = self.concurrent_requests_semaphore.acquire().await;
let bytes = self
.transport
.read_subnet_state(subnet_id, serialized_bytes)
.await?;
serde_cbor::from_slice(&bytes).map_err(AgentError::InvalidCborData)
}
async fn call_endpoint(
&self,
effective_canister_id: Principal,
request_id: RequestId,
serialized_bytes: Vec<u8>,
) -> Result<RequestId, AgentError> {
let _permit = self.concurrent_requests_semaphore.acquire().await;
self.transport
.call(effective_canister_id, serialized_bytes, request_id)
.await?;
Ok(request_id)
}
/// The simplest way to do a query call; sends a byte array and will return a byte vector.
/// The encoding is left as an exercise to the user.
#[allow(clippy::too_many_arguments)]
async fn query_raw(
&self,
canister_id: Principal,
effective_canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
use_nonce: bool,
explicit_verify_query_signatures: Option<bool>,
) -> Result<Vec<u8>, AgentError> {
let content = self.query_content(
canister_id,
method_name,
arg,
ingress_expiry_datetime,
use_nonce,
)?;
let serialized_bytes = sign_envelope(&content, self.identity.clone())?;
self.query_inner(
effective_canister_id,
serialized_bytes,
content.to_request_id(),
explicit_verify_query_signatures,
)
.await
}
/// Send the signed query to the network. Will return a byte vector.
/// The bytes will be checked if it is a valid query.
/// If you want to inspect the fields of the query call, use [`signed_query_inspect`] before calling this method.
pub async fn query_signed(
&self,
effective_canister_id: Principal,
signed_query: Vec<u8>,
) -> Result<Vec<u8>, AgentError> {
let envelope: Envelope =
serde_cbor::from_slice(&signed_query).map_err(AgentError::InvalidCborData)?;
self.query_inner(
effective_canister_id,
signed_query,
envelope.content.to_request_id(),
None,
)
.await
}
/// Helper function for performing both the query call and possibly a read_state to check the subnet node keys.
///
/// This should be used instead of `query_endpoint`. No validation is performed on `signed_query`.
async fn query_inner(
&self,
effective_canister_id: Principal,
signed_query: Vec<u8>,
request_id: RequestId,
explicit_verify_query_signatures: Option<bool>,
) -> Result<Vec<u8>, AgentError> {
let response = if explicit_verify_query_signatures.unwrap_or(self.verify_query_signatures) {
let (response, mut subnet) = futures_util::try_join!(
self.query_endpoint::<QueryResponse>(effective_canister_id, signed_query),
self.get_subnet_by_canister(&effective_canister_id)
)?;
if response.signatures().is_empty() {
return Err(AgentError::MissingSignature);
} else if response.signatures().len() > subnet.node_keys.len() {
return Err(AgentError::TooManySignatures {
had: response.signatures().len(),
needed: subnet.node_keys.len(),
});
}
for signature in response.signatures() {
if OffsetDateTime::now_utc()
- OffsetDateTime::from_unix_timestamp_nanos(signature.timestamp as _).unwrap()
> self.ingress_expiry
{
return Err(AgentError::CertificateOutdated(self.ingress_expiry));
}
let signable = response.signable(request_id, signature.timestamp);
let node_key = if let Some(node_key) = subnet.node_keys.get(&signature.identity) {
node_key
} else {
subnet = self
.fetch_subnet_by_canister(&effective_canister_id)
.await?;
subnet
.node_keys
.get(&signature.identity)
.ok_or(AgentError::CertificateNotAuthorized())?
};
if node_key.len() != 44 {
return Err(AgentError::DerKeyLengthMismatch {
expected: 44,
actual: node_key.len(),
});
}
const DER_PREFIX: [u8; 12] = [48, 42, 48, 5, 6, 3, 43, 101, 112, 3, 33, 0];
if node_key[..12] != DER_PREFIX {
return Err(AgentError::DerPrefixMismatch {
expected: DER_PREFIX.to_vec(),
actual: node_key[..12].to_vec(),
});
}
let pubkey =
VerificationKey::try_from(<[u8; 32]>::try_from(&node_key[12..]).unwrap())
.map_err(|_| AgentError::MalformedPublicKey)?;
let sig = Signature::from(
<[u8; 64]>::try_from(&signature.signature[..])
.map_err(|_| AgentError::MalformedSignature)?,
);
match pubkey.verify(&sig, &signable) {
Err(Ed25519Error::InvalidSignature) => {
return Err(AgentError::QuerySignatureVerificationFailed)
}
Err(Ed25519Error::InvalidSliceLength) => {
return Err(AgentError::MalformedSignature)
}
Err(Ed25519Error::MalformedPublicKey) => {
return Err(AgentError::MalformedPublicKey)
}
Ok(()) => (),
_ => unreachable!(),
}
}
response
} else {
self.query_endpoint::<QueryResponse>(effective_canister_id, signed_query)
.await?
};
match response {
QueryResponse::Replied { reply, .. } => Ok(reply.arg),
QueryResponse::Rejected { reject, .. } => Err(AgentError::UncertifiedReject(reject)),
}
}
fn query_content(
&self,
canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
use_nonce: bool,
) -> Result<EnvelopeContent, AgentError> {
Ok(EnvelopeContent::Query {
sender: self.identity.sender().map_err(AgentError::SigningError)?,
canister_id,
method_name,
arg,
ingress_expiry: ingress_expiry_datetime.unwrap_or_else(|| self.get_expiry_date()),
nonce: use_nonce.then(|| self.nonce_factory.generate()).flatten(),
})
}
/// The simplest way to do an update call; sends a byte array and will return a RequestId.
/// The RequestId should then be used for request_status (most likely in a loop).
async fn update_raw(
&self,
canister_id: Principal,
effective_canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
) -> Result<RequestId, AgentError> {
let nonce = self.nonce_factory.generate();
let content = self.update_content(
canister_id,
method_name,
arg,
ingress_expiry_datetime,
nonce,
)?;
let request_id = to_request_id(&content)?;
let serialized_bytes = sign_envelope(&content, self.identity.clone())?;
self.call_endpoint(effective_canister_id, request_id, serialized_bytes)
.await
}
/// Send the signed update to the network. Will return a [`RequestId`].
/// The bytes will be checked to verify that it is a valid update.
/// If you want to inspect the fields of the update, use [`signed_update_inspect`] before calling this method.
pub async fn update_signed(
&self,
effective_canister_id: Principal,
signed_update: Vec<u8>,
) -> Result<RequestId, AgentError> {
let envelope: Envelope =
serde_cbor::from_slice(&signed_update).map_err(AgentError::InvalidCborData)?;
let request_id = to_request_id(&envelope.content)?;
self.call_endpoint(effective_canister_id, request_id, signed_update)
.await
}
fn update_content(
&self,
canister_id: Principal,
method_name: String,
arg: Vec<u8>,
ingress_expiry_datetime: Option<u64>,
nonce: Option<Vec<u8>>,
) -> Result<EnvelopeContent, AgentError> {
Ok(EnvelopeContent::Call {
canister_id,
method_name,
arg,
nonce,
sender: self.identity.sender().map_err(AgentError::SigningError)?,
ingress_expiry: ingress_expiry_datetime.unwrap_or_else(|| self.get_expiry_date()),
})
}
/// Call request_status on the RequestId once and classify the result
pub async fn poll(
&self,
request_id: &RequestId,
effective_canister_id: Principal,
) -> Result<PollResult, AgentError> {
match self
.request_status_raw(request_id, effective_canister_id)
.await?
{
RequestStatusResponse::Unknown => Ok(PollResult::Submitted),
RequestStatusResponse::Received | RequestStatusResponse::Processing => {
Ok(PollResult::Accepted)
}
RequestStatusResponse::Replied(ReplyResponse { arg, .. }) => {
Ok(PollResult::Completed(arg))
}
RequestStatusResponse::Rejected(response) => Err(AgentError::CertifiedReject(response)),
RequestStatusResponse::Done => Err(AgentError::RequestStatusDoneNoReply(String::from(
*request_id,
))),
}
}
fn get_retry_policy() -> ExponentialBackoff<SystemClock> {
ExponentialBackoffBuilder::new()
.with_initial_interval(Duration::from_millis(500))
.with_max_interval(Duration::from_secs(1))
.with_multiplier(1.4)
.with_max_elapsed_time(Some(Duration::from_secs(60 * 5)))
.build()
}
/// Wait for request_status to return a Replied response and return the arg.
pub async fn wait_signed(
&self,
request_id: &RequestId,
effective_canister_id: Principal,
signed_request_status: Vec<u8>,
) -> Result<Vec<u8>, AgentError> {
let mut retry_policy = Self::get_retry_policy();
let mut request_accepted = false;
loop {
match self
.request_status_signed(
request_id,
effective_canister_id,
signed_request_status.clone(),
)
.await?
{
RequestStatusResponse::Unknown => {}
RequestStatusResponse::Received | RequestStatusResponse::Processing => {
if !request_accepted {
retry_policy.reset();
request_accepted = true;
}
}
RequestStatusResponse::Replied(ReplyResponse { arg, .. }) => return Ok(arg),
RequestStatusResponse::Rejected(response) => {
return Err(AgentError::CertifiedReject(response))
}
RequestStatusResponse::Done => {
return Err(AgentError::RequestStatusDoneNoReply(String::from(
*request_id,
)))
}
};
match retry_policy.next_backoff() {
Some(duration) => crate::util::sleep(duration).await,
None => return Err(AgentError::TimeoutWaitingForResponse()),
}
}
}
/// Call request_status on the RequestId in a loop and return the response as a byte vector.
pub async fn wait(
&self,
request_id: RequestId,
effective_canister_id: Principal,
) -> Result<Vec<u8>, AgentError> {
let mut retry_policy = Self::get_retry_policy();
let mut request_accepted = false;
loop {
match self.poll(&request_id, effective_canister_id).await? {
PollResult::Submitted => {}
PollResult::Accepted => {
if !request_accepted {
// The system will return RequestStatusResponse::Unknown
// (PollResult::Submitted) until the request is accepted
// and we generally cannot know how long that will take.
// State transitions between Received and Processing may be
// instantaneous. Therefore, once we know the request is accepted,
// we should restart the backoff so the request does not time out.
retry_policy.reset();
request_accepted = true;
}
}
PollResult::Completed(result) => return Ok(result),
};
match retry_policy.next_backoff() {
Some(duration) => crate::util::sleep(duration).await,
None => return Err(AgentError::TimeoutWaitingForResponse()),
}
}
}
/// Request the raw state tree directly, under an effective canister ID.
/// See [the protocol docs](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-read-state) for more information.
pub async fn read_state_raw(
&self,
paths: Vec<Vec<Label>>,
effective_canister_id: Principal,
) -> Result<Certificate, AgentError> {
let content = self.read_state_content(paths)?;
let serialized_bytes = sign_envelope(&content, self.identity.clone())?;
let read_state_response: ReadStateResponse = self
.read_state_endpoint(effective_canister_id, serialized_bytes)
.await?;
let cert: Certificate = serde_cbor::from_slice(&read_state_response.certificate)
.map_err(AgentError::InvalidCborData)?;
self.verify(&cert, effective_canister_id)?;
Ok(cert)
}
/// Request the raw state tree directly, under a subnet ID.
/// See [the protocol docs](https://internetcomputer.org/docs/current/references/ic-interface-spec#http-read-state) for more information.
pub async fn read_subnet_state_raw(
&self,
paths: Vec<Vec<Label>>,
subnet_id: Principal,
) -> Result<Certificate, AgentError> {
let content = self.read_state_content(paths)?;
let serialized_bytes = sign_envelope(&content, self.identity.clone())?;
let read_state_response: ReadStateResponse = self
.read_subnet_state_endpoint(subnet_id, serialized_bytes)
.await?;
let cert: Certificate = serde_cbor::from_slice(&read_state_response.certificate)
.map_err(AgentError::InvalidCborData)?;
self.verify_for_subnet(&cert, subnet_id)?;
Ok(cert)
}
fn read_state_content(&self, paths: Vec<Vec<Label>>) -> Result<EnvelopeContent, AgentError> {
Ok(EnvelopeContent::ReadState {
sender: self.identity.sender().map_err(AgentError::SigningError)?,
paths,
ingress_expiry: self.get_expiry_date(),
})
}
/// Verify a certificate, checking delegation if present.
/// Only passes if the certificate also has authority over the canister.
pub fn verify(
&self,
cert: &Certificate,
effective_canister_id: Principal,
) -> Result<(), AgentError> {
self.verify_cert(cert, effective_canister_id)?;
self.verify_cert_timestamp(cert)?;
Ok(())
}
fn verify_cert(
&self,
cert: &Certificate,
effective_canister_id: Principal,
) -> Result<(), AgentError> {
let sig = &cert.signature;
let root_hash = cert.tree.digest();
let mut msg = vec![];
msg.extend_from_slice(IC_STATE_ROOT_DOMAIN_SEPARATOR);
msg.extend_from_slice(&root_hash);
let der_key = self.check_delegation(&cert.delegation, effective_canister_id)?;
let key = extract_der(der_key)?;
ic_verify_bls_signature::verify_bls_signature(sig, &msg, &key)
.map_err(|_| AgentError::CertificateVerificationFailed())?;
Ok(())
}
/// Verify a certificate, checking delegation if present.
/// Only passes if the certificate is for the specified subnet.
pub fn verify_for_subnet(
&self,
cert: &Certificate,
subnet_id: Principal,
) -> Result<(), AgentError> {
self.verify_cert_for_subnet(cert, subnet_id)?;
self.verify_cert_timestamp(cert)?;
Ok(())
}
fn verify_cert_for_subnet(
&self,
cert: &Certificate,
subnet_id: Principal,
) -> Result<(), AgentError> {
let sig = &cert.signature;
let root_hash = cert.tree.digest();
let mut msg = vec![];
msg.extend_from_slice(IC_STATE_ROOT_DOMAIN_SEPARATOR);
msg.extend_from_slice(&root_hash);
let der_key = self.check_delegation_for_subnet(&cert.delegation, subnet_id)?;
let key = extract_der(der_key)?;
ic_verify_bls_signature::verify_bls_signature(sig, &msg, &key)
.map_err(|_| AgentError::CertificateVerificationFailed())?;
Ok(())
}
fn verify_cert_timestamp(&self, cert: &Certificate) -> Result<(), AgentError> {
let time = lookup_time(cert)?;
if (OffsetDateTime::now_utc()
- OffsetDateTime::from_unix_timestamp_nanos(time.into()).unwrap())
.abs()
> self.ingress_expiry
{
Err(AgentError::CertificateOutdated(self.ingress_expiry))
} else {
Ok(())
}
}
fn check_delegation(
&self,
delegation: &Option<Delegation>,
effective_canister_id: Principal,
) -> Result<Vec<u8>, AgentError> {
match delegation {
None => Ok(self.read_root_key()),
Some(delegation) => {
let cert: Certificate = serde_cbor::from_slice(&delegation.certificate)
.map_err(AgentError::InvalidCborData)?;
if cert.delegation.is_some() {
return Err(AgentError::CertificateHasTooManyDelegations);
}
self.verify_cert(&cert, effective_canister_id)?;
let canister_range_lookup = [
"subnet".as_bytes(),
delegation.subnet_id.as_ref(),
"canister_ranges".as_bytes(),
];
let canister_range = lookup_value(&cert.tree, canister_range_lookup)?;
let ranges: Vec<(Principal, Principal)> =
serde_cbor::from_slice(canister_range).map_err(AgentError::InvalidCborData)?;
if !principal_is_within_ranges(&effective_canister_id, &ranges[..]) {
// the certificate is not authorized to answer calls for this canister
return Err(AgentError::CertificateNotAuthorized());
}
let public_key_path = [
"subnet".as_bytes(),
delegation.subnet_id.as_ref(),
"public_key".as_bytes(),
];
lookup_value(&cert.tree, public_key_path).map(|pk| pk.to_vec())
}
}
}
fn check_delegation_for_subnet(
&self,
delegation: &Option<Delegation>,
subnet_id: Principal,
) -> Result<Vec<u8>, AgentError> {
match delegation {
None => Ok(self.read_root_key()),
Some(delegation) => {
let cert: Certificate = serde_cbor::from_slice(&delegation.certificate)
.map_err(AgentError::InvalidCborData)?;
if cert.delegation.is_some() {
return Err(AgentError::CertificateHasTooManyDelegations);
}
self.verify_cert_for_subnet(&cert, subnet_id)?;
let public_key_path = [
"subnet".as_bytes(),
delegation.subnet_id.as_ref(),
"public_key".as_bytes(),
];
let pk = lookup_value(&cert.tree, public_key_path)
.map_err(|_| AgentError::CertificateNotAuthorized())?
.to_vec();
Ok(pk)
}
}
}
/// Request information about a particular canister for a single state subkey.
/// See [the protocol docs](https://internetcomputer.org/docs/current/references/ic-interface-spec#state-tree-canister-information) for more information.
pub async fn read_state_canister_info(
&self,
canister_id: Principal,
path: &str,
) -> Result<Vec<u8>, AgentError> {
let paths: Vec<Vec<Label>> = vec![vec![
"canister".into(),
Label::from_bytes(canister_id.as_slice()),
path.into(),
]];
let cert = self.read_state_raw(paths, canister_id).await?;
lookup_canister_info(cert, canister_id, path)
}
/// Request the bytes of the canister's custom section `icp:public <path>` or `icp:private <path>`.
pub async fn read_state_canister_metadata(
&self,
canister_id: Principal,
path: &str,
) -> Result<Vec<u8>, AgentError> {
let paths: Vec<Vec<Label>> = vec![vec![
"canister".into(),
Label::from_bytes(canister_id.as_slice()),
"metadata".into(),
path.into(),
]];
let cert = self.read_state_raw(paths, canister_id).await?;
lookup_canister_metadata(cert, canister_id, path)
}
/// Request a list of metrics about the subnet.
pub async fn read_state_subnet_metrics(
&self,
subnet_id: Principal,
) -> Result<SubnetMetrics, AgentError> {
let paths = vec![vec![
"subnet".into(),
Label::from_bytes(subnet_id.as_slice()),
"metrics".into(),
]];
let cert = self.read_subnet_state_raw(paths, subnet_id).await?;
lookup_subnet_metrics(cert, subnet_id)