Skip to main content

ic_backup/model/ic_observation/
mod.rs

1//! Exact already reserved IC recovery observations and bounded passive replies.
2
3use crate::model::attempt_journal::{ObservationReservation, ObservationReservationError};
4use crate::model::{
5    artifacts::ArtifactChecksumRecord,
6    attempt_journal::{AttemptAuthorityRecord, AttemptJournalRecord, MAX_OPERATION_ATTEMPTS},
7    ic_lifecycle_reply::MAX_IC_LIFECYCLE_REPLY_BYTES,
8    ic_request::{IcManagementRequestRecord, IcRequestError},
9    ic_snapshot_reply::MAX_IC_SNAPSHOT_REPLY_BYTES,
10    operation_plan::{OperationPlanError, OperationPlanRecord, PlanContextRecord},
11};
12use std::fmt;
13use thiserror::Error;
14
15/// Raw observation reply bound derived from both existing method-specific codecs.
16pub const MAX_IC_OBSERVATION_REPLY_BYTES: usize =
17    if MAX_IC_SNAPSHOT_REPLY_BYTES < MAX_IC_LIFECYCLE_REPLY_BYTES {
18        MAX_IC_SNAPSHOT_REPLY_BYTES
19    } else {
20        MAX_IC_LIFECYCLE_REPLY_BYTES
21    };
22
23/// Structural binding to an original pending mutation and its reserved IC observation.
24///
25/// Retain original observation bytes before reserving their existing payload digest.
26/// This request neither spends nor proves dispatch custody, fresh read permission,
27/// authentication or effect attribution. Recovery never permits repeating a lost call.
28#[derive(Debug)]
29pub struct IcObservationRequest<'a> {
30    plan: &'a OperationPlanRecord,
31    mutation: &'a IcManagementRequestRecord,
32    payload: &'a IcManagementRequestRecord,
33    reservation: ObservationReservation,
34}
35
36impl<'a> IcObservationRequest<'a> {
37    /// Bind original mutation bytes and exact already reserved status/list bytes.
38    ///
39    /// Both payloads must name the same original target. Observation identity reuses
40    /// the existing IC payload digest; no second hash or journal owner is introduced.
41    /// # Errors
42    /// Rejects changed authority/payloads or missing original pending reservations.
43    pub fn new(
44        plan: &'a OperationPlanRecord,
45        operation_sequence: u64,
46        journal: &AttemptJournalRecord,
47        mutation: &'a IcManagementRequestRecord,
48        payload: &'a IcManagementRequestRecord,
49    ) -> Result<Self, IcObservationRequestError> {
50        let authority = plan.attempt_authority_for_journal(
51            operation_sequence,
52            journal,
53            IcObservationRequestError::Reservation(ObservationReservationError::AuthorityMismatch),
54        )?;
55        mutation.validate_mutation_binding(authority.binding())?;
56        payload.validate_observation_binding(authority.binding(), &payload.digest())?;
57        let reservation = ObservationReservation::new(authority, journal, payload.digest())?;
58        let request = Self {
59            plan,
60            mutation,
61            payload,
62            reservation,
63        };
64        Ok(request)
65    }
66    /// Read the full original context, inventory and selection.
67    #[must_use]
68    pub const fn plan(&self) -> &OperationPlanRecord {
69        self.plan
70    }
71    /// Read the exact original mutation, never an executable retry.
72    #[must_use]
73    pub const fn mutation(&self) -> &'a IcManagementRequestRecord {
74        self.mutation
75    }
76    /// Read exact observation receiver, routing target, method and Candid bytes.
77    #[must_use]
78    pub const fn payload(&self) -> &'a IcManagementRequestRecord {
79        self.payload
80    }
81    /// Read the original operation authority and immutable attempt limits.
82    #[must_use]
83    pub const fn authority(&self) -> &AttemptAuthorityRecord {
84        &self.reservation.authority
85    }
86    /// Read the original unresolved mutation attempt.
87    #[must_use]
88    pub const fn mutation_attempt(&self) -> u32 {
89        self.reservation.mutation_attempt
90    }
91    /// Read the original already consumed observation attempt.
92    #[must_use]
93    pub const fn observation_attempt(&self) -> u32 {
94        self.reservation.observation_attempt
95    }
96    /// Recheck current exact reservations and original observation bytes without IO.
97    /// # Errors
98    /// Rejects changed authority, settled/replaced attempts or different reserved bytes.
99    pub fn validate_journal(
100        &self,
101        journal: &AttemptJournalRecord,
102    ) -> Result<(), ObservationReservationError> {
103        self.reservation.validate(journal)
104    }
105}
106
107/// Passive provider fields; actual authentication and observation timing remain external.
108#[derive(Clone)]
109pub struct IcObservationResponseInput {
110    /// Exact full original authority digest including immutable allowances.
111    pub authority: ArtifactChecksumRecord,
112    /// Exact original unresolved mutation attempt.
113    pub mutation_attempt: u32,
114    /// Exact already reserved observation attempt, not another call number.
115    pub observation_attempt: u32,
116    /// Exact existing observation payload digest retained in its reservation.
117    pub request: ArtifactChecksumRecord,
118    /// Actual network/caller/release association claimed by the provider.
119    pub context: PlanContextRecord,
120    /// Actual response target claimed by the provider; canonicalized on admission.
121    pub target: String,
122    /// Exact bounded raw Candid reply.
123    pub reply: Vec<u8>,
124    /// Opaque retained association/authentication/timing evidence; not self-authenticating.
125    pub evidence: ArtifactChecksumRecord,
126}
127
128/// Immutable bounded passive observation, with no outcome, Default or Serde admission.
129#[derive(Clone)]
130pub struct IcObservationResponse {
131    input: IcObservationResponseInput,
132}
133impl IcObservationResponse {
134    /// Admit canonical target, chronological finite attempt IDs and bounded raw bytes.
135    /// # Errors
136    /// Rejects zero/excessive/reversed attempts, oversized replies and invalid principals.
137    pub fn new(mut input: IcObservationResponseInput) -> Result<Self, IcObservationResponseError> {
138        validate_response_input(&mut input, MAX_IC_OBSERVATION_REPLY_BYTES)?;
139        Ok(Self { input })
140    }
141    /// Read immutable canonical claims and exact raw bytes; no mutation access.
142    #[must_use]
143    pub const fn input(&self) -> &IcObservationResponseInput {
144        &self.input
145    }
146}
147impl fmt::Debug for IcObservationResponse {
148    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149        fmt_response_input(&self.input, formatter, "IcObservationResponse")
150    }
151}
152
153pub(crate) fn validate_response_input(
154    input: &mut IcObservationResponseInput,
155    max_reply_bytes: usize,
156) -> Result<(), IcObservationResponseError> {
157    if input.mutation_attempt == 0
158        || input.observation_attempt <= input.mutation_attempt
159        || input.observation_attempt > MAX_OPERATION_ATTEMPTS
160    {
161        return Err(IcObservationResponseError::InvalidAttempts);
162    }
163    if input.reply.len() > max_reply_bytes {
164        return Err(IcObservationResponseError::ReplyTooLarge);
165    }
166    input.target = crate::model::principal::canonical_text(&input.target)
167        .ok_or(IcObservationResponseError::InvalidTarget)?;
168    Ok(())
169}
170
171pub(crate) fn fmt_response_input(
172    input: &IcObservationResponseInput,
173    formatter: &mut fmt::Formatter<'_>,
174    name: &str,
175) -> fmt::Result {
176    formatter
177        .debug_struct(name)
178        .field("authority", &input.authority)
179        .field("mutation_attempt", &input.mutation_attempt)
180        .field("observation_attempt", &input.observation_attempt)
181        .field("request", &input.request)
182        .field("target", &input.target)
183        .field("reply_bytes", &input.reply.len())
184        .finish_non_exhaustive()
185}
186
187/// Structural original observation denial; no spending or effect outcome changes.
188#[derive(Debug, Error)]
189pub enum IcObservationRequestError {
190    /// Original observation reservation failed without changing accounting.
191    #[error(transparent)]
192    Reservation(#[from] ObservationReservationError),
193    /// Original mutation or observation target/digest/class differs.
194    #[error(transparent)]
195    Payload(#[from] IcRequestError),
196    /// Original plan cannot derive the requested operation authority.
197    #[error(transparent)]
198    Plan(#[from] OperationPlanError),
199}
200
201/// Bounded passive response rejection with no raw bytes in diagnostics.
202#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
203pub enum IcObservationResponseError {
204    /// IDs must be chronological within the existing 1,024 total-attempt bound.
205    #[error("invalid IC observation response attempts")]
206    InvalidAttempts,
207    /// Raw bytes exceed the existing finite codec ceilings.
208    #[error("IC observation response reply too large")]
209    ReplyTooLarge,
210    /// Actual target is not a principal.
211    #[error("invalid IC observation response target")]
212    InvalidTarget,
213}
214
215mod settlement;
216pub use settlement::IcLifecycleSettlement;
217
218#[cfg(test)]
219mod tests;