ic-query 0.30.25

Internet Computer query library for 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
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
//! Module: nns::registry::replay::certified_catalog_cache
//!
//! Responsibility: publish and load archive-bound catalogs under explicit local cache policy.
//! Does not own: archive collection, archive refresh, network read-through, defaults, or CLI.
//! Boundary: serialized cache content gains authority only by exact comparison with a fresh
//! projection from the caller-supplied authenticated archive.

use super::{
    NnsAuthenticatedRegistryArchive, NnsCertifiedSubnetCatalogAuthority,
    NnsCertifiedSubnetCatalogProjectionRequest, NnsRegistrySubnetCatalogProjectionError,
    project_nns_certified_subnet_catalog,
};
use crate::{
    cache_file::{
        BoundedManagedFileReadError, CacheFileError, RefreshLockRequest,
        create_managed_parent_directory, read_bounded_managed_file, with_refresh_lock,
        write_managed_file_atomically,
    },
    hex::hex_bytes,
    subnet_catalog::{CatalogAssurance, MAINNET_NETWORK, RawSubnetCatalog},
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
    io::{self, Write},
    path::{Path, PathBuf},
};
use thiserror::Error as ThisError;

const CERTIFIED_CATALOG_FILE_NAME: &str = "catalog.json";
const CERTIFIED_CATALOG_LOCK_FILE_NAME: &str = "refresh.lock";

/// Version of the archive-bound certified Subnet Catalog cache envelope.
pub const NNS_CERTIFIED_SUBNET_CATALOG_CACHE_SCHEMA_VERSION: u32 = 1;

///
/// NnsCertifiedSubnetCatalogCacheLocation
///
/// Caller-selected confined location and byte ceiling for one certified catalog cache.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NnsCertifiedSubnetCatalogCacheLocation {
    /// Capability root that confines the cache directory and files.
    pub cache_root: PathBuf,
    /// Dedicated certified-catalog directory beneath `cache_root`.
    pub cache_directory: PathBuf,
    /// Maximum canonical bytes accepted for the complete cache envelope.
    pub maximum_cache_bytes: u64,
}

impl NnsCertifiedSubnetCatalogCacheLocation {
    /// Create one explicit certified cache location without choosing a default path or ceiling.
    #[must_use]
    pub fn new(
        cache_root: impl Into<PathBuf>,
        cache_directory: impl Into<PathBuf>,
        maximum_cache_bytes: u64,
    ) -> Self {
        Self {
            cache_root: cache_root.into(),
            cache_directory: cache_directory.into(),
            maximum_cache_bytes,
        }
    }
}

///
/// NnsCertifiedSubnetCatalogReadPolicy
///
/// Exact local cache behavior authorized for one certified catalog load.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NnsCertifiedSubnetCatalogReadPolicy {
    /// Load and authenticate existing cache content without mutating it.
    CacheOnly,
    /// Publish from the supplied archive only when cache content is absent.
    PublishMissing {
        /// Age after which an abandoned publication lock is reported as stale.
        lock_stale_after_seconds: u64,
    },
    /// Publish from the supplied archive when cache content is absent or recoverably invalid.
    PublishMissingOrInvalid {
        /// Age after which an abandoned publication lock is reported as stale.
        lock_stale_after_seconds: u64,
    },
    /// Unconditionally publish from the supplied archive.
    ForcePublication {
        /// Age after which an abandoned publication lock is reported as stale.
        lock_stale_after_seconds: u64,
    },
}

///
/// NnsCertifiedSubnetCatalogLoadRequest
///
/// Caller-selected confined location and exact certified cache read policy.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NnsCertifiedSubnetCatalogLoadRequest {
    /// Confined cache location and canonical byte ceiling.
    pub location: NnsCertifiedSubnetCatalogCacheLocation,
    /// Authorized local cache behavior.
    pub policy: NnsCertifiedSubnetCatalogReadPolicy,
}

