Skip to main content

qualia_core_db/sensing/local_custody/
chain.rs

1//! Chain-aware publication using host-supplied authenticated head state.
2//!
3//! This module cannot itself provide a durable head, lease, rollback defence,
4//! or atomic compare-and-swap. The host must supply and qualify those services.
5//! A bundle may be published without its head being committed; such an orphan
6//! requires host-controlled recovery and must not be treated as a chain member.
7use std::path::Path;
8
9use super::{
10    entry_size, publish_bundle, validate_root, CustodyAuthority, CustodyError, PublishedBundle,
11    SidecarReceipt, SIDECAR_BYTES,
12};
13
14/// Current chain state asserted by a host-protected, anti-rollback registry.
15/// `Empty` must mean authenticated absence, not an unavailable lookup.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum ChainHead {
18    Empty,
19    Present { sequence: u64, checkpoint: [u8; 32] },
20}
21
22/// Result reported by the host's atomic head update.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum HeadCommit {
25    Committed,
26    /// Another head won or the expected head no longer matches.
27    Conflict,
28    /// The host cannot say whether its update committed. Reconcile before use.
29    Indeterminate,
30}
31
32/// A failure to obtain current authenticated chain state is not an empty chain.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum ChainAuthorityError {
35    Unavailable,
36    NotAuthorized,
37    InvalidState,
38}
39
40/// Host boundary for an exact root and chain. Implementations must provide an
41/// authenticated, complete, anti-rollback head and maintain the exclusive
42/// chain lease through publication and commit. `compare_and_commit` must be
43/// atomic with respect to competing writers and check current Store policy;
44/// the host must hold a policy lease through the complete head update so
45/// expiry and revocation checks do not race a blocking commit;
46/// on uncertain completion it must return `Indeterminate`, never `Committed`.
47/// Durability and trusted freshness are host obligations, not checked here.
48pub trait ChainAuthority: CustodyAuthority {
49    fn authenticated_head(
50        &mut self,
51        root: &Path,
52        chain_id: &[u8; 32],
53    ) -> Result<ChainHead, ChainAuthorityError>;
54
55    fn compare_and_commit(
56        &mut self,
57        root: &Path,
58        chain_id: &[u8; 32],
59        expected: ChainHead,
60        next: ChainHead,
61        receipt: &SidecarReceipt,
62    ) -> HeadCommit;
63}
64
65#[derive(Debug)]
66pub enum ChainPublicationError {
67    Authority(ChainAuthorityError),
68    InvalidHead,
69    WrongSequence,
70    WrongPredecessor,
71    SequenceExhausted,
72    Publication(CustodyError),
73    /// The bundle was linked but the head did not commit or its result is
74    /// uncertain. Host recovery must inspect authenticated durable state.
75    PublishedUncommitted {
76        bundle: PublishedBundle,
77        outcome: HeadCommit,
78    },
79}
80
81/// Result is based on the host's commit assertion, not local proof of durable
82/// head state or directory synchronization.
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub struct ChainPublication {
85    pub bundle: PublishedBundle,
86    pub head: ChainHead,
87}
88
89fn expected_transition(
90    head: ChainHead,
91    receipt: &SidecarReceipt,
92) -> Result<ChainHead, ChainPublicationError> {
93    if receipt.chain_id().iter().all(|byte| *byte == 0) {
94        return Err(ChainPublicationError::InvalidHead);
95    }
96    match head {
97        ChainHead::Empty => {
98            if receipt.sequence() != 0 {
99                return Err(ChainPublicationError::WrongSequence);
100            }
101            if receipt.previous().iter().any(|byte| *byte != 0) {
102                return Err(ChainPublicationError::WrongPredecessor);
103            }
104        }
105        ChainHead::Present {
106            sequence,
107            checkpoint,
108        } => {
109            if checkpoint.iter().all(|byte| *byte == 0) {
110                return Err(ChainPublicationError::InvalidHead);
111            }
112            let next = sequence
113                .checked_add(1)
114                .ok_or(ChainPublicationError::SequenceExhausted)?;
115            if receipt.sequence() != next {
116                return Err(ChainPublicationError::WrongSequence);
117            }
118            if receipt.previous() != &checkpoint {
119                return Err(ChainPublicationError::WrongPredecessor);
120            }
121        }
122    }
123    let checkpoint = receipt.checkpoint();
124    if checkpoint.iter().all(|byte| *byte == 0) {
125        return Err(ChainPublicationError::InvalidHead);
126    }
127    Ok(ChainHead::Present {
128        sequence: receipt.sequence(),
129        checkpoint,
130    })
131}
132
133/// Verify and publish a bundle against an authenticated head, then ask the host
134/// for atomic compare-and-commit. Store policy, locality and receipt authority
135/// are also checked by `publish_bundle`. A publish error, panic, process crash,
136/// or indeterminate head response can leave artifacts or an uncertain outcome;
137/// callers must reconcile using the host's authenticated recovery protocol.
138#[allow(clippy::too_many_arguments)]
139pub fn publish_chain_bundle(
140    root: &Path,
141    sidecar: &[u8; SIDECAR_BYTES],
142    payload: &[u8],
143    receipt: &SidecarReceipt,
144    byte_budget: usize,
145    authority: &mut impl ChainAuthority,
146) -> Result<ChainPublication, ChainPublicationError> {
147    validate_root(root).map_err(ChainPublicationError::Publication)?;
148    let total =
149        entry_size(payload.len(), byte_budget).map_err(ChainPublicationError::Publication)?;
150    receipt
151        .verify_with_authority(sidecar, payload, payload.len(), authority)
152        .map_err(|error| ChainPublicationError::Publication(CustodyError::Receipt(error)))?;
153    if !authority.permit_publish(root, receipt, sidecar, payload, total) {
154        return Err(ChainPublicationError::Publication(
155            CustodyError::PermissionDenied,
156        ));
157    }
158    let expected = authority
159        .authenticated_head(root, receipt.chain_id())
160        .map_err(ChainPublicationError::Authority)?;
161    let next = expected_transition(expected, receipt)?;
162    let bundle = publish_bundle(root, sidecar, payload, receipt, byte_budget, authority)
163        .map_err(ChainPublicationError::Publication)?;
164    let outcome = authority.compare_and_commit(root, receipt.chain_id(), expected, next, receipt);
165    match outcome {
166        HeadCommit::Committed => Ok(ChainPublication { bundle, head: next }),
167        HeadCommit::Conflict | HeadCommit::Indeterminate => {
168            Err(ChainPublicationError::PublishedUncommitted { bundle, outcome })
169        }
170    }
171}
172
173#[cfg(test)]
174#[path = "chain_tests.rs"]
175mod tests;