ic-query 0.42.0

Internet Computer query library for CloudEngine, NNS, SNS, ICRC, system canisters, and public network metadata
Documentation
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
use super::{
    SubnetCatalogHostError, SubnetCatalogSourceFailure, SubnetCatalogSubject,
    failure::subject_from_catalog_error,
};
use crate::{
    hex::hex_bytes,
    http_endpoint::parse_http_endpoint,
    ic_registry::{
        fetch_mainnet_subnet_catalog_async, fetch_mainnet_subnet_catalog_detailed_async,
    },
    nns::{LiveNnsSource, NnsSourceRequest, source::mainnet_registry_fetch_request},
    subnet_catalog::{
        CatalogAssurance, CatalogValidationContext, MAINNET_REGISTRY_CANISTER_ID,
        MAX_SUBNET_CATALOG_AGREEMENT_ENDPOINTS, MIN_SUBNET_CATALOG_AGREEMENT_ENDPOINTS,
        RawSubnetCatalog, ValidatedSubnetCatalog, catalog_agreement_digest,
    },
};
use std::{collections::BTreeSet, future::Future, pin::Pin};

///
/// SubnetCatalogSourceFuture
///
/// Boxed caller-runtime future returned by a Subnet Catalog source.
///

pub type SubnetCatalogSourceFuture<'a> =
    Pin<Box<dyn Future<Output = Result<RawSubnetCatalog, SubnetCatalogHostError>> + Send + 'a>>;

///
/// SubnetCatalogDetailedSourceFuture
///
/// Boxed caller-runtime future retaining typed source failure provenance.
///

pub type SubnetCatalogDetailedSourceFuture<'a> =
    Pin<Box<dyn Future<Output = Result<RawSubnetCatalog, SubnetCatalogSourceFailure>> + Send + 'a>>;

///
/// CatalogSourceSelection
///
/// Explicit bounded Registry endpoint selection for one live catalog collection.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CatalogSourceSelection {
    /// Collect ordinary version-consistent evidence from one endpoint.
    UncertifiedQuery {
        /// Exact caller-selected endpoint.
        endpoint: String,
    },
    /// Require an identical Registry version and canonical payload across endpoints.
    MultiEndpointAgreement {
        /// Caller-selected endpoints; each must have a distinct hostname.
        endpoints: Vec<String>,
    },
}

impl CatalogSourceSelection {
    /// Build a single-endpoint uncertified query selection.
    #[must_use]
    pub fn uncertified_query(endpoint: impl Into<String>) -> Self {
        Self::UncertifiedQuery {
            endpoint: endpoint.into(),
        }
    }

    /// Build a bounded multi-endpoint agreement selection.
    #[must_use]
    pub const fn multi_endpoint_agreement(endpoints: Vec<String>) -> Self {
        Self::MultiEndpointAgreement { endpoints }
    }

    /// Return the assurance this source selection attempts to establish.
    #[must_use]
    pub const fn assurance(&self) -> CatalogAssurance {
        match self {
            Self::UncertifiedQuery { .. } => CatalogAssurance::UncertifiedQuery,
            Self::MultiEndpointAgreement { .. } => CatalogAssurance::MultiEndpointAgreement,
        }
    }

    #[expect(
        clippy::result_large_err,
        reason = "source selection failures retain the original host error and endpoint"
    )]
    pub(super) fn validated_endpoints(&self) -> Result<Vec<String>, SubnetCatalogSourceFailure> {
        let (endpoints, agreement) = match self {
            Self::UncertifiedQuery { endpoint } => (vec![endpoint.clone()], false),
            Self::MultiEndpointAgreement { endpoints } => (endpoints.clone(), true),
        };
        if agreement
            && !(MIN_SUBNET_CATALOG_AGREEMENT_ENDPOINTS..=MAX_SUBNET_CATALOG_AGREEMENT_ENDPOINTS)
                .contains(&endpoints.len())
        {
            return Err(SubnetCatalogSourceFailure::from_source(
                SubnetCatalogHostError::InvalidSourceSelection {
                    reason: format!(
                        "multi-endpoint agreement requires {MIN_SUBNET_CATALOG_AGREEMENT_ENDPOINTS}..={MAX_SUBNET_CATALOG_AGREEMENT_ENDPOINTS} endpoints"
                    ),
                },
            ));
        }
        let mut hostnames = BTreeSet::new();
        for endpoint in &endpoints {
            let parsed = parse_http_endpoint(endpoint).map_err(|reason| {
                SubnetCatalogSourceFailure::new(
                    None,
                    Some(SubnetCatalogSubject::Endpoint(endpoint.clone())),
                    SubnetCatalogHostError::InvalidSourceSelection {
                        reason: format!("invalid endpoint {endpoint:?}: {reason}"),
                    },
                )
            })?;
            let hostname = parsed
                .host_str()
                .expect("validated HTTP endpoint has a hostname")
                .to_ascii_lowercase();
            if !hostnames.insert(hostname) {
                return Err(SubnetCatalogSourceFailure::new(
                    None,
                    Some(SubnetCatalogSubject::Endpoint(endpoint.clone())),
                    SubnetCatalogHostError::InvalidSourceSelection {
                        reason: "source endpoints must use distinct hostnames".to_string(),
                    },
                ));
            }
        }
        let mut endpoints = endpoints;
        endpoints.sort();
        Ok(endpoints)
    }
}

