lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

coverage.rs (4550B)


      1 //! Exact portable local coverage data. Neither a digest nor a complete supplied
      2 //! graph proves authentic store coverage, participant permission or order state.
      3 use super::{EncodedRecord, RecordWireError};
      4 use alloc::{collections::BTreeSet, vec::Vec};
      5 use core::fmt;
      6 use radroots_domain::{
      7     CheckpointDigest, CheckpointRef, Coverage, Sequence, SourceId,
      8     causal::{self, CausalAnalysis, CausalRecord, CausalScope},
      9 };
     10 use sha2::{Digest, Sha256};
     11 
     12 /// Checked canonical identity/graph data and an optional complete local scope
     13 /// descriptor. Constructors never grant read, execute, signer or stock rights.
     14 pub struct CapturedCausalCoverage {
     15     analysis: CausalAnalysis,
     16     checkpoint: Option<CheckpointRef>,
     17 }
     18 impl CapturedCausalCoverage {
     19     /// Checks every complete canonical record identity before deriving the
     20     /// descriptor. External identities and completeness are still caller claims;
     21     /// concrete stores must independently authenticate them and their coverage.
     22     pub fn capture(
     23         scope: CausalScope,
     24         records: &[CausalRecord<'_>],
     25         external: &[SourceId],
     26         uninterpreted: &[SourceId],
     27     ) -> Result<Self, RecordWireError> {
     28         let analysis = causal::analyze(scope, records, external, uninterpreted).map_err(
     29             |error| match error {
     30                 causal::CausalError::LimitExceeded => RecordWireError::LimitExceeded,
     31                 causal::CausalError::IdentityConflict => RecordWireError::IdentityMismatch,
     32                 _ => RecordWireError::InvalidInput,
     33             },
     34         )?;
     35         let mut known = BTreeSet::new();
     36         let mut required = BTreeSet::<SourceId>::new();
     37         for record in records {
     38             if EncodedRecord::capture(record.content())?.record_id() != record.record_id() {
     39                 return Err(RecordWireError::IdentityMismatch);
     40             }
     41             known.insert(SourceId::from_bytes(record.record_id().into_bytes()));
     42             required.extend(record.content().header().parents().iter().copied());
     43         }
     44         let checkpoint = if analysis.readiness() == causal::CausalReadiness::Complete {
     45             let external: BTreeSet<_> = external
     46                 .iter()
     47                 .copied()
     48                 .filter(|id| required.contains(id) && !known.contains(id))
     49                 .collect();
     50             let barriers: BTreeSet<_> = uninterpreted.iter().copied().collect();
     51             let mut hash = Sha256::new();
     52             hash.update(b"radroots.commerce.coverage.v1\0");
     53             // Fixed-width scope fields, then three length-prefixed sorted sets.
     54             // No host word size, JSON map ordering or transport encoding enters
     55             // this transcript. Public record IDs commit complete content.
     56             hash.update(scope.thread_id().as_bytes());
     57             hash.update(scope.order_id().as_bytes());
     58             hash.update(scope.buyer().as_bytes());
     59             hash.update(scope.seller().as_bytes());
     60             for identities in [&known, &external, &barriers] {
     61                 hash.update((identities.len() as u64).to_be_bytes());
     62                 for id in identities {
     63                     hash.update(id.as_bytes());
     64                 }
     65             }
     66             let sequence = Sequence::new((known.len() + external.len() + barriers.len()) as u64)
     67                 .map_err(|_| RecordWireError::LimitExceeded)?;
     68             Some(
     69                 CheckpointRef::new(
     70                     CheckpointDigest::from_bytes(hash.finalize().into()),
     71                     sequence,
     72                     Coverage::ScopeSatisfied,
     73                     Vec::new(),
     74                 )
     75                 .map_err(|_| RecordWireError::InvalidInput)?,
     76             )
     77         } else {
     78             None
     79         };
     80         Ok(Self {
     81             analysis,
     82             checkpoint,
     83         })
     84     }
     85     /// Borrows exact known gaps/forks and local causal classification.
     86     pub const fn analysis(&self) -> &CausalAnalysis {
     87         &self.analysis
     88     }
     89     /// Returns a complete supplied scope descriptor; it grants no permission.
     90     pub const fn checkpoint(&self) -> Option<&CheckpointRef> {
     91         self.checkpoint.as_ref()
     92     }
     93     /// Moves the checked data without promoting it to authenticated evidence.
     94     pub fn into_parts(self) -> (CausalAnalysis, Option<CheckpointRef>) {
     95         (self.analysis, self.checkpoint)
     96     }
     97 }
     98 impl fmt::Debug for CapturedCausalCoverage {
     99     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    100         f.write_str("CapturedCausalCoverage(<local coverage claims>)")
    101     }
    102 }