impl NnsCertifiedSubnetCatalogLoadRequest {
    /// Build a cache-only request that cannot publish or make a network call.
    #[must_use]
    pub const fn cache_only(location: NnsCertifiedSubnetCatalogCacheLocation) -> Self {
        Self {
            location,
            policy: NnsCertifiedSubnetCatalogReadPolicy::CacheOnly,
        }
    }

    /// Build a request that publishes only when cache content is absent.
    #[must_use]
    pub const fn publish_missing(
        location: NnsCertifiedSubnetCatalogCacheLocation,
        lock_stale_after_seconds: u64,
    ) -> Self {
        Self {
            location,
            policy: NnsCertifiedSubnetCatalogReadPolicy::PublishMissing {
                lock_stale_after_seconds,
            },
        }
    }

    /// Build a request that publishes when cache content is absent or recoverably invalid.
    #[must_use]
    pub const fn publish_missing_or_invalid(
        location: NnsCertifiedSubnetCatalogCacheLocation,
        lock_stale_after_seconds: u64,
    ) -> Self {
        Self {
            location,
            policy: NnsCertifiedSubnetCatalogReadPolicy::PublishMissingOrInvalid {
                lock_stale_after_seconds,
            },
        }
    }

    /// Build a request that unconditionally publishes from the supplied archive.
    #[must_use]
    pub const fn force_publication(
        location: NnsCertifiedSubnetCatalogCacheLocation,
        lock_stale_after_seconds: u64,
    ) -> Self {
        Self {
            location,
            policy: NnsCertifiedSubnetCatalogReadPolicy::ForcePublication {
                lock_stale_after_seconds,
            },
        }
    }

    /// Replace the exact local cache policy.
    #[must_use]
    pub const fn with_policy(mut self, policy: NnsCertifiedSubnetCatalogReadPolicy) -> Self {
        self.policy = policy;
        self
    }
}

///
/// NnsCertifiedSubnetCatalogCacheEnvelope
///
/// Serializable catalog and archive commitments; this DTO is untrusted outside a cache authority.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct NnsCertifiedSubnetCatalogCacheEnvelope {
    /// Certified-catalog cache schema version.
    pub schema_version: u32,
    /// SHA-256 of the canonical authenticated archive manifest.
    pub archive_manifest_sha256: String,
    /// Complete canonical catalog, including Registry, assurance, certificate, and policy identity.
    /// This serde-facing field cannot self-promote its `Certified` assurance.
    pub catalog: RawSubnetCatalog,
}

#[derive(Serialize)]
struct CertifiedCatalogCacheEnvelopeRef<'a> {
    schema_version: u32,
    archive_manifest_sha256: String,
    catalog: &'a RawSubnetCatalog,
}

///
/// NnsCertifiedSubnetCatalogCacheDisposition
///
/// Observable local cache action that supplied one certified catalog authority.
///

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum NnsCertifiedSubnetCatalogCacheDisposition {
    /// Existing cache content exactly matched the authenticated archive projection.
    CacheHit,
    /// Missing cache content was explicitly published from the supplied archive.
    PublishedMissing,
    /// Recoverably invalid cache content was explicitly replaced from the supplied archive.
    PublishedInvalid,
    /// The caller explicitly requested unconditional atomic publication.
    ForcedPublication,
}

impl NnsCertifiedSubnetCatalogCacheDisposition {
    /// Return the stable JSON and diagnostic label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CacheHit => "cache_hit",
            Self::PublishedMissing => "published_missing",
            Self::PublishedInvalid => "published_invalid",
            Self::ForcedPublication => "forced_publication",
        }
    }
}