/// Fetch one live mainnet catalog without creating a Tokio runtime or helper thread.
pub async fn fetch_subnet_catalog_async(
    request: &NnsSourceRequest,
) -> Result<RawSubnetCatalog, SubnetCatalogHostError> {
    let fetch_request = mainnet_registry_fetch_request(request, |network| {
        SubnetCatalogHostError::UnsupportedNetwork { network }
    })?;
    Ok(fetch_mainnet_subnet_catalog_async(&fetch_request).await?)
}

///
/// SubnetCatalogSource
///
/// Source contract for fetching complete subnet catalog snapshots.
///

pub trait SubnetCatalogSource: Send + Sync {
    /// Fetch one complete single-endpoint snapshot on the caller's async runtime.
    fn fetch_catalog<'a>(&'a self, request: &'a NnsSourceRequest) -> SubnetCatalogSourceFuture<'a>;

    /// Fetch a snapshot while retaining typed failure provenance when the source can provide it.
    fn fetch_catalog_detailed<'a>(
        &'a self,
        request: &'a NnsSourceRequest,
    ) -> SubnetCatalogDetailedSourceFuture<'a> {
        let future = self.fetch_catalog(request);
        Box::pin(async move {
            future
                .await
                .map_err(SubnetCatalogSourceFailure::from_source)
        })
    }
}

impl SubnetCatalogSource for LiveNnsSource {
    fn fetch_catalog<'a>(&'a self, request: &'a NnsSourceRequest) -> SubnetCatalogSourceFuture<'a> {
        Box::pin(fetch_subnet_catalog_async(request))
    }

    fn fetch_catalog_detailed<'a>(
        &'a self,
        request: &'a NnsSourceRequest,
    ) -> SubnetCatalogDetailedSourceFuture<'a> {
        Box::pin(async move {
            let fetch_request = mainnet_registry_fetch_request(request, |network| {
                SubnetCatalogHostError::UnsupportedNetwork { network }
            })
            .map_err(SubnetCatalogSourceFailure::from_source)?;
            fetch_mainnet_subnet_catalog_detailed_async(&fetch_request)
                .await
                .map_err(|failure| {
                    SubnetCatalogSourceFailure::new(
                        failure.registry_version,
                        failure.subject,
                        SubnetCatalogHostError::RegistryRefresh(failure.source),
                    )
                    .with_registry_evidence(
                        failure.returned_registry_value_version,
                        failure.source_endpoint,
                        failure.assurance,
                        failure.registry_records,
                    )
                })
        })
    }
}

pub(super) async fn collect_subnet_catalog_detailed(
    network: &str,
    endpoints: Vec<String>,
    fetched_at: &str,
    fetched_by: &str,
    now_unix_secs: u64,
    max_future_skew_seconds: u64,
    source: &dyn SubnetCatalogSource,
) -> Result<RawSubnetCatalog, SubnetCatalogSourceFailure> {
    let validation = CatalogValidationContext::new(
        network,
        MAINNET_REGISTRY_CANISTER_ID,
        now_unix_secs,
        max_future_skew_seconds,
    );
    let mut snapshots = Vec::with_capacity(endpoints.len());
    for endpoint in &endpoints {
        let request = NnsSourceRequest::new(network, endpoint, fetched_at, fetched_by);
        let raw = source
            .fetch_catalog_detailed(&request)
            .await
            .map_err(|error| endpoint_error(error, endpoint, endpoints.len()))?;
        let registry_version = raw.provenance.registry_version;
        let registry_records = raw.provenance.registry_records.clone();
        let catalog = ValidatedSubnetCatalog::try_from_raw(raw, &validation)
            .map_err(|source| {
                let subject = subject_from_catalog_error(&source);
                SubnetCatalogSourceFailure::new(
                    Some(registry_version),
                    subject,
                    SubnetCatalogHostError::from(source),
                )
                .with_registry_evidence(None, None, None, registry_records)
            })
            .map_err(|error| endpoint_error(error, endpoint, endpoints.len()))?;
        if catalog.provenance().assurance != CatalogAssurance::UncertifiedQuery
            || catalog.provenance().source_endpoints.len() != 1
            || catalog.provenance().source_endpoints[0] != *endpoint
        {
            return Err(SubnetCatalogSourceFailure::new(
                Some(catalog.provenance().registry_version),
                Some(SubnetCatalogSubject::Endpoint(endpoint.clone())),
                SubnetCatalogHostError::SourceEvidenceMismatch {
                    requested: endpoint.clone(),
                    actual_assurance: catalog.provenance().assurance,
                    actual_endpoints: catalog.provenance().source_endpoints.clone(),
                },
            )
            .with_registry_evidence(
                None,
                None,
                None,
                catalog.provenance().registry_records.clone(),
            ));
        }
        snapshots.push(catalog.into_raw());
    }

    if snapshots.len() == 1 {
        return Ok(snapshots.pop().expect("single endpoint snapshot"));
    }

    finish_agreement(snapshots, endpoints, &validation)
}

