lib

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

installation.rs (15418B)


      1 //! Actual exactly-once chat installation and append-only recipient work.
      2 mod codec;
      3 use super::journal::{OperationChange, Records as PreparationRecords, storage_error};
      4 use super::{
      5     BrowserWorkspace, Mutation, State, WorkspaceError, address, crypto, owned, retained::Graph,
      6 };
      7 use crate::ReadSnapshot;
      8 use radroots_domain::{CommandDigest, OperationId, TransactionId, UnixSeconds};
      9 use radroots_secrets::context::{
     10     EnvelopeContext, EnvelopePurpose, EnvelopeSubject, PayloadSchemaId,
     11 };
     12 use radroots_storage::{
     13     command::{
     14         BoundSigningPlan, ChatInstallation, CommitAttempt, InstallationOutcome,
     15         InstallationRequest, OperationError, OperationSnapshot, PublicationWork,
     16     },
     17     workspace::{AttachmentProof, WorkspaceBinding},
     18 };
     19 use sha2::{Digest, Sha256};
     20 
     21 fn context(
     22     state: &State,
     23     bound: &BoundSigningPlan,
     24     recipient: Option<u8>,
     25 ) -> Result<EnvelopeContext, OperationError> {
     26     let mut hash = Sha256::new()
     27         .chain_update(b"radroots.browser.local_outbox.installation.context.v2\0")
     28         .chain_update(state.selected.workspace_id().as_bytes())
     29         .chain_update(bound.prepared().identity().operation_id().as_bytes())
     30         .chain_update(bound.plan().digest());
     31     let schema = if let Some(index) = recipient {
     32         let seal = bound
     33             .chat_plan()?
     34             .seals()
     35             .get(index as usize)
     36             .ok_or(OperationError::RecoveryRequired)?;
     37         hash.update([1, index]);
     38         hash.update(seal.recipient().as_bytes());
     39         "radroots.browser.workspace.publication.v2"
     40     } else {
     41         hash.update([0]);
     42         "radroots.browser.workspace.message.v2"
     43     };
     44     let subject = hash
     45         .finalize()
     46         .iter()
     47         .map(|b| format!("{b:02x}"))
     48         .collect::<String>();
     49     Ok(EnvelopeContext::new(
     50         EnvelopePurpose::parse("radroots.browser.workspace.installation")
     51             .map_err(|_| OperationError::InvalidCommand)?,
     52         EnvelopeSubject::parse("workspace_installation", subject)
     53             .map_err(|_| OperationError::InvalidCommand)?,
     54         PayloadSchemaId::parse(schema).map_err(|_| OperationError::InvalidCommand)?,
     55     ))
     56 }
     57 pub(super) struct Records {
     58     pub message: Option<ChatInstallation>,
     59     pub work: Vec<PublicationWork>,
     60     pub listing: Option<radroots_storage::command::ListingInstallation>,
     61     pub public: Option<radroots_storage::command::PublicPublicationWork>,
     62 }
     63 impl Records {
     64     pub(super) async fn read(
     65         state: &State,
     66         view: &ReadSnapshot,
     67         graph: &Graph,
     68         operation: OperationId,
     69     ) -> Result<Self, OperationError> {
     70         if graph.bound().is_some_and(|v| v.plan().listing().is_some()) {
     71             let (listing, public) = state
     72                 .read_public_installation(view, graph, operation)
     73                 .await?;
     74             return Ok(Self {
     75                 message: None,
     76                 work: Vec::new(),
     77                 listing,
     78                 public,
     79             });
     80         }
     81         let message = if let Some(raw) = state
     82             .read_view_key(view, address::key(operation, address::INSTALLATION, 0, 0))
     83             .await?
     84         {
     85             let bound = graph.bound().ok_or(OperationError::RecoveryRequired)?;
     86             let clear = crypto::open_bound(
     87                 state.provider.as_ref(),
     88                 &state.reference,
     89                 context(state, bound, None)?,
     90                 &raw,
     91             )
     92             .await?;
     93             Some(clear.expose_secret(|raw| codec::decode_message(raw, graph))?)
     94         } else {
     95             None
     96         };
     97         let mut work = Vec::with_capacity(2);
     98         if let Some(bound) = graph.bound() {
     99             for (index, seal) in bound.chat_plan()?.seals().iter().enumerate() {
    100                 if let Some(raw) = state
    101                     .read_view_key(
    102                         view,
    103                         address::key(operation, address::PUBLICATION, index as u8, 0),
    104                     )
    105                     .await?
    106                 {
    107                     let installed = message.ok_or(OperationError::RecoveryRequired)?;
    108                     let clear = crypto::open_bound(
    109                         state.provider.as_ref(),
    110                         &state.reference,
    111                         context(state, bound, Some(index as u8))?,
    112                         &raw,
    113                     )
    114                     .await?;
    115                     work.push(clear.expose_secret(|raw| {
    116                         codec::decode_work(raw, graph, installed, seal.recipient())
    117                     })?);
    118                 }
    119             }
    120         }
    121         if let Some(message) = message
    122             && !work.iter().any(|value| value.evidence() == message.basis())
    123         {
    124             return Err(OperationError::RecoveryRequired);
    125         }
    126         Ok(Self {
    127             message,
    128             work,
    129             listing: None,
    130             public: None,
    131         })
    132     }
    133 }
    134 pub(super) fn work_commitment(message: ChatInstallation, work: PublicationWork) -> [u8; 32] {
    135     Sha256::digest(codec::work(message, work)).into()
    136 }
    137 impl Records {
    138     pub(super) fn artifact(
    139         &self,
    140         target: radroots_storage::command::SigningTarget,
    141     ) -> Result<radroots_storage::command::PublicationArtifact, OperationError> {
    142         if target == radroots_storage::command::SigningTarget::PublicEvent {
    143             return self
    144                 .public
    145                 .map(Into::into)
    146                 .ok_or(OperationError::RecoveryRequired);
    147         }
    148         self.work
    149             .iter()
    150             .find(|v| Some(v.recipient()) == target.recipient())
    151             .copied()
    152             .map(Into::into)
    153             .ok_or(OperationError::RecoveryRequired)
    154     }
    155     pub(super) fn commitment(
    156         &self,
    157         work: radroots_storage::command::PublicationArtifact,
    158     ) -> Result<[u8; 32], OperationError> {
    159         match work {
    160             radroots_storage::command::PublicationArtifact::Private(value) => Ok(work_commitment(
    161                 self.message.ok_or(OperationError::RecoveryRequired)?,
    162                 value,
    163             )),
    164             radroots_storage::command::PublicationArtifact::Public(value) => {
    165                 Ok(super::listing_installation::commitment(
    166                     self.listing.ok_or(OperationError::RecoveryRequired)?,
    167                     value,
    168                 ))
    169             }
    170         }
    171     }
    172 }
    173 pub(super) fn publication_commitment(
    174     snapshot: &OperationSnapshot,
    175     work: radroots_storage::command::PublicationArtifact,
    176 ) -> Result<[u8; 32], OperationError> {
    177     match work {
    178         radroots_storage::command::PublicationArtifact::Private(value) => Ok(work_commitment(
    179             snapshot
    180                 .installation()
    181                 .ok_or(OperationError::RecoveryRequired)?,
    182             value,
    183         )),
    184         radroots_storage::command::PublicationArtifact::Public(value) => {
    185             Ok(super::listing_installation::commitment(
    186                 snapshot
    187                     .listing_installation()
    188                     .ok_or(OperationError::RecoveryRequired)?,
    189                 value,
    190             ))
    191         }
    192     }
    193 }
    194 impl State {
    195     /// A missing claim must not conceal installation/publication descendants.
    196     /// The complete witnessed prefix still fences all facts at actual commit.
    197     pub(super) async fn check_claim_absence(
    198         &self,
    199         view: &ReadSnapshot,
    200         operation: OperationId,
    201         digest: CommandDigest,
    202         t0: &PreparationRecords,
    203         observed: UnixSeconds,
    204     ) -> Result<(), OperationError> {
    205         self.delivery_facts(view, operation, Some(digest), t0, observed, None)
    206             .await?;
    207         Ok(())
    208     }
    209 }
    210 impl BrowserWorkspace {
    211     /// Installs the original logical message once and appends work for each
    212     /// actual obtained recipient. This performs no signing or delivery.
    213     pub async fn install_transition_and_outbox(
    214         &self,
    215         request: InstallationRequest,
    216         proof: AttachmentProof,
    217     ) -> Result<InstallationOutcome, OperationError> {
    218         let fallback = request.identity();
    219         let work = self.state.admit()?;
    220         let state = self.state.clone();
    221         let result = owned(work, async move {
    222             let access = state.operation_access(request.binding(), proof).await?;
    223             let operation = request.operation_id();
    224             let view = state.read_view(operation).await?;
    225             let t0 = state.operation_records(&view, operation).await?;
    226             let snapshot = state
    227                 .delivery_facts(
    228                     &view,
    229                     operation,
    230                     Some(request.command_digest()),
    231                     &t0,
    232                     access.binding.observed_at(),
    233                     None,
    234                 )
    235                 .await?
    236                 .snapshot
    237                 .ok_or(OperationError::RecoveryRequired)?;
    238             let bound = snapshot
    239                 .bound_plan()
    240                 .ok_or(OperationError::RecoveryRequired)?;
    241             radroots_storage::command::protected::same_binding(
    242                 bound.prepared().request().binding(),
    243                 request.binding(),
    244             )?;
    245             if bound.plan().digest() != request.plan_digest() {
    246                 return Err(OperationError::IdempotencyConflict);
    247             }
    248             if bound.plan().listing().is_some() {
    249                 return state
    250                     .install_listing(request, access, view, t0, snapshot)
    251                     .await;
    252             }
    253             let original = snapshot.installation();
    254             let missing = snapshot
    255                 .artifacts()
    256                 .iter()
    257                 .filter_map(|value| value.obtained())
    258                 .filter(|evidence| {
    259                     !snapshot
    260                         .publications()
    261                         .iter()
    262                         .any(|value| value.evidence().target() == evidence.target())
    263                 })
    264                 .collect::<Vec<_>>();
    265             if original.is_none() && missing.is_empty() {
    266                 return Err(OperationError::InvalidEvidence);
    267             }
    268             let fresh = original.is_none() || !missing.is_empty();
    269             let transaction = if fresh {
    270                 TransactionId::from_bytes(*crypto::random::<32>()?)
    271             } else {
    272                 original
    273                     .ok_or(OperationError::RecoveryRequired)?
    274                     .transaction_id()
    275             };
    276             let installed = if let Some(value) = original {
    277                 value
    278             } else {
    279                 ChatInstallation::from_committed_store(
    280                     bound,
    281                     *missing.first().ok_or(OperationError::InvalidEvidence)?,
    282                     transaction,
    283                     access.binding.observed_at(),
    284                 )?
    285             };
    286             let mut extra = Vec::with_capacity(3);
    287             if original.is_none() {
    288                 let raw = codec::message(bound, installed)?;
    289                 let protected = crypto::seal_bound(
    290                     state.provider.as_ref(),
    291                     &state.reference,
    292                     context(&state, bound, None)?,
    293                     &raw,
    294                 )
    295                 .await?;
    296                 extra.push(
    297                     Mutation::new(
    298                         address::key(operation, address::INSTALLATION, 0, 0),
    299                         None,
    300                         Some(protected),
    301                     )
    302                     .map_err(storage_error)?,
    303                 );
    304             }
    305             for evidence in missing {
    306                 let index = bound
    307                     .chat_plan()?
    308                     .seals()
    309                     .iter()
    310                     .position(|seal| Some(seal.recipient()) == evidence.target().recipient())
    311                     .ok_or(OperationError::RecoveryRequired)? as u8;
    312                 let value = PublicationWork::from_committed_store(
    313                     bound,
    314                     installed,
    315                     evidence,
    316                     transaction,
    317                     access.binding.observed_at(),
    318                 )?;
    319                 let raw = codec::work(installed, value);
    320                 let protected = crypto::seal_bound(
    321                     state.provider.as_ref(),
    322                     &state.reference,
    323                     context(&state, bound, Some(index))?,
    324                     &raw,
    325                 )
    326                 .await?;
    327                 extra.push(
    328                     Mutation::new(
    329                         address::key(operation, address::PUBLICATION, index, 0),
    330                         None,
    331                         Some(protected),
    332                     )
    333                     .map_err(storage_error)?,
    334                 );
    335             }
    336             let anchor = CommitAttempt::new(
    337                 installed.workspace_id(),
    338                 operation,
    339                 installed.command_digest(),
    340                 Some(transaction),
    341             );
    342             match state
    343                 .check_operation(
    344                     access,
    345                     operation,
    346                     OperationChange {
    347                         before: t0,
    348                         after: None,
    349                         window: None,
    350                         delivery_deadline: None,
    351                         extra,
    352                     },
    353                     view,
    354                 )
    355                 .await
    356             {
    357                 Ok(()) => Ok(InstallationOutcome::Committed(Box::new(installed))),
    358                 Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    359                     state.mark_unknown();
    360                     Ok(InstallationOutcome::Unknown(anchor))
    361                 }
    362                 Err(error) => Err(error),
    363             }
    364         })
    365         .await;
    366         match result {
    367             Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    368                 self.state.mark_unknown();
    369                 Ok(InstallationOutcome::Unknown(fallback))
    370             }
    371             other => other,
    372         }
    373     }
    374     /// Confirms the original coherent T0/T1/S/T2 graph. Querying never dispatches
    375     /// a signer or implies a missing delivery acknowledgement.
    376     pub async fn operation_snapshot(
    377         &self,
    378         binding: WorkspaceBinding,
    379         operation: OperationId,
    380         digest: Option<CommandDigest>,
    381         proof: AttachmentProof,
    382     ) -> Result<Option<OperationSnapshot>, OperationError> {
    383         let work = self.state.admit()?;
    384         let state = self.state.clone();
    385         owned(work, async move {
    386             let access = state.operation_access(&binding, proof).await?;
    387             let observed = access.binding.observed_at();
    388             let view = state.read_view(operation).await?;
    389             let t0 = state.operation_records(&view, operation).await?;
    390             let snapshot = state
    391                 .delivery_facts(&view, operation, digest, &t0, observed, None)
    392                 .await?
    393                 .snapshot;
    394             if let Some(snapshot) = &snapshot {
    395                 radroots_storage::command::protected::same_binding(
    396                     snapshot.prepared().request().binding(),
    397                     &binding,
    398                 )?;
    399             }
    400             state
    401                 .check_operation(access, operation, OperationChange::observe(t0), view)
    402                 .await?;
    403             Ok(snapshot)
    404         })
    405         .await
    406     }
    407 }