lib

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

retained.rs (8310B)


      1 //! Authenticated bounded T0/T1/S data; mutation authority remains in the host.
      2 use super::{State, address, issuance::Claim, journal::Records};
      3 use crate::ReadSnapshot;
      4 use radroots_domain::{CommandDigest, EnvelopeEventId, OperationId, PublicKey, UnixSeconds};
      5 use radroots_storage::command::{
      6     ArtifactEvidence, ArtifactSnapshot, BoundSigningPlan, ClaimSnapshot, EvidenceReceipt,
      7     OperationError, OperationSnapshot, RetainedOperation, SigningTarget, protected,
      8 };
      9 
     10 pub(super) async fn header(
     11     state: &State,
     12     view: &ReadSnapshot,
     13     operation: OperationId,
     14     digest: Option<CommandDigest>,
     15     t0: &Records,
     16 ) -> Result<Option<RetainedOperation>, OperationError> {
     17     let Some(prepared) = state.preparation(operation, t0).await? else {
     18         if !view.is_empty() {
     19             return Err(OperationError::RecoveryRequired);
     20         }
     21         return Ok(None);
     22     };
     23     if prepared.request().binding().input() != &state.selected
     24         || prepared.request().command().context().actor().participant()
     25             != state.selected.participant()
     26     {
     27         return Err(OperationError::Unauthorized);
     28     }
     29     protected::check_digest(
     30         &prepared,
     31         prepared.request().command().context().actor(),
     32         digest,
     33     )?;
     34     let records = state.plan_records(view, operation).await?;
     35     let Some((manifest, plan)) = state.retained_plan(&prepared, &records).await? else {
     36         state.absent_plans(view, operation).await?;
     37         return Ok(Some(RetainedOperation::Prepared(prepared)));
     38     };
     39     for key in view.keys() {
     40         let (kind, recipient, _) = address::fields(key)?;
     41         if matches!(kind, address::PREPARED | address::PLAN) {
     42             continue;
     43         }
     44         if matches!(kind, address::LISTING_INSTALLATION | address::PUBLIC_WORK) {
     45             if plan.listing().is_none() {
     46                 return Err(OperationError::RecoveryRequired);
     47             }
     48         } else if matches!(kind, address::INSTALLATION | address::PUBLICATION) {
     49             if plan.chat().is_none() {
     50                 return Err(OperationError::RecoveryRequired);
     51             }
     52             if kind == address::PUBLICATION
     53                 && recipient as usize
     54                     >= plan
     55                         .chat()
     56                         .ok_or(OperationError::RecoveryRequired)?
     57                         .seals()
     58                         .len()
     59             {
     60                 return Err(OperationError::RecoveryRequired);
     61             }
     62         } else {
     63             let valid = if plan.listing().is_some() {
     64                 recipient == 2
     65             } else {
     66                 (recipient as usize)
     67                     < plan
     68                         .chat()
     69                         .ok_or(OperationError::RecoveryRequired)?
     70                         .seals()
     71                         .len()
     72             };
     73             if !valid {
     74                 return Err(OperationError::RecoveryRequired);
     75             }
     76         }
     77     }
     78     Ok(Some(RetainedOperation::Planned(Box::new(
     79         manifest.bind(prepared, plan)?,
     80     ))))
     81 }
     82 
     83 pub(super) struct Graph {
     84     retained: Option<RetainedOperation>,
     85     recipients: Vec<ArtifactSnapshot>,
     86     output: Option<ArtifactEvidence>,
     87 }
     88 impl Graph {
     89     pub(super) async fn read_for_output(
     90         state: &State,
     91         view: &ReadSnapshot,
     92         operation: OperationId,
     93         digest: Option<CommandDigest>,
     94         t0: &Records,
     95         selected: Option<SigningTarget>,
     96     ) -> Result<Self, OperationError> {
     97         let retained = header(state, view, operation, digest, t0).await?;
     98         let mut recipients = Vec::with_capacity(2);
     99         let mut output = None;
    100         let retained = match retained {
    101             Some(RetainedOperation::Planned(bound)) => {
    102                 let mut bound = *bound;
    103                 let keys = match bound.plan().chat() {
    104                     Some(chat) => chat
    105                         .seals()
    106                         .iter()
    107                         .map(|seal| SigningTarget::BusinessSeal(seal.recipient()))
    108                         .collect::<Vec<_>>(),
    109                     None => vec![SigningTarget::PublicEvent],
    110                 };
    111                 for recipient in keys {
    112                     let expected = EnvelopeEventId::from_bytes(
    113                         bound
    114                             .plan()
    115                             .artifact(recipient)
    116                             .map_err(|_| OperationError::RecoveryRequired)?
    117                             .event_id(),
    118                     );
    119                     let index = super::issuance::position(&bound, recipient)?
    120                         .ok_or(OperationError::RecoveryRequired)?;
    121                     match state.claim(view, bound, recipient, index).await? {
    122                         Claim::Absent(returned, _) => {
    123                             recipients.push(ArtifactSnapshot::from_store_report(
    124                                 recipient,
    125                                 Some(expected),
    126                                 None,
    127                                 None,
    128                             ));
    129                             bound = returned;
    130                         }
    131                         Claim::Present(attempt) => {
    132                             let claim = ClaimSnapshot::from_store_report(&attempt)?;
    133                             // Verify one bounded exact seal at a time; retaining a
    134                             // receipt does not duplicate private plan/raw bodies.
    135                             let obtained = state.evidence(view, &attempt, index).await?;
    136                             let receipt = obtained.as_ref().map(|(_, receipt)| *receipt);
    137                             if Some(recipient) == selected {
    138                                 output = obtained.map(|(value, _)| value);
    139                             }
    140                             recipients.push(ArtifactSnapshot::from_store_report(
    141                                 recipient,
    142                                 Some(expected),
    143                                 Some(claim),
    144                                 receipt,
    145                             ));
    146                             bound = (*attempt).into_bound_plan();
    147                         }
    148                     }
    149                 }
    150                 Some(RetainedOperation::Planned(Box::new(bound)))
    151             }
    152             Some(RetainedOperation::Prepared(prepared)) => {
    153                 let mut keys = match prepared.request().command().chat() {
    154                     Some(command) => vec![
    155                         SigningTarget::BusinessSeal(command.context().actor().participant()),
    156                         SigningTarget::BusinessSeal(command.peer()),
    157                     ],
    158                     None => vec![SigningTarget::PublicEvent],
    159                 };
    160                 keys.sort_unstable_by_key(|target| target.key());
    161                 keys.dedup();
    162                 for recipient in keys {
    163                     recipients.push(ArtifactSnapshot::from_store_report(
    164                         recipient, None, None, None,
    165                     ));
    166                 }
    167                 Some(RetainedOperation::Prepared(prepared))
    168             }
    169             None => None,
    170         };
    171         Ok(Self {
    172             retained,
    173             recipients,
    174             output,
    175         })
    176     }
    177     pub(super) fn take_output(&mut self) -> Option<ArtifactEvidence> {
    178         self.output.take()
    179     }
    180     pub(super) fn bound(&self) -> Option<&BoundSigningPlan> {
    181         self.retained
    182             .as_ref()
    183             .and_then(RetainedOperation::bound_plan)
    184     }
    185     pub(super) fn receipt(&self, recipient: PublicKey) -> Result<EvidenceReceipt, OperationError> {
    186         self.receipt_target(SigningTarget::BusinessSeal(recipient))
    187     }
    188     pub(super) fn receipt_target(
    189         &self,
    190         target: SigningTarget,
    191     ) -> Result<EvidenceReceipt, OperationError> {
    192         self.recipients
    193             .iter()
    194             .find(|value| value.target() == target)
    195             .and_then(|value| value.obtained())
    196             .ok_or(OperationError::RecoveryRequired)
    197     }
    198     pub(super) fn into_snapshot(
    199         self,
    200         observed: UnixSeconds,
    201     ) -> Result<Option<OperationSnapshot>, OperationError> {
    202         self.retained
    203             .map(|source| OperationSnapshot::from_store_report(source, self.recipients, observed))
    204             .transpose()
    205     }
    206 }