#[expect(
    clippy::result_large_err,
    clippy::too_many_lines,
    reason = "agreement failures retain completed per-endpoint evidence in one auditable sequence"
)]
fn finish_agreement(
    mut snapshots: Vec<RawSubnetCatalog>,
    endpoints: Vec<String>,
    validation: &CatalogValidationContext,
) -> Result<RawSubnetCatalog, SubnetCatalogSourceFailure> {
    let completed_registry_records = snapshots
        .iter()
        .flat_map(|snapshot| snapshot.provenance.registry_records.iter().cloned())
        .collect::<Vec<_>>();
    let mut first = snapshots.remove(0);
    let reference_endpoint = endpoints[0].clone();
    let reference_registry_version = first.provenance.registry_version;
    let reference_agreement_digest =
        hex_bytes(&catalog_agreement_digest(&first).map_err(|source| {
            let subject = subject_from_catalog_error(&source);
            SubnetCatalogSourceFailure::new(
                Some(reference_registry_version),
                subject,
                SubnetCatalogHostError::Catalog(source),
            )
            .with_registry_evidence(
                None,
                None,
                None,
                completed_registry_records.clone(),
            )
        })?);
    let mut registry_query_call_count = first.provenance.registry_query_call_count;
    for (endpoint, snapshot) in endpoints.iter().skip(1).zip(&snapshots) {
        let registry_version = snapshot.provenance.registry_version;
        let agreement_digest =
            hex_bytes(&catalog_agreement_digest(snapshot).map_err(|source| {
                let subject = subject_from_catalog_error(&source);
                SubnetCatalogSourceFailure::new(
                    Some(registry_version),
                    subject,
                    SubnetCatalogHostError::Catalog(source),
                )
                .with_registry_evidence(
                    None,
                    None,
                    None,
                    completed_registry_records.clone(),
                )
            })?);
        if registry_version != reference_registry_version
            || agreement_digest != reference_agreement_digest
        {
            return Err(SubnetCatalogSourceFailure::new(
                Some(registry_version),
                Some(SubnetCatalogSubject::Endpoint(endpoint.clone())),
                SubnetCatalogHostError::AgreementMismatch {
                    reference_endpoint,
                    reference_registry_version,
                    reference_agreement_digest,
                    endpoint: endpoint.clone(),
                    registry_version,
                    agreement_digest,
                },
            )
            .with_registry_evidence(None, None, None, completed_registry_records));
        }
        registry_query_call_count = registry_query_call_count
            .checked_add(snapshot.provenance.registry_query_call_count)
            .ok_or_else(|| {
                SubnetCatalogSourceFailure::new(
                    Some(reference_registry_version),
                    None,
                    SubnetCatalogHostError::RegistryQueryCallCountOverflow,
                )
                .with_registry_evidence(
                    None,
                    None,
                    None,
                    completed_registry_records.clone(),
                )
            })?;
    }
    first
        .provenance
        .registry_records
        .clone_from(&completed_registry_records);
    first
        .promote_to_multi_endpoint_agreement(endpoints, registry_query_call_count)
        .map_err(|source| {
            let subject = subject_from_catalog_error(&source);
            SubnetCatalogSourceFailure::new(
                Some(reference_registry_version),
                subject,
                SubnetCatalogHostError::Catalog(source),
            )
            .with_registry_evidence(
                None,
                None,
                None,
                completed_registry_records.clone(),
            )
        })?;
    ValidatedSubnetCatalog::try_from_raw(first.clone(), validation).map_err(|source| {
        let subject = subject_from_catalog_error(&source);
        SubnetCatalogSourceFailure::new(
            Some(reference_registry_version),
            subject,
            SubnetCatalogHostError::Catalog(source),
        )
        .with_registry_evidence(None, None, None, completed_registry_records)
    })?;
    Ok(first)
}

fn endpoint_error(
    error: SubnetCatalogSourceFailure,
    endpoint: &str,
    endpoint_count: usize,
) -> SubnetCatalogSourceFailure {
    if endpoint_count == 1 {
        error
    } else {
        SubnetCatalogSourceFailure::new(
            error.registry_version,
            error.subject,
            SubnetCatalogHostError::AgreementEndpoint {
                endpoint: endpoint.to_string(),
                source: Box::new(error.source),
            },
        )
        .with_registry_evidence(
            error.returned_registry_value_version,
            error.source_endpoint.or_else(|| Some(endpoint.to_string())),
            error.assurance,
            error.registry_records,
        )
    }
}