///
/// NnsCertifiedSubnetCatalogCacheEvidence
///
/// Compact persistable catalog, archive, certificate, and cache-action identity.
/// This serde DTO describes a successful authority but cannot reconstruct or self-assert it.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct NnsCertifiedSubnetCatalogCacheEvidence {
    /// Exact Registry version represented by the certified catalog.
    pub registry_version: u64,
    /// Lowercase SHA-256 digest of the canonical catalog authority payload.
    pub catalog_digest: String,
    /// Assurance established by the attached authenticated archive.
    pub assurance: CatalogAssurance,
    /// Canonically ordered source endpoints retained by the archive.
    pub source_endpoints: Vec<String>,
    /// Lowercase SHA-256 of the complete canonical archive manifest.
    pub archive_manifest_sha256: String,
    /// Lowercase digest of the trusted mainnet root key used by the archive.
    pub root_key_digest: String,
    /// Lowercase commitment to the ordered authenticated report sequence.
    pub evidence_chain_digest: String,
    /// Lowercase commitment to the exact reconstructed Registry state.
    pub complete_state_digest: String,
    /// Earliest authenticated certificate time across retained archive batches.
    pub minimum_certificate_time_nanos: u64,
    /// Latest authenticated certificate time across retained archive batches.
    pub maximum_certificate_time_nanos: u64,
    /// Observable local cache action that supplied the authority.
    pub cache_disposition: NnsCertifiedSubnetCatalogCacheDisposition,
}

///
/// NnsCertifiedSubnetCatalogLoadOutcome
///
/// Cache envelope exactly matched to a fresh projection from its attached authenticated archive.
///

#[derive(Debug, Eq, PartialEq)]
pub struct NnsCertifiedSubnetCatalogLoadOutcome<'a> {
    authority: NnsCertifiedSubnetCatalogAuthority<'a>,
    path: PathBuf,
    archive_manifest_sha256: String,
    disposition: NnsCertifiedSubnetCatalogCacheDisposition,
}

impl<'a> NnsCertifiedSubnetCatalogLoadOutcome<'a> {
    /// Return the freshly projected catalog authority qualifying the cached snapshot.
    #[must_use]
    pub const fn authority(&self) -> &NnsCertifiedSubnetCatalogAuthority<'a> {
        &self.authority
    }

    /// Return the exact confined cache path supplying or receiving the snapshot.
    #[must_use]
    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    /// Return the observable local cache action used by this operation.
    #[must_use]
    pub const fn disposition(&self) -> NnsCertifiedSubnetCatalogCacheDisposition {
        self.disposition
    }

    /// Return compact authority evidence suitable for embedding in a durable plan.
    #[must_use]
    pub fn authority_evidence(&self) -> NnsCertifiedSubnetCatalogCacheEvidence {
        let provenance = self.authority.catalog().provenance();
        let manifest = self.authority.archive().manifest();
        NnsCertifiedSubnetCatalogCacheEvidence {
            registry_version: provenance.registry_version,
            catalog_digest: self.authority.catalog().raw().catalog_digest.clone(),
            assurance: provenance.assurance,
            source_endpoints: provenance.source_endpoints.clone(),
            archive_manifest_sha256: self.archive_manifest_sha256.clone(),
            root_key_digest: manifest.root_key_digest.clone(),
            evidence_chain_digest: manifest.evidence_chain_digest.clone(),
            complete_state_digest: manifest.complete_state_digest.clone(),
            minimum_certificate_time_nanos: manifest.minimum_certificate_time_nanos,
            maximum_certificate_time_nanos: manifest.maximum_certificate_time_nanos,
            cache_disposition: self.disposition,
        }
    }
}

///
/// NnsCertifiedSubnetCatalogCacheError
///
/// Typed projection, confinement, limit, encoding, and archive-binding failures.
///

