lib

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

replacement.rs (10514B)


      1 //! Replacement authorization claims. Actual source authentication, canonical
      2 //! terms hashing, current installed state and stock effects belong to execution.
      3 use super::*;
      4 use crate::{AgreementCommitment, CommercePayload, Terms, TermsDigest, UnixSeconds};
      5 
      6 /// Explicit existing-agreement/proposal/authorization selectors and an
      7 /// independently computed complete terms digest. Construction proves no claim.
      8 #[derive(Clone, Copy, Eq, PartialEq)]
      9 pub struct ReplacementTermsSelection {
     10     base: RecordId,
     11     proposal: RecordId,
     12     authorization: RecordId,
     13     digest: TermsDigest,
     14 }
     15 impl ReplacementTermsSelection {
     16     /// Captures exact identities only. The consumer must recompute the digest
     17     /// from the actual complete proposal and compare the live installed head.
     18     pub const fn new(
     19         base: RecordId,
     20         proposal: RecordId,
     21         authorization: RecordId,
     22         digest: TermsDigest,
     23     ) -> Self {
     24         Self {
     25             base,
     26             proposal,
     27             authorization,
     28             digest,
     29         }
     30     }
     31     /// Explicit existing agreement, not proof that it is the current head.
     32     pub const fn base_agreement(self) -> RecordId {
     33         self.base
     34     }
     35     /// Exact selected complete replacement proposal.
     36     pub const fn proposal(self) -> RecordId {
     37         self.proposal
     38     }
     39     /// Exact selected counterparty authorization.
     40     pub const fn authorization(self) -> RecordId {
     41         self.authorization
     42     }
     43     /// Declared expected digest; this value performs no canonical hashing.
     44     pub const fn terms_digest(self) -> TermsDigest {
     45         self.digest
     46     }
     47 }
     48 impl fmt::Debug for ReplacementTermsSelection {
     49     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     50         f.write_str("ReplacementTermsSelection(<private identities>)")
     51     }
     52 }
     53 
     54 /// Borrowed replacement claims after bounded local causal/time checks. This
     55 /// grants no authenticity, consent, current authority, residual or stock effect.
     56 pub struct ReplacementTermsClaim<'a> {
     57     selection: ReplacementTermsSelection,
     58     base: AgreementCommitment,
     59     terms: &'a Terms,
     60     expires: UnixSeconds,
     61 }
     62 impl ReplacementTermsClaim<'_> {
     63     /// Exact selected identities and declared terms digest.
     64     pub const fn selection(&self) -> ReplacementTermsSelection {
     65         self.selection
     66     }
     67     /// Original base commitment claim, not current executor authority.
     68     pub const fn base_commitment(&self) -> AgreementCommitment {
     69         self.base
     70     }
     71     /// Complete proposed terms; execution must independently hash these bytes.
     72     pub const fn terms(&self) -> &Terms {
     73         self.terms
     74     }
     75     /// Earliest proposal/authorization deadline, excluding executor bounds.
     76     pub const fn expires_at(&self) -> UnixSeconds {
     77         self.expires
     78     }
     79 }
     80 impl fmt::Debug for ReplacementTermsClaim<'_> {
     81     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     82         f.write_str("ReplacementTermsClaim(<private data>)")
     83     }
     84 }
     85 
     86 /// Bounded input-free failures of the selected replacement claims.
     87 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     88 #[non_exhaustive]
     89 pub enum ReplacementTermsError {
     90     /// Source bounds, identities or the declared bilateral scope differ.
     91     InvalidGraph,
     92     /// Required original records or causal predecessors are absent.
     93     MissingHistory,
     94     /// Known author forks or cycles prevent a complete scoped claim.
     95     Conflicted,
     96     /// Retained authenticated uninterpreted evidence prevents reduction.
     97     Uninterpreted,
     98     /// The selected base is not a seller agreement commitment in this scope.
     99     WrongBase,
    100     /// The proposal does not identify the exact selected existing agreement.
    101     WrongProposal,
    102     /// The authorization names another proposal or is authored by its proposer.
    103     WrongAuthorization,
    104     /// The authorization differs from the supplied complete terms digest.
    105     TermsDigestMismatch,
    106     /// The current observation is at or beyond either selected deadline.
    107     Expired,
    108     /// A known scoped author time is ahead of the supplied observation.
    109     ClockAhead,
    110     /// The author withdrew the selected authorization.
    111     Withdrawn,
    112     /// The counterparty rejected the selected proposal.
    113     Rejected,
    114     /// Another live authorization for this base declares incompatible terms.
    115     ConflictingAuthorizations,
    116 }
    117 impl fmt::Display for ReplacementTermsError {
    118     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    119         f.write_str(match self {
    120             Self::InvalidGraph => "invalid replacement graph",
    121             Self::MissingHistory => "replacement history missing",
    122             Self::Conflicted => "replacement history conflicted",
    123             Self::Uninterpreted => "replacement history uninterpreted",
    124             Self::WrongBase => "replacement base differs",
    125             Self::WrongProposal => "replacement proposal differs",
    126             Self::WrongAuthorization => "replacement authorization differs",
    127             Self::TermsDigestMismatch => "replacement terms digest differs",
    128             Self::Expired => "replacement deadline expired",
    129             Self::ClockAhead => "replacement clock observation insufficient",
    130             Self::Withdrawn => "replacement authorization withdrawn",
    131             Self::Rejected => "replacement proposal rejected",
    132             Self::ConflictingAuthorizations => "replacement authorizations conflict",
    133         })
    134     }
    135 }
    136 impl core::error::Error for ReplacementTermsError {}
    137 
    138 /// Checks one explicit replacement proposal/authorization against the complete
    139 /// supplied local graph, with either participant permitted to propose. Generic
    140 /// external sources cannot substitute for the three selected original records.
    141 /// Losing observation or expiry does not erase an already prepared operation;
    142 /// recover such an operation before using this fresh-claim planner.
    143 ///
    144 /// The caller must authenticate all sources, independently recompute the actual
    145 /// complete proposal digest, and revalidate current installed agreement, residual,
    146 /// permissions, original allocations and pending-operation fences in its native
    147 /// transaction. This pure result does not select a current agreement or acquire,
    148 /// release, consume, restore or resolve any physical backing or deficit.
    149 pub fn prepare_replacement_terms<'a>(
    150     scope: CausalScope,
    151     selected: ReplacementTermsSelection,
    152     records: &[CausalRecord<'a>],
    153     external: &[SourceId],
    154     uninterpreted: &[SourceId],
    155     observed_at: UnixSeconds,
    156 ) -> Result<ReplacementTermsClaim<'a>, ReplacementTermsError> {
    157     use ReplacementTermsError as E;
    158     let analysis = analyze(scope, records, external, uninterpreted).map_err(|_| E::InvalidGraph)?;
    159     match analysis.readiness() {
    160         CausalReadiness::Complete => {}
    161         CausalReadiness::MissingHistory => return Err(E::MissingHistory),
    162         CausalReadiness::Conflicted => return Err(E::Conflicted),
    163         CausalReadiness::Uninterpreted => return Err(E::Uninterpreted),
    164     }
    165     let known: BTreeMap<_, _> = records
    166         .iter()
    167         .map(|record| (record.id, record.content))
    168         .collect();
    169     let base = known
    170         .get(&selected.base)
    171         .copied()
    172         .ok_or(E::MissingHistory)?;
    173     let CommercePayload::AgreementCommitted(base) = base.payload() else {
    174         return Err(E::WrongBase);
    175     };
    176     let proposal = known
    177         .get(&selected.proposal)
    178         .copied()
    179         .ok_or(E::MissingHistory)?;
    180     let CommercePayload::TermsProposed(terms) = proposal.payload() else {
    181         return Err(E::WrongProposal);
    182     };
    183     if terms.base_agreement() != Some(selected.base) {
    184         return Err(E::WrongProposal);
    185     }
    186     let authorization = known
    187         .get(&selected.authorization)
    188         .copied()
    189         .ok_or(E::MissingHistory)?;
    190     let CommercePayload::TermsAuthorized(authorized) = authorization.payload() else {
    191         return Err(E::WrongAuthorization);
    192     };
    193     if authorized.proposal() != selected.proposal
    194         || authorization.header().author() == proposal.header().author()
    195     {
    196         return Err(E::WrongAuthorization);
    197     }
    198     if authorized.terms_digest() != selected.digest {
    199         return Err(E::TermsDigestMismatch);
    200     }
    201     if records
    202         .iter()
    203         .any(|record| record.content.header().created_at() > observed_at)
    204     {
    205         return Err(E::ClockAhead);
    206     }
    207     let expires = terms.expires_at().min(authorized.expires_at());
    208     if observed_at >= expires {
    209         return Err(E::Expired);
    210     }
    211     let withdrawn = |id, author| {
    212         known.values().any(|record| {
    213         record.header().author() == author && matches!(record.payload(), CommercePayload::WithdrawalRequested(value) if value.target() == id)
    214     })
    215     };
    216     let rejected = |id, author| {
    217         known.values().any(|record| {
    218         record.header().author() != author && matches!(record.payload(), CommercePayload::TermsRejected(value) if value.target() == id)
    219     })
    220     };
    221     if withdrawn(selected.authorization, authorization.header().author()) {
    222         return Err(E::Withdrawn);
    223     }
    224     if rejected(selected.proposal, proposal.header().author()) {
    225         return Err(E::Rejected);
    226     }
    227     for (id, other) in &known {
    228         let CommercePayload::TermsAuthorized(other_authorization) = other.payload() else {
    229             continue;
    230         };
    231         if *id == selected.authorization
    232             || other_authorization.expires_at() <= observed_at
    233             || withdrawn(*id, other.header().author())
    234         {
    235             continue;
    236         }
    237         let other_proposal = known
    238             .get(&other_authorization.proposal())
    239             .ok_or(E::MissingHistory)?;
    240         let CommercePayload::TermsProposed(other_terms) = other_proposal.payload() else {
    241             return Err(E::WrongAuthorization);
    242         };
    243         if other_proposal.header().author() == other.header().author() {
    244             return Err(E::WrongAuthorization);
    245         }
    246         if other_terms.base_agreement() != Some(selected.base)
    247             || other_terms.expires_at() <= observed_at
    248             || rejected(
    249                 other_authorization.proposal(),
    250                 other_proposal.header().author(),
    251             )
    252         {
    253             continue;
    254         }
    255         if other_terms.terms() != terms.terms()
    256             || other_authorization.terms_digest() != selected.digest
    257         {
    258             return Err(E::ConflictingAuthorizations);
    259         }
    260     }
    261     Ok(ReplacementTermsClaim {
    262         selection: selected,
    263         base: *base,
    264         terms: terms.terms(),
    265         expires,
    266     })
    267 }