lib

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

operations.rs (14621B)


      1 use super::{Selection, codec, graph, routes};
      2 use crate::workspace::{
      3     BrowserWorkspace, WorkspaceError, crypto, installation::publication_commitment,
      4     journal::OperationChange, owned,
      5 };
      6 use nostr::JsonUtil;
      7 use radroots_domain::{CommandDigest, OperationId, TransactionId};
      8 use radroots_storage::{
      9     command::{
     10         ArtifactEvidence, BoundSigningPlan, CommitAttempt, DeliveryAttempt, DeliveryAttemptOutcome,
     11         DeliveryAttemptRequest, DeliveryAttemptSummary, EnvelopeCandidate, OperationError,
     12         PublicationArtifact, PublicationWork, SigningTarget,
     13     },
     14     workspace::{AttachmentProof, WorkspaceBinding},
     15 };
     16 use radroots_transport::sink::DeliveryRequestId;
     17 use zeroize::Zeroizing;
     18 
     19 fn contains_original(
     20     candidate: &EnvelopeCandidate,
     21     work: PublicationWork,
     22     bound: &BoundSigningPlan,
     23     source: &ArtifactEvidence,
     24 ) -> Result<(), OperationError> {
     25     let actor = bound
     26         .prepared()
     27         .request()
     28         .command()
     29         .context()
     30         .actor()
     31         .participant();
     32     if candidate.work() != work
     33         || candidate.author() == actor
     34         || candidate.author() == bound.prepared().request().chat_command()?.peer()
     35         || candidate.author() == work.recipient()
     36         || source.digest() != work.evidence().digest()
     37     {
     38         return Err(OperationError::InvalidEvidence);
     39     }
     40     let event = nostr::Event::from_json(candidate.raw_json())
     41         .map_err(|_| OperationError::InvalidEvidence)?;
     42     let mut secp = nostr::secp256k1::Secp256k1::new();
     43     secp.seeded_randomize(&*crypto::random::<32>()?);
     44     event
     45         .verify_with_ctx(&secp)
     46         .map_err(|_| OperationError::InvalidEvidence)?;
     47     let recipient = nostr::PublicKey::from_slice(work.recipient().as_bytes())
     48         .map_err(|_| OperationError::InvalidEvidence)?;
     49     let opened = candidate.with_wrapping_key(|key| {
     50         let secret =
     51             nostr::SecretKey::from_slice(key).map_err(|_| OperationError::InvalidEvidence)?;
     52         let keys = nostr::Keys::new_with_ctx(&secp, secret);
     53         if keys.public_key().to_bytes() != *candidate.author().as_bytes() {
     54             return Err(OperationError::InvalidEvidence);
     55         }
     56         nostr::nips::nip44::decrypt(keys.secret_key(), &recipient, &event.content)
     57             .map(Zeroizing::new)
     58             .map_err(|_| OperationError::InvalidEvidence)
     59     })?;
     60     if opened.as_bytes() != source.raw_json().as_bytes() {
     61         return Err(OperationError::InvalidEvidence);
     62     }
     63     Ok(())
     64 }
     65 fn unknown(operation: CommitAttempt, attempt: DeliveryRequestId) -> DeliveryAttemptOutcome {
     66     DeliveryAttemptOutcome::Unknown { operation, attempt }
     67 }
     68 impl BrowserWorkspace {
     69     /// Retains actual original outer bytes and selected target intent before a
     70     /// potential invocation. Only a fresh actual commit yields `Claimed`.
     71     pub async fn prepare_delivery_attempt(
     72         &self,
     73         request: DeliveryAttemptRequest,
     74         proof: AttachmentProof,
     75         candidate: Option<&EnvelopeCandidate>,
     76     ) -> Result<DeliveryAttemptOutcome, OperationError> {
     77         let fallback = request.identity();
     78         let request_id = request.intent().request_id().clone();
     79         let work = self.state.admit()?;
     80         let candidate = candidate.map(EnvelopeCandidate::retained_copy);
     81         let state = self.state.clone();
     82         let result = owned(work, async move {
     83             let access = state.operation_access(request.binding(), proof).await?;
     84             let actual = request.work();
     85             let evidence = actual.evidence();
     86             let operation = evidence.operation_id();
     87             let view = state.read_view(operation).await?;
     88             let t0 = state.operation_records(&view, operation).await?;
     89             let facts = state
     90                 .delivery_facts(
     91                     &view,
     92                     operation,
     93                     Some(evidence.command_digest()),
     94                     &t0,
     95                     access.binding.observed_at(),
     96                     Some(Selection {
     97                         recipient: evidence.target(),
     98                         request: request.intent().request_id(),
     99                         event: Some(request.intent().event_id()),
    100                         retain_seal: true,
    101                     }),
    102                 )
    103                 .await?;
    104             let snapshot = facts.snapshot.ok_or(OperationError::RecoveryRequired)?;
    105             radroots_storage::command::protected::same_binding(
    106                 snapshot.prepared().request().binding(),
    107                 request.binding(),
    108             )?;
    109             if !match actual {
    110                 PublicationArtifact::Private(work) => snapshot.publications().contains(&work),
    111                 PublicationArtifact::Public(work) => snapshot.public_publications().contains(&work),
    112             } {
    113                 return Err(OperationError::InvalidEvidence);
    114             }
    115             let bound = snapshot
    116                 .bound_plan()
    117                 .ok_or(OperationError::RecoveryRequired)?;
    118             let recipient = super::super::issuance::position(bound, evidence.target())?
    119                 .ok_or(OperationError::InvalidEvidence)?;
    120             let retained = facts
    121                 .selected
    122                 .as_ref()
    123                 .filter(|value| value.intent().request_id() == request.intent().request_id());
    124             if let Some(retained) = retained
    125                 && (retained.work() != actual
    126                     || retained.intent().digest() != request.intent().digest()
    127                     || candidate.as_ref().is_some_and(|value| {
    128                         PublicationArtifact::Private(value.work()) != actual
    129                             || value.raw_json() != retained.raw_json()
    130                     }))
    131             {
    132                 return Err(OperationError::IdempotencyConflict);
    133             }
    134             let fresh = retained.is_none();
    135             let (report, extra) = if fresh {
    136                 routes(bound, evidence.target(), request.intent())?;
    137                 if snapshot.delivery_attempts().iter().any(|value| {
    138                     value.work() == actual
    139                         && value.intent().publication_policy_digest()
    140                             != request.intent().publication_policy_digest()
    141                 }) {
    142                     return Err(OperationError::IdempotencyConflict);
    143                 }
    144                 let now = access.binding.observed_at();
    145                 if now < actual.queued_at()
    146                     || snapshot
    147                         .delivery_attempts()
    148                         .iter()
    149                         .any(|value| value.retained_at() > now)
    150                 {
    151                     return Err(WorkspaceError::Unavailable.into());
    152                 }
    153                 if now
    154                     .get()
    155                     .checked_mul(1000)
    156                     .is_none_or(|time| time >= request.intent().deadline_unix_ms().get())
    157                 {
    158                     return Err(OperationError::DeadlineExceeded);
    159                 }
    160                 let mut ordinals = Vec::with_capacity(request.intent().selection().len());
    161                 for target in request.intent().selected_targets() {
    162                     let count = snapshot
    163                         .delivery_attempts()
    164                         .iter()
    165                         .filter(|value| value.work() == actual)
    166                         .flat_map(|value| value.intent().selected_targets())
    167                         .filter(|old| old.uri() == target.uri())
    168                         .count();
    169                     if count >= 12 {
    170                         return Err(OperationError::DeliveryAttemptLimit);
    171                     }
    172                     ordinals.push(count as u8 + 1);
    173                 }
    174                 let raw = if matches!(actual, PublicationArtifact::Public(_)) {
    175                     if candidate.is_some() {
    176                         return Err(OperationError::InvalidEvidence);
    177                     }
    178                     let source = facts
    179                         .original
    180                         .as_ref()
    181                         .ok_or(OperationError::RecoveryRequired)?;
    182                     if source.target() != SigningTarget::PublicEvent
    183                         || source.digest() != actual.evidence().digest()
    184                         || source.event_id() != request.intent().event_id()
    185                     {
    186                         return Err(OperationError::InvalidEvidence);
    187                     }
    188                     Zeroizing::new(source.raw_json().to_owned())
    189                 } else if let Some(candidate) = &candidate {
    190                     if candidate.event_id() != request.intent().event_id() {
    191                         return Err(OperationError::InvalidEvidence);
    192                     }
    193                     contains_original(
    194                         candidate,
    195                         actual.private()?,
    196                         bound,
    197                         facts
    198                             .original
    199                             .as_ref()
    200                             .ok_or(OperationError::RecoveryRequired)?,
    201                     )?;
    202                     Zeroizing::new(candidate.raw_json().to_owned())
    203                 } else {
    204                     let original = facts
    205                         .selected
    206                         .as_ref()
    207                         .filter(|value| {
    208                             value.work() == actual
    209                                 && value.intent().event_id() == request.intent().event_id()
    210                         })
    211                         .ok_or(OperationError::InvalidEvidence)?;
    212                     Zeroizing::new(original.raw_json().to_owned())
    213                 };
    214                 if facts.selected.as_ref().is_some_and(|value| {
    215                     value.intent().event_id() == request.intent().event_id()
    216                         && value.raw_json() != raw.as_str()
    217                 }) {
    218                     return Err(OperationError::IdempotencyConflict);
    219                 }
    220                 if facts.slots[recipient as usize] >= 192 {
    221                     return Err(OperationError::DeliveryAttemptLimit);
    222                 }
    223                 let report = DeliveryAttempt::from_store_report(
    224                     actual,
    225                     request.intent().clone(),
    226                     &raw,
    227                     TransactionId::from_bytes(*crypto::random::<32>()?),
    228                     now,
    229                     ordinals,
    230                 )?;
    231                 let commitment = publication_commitment(&snapshot, actual)?;
    232                 let mut summaries = snapshot.delivery_attempts().to_vec();
    233                 summaries.push(DeliveryAttemptSummary::from_attempt(&report));
    234                 snapshot.with_delivery(summaries, Vec::new())?;
    235                 let extra = graph::protect(
    236                     &state,
    237                     operation,
    238                     recipient,
    239                     facts.slots[recipient as usize] + 1,
    240                     commitment,
    241                     &report,
    242                 )
    243                 .await?;
    244                 (report, extra)
    245             } else {
    246                 (
    247                     facts.selected.ok_or(OperationError::RecoveryRequired)?,
    248                     Vec::new(),
    249                 )
    250             };
    251             let anchor = CommitAttempt::new(
    252                 evidence.workspace_id(),
    253                 operation,
    254                 evidence.command_digest(),
    255                 Some(report.transaction_id()),
    256             );
    257             let identity = report.intent().request_id().clone();
    258             let deadline = fresh.then_some(report.intent().deadline_unix_ms());
    259             match state
    260                 .check_operation(
    261                     access,
    262                     operation,
    263                     OperationChange {
    264                         before: t0,
    265                         after: None,
    266                         window: None,
    267                         delivery_deadline: deadline,
    268                         extra,
    269                     },
    270                     view,
    271                 )
    272                 .await
    273             {
    274                 Ok(()) => Ok(if fresh {
    275                     DeliveryAttemptOutcome::Claimed(Box::new(report))
    276                 } else {
    277                     DeliveryAttemptOutcome::Retained(Box::new(report))
    278                 }),
    279                 Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    280                     state.mark_unknown();
    281                     Ok(unknown(anchor, identity))
    282                 }
    283                 Err(error) => Err(error),
    284             }
    285         })
    286         .await;
    287         match result {
    288             Err(OperationError::Workspace(WorkspaceError::CommitUnknown)) => {
    289                 self.state.mark_unknown();
    290                 Ok(unknown(fallback, request_id))
    291             }
    292             other => other,
    293         }
    294     }
    295     /// Reads the exact original attempt without dispatch or safe-reissue rights.
    296     pub async fn delivery_attempt(
    297         &self,
    298         binding: WorkspaceBinding,
    299         operation: OperationId,
    300         digest: CommandDigest,
    301         target: radroots_storage::command::SigningTarget,
    302         request: DeliveryRequestId,
    303         proof: AttachmentProof,
    304     ) -> Result<Option<DeliveryAttempt>, OperationError> {
    305         if !codec::valid_request(request.as_str()) {
    306             return Err(OperationError::InvalidCommand);
    307         }
    308         let work = self.state.admit()?;
    309         let state = self.state.clone();
    310         owned(work, async move {
    311             let access = state.operation_access(&binding, proof).await?;
    312             let recipient = target;
    313             let view = state.read_view(operation).await?;
    314             let t0 = state.operation_records(&view, operation).await?;
    315             let facts = state
    316                 .delivery_facts(
    317                     &view,
    318                     operation,
    319                     Some(digest),
    320                     &t0,
    321                     access.binding.observed_at(),
    322                     Some(Selection {
    323                         recipient,
    324                         request: &request,
    325                         event: None,
    326                         retain_seal: false,
    327                     }),
    328                 )
    329                 .await?;
    330             if let Some(snapshot) = &facts.snapshot {
    331                 radroots_storage::command::protected::same_binding(
    332                     snapshot.prepared().request().binding(),
    333                     &binding,
    334                 )?;
    335             }
    336             state
    337                 .check_operation(access, operation, OperationChange::observe(t0), view)
    338                 .await?;
    339             Ok(facts.selected)
    340         })
    341         .await
    342     }
    343 }