#[derive(Debug, ThisError)]
pub enum NnsCertifiedSubnetCatalogCacheError {
    /// The authenticated archive did not qualify for certified catalog projection.
    #[error(transparent)]
    Projection(#[from] NnsRegistrySubnetCatalogProjectionError),

    /// A confined cache or publication-lock operation failed.
    #[error("certified Subnet Catalog cache filesystem operation failed: {source}")]
    FileOperation {
        /// Underlying confined cache-file failure.
        #[source]
        source: CacheFileError,
    },

    /// The caller-selected cache file does not exist.
    #[error("certified Subnet Catalog cache is missing at {path}")]
    MissingCache {
        /// Exact managed cache path that was absent.
        path: PathBuf,
    },

    /// The cache exceeded the caller-selected canonical byte ceiling.
    #[error(
        "certified Subnet Catalog cache at {path} exceeds its byte limit: actual={actual}, maximum={maximum}"
    )]
    CacheLimitExceeded {
        /// Exact managed cache path.
        path: PathBuf,
        /// Observed or encoded cache bytes.
        actual: u64,
        /// Caller-selected maximum bytes.
        maximum: u64,
    },

    /// Cache bytes are not a valid strict envelope.
    #[error("certified Subnet Catalog cache at {path} is invalid JSON: {source}")]
    InvalidJson {
        /// Exact managed cache path.
        path: PathBuf,
        /// Strict JSON decoding failure.
        #[source]
        source: serde_json::Error,
    },

    /// Cache JSON is valid but is not the one canonical compact encoding.
    #[error("certified Subnet Catalog cache at {path} is not canonical compact JSON")]
    NonCanonicalEncoding {
        /// Exact managed cache path.
        path: PathBuf,
    },

    /// The decoded cache uses an unsupported envelope schema.
    #[error(
        "unsupported certified Subnet Catalog cache schema {found}; supported schema is {supported}"
    )]
    UnsupportedSchemaVersion {
        /// Schema found in the cache.
        found: u32,
        /// Schema implemented by this library version.
        supported: u32,
    },

    /// Cache content does not exactly match the caller-supplied authenticated archive projection.
    #[error(
        "certified Subnet Catalog cache field {field} does not match the supplied authenticated Registry archive projection"
    )]
    ArchiveBindingMismatch {
        /// First deterministic envelope field that disagreed.
        field: &'static str,
    },

    /// Canonical serialization or byte accounting failed.
    #[error("certified Subnet Catalog cache serialization failed: {source}")]
    Serialization {
        /// JSON serialization failure.
        #[source]
        source: serde_json::Error,
    },

    /// A platform byte count cannot be represented by the public accounting type.
    #[error("certified Subnet Catalog cache byte accounting overflowed")]
    Accounting,
}

/// Return the fixed cache-envelope path beneath a caller-selected dedicated directory.
#[must_use]
pub fn nns_certified_subnet_catalog_cache_path(cache_directory: &Path) -> PathBuf {
    cache_directory.join(CERTIFIED_CATALOG_FILE_NAME)
}

/// Return the dedicated publication-lock path beneath a caller-selected cache directory.
#[must_use]
pub fn nns_certified_subnet_catalog_cache_refresh_lock_path(cache_directory: &Path) -> PathBuf {
    cache_directory.join(CERTIFIED_CATALOG_LOCK_FILE_NAME)
}

