/
http.rs
880 lines (785 loc) · 27.5 KB
/
http.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
// DFN-467: clippy complains about the code generated by derive(Arbitrary)
#![cfg_attr(test, allow(clippy::unit_arg))]
//! HTTP requests that the Internet Computer is prepared to handle.
use super::Blob;
use crate::{
crypto::SignedBytesWithoutDomainSeparator,
messages::{
message_id::hash_of_map, MessageId, ReadState, SignedIngressContent, UserQuery,
UserSignature,
},
Height, Time, UserId,
};
use derive_more::Display;
use ic_base_types::{CanisterId, CanisterIdError, PrincipalId};
use ic_crypto_tree_hash::{MixedHashTree, Path};
use maplit::btreemap;
#[cfg(test)]
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeSet, convert::TryFrom, error::Error, fmt};
#[cfg(test)]
mod tests;
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum CallOrQuery {
Call,
Query,
}
pub(crate) fn representation_indepent_hash_call_or_query(
request_type: CallOrQuery,
canister_id: Vec<u8>,
method_name: &str,
arg: Vec<u8>,
ingress_expiry: u64,
sender: Vec<u8>,
nonce: Option<&[u8]>,
) -> [u8; 32] {
use RawHttpRequestVal::*;
let mut map = btreemap! {
"request_type".to_string() => match request_type {
CallOrQuery::Call => String("call".to_string()),
CallOrQuery::Query => String("query".to_string()),
},
"canister_id".to_string() => Bytes(canister_id),
"method_name".to_string() => String(method_name.to_string()),
"arg".to_string() => Bytes(arg),
"ingress_expiry".to_string() => U64(ingress_expiry),
"sender".to_string() => Bytes(sender),
};
if let Some(some_nonce) = nonce {
map.insert("nonce".to_string(), Bytes(some_nonce.to_vec()));
}
hash_of_map(&map)
}
pub(crate) fn representation_independent_hash_read_state(
ingress_expiry: u64,
paths: &[Path],
sender: Vec<u8>,
nonce: Option<&[u8]>,
) -> [u8; 32] {
use RawHttpRequestVal::*;
let mut map = btreemap! {
"request_type".to_string() => String("read_state".to_string()),
"ingress_expiry".to_string() => U64(ingress_expiry),
"paths".to_string() => Array(paths
.iter()
.map(|p| {
RawHttpRequestVal::Array(
p.iter()
.map(|b| RawHttpRequestVal::Bytes(b.clone().to_vec()))
.collect(),
)
})
.collect()),
"sender".to_string() => Bytes(sender),
};
if let Some(some_nonce) = nonce {
map.insert("nonce".to_string(), Bytes(some_nonce.to_vec()));
}
hash_of_map(&map)
}
/// Describes the fields of a canister update call as defined in
/// `<https://internetcomputer.org/docs/current/references/ic-interface-spec#http-call>`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct HttpCanisterUpdate {
pub canister_id: Blob,
pub method_name: String,
pub arg: Blob,
pub sender: Blob,
/// Indicates when the message should expire. Represented as nanoseconds
/// since UNIX epoch.
pub ingress_expiry: u64,
// Do not include omitted fields in MessageId calculation
#[serde(skip_serializing_if = "Option::is_none")]
pub nonce: Option<Blob>,
}
impl HttpCanisterUpdate {
/// Returns the representation-independent hash.
pub fn representation_independent_hash(&self) -> [u8; 32] {
representation_indepent_hash_call_or_query(
CallOrQuery::Call,
self.canister_id.0.clone(),
&self.method_name,
self.arg.0.clone(),
self.ingress_expiry,
self.sender.0.clone(),
self.nonce.as_ref().map(|x| x.0.as_slice()),
)
}
pub fn id(&self) -> MessageId {
MessageId::from(self.representation_independent_hash())
}
}
/// Describes the contents of a /api/v2/canister/_/call request.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(test, derive(Arbitrary))]
#[serde(rename_all = "snake_case")]
#[serde(tag = "request_type")]
pub enum HttpCallContent {
Call {
#[serde(flatten)]
update: HttpCanisterUpdate,
},
}
impl HttpCallContent {
/// Returns the representation-independent hash.
pub fn representation_independent_hash(&self) -> [u8; 32] {
let Self::Call { update } = self;
update.representation_independent_hash()
}
pub fn ingress_expiry(&self) -> u64 {
match self {
Self::Call { update } => update.ingress_expiry,
}
}
}
/// Describes the fields of a canister query call (a query from a user to a canister) as
/// defined in `<https://internetcomputer.org/docs/current/references/ic-interface-spec#http-query>`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HttpUserQuery {
pub canister_id: Blob,
pub method_name: String,
pub arg: Blob,
pub sender: Blob,
/// Indicates when the message should expire. Represented as nanoseconds
/// since UNIX epoch.
pub ingress_expiry: u64,
// Do not include omitted fields in MessageId calculation
#[serde(skip_serializing_if = "Option::is_none")]
pub nonce: Option<Blob>,
}
/// Describes the contents of a /api/v2/canister/_/query request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "request_type")]
pub enum HttpQueryContent {
Query {
#[serde(flatten)]
query: HttpUserQuery,
},
}
impl HttpQueryContent {
pub fn representation_independent_hash(&self) -> [u8; 32] {
match self {
Self::Query { query } => query.representation_independent_hash(),
}
}
pub fn id(&self) -> MessageId {
MessageId::from(self.representation_independent_hash())
}
}
/// A `read_state` request as defined in `<https://internetcomputer.org/docs/current/references/ic-interface-spec#http-read-state>`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HttpReadState {
pub sender: Blob,
// A list of paths, where a path is itself a sequence of labels.
pub paths: Vec<Path>,
#[serde(skip_serializing_if = "Option::is_none")]
pub nonce: Option<Blob>,
pub ingress_expiry: u64,
}
/// Describes the contents of a /api/v2/canister/_/read_state request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "request_type")]
pub enum HttpReadStateContent {
ReadState {
#[serde(flatten)]
read_state: HttpReadState,
},
}
impl HttpReadStateContent {
pub fn representation_independent_hash(&self) -> [u8; 32] {
match self {
Self::ReadState { read_state } => read_state.representation_independent_hash(),
}
}
pub fn id(&self) -> MessageId {
MessageId::from(self.representation_independent_hash())
}
}
impl HttpUserQuery {
/// Returns the representation-independent hash.
pub fn representation_independent_hash(&self) -> [u8; 32] {
representation_indepent_hash_call_or_query(
CallOrQuery::Query,
self.canister_id.0.clone(),
&self.method_name,
self.arg.0.clone(),
self.ingress_expiry,
self.sender.0.clone(),
self.nonce.as_ref().map(|x| x.0.as_slice()),
)
}
}
impl HttpReadState {
/// Returns the representation-independent hash.
pub fn representation_independent_hash(&self) -> [u8; 32] {
representation_independent_hash_read_state(
self.ingress_expiry,
self.paths.as_slice(),
self.sender.0.clone(),
self.nonce.as_ref().map(|x| x.0.as_slice()),
)
}
}
/// A request envelope as defined in
/// `<https://internetcomputer.org/docs/current/references/ic-interface-spec#authentication>`.
///
/// The content is either [`HttpCallContent`], [`HttpQueryContent`] or
/// [`HttpReadStateContent`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct HttpRequestEnvelope<C> {
pub content: C,
#[serde(skip_serializing_if = "Option::is_none")]
pub sender_pubkey: Option<Blob>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sender_sig: Option<Blob>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sender_delegation: Option<Vec<SignedDelegation>>,
}
/// A strongly-typed version of [`HttpRequestEnvelope`].
#[derive(Debug, Eq, PartialEq, Clone, Hash, Serialize, Deserialize)]
pub struct HttpRequest<C> {
content: C,
auth: Authentication,
}
/// The authentication associated with an HTTP request.
#[derive(Debug, Eq, PartialEq, Clone, Hash, Serialize, Deserialize)]
pub enum Authentication {
Authenticated(UserSignature),
Anonymous,
}
impl<C> TryFrom<&HttpRequestEnvelope<C>> for Authentication {
type Error = HttpRequestError;
fn try_from(env: &HttpRequestEnvelope<C>) -> Result<Self, Self::Error> {
match (&env.sender_pubkey, &env.sender_sig, &env.sender_delegation) {
(Some(pubkey), Some(signature), delegation) => {
Ok(Authentication::Authenticated(UserSignature {
signature: signature.0.clone(),
signer_pubkey: pubkey.0.clone(),
sender_delegation: delegation.clone(),
}))
}
(None, None, None) => Ok(Authentication::Anonymous),
rest => Err(Self::Error::MissingPubkeyOrSignature(format!(
"Got {:?}",
rest
))),
}
}
}
/// Common attributes that all HTTP request contents should have.
pub trait HttpRequestContent {
fn id(&self) -> MessageId;
fn sender(&self) -> UserId;
fn ingress_expiry(&self) -> u64;
fn nonce(&self) -> Option<Vec<u8>>;
}
/// A trait implemented by HTTP requests that contain a `canister_id`.
pub trait HasCanisterId {
fn canister_id(&self) -> CanisterId;
}
impl<C: HttpRequestContent> HttpRequest<C> {
pub fn id(&self) -> MessageId {
self.content.id()
}
pub fn sender(&self) -> UserId {
self.content.sender()
}
pub fn ingress_expiry(&self) -> u64 {
self.content.ingress_expiry()
}
pub fn nonce(&self) -> Option<Vec<u8>> {
self.content.nonce()
}
}
impl<C> HttpRequest<C> {
pub fn content(&self) -> &C {
&self.content
}
pub fn take_content(self) -> C {
self.content
}
pub fn authentication(&self) -> &Authentication {
&self.auth
}
}
impl HttpRequestContent for UserQuery {
fn id(&self) -> MessageId {
self.id()
}
fn sender(&self) -> UserId {
self.source
}
fn ingress_expiry(&self) -> u64 {
self.ingress_expiry
}
fn nonce(&self) -> Option<Vec<u8>> {
self.nonce.clone()
}
}
impl HttpRequestContent for ReadState {
fn id(&self) -> MessageId {
self.id()
}
fn sender(&self) -> UserId {
self.source
}
fn ingress_expiry(&self) -> u64 {
self.ingress_expiry
}
fn nonce(&self) -> Option<Vec<u8>> {
self.nonce.clone()
}
}
impl TryFrom<HttpRequestEnvelope<HttpQueryContent>> for HttpRequest<UserQuery> {
type Error = HttpRequestError;
fn try_from(envelope: HttpRequestEnvelope<HttpQueryContent>) -> Result<Self, Self::Error> {
let auth = Authentication::try_from(&envelope)?;
match envelope.content {
HttpQueryContent::Query { query } => Ok(HttpRequest {
content: UserQuery::try_from(query)?,
auth,
}),
}
}
}
impl TryFrom<HttpRequestEnvelope<HttpReadStateContent>> for HttpRequest<ReadState> {
type Error = HttpRequestError;
fn try_from(envelope: HttpRequestEnvelope<HttpReadStateContent>) -> Result<Self, Self::Error> {
let auth = Authentication::try_from(&envelope)?;
match envelope.content {
HttpReadStateContent::ReadState { read_state } => Ok(HttpRequest {
content: ReadState::try_from(read_state)?,
auth,
}),
}
}
}
impl TryFrom<HttpRequestEnvelope<HttpCallContent>> for HttpRequest<SignedIngressContent> {
type Error = HttpRequestError;
fn try_from(envelope: HttpRequestEnvelope<HttpCallContent>) -> Result<Self, Self::Error> {
let auth = Authentication::try_from(&envelope)?;
match envelope.content {
HttpCallContent::Call { update } => Ok(HttpRequest {
content: SignedIngressContent::try_from(update)?,
auth,
}),
}
}
}
/// Errors returned by `HttpHandler` when processing ingress messages.
#[derive(Debug, Clone, Serialize)]
pub enum HttpRequestError {
InvalidMessageId(String),
InvalidIngressExpiry(String),
InvalidDelegationExpiry(String),
InvalidPrincipalId(String),
MissingPubkeyOrSignature(String),
InvalidEncoding(String),
}
impl From<serde_cbor::Error> for HttpRequestError {
fn from(err: serde_cbor::Error) -> Self {
HttpRequestError::InvalidEncoding(format!("{}", err))
}
}
impl fmt::Display for HttpRequestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
HttpRequestError::InvalidMessageId(msg) => write!(f, "invalid message ID: {}", msg),
HttpRequestError::InvalidIngressExpiry(msg) => write!(f, "{}", msg),
HttpRequestError::InvalidDelegationExpiry(msg) => write!(f, "{}", msg),
HttpRequestError::InvalidPrincipalId(msg) => write!(f, "invalid princial id: {}", msg),
HttpRequestError::MissingPubkeyOrSignature(msg) => {
write!(f, "missing pubkey or signature: {}", msg)
}
HttpRequestError::InvalidEncoding(err) => write!(f, "Invalid CBOR encoding: {}", err),
}
}
}
impl Error for HttpRequestError {}
impl From<CanisterIdError> for HttpRequestError {
fn from(err: CanisterIdError) -> Self {
Self::InvalidPrincipalId(format!("Converting to canister id failed with {}", err))
}
}
/// Describes a delegation map as defined in
/// `<https://internetcomputer.org/docs/current/references/ic-interface-spec#certification-delegation>`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct Delegation {
pubkey: Blob,
expiration: Time,
targets: Option<Vec<Blob>>,
}
impl Delegation {
pub fn new(pubkey: Vec<u8>, expiration: Time) -> Self {
Self {
pubkey: Blob(pubkey),
expiration,
targets: None,
}
}
pub fn new_with_targets(pubkey: Vec<u8>, expiration: Time, targets: Vec<CanisterId>) -> Self {
Self {
pubkey: Blob(pubkey),
expiration,
targets: Some(targets.iter().map(|c| Blob(c.get().to_vec())).collect()),
}
}
pub fn pubkey(&self) -> &Vec<u8> {
&self.pubkey.0
}
pub fn expiration(&self) -> Time {
self.expiration
}
pub fn targets(&self) -> Result<Option<BTreeSet<CanisterId>>, String> {
match &self.targets {
None => Ok(None),
Some(targets) => {
let mut target_canister_ids = BTreeSet::new();
for target in targets {
target_canister_ids.insert(
CanisterId::new(
PrincipalId::try_from(target.0.as_slice())
.map_err(|e| format!("Error parsing canister ID: {}", e))?,
)
.map_err(|e| format!("Error parsing canister ID: {}", e))?,
);
}
Ok(Some(target_canister_ids))
}
}
}
pub fn number_of_targets(&self) -> Option<usize> {
self.targets.as_ref().map(Vec::len)
}
}
impl SignedBytesWithoutDomainSeparator for Delegation {
fn as_signed_bytes_without_domain_separator(&self) -> Vec<u8> {
use RawHttpRequestVal::*;
let mut map = btreemap! {
"pubkey" => Bytes(self.pubkey.0.clone()),
"expiration" => U64(self.expiration.as_nanos_since_unix_epoch()),
};
if let Some(targets) = &self.targets {
map.insert(
"targets",
Array(targets.iter().map(|t| Bytes(t.0.clone())).collect()),
);
}
hash_of_map(&map).to_vec()
}
}
/// Describes a delegation as defined in
/// `<https://internetcomputer.org/docs/current/references/ic-interface-spec#certification-delegation>`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[cfg_attr(test, derive(Arbitrary))]
pub struct SignedDelegation {
delegation: Delegation,
signature: Blob,
}
impl SignedDelegation {
pub fn new(delegation: Delegation, signature: Vec<u8>) -> Self {
Self {
delegation,
signature: Blob(signature),
}
}
pub fn delegation(&self) -> &Delegation {
&self.delegation
}
pub fn take_delegation(self) -> Delegation {
self.delegation
}
pub fn signature(&self) -> &Blob {
&self.signature
}
}
/// The different types of values supported in `RawHttpRequest`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum RawHttpRequestVal {
Bytes(#[serde(with = "serde_bytes")] Vec<u8>),
String(String),
U64(u64),
Array(Vec<RawHttpRequestVal>),
}
/// The reply to an update call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum HttpReply {
CodeCall { arg: Blob },
Empty {},
}
/// The response to `/api/v2/canister/_/{read_state|query}` with `request_type`
/// set to `query`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "status")]
pub enum HttpQueryResponse {
Replied {
reply: HttpQueryResponseReply,
},
Rejected {
error_code: String,
reject_code: u64,
reject_message: String,
},
}
/// The body of the `QueryResponse`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HttpQueryResponseReply {
pub arg: Blob,
}
/// The response to a `read_state` request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HttpReadStateResponse {
/// The CBOR-encoded `Certificate`.
pub certificate: Blob,
}
/// A `Certificate` as defined in `<https://internetcomputer.org/docs/current/references/ic-interface-spec#certificate>`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Certificate {
pub tree: MixedHashTree,
pub signature: Blob,
#[serde(skip_serializing_if = "Option::is_none")]
pub delegation: Option<CertificateDelegation>,
}
/// A `CertificateDelegation` as defined in `<https://internetcomputer.org/docs/current/references/ic-interface-spec#certification-delegation>`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CertificateDelegation {
pub subnet_id: Blob,
pub certificate: Blob,
}
/// Different stages required for the full initialization of the HTTPS endpoint.
/// The fields are listed in order of execution/transition.
#[derive(Debug, Display, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReplicaHealthStatus {
/// Marks the start state of the HTTPS endpoint. Some requests will fail
/// while initialization is on-going.
Starting,
/// Waiting for the first non-empty certifited state available on
/// the node.
WaitingForCertifiedState,
/// Waiting for the root delegation in case of non-NNS subnet.
WaitingForRootDelegation,
/// Happens when the replica's finalized height is significantly greater
/// than the certified height.
/// If the finalized height is significantly greater than the
/// certified height, this is a signal that execution is lagging
/// consensus, and that consensus needs to be throttled.
/// More information can be found in the whitepaper
/// `<https://internetcomputer.org/whitepaper.pdf>`
/// under "Per-round certified state" section(s).
///
/// If execution (or certification) is lagging significantly on this replica,
/// then we better not serve queries because we risk returning stale data.
/// According to the IC's spec - `<https://internetcomputer.org/docs/current/references/ic-interface-spec#query_call>`,
/// we should execute queries on "recent enough" state tree.
CertifiedStateBehind,
/// Signals that the replica can serve all types of API requests.
/// When users programatically access this information they should
/// check only if 'ReplicaHealthStatus' is equal to 'Healthy' or not.
Healthy,
}
/// The response to `/api/v2/status`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct HttpStatusResponse {
pub ic_api_version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub root_key: Option<Blob>,
#[serde(skip_serializing_if = "Option::is_none")]
pub impl_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub impl_hash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub replica_health_status: Option<ReplicaHealthStatus>,
#[serde(skip_serializing_if = "Option::is_none")]
pub certified_height: Option<Height>,
}
#[cfg(test)]
mod test {
use super::*;
use crate::{time::UNIX_EPOCH, AmountOf};
use pretty_assertions::assert_eq;
use serde::Serialize;
use serde_cbor::Value;
/// Makes sure that the serialized CBOR version of `obj` is the same as
/// `Value`. Used when testing _outgoing_ messages from the HTTP
/// Handler's point of view
fn assert_cbor_ser_equal<T>(obj: &T, val: Value)
where
for<'de> T: Serialize,
{
assert_eq!(serde_cbor::value::to_value(obj).unwrap(), val)
}
fn text(text: &'static str) -> Value {
Value::Text(text.to_string())
}
fn int(i: u64) -> Value {
Value::Integer(i.into())
}
fn bytes(bs: &[u8]) -> Value {
Value::Bytes(bs.to_vec())
}
#[test]
fn encoding_read_query_response() {
assert_cbor_ser_equal(
&HttpQueryResponse::Replied {
reply: HttpQueryResponseReply {
arg: Blob(b"some_bytes".to_vec()),
},
},
Value::Map(btreemap! {
text("status") => text("replied"),
text("reply") => Value::Map(btreemap!{
text("arg") => bytes(b"some_bytes")
})
}),
);
}
#[test]
fn encoding_read_query_reject() {
assert_cbor_ser_equal(
&HttpQueryResponse::Rejected {
reject_code: 1,
reject_message: "system error".to_string(),
error_code: "IC500".to_string(),
},
Value::Map(btreemap! {
text("status") => text("rejected"),
text("reject_code") => int(1),
text("reject_message") => text("system error"),
text("error_code") => text("IC500"),
}),
);
}
#[test]
fn encoding_status_without_root_key() {
assert_cbor_ser_equal(
&HttpStatusResponse {
ic_api_version: "foobar".to_string(),
root_key: None,
impl_version: Some("0.0".to_string()),
impl_hash: None,
replica_health_status: Some(ReplicaHealthStatus::Starting),
certified_height: None,
},
Value::Map(btreemap! {
text("ic_api_version") => text("foobar"),
text("impl_version") => text("0.0"),
text("replica_health_status") => text("starting"),
}),
);
}
#[test]
fn encoding_status_with_root_key() {
assert_cbor_ser_equal(
&HttpStatusResponse {
ic_api_version: "foobar".to_string(),
root_key: Some(Blob(vec![1, 2, 3])),
impl_version: Some("0.0".to_string()),
impl_hash: None,
replica_health_status: Some(ReplicaHealthStatus::Healthy),
certified_height: None,
},
Value::Map(btreemap! {
text("ic_api_version") => text("foobar"),
text("root_key") => bytes(&[1, 2, 3]),
text("impl_version") => text("0.0"),
text("replica_health_status") => text("healthy"),
}),
);
}
#[test]
fn encoding_status_without_health_status() {
assert_cbor_ser_equal(
&HttpStatusResponse {
ic_api_version: "foobar".to_string(),
root_key: Some(Blob(vec![1, 2, 3])),
impl_version: Some("0.0".to_string()),
impl_hash: None,
replica_health_status: None,
certified_height: None,
},
Value::Map(btreemap! {
text("ic_api_version") => text("foobar"),
text("root_key") => bytes(&[1, 2, 3]),
text("impl_version") => text("0.0"),
}),
);
}
#[test]
fn encoding_status_with_certified_height() {
assert_cbor_ser_equal(
&HttpStatusResponse {
ic_api_version: "foobar".to_string(),
root_key: Some(Blob(vec![1, 2, 3])),
impl_version: Some("0.0".to_string()),
impl_hash: None,
replica_health_status: Some(ReplicaHealthStatus::Healthy),
certified_height: Some(AmountOf::new(1)),
},
Value::Map(btreemap! {
text("ic_api_version") => text("foobar"),
text("root_key") => bytes(&[1, 2, 3]),
text("impl_version") => text("0.0"),
text("replica_health_status") => text("healthy"),
text("certified_height") => serde_cbor::Value::Integer(1),
}),
);
}
#[test]
fn encoding_delegation() {
assert_cbor_ser_equal(
&Delegation {
pubkey: Blob(vec![1, 2, 3]),
expiration: UNIX_EPOCH,
targets: None,
},
Value::Map(btreemap! {
text("pubkey") => bytes(&[1, 2, 3]),
text("expiration") => int(0),
text("targets") => Value::Null,
}),
);
assert_cbor_ser_equal(
&Delegation {
pubkey: Blob(vec![1, 2, 3]),
expiration: UNIX_EPOCH,
targets: Some(vec![Blob(vec![4, 5, 6])]),
},
Value::Map(btreemap! {
text("pubkey") => bytes(&[1, 2, 3]),
text("expiration") => int(0),
text("targets") => Value::Array(vec![bytes(&[4, 5, 6])]),
}),
);
}
#[test]
fn encoding_signed_delegation() {
assert_cbor_ser_equal(
&SignedDelegation {
delegation: Delegation {
pubkey: Blob(vec![1, 2, 3]),
expiration: UNIX_EPOCH,
targets: None,
},
signature: Blob(vec![4, 5, 6]),
},
Value::Map(btreemap! {
text("delegation") => Value::Map(btreemap! {
text("pubkey") => bytes(&[1, 2, 3]),
text("expiration") => int(0),
text("targets") => Value::Null,
}),
text("signature") => bytes(&[4, 5, 6]),
}),
);
}
}