/// Load certified Subnet Catalog authority under one explicit local cache policy.
///
/// Every successful outcome is recomputed from and exactly matched to `archive`. No policy refreshes
/// that archive or makes a network call. Publication completes projection before filesystem mutation
/// and preserves prior cache content if qualification, lock acquisition, serialization, or atomic
/// replacement fails. A lock-release error can be reported after replacement has completed.
pub fn load_nns_certified_subnet_catalog<'a>(
    archive: &'a NnsAuthenticatedRegistryArchive,
    projection_request: &NnsCertifiedSubnetCatalogProjectionRequest,
    request: &NnsCertifiedSubnetCatalogLoadRequest,
) -> Result<NnsCertifiedSubnetCatalogLoadOutcome<'a>, NnsCertifiedSubnetCatalogCacheError> {
    match request.policy {
        NnsCertifiedSubnetCatalogReadPolicy::CacheOnly => {
            load_cached_catalog(archive, projection_request, &request.location)
        }
        NnsCertifiedSubnetCatalogReadPolicy::PublishMissing {
            lock_stale_after_seconds,
        } => match load_cached_catalog(archive, projection_request, &request.location) {
            Err(NnsCertifiedSubnetCatalogCacheError::MissingCache { .. }) => {
                publish_cache_with_disposition(
                    archive,
                    projection_request,
                    &request.location,
                    lock_stale_after_seconds,
                    NnsCertifiedSubnetCatalogCacheDisposition::PublishedMissing,
                )
            }
            result => result,
        },
        NnsCertifiedSubnetCatalogReadPolicy::PublishMissingOrInvalid {
            lock_stale_after_seconds,
        } => match load_cached_catalog(archive, projection_request, &request.location) {
            Err(error) => {
                let disposition = recoverable_publication_disposition(error)?;
                publish_cache_with_disposition(
                    archive,
                    projection_request,
                    &request.location,
                    lock_stale_after_seconds,
                    disposition,
                )
            }
            result => result,
        },
        NnsCertifiedSubnetCatalogReadPolicy::ForcePublication {
            lock_stale_after_seconds,
        } => publish_cache_with_disposition(
            archive,
            projection_request,
            &request.location,
            lock_stale_after_seconds,
            NnsCertifiedSubnetCatalogCacheDisposition::ForcedPublication,
        ),
    }
}

fn publish_cache_with_disposition<'a>(
    archive: &'a NnsAuthenticatedRegistryArchive,
    projection_request: &NnsCertifiedSubnetCatalogProjectionRequest,
    location: &NnsCertifiedSubnetCatalogCacheLocation,
    lock_stale_after_seconds: u64,
    disposition: NnsCertifiedSubnetCatalogCacheDisposition,
) -> Result<NnsCertifiedSubnetCatalogLoadOutcome<'a>, NnsCertifiedSubnetCatalogCacheError> {
    let authority = project_nns_certified_subnet_catalog(archive, projection_request)?;
    let envelope = cache_envelope(&authority)?;
    let cache_path = nns_certified_subnet_catalog_cache_path(&location.cache_directory);
    let lock_path = nns_certified_subnet_catalog_cache_refresh_lock_path(&location.cache_directory);
    let encoded_length = canonical_serialized_len(&envelope)?;
    enforce_cache_limit(&cache_path, encoded_length, location.maximum_cache_bytes)?;
    create_managed_parent_directory(&location.cache_root, &cache_path).map_err(file_operation)?;
    with_refresh_lock(
        RefreshLockRequest {
            cache_root: &location.cache_root,
            lock_path: &lock_path,
            target_path: &cache_path,
            network: MAINNET_NETWORK,
            now_unix_secs: projection_request.validation.now_unix_secs,
            lock_stale_after_seconds,
        },
        file_operation,
        || {
            write_managed_file_atomically(&location.cache_root, &cache_path, |file| {
                serde_json::to_writer(file, &envelope).map_err(json_io_error)
            })
            .map_err(file_operation)
        },
    )?;
    let archive_manifest_sha256 = envelope.archive_manifest_sha256;
    Ok(NnsCertifiedSubnetCatalogLoadOutcome {
        authority,
        path: cache_path,
        archive_manifest_sha256,
        disposition,
    })
}

fn load_cached_catalog<'a>(
    archive: &'a NnsAuthenticatedRegistryArchive,
    projection_request: &NnsCertifiedSubnetCatalogProjectionRequest,
    location: &NnsCertifiedSubnetCatalogCacheLocation,
) -> Result<NnsCertifiedSubnetCatalogLoadOutcome<'a>, NnsCertifiedSubnetCatalogCacheError> {
    let cache_path = nns_certified_subnet_catalog_cache_path(&location.cache_directory);
    let bytes = read_bounded_cache(location, &cache_path)?.ok_or_else(|| {
        NnsCertifiedSubnetCatalogCacheError::MissingCache {
            path: cache_path.clone(),
        }
    })?;
    let envelope: NnsCertifiedSubnetCatalogCacheEnvelope =
        serde_json::from_slice(&bytes).map_err(|source| {
            NnsCertifiedSubnetCatalogCacheError::InvalidJson {
                path: cache_path.clone(),
                source,
            }
        })?;
    if envelope.schema_version != NNS_CERTIFIED_SUBNET_CATALOG_CACHE_SCHEMA_VERSION {
        return Err(
            NnsCertifiedSubnetCatalogCacheError::UnsupportedSchemaVersion {
                found: envelope.schema_version,
                supported: NNS_CERTIFIED_SUBNET_CATALOG_CACHE_SCHEMA_VERSION,
            },
        );
    }
    if !is_canonical_encoding(&envelope, &bytes)? {
        return Err(NnsCertifiedSubnetCatalogCacheError::NonCanonicalEncoding { path: cache_path });
    }
    let authority = project_nns_certified_subnet_catalog(archive, projection_request)?;
    let expected = cache_envelope(&authority)?;
    if let Some(field) = first_envelope_mismatch(&envelope, &expected) {
        return Err(NnsCertifiedSubnetCatalogCacheError::ArchiveBindingMismatch { field });
    }
    Ok(NnsCertifiedSubnetCatalogLoadOutcome {
        authority,
        path: cache_path,
        archive_manifest_sha256: envelope.archive_manifest_sha256,
        disposition: NnsCertifiedSubnetCatalogCacheDisposition::CacheHit,
    })
}

fn recoverable_publication_disposition(
    error: NnsCertifiedSubnetCatalogCacheError,
) -> Result<NnsCertifiedSubnetCatalogCacheDisposition, NnsCertifiedSubnetCatalogCacheError> {
    match error {
        NnsCertifiedSubnetCatalogCacheError::MissingCache { .. } => {
            Ok(NnsCertifiedSubnetCatalogCacheDisposition::PublishedMissing)
        }
        NnsCertifiedSubnetCatalogCacheError::CacheLimitExceeded { .. }
        | NnsCertifiedSubnetCatalogCacheError::InvalidJson { .. }
        | NnsCertifiedSubnetCatalogCacheError::NonCanonicalEncoding { .. }
        | NnsCertifiedSubnetCatalogCacheError::UnsupportedSchemaVersion { .. }
        | NnsCertifiedSubnetCatalogCacheError::ArchiveBindingMismatch { .. } => {
            Ok(NnsCertifiedSubnetCatalogCacheDisposition::PublishedInvalid)
        }
        error => Err(error),
    }
}

fn first_envelope_mismatch(
    cached: &NnsCertifiedSubnetCatalogCacheEnvelope,
    expected: &CertifiedCatalogCacheEnvelopeRef<'_>,
) -> Option<&'static str> {
    if cached.schema_version != expected.schema_version {
        return Some("schema_version");
    }
    if cached.archive_manifest_sha256 != expected.archive_manifest_sha256 {
        return Some("archive_manifest_sha256");
    }
    if &cached.catalog != expected.catalog {
        return Some("catalog");
    }
    None
}

fn cache_envelope<'a>(
    authority: &'a NnsCertifiedSubnetCatalogAuthority<'_>,
) -> Result<CertifiedCatalogCacheEnvelopeRef<'a>, NnsCertifiedSubnetCatalogCacheError> {
    let manifest = authority.archive().manifest();
    let catalog = authority.catalog().raw();
    Ok(CertifiedCatalogCacheEnvelopeRef {
        schema_version: NNS_CERTIFIED_SUBNET_CATALOG_CACHE_SCHEMA_VERSION,
        archive_manifest_sha256: canonical_sha256(manifest)?,
        catalog,
    })
}

fn canonical_sha256(value: &impl Serialize) -> Result<String, NnsCertifiedSubnetCatalogCacheError> {
    let mut digest = Sha256::new();
    serde_json::to_writer(&mut digest, value)
        .map_err(|source| NnsCertifiedSubnetCatalogCacheError::Serialization { source })?;
    Ok(hex_bytes(&digest.finalize()))
}

fn canonical_serialized_len(
    value: &impl Serialize,
) -> Result<u64, NnsCertifiedSubnetCatalogCacheError> {
    let mut writer = CountingWriter::default();
    serde_json::to_writer(&mut writer, value)
        .map_err(|source| NnsCertifiedSubnetCatalogCacheError::Serialization { source })?;
    Ok(writer.bytes)
}

fn is_canonical_encoding(
    value: &impl Serialize,
    bytes: &[u8],
) -> Result<bool, NnsCertifiedSubnetCatalogCacheError> {
    let mut writer = MatchingWriter::new(bytes);
    serde_json::to_writer(&mut writer, value)
        .map_err(|source| NnsCertifiedSubnetCatalogCacheError::Serialization { source })?;
    Ok(writer.is_complete_match())
}

fn read_bounded_cache(
    location: &NnsCertifiedSubnetCatalogCacheLocation,
    path: &Path,
) -> Result<Option<Vec<u8>>, NnsCertifiedSubnetCatalogCacheError> {
    read_bounded_managed_file(&location.cache_root, path, location.maximum_cache_bytes).map_err(
        |error| match error {
            BoundedManagedFileReadError::Operation(source) => file_operation(source),
            BoundedManagedFileReadError::Read { path, source } => {
                file_operation(CacheFileError::OpenManagedPath {
                    root: location.cache_root.clone(),
                    path,
                    source,
                })
            }
            BoundedManagedFileReadError::LimitExceeded {
                path,
                actual,
                maximum,
            } => NnsCertifiedSubnetCatalogCacheError::CacheLimitExceeded {
                path,
                actual,
                maximum,
            },
            BoundedManagedFileReadError::Accounting { .. } => {
                NnsCertifiedSubnetCatalogCacheError::Accounting
            }
        },
    )
}

fn enforce_cache_limit(
    path: &Path,
    actual: u64,
    maximum: u64,
) -> Result<(), NnsCertifiedSubnetCatalogCacheError> {
    if actual > maximum {
        return Err(NnsCertifiedSubnetCatalogCacheError::CacheLimitExceeded {
            path: path.to_path_buf(),
            actual,
            maximum,
        });
    }
    Ok(())
}

const fn file_operation(source: CacheFileError) -> NnsCertifiedSubnetCatalogCacheError {
    NnsCertifiedSubnetCatalogCacheError::FileOperation { source }
}

fn json_io_error(source: serde_json::Error) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, source)
}

#[derive(Default)]
struct CountingWriter {
    bytes: u64,
}

impl Write for CountingWriter {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let length = u64::try_from(bytes.len())
            .map_err(|_| io::Error::other("serialized byte count overflowed"))?;
        self.bytes = self
            .bytes
            .checked_add(length)
            .ok_or_else(|| io::Error::other("serialized byte count overflowed"))?;
        Ok(bytes.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

struct MatchingWriter<'a> {
    expected: &'a [u8],
    position: usize,
    matches: bool,
}

impl<'a> MatchingWriter<'a> {
    const fn new(expected: &'a [u8]) -> Self {
        Self {
            expected,
            position: 0,
            matches: true,
        }
    }

    const fn is_complete_match(&self) -> bool {
        self.matches && self.position == self.expected.len()
    }
}

impl Write for MatchingWriter<'_> {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let end = self
            .position
            .checked_add(bytes.len())
            .ok_or_else(|| io::Error::other("serialized byte count overflowed"))?;
        if self.expected.get(self.position..end) != Some(bytes) {
            self.matches = false;
        }
        self.position = end;
        Ok(bytes.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}