lib

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

command.rs (31408B)


      1 //! Owned ordinary public/private command execution over explicit host IO and protected storage.
      2 #[path = "inquiry_routes.rs"]
      3 mod routes;
      4 pub use routes::{capture_dm_route, selected_dm_targets};
      5 #[path = "command_obtained.rs"]
      6 mod obtained;
      7 use obtained::Obtained;
      8 
      9 use super::{HostBound, HostFuture, Shared, SignerSession};
     10 use alloc::{string::String, vec::Vec};
     11 use core::num::NonZeroU64;
     12 use radroots_domain::{PublicKey, UnixSeconds};
     13 use radroots_protocol::chat::{ChatRumor, ChatSeal, ChatSigningPlan};
     14 use radroots_protocol::nip59::CapturedDmRoute;
     15 use radroots_protocol::{
     16     intent::SigningReplay,
     17     listing::PublicSigningPlan,
     18     plan::{CapturedSigningPlan, SigningTarget},
     19 };
     20 use radroots_signing::{
     21     issuance::{OutcomeKind, RejectedArtifact, SigningIntent},
     22     provider::{PrivateCiphertext, PrivateText, ProviderCall},
     23     request::CancellationSignal,
     24 };
     25 use radroots_storage::{
     26     command::{
     27         BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, DeliveryAttemptOutcome,
     28         DeliveryAttemptRequest, DeliveryIntent, DeliveryObservation, EnvelopeCandidate,
     29         EvidenceCaptureOutcome, InstallationRequest, OperationError, OperationJournal,
     30         PlanBindingOutcome, PreparedOperation, PrivateEnvelopeCandidate, PublicationArtifact,
     31     },
     32     workspace::{AttachmentProof, WorkspaceBinding},
     33 };
     34 use radroots_transport::{DeliveryReceipt, SinkFailure, TargetSet};
     35 use std::sync::Mutex;
     36 
     37 /// Target IO, not command authority. Construction/start/query must not perform
     38 /// network work or replay an outbox. Implementations must enforce their explicit
     39 /// destination policy and bound every actual request.
     40 pub trait CommandIo: HostBound {
     41     /// Whether explicit online startup permits this workflow's network work.
     42     fn enabled(&self) -> bool;
     43     /// Current positive supported time; never renews a first-issue window.
     44     fn now(&self) -> Result<UnixSeconds, OperationError>;
     45     /// Explicit configured public publication targets. An unsupported host must
     46     /// refuse; public work never borrows a private participant's route.
     47     fn public_targets(&self) -> Result<TargetSet, OperationError> {
     48         Err(OperationError::UnsupportedOperation)
     49     }
     50     /// CSPRNG-backed NIP-59 past time within the supported two-day interval.
     51     fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError>;
     52     /// Authenticates a bounded current kind-10050 head and captures only its
     53     /// explicitly approved write endpoints, preserving original signed bytes.
     54     fn route(
     55         &self,
     56         recipient: PublicKey,
     57         deadline: NonZeroU64,
     58     ) -> HostFuture<'_, Result<CapturedDmRoute, OperationError>>;
     59     /// Resolves only the original captured route against current write policy.
     60     fn targets(&self, route: &CapturedDmRoute) -> Result<TargetSet, OperationError>;
     61     /// Explicit relay acceptance criterion, frozen by the first retained D.
     62     fn publication_policy(&self) -> radroots_transport::policy::SatisfactionPolicy;
     63     /// Wraps the original obtained seal with a fresh temporary envelope key.
     64     fn private_envelope(
     65         &self,
     66         recipient: PublicKey,
     67         raw_seal: &str,
     68     ) -> Result<PrivateEnvelopeCandidate, OperationError>;
     69     /// Fresh full-width transport-attempt identity from qualified entropy.
     70     fn delivery_id(&self) -> Result<String, OperationError>;
     71     /// Dispatches only an actual freshly committed original delivery claim.
     72     fn publish(
     73         &self,
     74         request: radroots_transport::sink::DeliveryRequest,
     75         selected: TargetSet,
     76     ) -> HostFuture<'_, Result<DeliveryReceipt, SinkFailure>>;
     77 }
     78 
     79 struct PendingCapture {
     80     journal: Shared<dyn OperationJournal>,
     81     binding: WorkspaceBinding,
     82     proof: AttachmentProof,
     83     obtained: Obtained,
     84     // Keeps both the resource permit and conservative live-byte reservation.
     85     _lease: Shared<dyn HostBound>,
     86 }
     87 struct PendingObservation {
     88     journal: Shared<dyn OperationJournal>,
     89     binding: WorkspaceBinding,
     90     proof: AttachmentProof,
     91     observation: DeliveryObservation,
     92     _lease: Shared<dyn HostBound>,
     93 }
     94 
     95 /// Shared workflow and obtained-material owner. Its lifecycle host must call
     96 /// `drain` before releasing work permits, callbacks or protected storage.
     97 pub struct CommandRuntime {
     98     pub(super) io: Shared<dyn CommandIo>,
     99     pending: Mutex<Vec<Shared<PendingCapture>>>,
    100     observations: Mutex<Vec<Shared<PendingObservation>>>,
    101     draining: futures::lock::Mutex<()>,
    102 }
    103 pub(super) struct SigningResources {
    104     pub(super) signer: Option<SignerSession>,
    105     pub(super) lease: Shared<dyn HostBound>,
    106     pub(super) stock_captures: Shared<super::stock_evidence::Owner>,
    107 }
    108 #[derive(Clone, Copy)]
    109 pub(super) enum RunMode {
    110     Command,
    111     Resume,
    112 }
    113 pub(super) enum CommandFailure {
    114     Retained(crate::Error),
    115     Host(OperationError, Option<RejectedArtifact>),
    116     Capture(OperationError),
    117     Rejected(RejectedArtifact),
    118 }
    119 impl From<crate::Error> for CommandFailure {
    120     fn from(error: crate::Error) -> Self {
    121         Self::Retained(error)
    122     }
    123 }
    124 impl From<OperationError> for CommandFailure {
    125     fn from(error: OperationError) -> Self {
    126         Self::Host(error, None)
    127     }
    128 }
    129 impl CommandFailure {
    130     pub(super) fn into_failure(
    131         self,
    132         operation: radroots_domain::OperationId,
    133     ) -> crate::ExecutionFailure {
    134         let context = crate::OperationContext::retained(operation);
    135         match self {
    136             Self::Retained(error) => error.into(),
    137             Self::Host(error, Some(rejected)) => {
    138                 crate::ExecutionFailure::host_after_rejection(error, operation, rejected)
    139             }
    140             Self::Host(error, None) => crate::Error::operation(error, context).into(),
    141             Self::Capture(error) => crate::Error::capture_pending(error, context).into(),
    142             Self::Rejected(rejected) => crate::ExecutionFailure::rejected(operation, rejected),
    143         }
    144     }
    145 }
    146 impl CommandRuntime {
    147     /// Owns explicit IO without performing effects or starting a runtime.
    148     pub fn new(io: Shared<dyn CommandIo>) -> Self {
    149         Self {
    150             io,
    151             pending: Mutex::new(Vec::new()),
    152             observations: Mutex::new(Vec::new()),
    153             draining: futures::lock::Mutex::new(()),
    154         }
    155     }
    156     /// Retries only already obtained original evidence. Failure retains its
    157     /// exact bytes and resource ownership, including when this wait is dropped.
    158     pub async fn drain(&self) -> crate::Result<()> {
    159         let _serial = self.draining.lock().await;
    160         loop {
    161             let next = self
    162                 .pending
    163                 .lock()
    164                 .unwrap_or_else(std::sync::PoisonError::into_inner)
    165                 .first()
    166                 .cloned();
    167             let Some(next) = next else {
    168                 break;
    169             };
    170             let fail = |error| {
    171                 crate::Error::capture_pending(
    172                     error,
    173                     crate::OperationContext::retained(next.obtained.operation()),
    174                 )
    175             };
    176             let evidence = next.obtained.evidence().map_err(fail)?;
    177             match next
    178                 .journal
    179                 .reconcile_unknown(next.binding.input().clone(), &next.proof, evidence)
    180                 .await
    181                 .map_err(fail)?
    182             {
    183                 EvidenceCaptureOutcome::Committed(_) => self.remove(&next),
    184                 EvidenceCaptureOutcome::Unknown(_) => {
    185                     return Err(fail(OperationError::RecoveryRequired));
    186                 }
    187             }
    188         }
    189         loop {
    190             let next = self
    191                 .observations
    192                 .lock()
    193                 .unwrap_or_else(std::sync::PoisonError::into_inner)
    194                 .first()
    195                 .cloned();
    196             let Some(next) = next else {
    197                 return Ok(());
    198             };
    199             self.capture_observation(&next).await.map_err(|error| {
    200                 crate::Error::capture_pending(
    201                     error,
    202                     crate::OperationContext::retained(
    203                         next.observation.work().evidence().operation_id(),
    204                     ),
    205                 )
    206             })?;
    207         }
    208     }
    209     pub(super) fn ensure_ready(&self) -> crate::Result<()> {
    210         let pending = self
    211             .pending
    212             .lock()
    213             .unwrap_or_else(std::sync::PoisonError::into_inner);
    214         if let Some(entry) = pending.first() {
    215             return Err(crate::Error::capture_pending(
    216                 OperationError::RecoveryRequired,
    217                 crate::OperationContext::retained(entry.obtained.operation()),
    218             ));
    219         }
    220         Ok(())
    221     }
    222     async fn capture_observation(
    223         &self,
    224         entry: &Shared<PendingObservation>,
    225     ) -> Result<(), OperationError> {
    226         match entry
    227             .journal
    228             .record_delivery_observation(
    229                 entry.binding.clone(),
    230                 copy(&entry.proof)?,
    231                 entry.observation.clone(),
    232             )
    233             .await?
    234         {
    235             radroots_storage::command::DeliveryObservationOutcome::Committed(_) => {
    236                 let removed = {
    237                     let mut pending = self
    238                         .observations
    239                         .lock()
    240                         .unwrap_or_else(std::sync::PoisonError::into_inner);
    241                     pending
    242                         .iter()
    243                         .position(|value| Shared::ptr_eq(value, entry))
    244                         .map(|index| pending.remove(index))
    245                 };
    246                 drop(removed);
    247                 Ok(())
    248             }
    249             radroots_storage::command::DeliveryObservationOutcome::Unknown(_) => {
    250                 Err(OperationError::RecoveryRequired)
    251             }
    252         }
    253     }
    254     fn remove(&self, entry: &Shared<PendingCapture>) {
    255         let removed = {
    256             let mut pending = self
    257                 .pending
    258                 .lock()
    259                 .unwrap_or_else(std::sync::PoisonError::into_inner);
    260             pending
    261                 .iter()
    262                 .position(|value| Shared::ptr_eq(value, entry))
    263                 .map(|index| pending.remove(index))
    264         };
    265         drop(removed);
    266     }
    267     pub(super) async fn run(
    268         &self,
    269         journal: Shared<dyn OperationJournal>,
    270         prepared: PreparedOperation,
    271         proof: &AttachmentProof,
    272         resources: SigningResources,
    273         mode: RunMode,
    274     ) -> Result<(), CommandFailure> {
    275         if !self.io.enabled() {
    276             return Ok(());
    277         }
    278         self.drain().await?;
    279         resources.stock_captures.ensure_ready()?;
    280         let signer = &resources.signer;
    281         let binding = prepared.request().binding().clone();
    282         let operation = prepared.identity().operation_id();
    283         let digest = prepared.identity().command_digest();
    284         let original = journal
    285             .signing_plan(binding.clone(), operation, digest, copy(proof)?)
    286             .await?;
    287         let bound = match original {
    288             Some(bound) => bound,
    289             None => {
    290                 let signer = signer.as_ref().ok_or(OperationError::Unauthorized)?;
    291                 let plan = self.plan(&prepared, signer).await?;
    292                 match journal
    293                     .bind_signing_intents(binding.clone(), plan, copy(proof)?)
    294                     .await?
    295                 {
    296                     PlanBindingOutcome::Committed(bound) => bound,
    297                     PlanBindingOutcome::Unknown(_) => {
    298                         return Err(OperationError::RecoveryRequired.into());
    299                     }
    300                 }
    301             }
    302         };
    303         let rejected = self
    304             .issue(
    305                 journal.clone(),
    306                 &bound,
    307                 proof,
    308                 signer.as_ref(),
    309                 resources.lease.clone(),
    310                 &resources.stock_captures,
    311             )
    312             .await?;
    313         let installation: Result<(), OperationError> = async {
    314             let snapshot = journal
    315                 .operation_snapshot(binding.clone(), operation, Some(digest), copy(proof)?)
    316                 .await?
    317                 .ok_or(OperationError::RecoveryRequired)?;
    318             if snapshot
    319                 .artifacts()
    320                 .iter()
    321                 .any(|recipient| recipient.obtained().is_some())
    322             {
    323                 let outcome = journal
    324                     .install_transition_and_outbox(
    325                         InstallationRequest::new(
    326                             binding.clone(),
    327                             operation,
    328                             digest,
    329                             *bound.plan().digest(),
    330                         ),
    331                         copy(proof)?,
    332                     )
    333                     .await?;
    334                 if matches!(
    335                     outcome,
    336                     radroots_storage::command::InstallationOutcome::Unknown(_)
    337                 ) {
    338                     return Err(OperationError::RecoveryRequired);
    339                 }
    340             }
    341             Ok(())
    342         }
    343         .await;
    344         if let Err(error) = installation {
    345             return Err(CommandFailure::Host(error, rejected));
    346         }
    347         if let Some(rejected) = rejected {
    348             return Err(CommandFailure::Rejected(rejected));
    349         }
    350         self.deliver(journal, &bound, proof, resources.lease, mode)
    351             .await
    352             .map_err(Into::into)
    353     }
    354     async fn plan(
    355         &self,
    356         prepared: &PreparedOperation,
    357         signer: &SignerSession,
    358     ) -> Result<CapturedSigningPlan, OperationError> {
    359         let now = self.io.now()?;
    360         let deadline = NonZeroU64::new(
    361             prepared
    362                 .issuance_window()
    363                 .first_issue_not_after()
    364                 .get()
    365                 .checked_mul(1000)
    366                 .ok_or(OperationError::RecoveryRequired)?,
    367         )
    368         .ok_or(OperationError::RecoveryRequired)?;
    369         if now >= prepared.issuance_window().first_issue_not_after() {
    370             return Err(OperationError::DeadlineExceeded);
    371         }
    372         let observed = signer
    373             .observe()
    374             .await
    375             .map_err(|_| OperationError::Unauthorized)?;
    376         if observed.identity() != prepared.request().command().context().actor().participant() {
    377             return Err(OperationError::Unauthorized);
    378         }
    379         let replay = match observed
    380             .exact_issuance()
    381             .ok_or(OperationError::Unauthorized)?
    382         {
    383             radroots_signing::recovery::ReplayCapability::NonReplayable => {
    384                 SigningReplay::NonReplayable
    385             }
    386             radroots_signing::recovery::ReplayCapability::LocalReplaySafe => {
    387                 SigningReplay::LocalReplaySafe
    388             }
    389             radroots_signing::recovery::ReplayCapability::ExactReplayByRequestId => {
    390                 SigningReplay::ExactReplayByRequestId
    391             }
    392             _ => return Err(OperationError::Unauthorized),
    393         };
    394         if let Some(command) = prepared.request().command().listing() {
    395             let targets = self.io.public_targets()?;
    396             let urls = targets
    397                 .targets()
    398                 .iter()
    399                 .map(|target| target.uri().as_str().into())
    400                 .collect::<Vec<String>>();
    401             return PublicSigningPlan::capture(command, now, &urls, replay)
    402                 .map(CapturedSigningPlan::Listing)
    403                 .map_err(|_| OperationError::InvalidCommand);
    404         }
    405         let command = prepared.request().chat_command()?;
    406         if observed.encryption() != radroots_signing::provider::PrivateCryptoCapability::Nip44V2
    407             || observed.decryption() != radroots_signing::provider::PrivateCryptoCapability::Nip44V2
    408         {
    409             return Err(OperationError::Unauthorized);
    410         }
    411         let rumor =
    412             ChatRumor::from_command(command, now).map_err(|_| OperationError::InvalidCommand)?;
    413         let mut routes = Vec::new();
    414         // Resolve every original route before provider encryption or T1.
    415         for recipient in rumor.recipients() {
    416             routes.push(self.io.route(*recipient, deadline).await?);
    417         }
    418         let mut seals = Vec::new();
    419         for recipient in rumor.recipients() {
    420             let call = || ProviderCall::new(rumor.author(), deadline, CancellationSignal::new());
    421             let text =
    422                 PrivateText::new(rumor.json()).map_err(|_| OperationError::InvalidCommand)?;
    423             let encrypted = signer
    424                 .encrypt_private(call(), *recipient, text)
    425                 .await
    426                 .map_err(|_| OperationError::Unauthorized)?;
    427             let check = PrivateCiphertext::parse(encrypted.as_str())
    428                 .map_err(|_| OperationError::InvalidEvidence)?;
    429             let decrypted = signer
    430                 .decrypt_private(call(), *recipient, check)
    431                 .await
    432                 .map_err(|_| OperationError::InvalidEvidence)?;
    433             if decrypted.expose() != rumor.json() {
    434                 return Err(OperationError::InvalidEvidence);
    435             }
    436             seals.push(
    437                 ChatSeal::new(
    438                     &rumor,
    439                     *recipient,
    440                     self.io.seal_time(now)?,
    441                     encrypted.as_str(),
    442                 )
    443                 .map_err(|_| OperationError::InvalidCommand)?,
    444             );
    445         }
    446         ChatSigningPlan::new(command, now, seals, routes, replay)
    447             .map(CapturedSigningPlan::Chat)
    448             .map_err(|_| OperationError::InvalidCommand)
    449     }
    450     async fn issue(
    451         &self,
    452         journal: Shared<dyn OperationJournal>,
    453         bound: &BoundSigningPlan,
    454         proof: &AttachmentProof,
    455         signer: Option<&SignerSession>,
    456         lease: Shared<dyn HostBound>,
    457         stock_captures: &super::stock_evidence::Owner,
    458     ) -> Result<Option<RejectedArtifact>, CommandFailure> {
    459         let prepared = bound.prepared();
    460         let binding = prepared.request().binding();
    461         let targets = match bound.plan() {
    462             CapturedSigningPlan::Listing(_) => alloc::vec![SigningTarget::PublicEvent],
    463             CapturedSigningPlan::Chat(plan) => plan
    464                 .seals()
    465                 .iter()
    466                 .map(|seal| SigningTarget::BusinessSeal(seal.recipient()))
    467                 .collect(),
    468         };
    469         for target in targets {
    470             let select = || {
    471                 ClaimAttemptRequest::for_artifact(
    472                     binding.clone(),
    473                     prepared.identity().operation_id(),
    474                     prepared.identity().command_digest(),
    475                     *bound.plan().digest(),
    476                     target,
    477                 )
    478             };
    479             if journal
    480                 .signing_attempt(select(), copy(proof)?)
    481                 .await?
    482                 .is_some()
    483             {
    484                 continue;
    485             }
    486             let Some(signer) = signer else {
    487                 continue;
    488             };
    489             if signer.state() != super::SessionState::Running
    490                 || !self
    491                     .io
    492                     .now()
    493                     .is_ok_and(|now| now < prepared.issuance_window().first_issue_not_after())
    494             {
    495                 continue;
    496             }
    497             stock_captures.ensure_ready()?;
    498             let attempt = match journal.claim_attempt(select(), copy(proof)?).await {
    499                 Err(OperationError::DeadlineExceeded) => continue,
    500                 Err(error) => return Err(error.into()),
    501                 Ok(outcome) => match outcome {
    502                     ClaimAttemptOutcome::Claimed(attempt) => attempt,
    503                     ClaimAttemptOutcome::Retained(_) | ClaimAttemptOutcome::Unknown(_) => continue,
    504                 },
    505             };
    506             let intent = SigningIntent::from_plan(
    507                 attempt.bound_plan().plan(),
    508                 attempt.target(),
    509                 ProviderCall::new(
    510                     attempt
    511                         .bound_plan()
    512                         .plan()
    513                         .artifact(attempt.target())
    514                         .map_err(|_| OperationError::RecoveryRequired)?
    515                         .fields()
    516                         .author,
    517                     attempt.deadline_unix_ms(),
    518                     CancellationSignal::new(),
    519                 ),
    520             )
    521             .map_err(|_| OperationError::InvalidCommand)?;
    522             if intent.binding() != attempt.binding() {
    523                 return Err(OperationError::RecoveryRequired.into());
    524             }
    525             let capture_proof = copy(proof)?;
    526             self.ensure_ready()?;
    527             stock_captures.ensure_ready()?;
    528             let outcome = signer.sign_exact(intent).await;
    529             let (_, kind) = outcome.into_parts();
    530             if let OutcomeKind::Rejected(rejected) = kind {
    531                 return Ok(Some(rejected));
    532             }
    533             if let OutcomeKind::Obtained(artifact) = kind {
    534                 let entry = Shared::new(PendingCapture {
    535                     journal: journal.clone(),
    536                     binding: binding.clone(),
    537                     proof: capture_proof,
    538                     obtained: Obtained::new(attempt, artifact),
    539                     _lease: lease.clone(),
    540                 });
    541                 self.pending
    542                     .lock()
    543                     .unwrap_or_else(std::sync::PoisonError::into_inner)
    544                     .push(entry.clone());
    545                 let evidence = entry.obtained.evidence().map_err(CommandFailure::Capture)?;
    546                 match journal
    547                     .capture_evidence(binding.input().clone(), &entry.proof, evidence)
    548                     .await
    549                     .map_err(CommandFailure::Capture)?
    550                 {
    551                     EvidenceCaptureOutcome::Committed(_) => self.remove(&entry),
    552                     EvidenceCaptureOutcome::Unknown(_) => {
    553                         return Err(CommandFailure::Capture(OperationError::RecoveryRequired));
    554                     }
    555                 }
    556             }
    557         }
    558         Ok(None)
    559     }
    560     async fn deliver(
    561         &self,
    562         journal: Shared<dyn OperationJournal>,
    563         bound: &BoundSigningPlan,
    564         proof: &AttachmentProof,
    565         lease: Shared<dyn HostBound>,
    566         mode: RunMode,
    567     ) -> Result<(), OperationError> {
    568         let prepared = bound.prepared();
    569         let binding = prepared.request().binding();
    570         let snapshot = journal
    571             .operation_snapshot(
    572                 binding.clone(),
    573                 prepared.identity().operation_id(),
    574                 Some(prepared.identity().command_digest()),
    575                 copy(proof)?,
    576             )
    577             .await?
    578             .ok_or(OperationError::RecoveryRequired)?;
    579         let work = snapshot
    580             .publications()
    581             .iter()
    582             .copied()
    583             .map(PublicationArtifact::Private)
    584             .chain(
    585                 snapshot
    586                     .public_publications()
    587                     .iter()
    588                     .copied()
    589                     .map(PublicationArtifact::Public),
    590             );
    591         for work in work {
    592             if snapshot.publication_accepted(work)? {
    593                 continue;
    594             }
    595             // Replaying a command never dispatches a previously claimed attempt.
    596             let original = snapshot
    597                 .delivery_attempts()
    598                 .iter()
    599                 .find(|attempt| attempt.work() == work);
    600             if original.is_some() && matches!(mode, RunMode::Command) {
    601                 continue;
    602             }
    603             let (targets, envelope, event) = match work {
    604                 PublicationArtifact::Private(private) => {
    605                     let recipient = private.recipient();
    606                     let route = bound
    607                         .chat_plan()?
    608                         .routes()
    609                         .iter()
    610                         .find(|route| route.participant() == recipient)
    611                         .ok_or(OperationError::RecoveryRequired)?;
    612                     let targets = self.io.targets(route)?;
    613                     let captured = journal
    614                         .obtained_evidence(
    615                             ClaimAttemptRequest::new(
    616                                 binding.clone(),
    617                                 prepared.identity().operation_id(),
    618                                 prepared.identity().command_digest(),
    619                                 *bound.plan().digest(),
    620                                 recipient,
    621                             ),
    622                             copy(proof)?,
    623                         )
    624                         .await?
    625                         .ok_or(OperationError::RecoveryRequired)?;
    626                     let envelope = if original.is_none() {
    627                         Some(EnvelopeCandidate::from_private(
    628                             private,
    629                             self.io.private_envelope(
    630                                 private.recipient(),
    631                                 captured.evidence().raw_json(),
    632                             )?,
    633                         )?)
    634                     } else {
    635                         None
    636                     };
    637                     let event = match original {
    638                         Some(v) => v.intent().event_id(),
    639                         None => envelope
    640                             .as_ref()
    641                             .ok_or(OperationError::RecoveryRequired)?
    642                             .event_id(),
    643                     };
    644                     (targets, envelope, event)
    645                 }
    646                 PublicationArtifact::Public(public) => {
    647                     let configured = self.io.public_targets()?;
    648                     let plan = bound
    649                         .plan()
    650                         .listing()
    651                         .ok_or(OperationError::RecoveryRequired)?;
    652                     let targets = TargetSet::new(
    653                         plan.selected_targets()
    654                             .iter()
    655                             .map(|uri| radroots_transport::Target::nostr_relay(uri.as_ref()))
    656                             .collect::<Result<Vec<_>, _>>()
    657                             .map_err(|_| OperationError::RecoveryRequired)?,
    658                     )
    659                     .map_err(|_| OperationError::RecoveryRequired)?;
    660                     if targets.targets().iter().any(|target| {
    661                         !configured
    662                             .targets()
    663                             .iter()
    664                             .any(|allowed| allowed.fingerprint() == target.fingerprint())
    665                     }) {
    666                         return Err(OperationError::UnverifiedApproval);
    667                     }
    668                     (targets, None, public.evidence().event_id())
    669                 }
    670             };
    671             let deadline = NonZeroU64::new(
    672                 self.io
    673                     .now()?
    674                     .get()
    675                     .checked_add(30)
    676                     .and_then(|time| time.checked_mul(1000))
    677                     .ok_or(OperationError::RecoveryRequired)?,
    678             )
    679             .ok_or(OperationError::RecoveryRequired)?;
    680             let (event, targets, policy) = match original {
    681                 Some(original) => (
    682                     original.intent().event_id(),
    683                     original.intent().targets().clone(),
    684                     original.intent().policy().clone(),
    685                 ),
    686                 None => (event, targets, self.io.publication_policy()),
    687             };
    688             let selected = targets
    689                 .targets()
    690                 .iter()
    691                 .filter(|target| {
    692                     !snapshot.delivery_observations().iter().any(|observation| {
    693                         observation.work() == work
    694                             && observation.target_receipt().target().fingerprint()
    695                                 == target.fingerprint()
    696                             && observation.kind()
    697                                 == radroots_storage::command::DeliveryObservationKind::Accepted
    698                     })
    699                 })
    700                 .cloned()
    701                 .collect::<Vec<_>>();
    702             if selected.is_empty() {
    703                 continue;
    704             }
    705             let selected =
    706                 TargetSet::new(selected).map_err(|_| OperationError::RecoveryRequired)?;
    707             let request_id = self.io.delivery_id()?;
    708             let intent = match work {
    709                 PublicationArtifact::Private(_) => {
    710                     DeliveryIntent::new(&request_id, event, &targets, &policy, deadline)
    711                 }
    712                 PublicationArtifact::Public(_) => {
    713                     DeliveryIntent::public(&request_id, event, &targets, &policy, deadline)
    714                 }
    715             }?
    716             .with_selection(&selected)?;
    717             let request = DeliveryAttemptRequest::new(binding.clone(), work, intent)?;
    718             let attempt = match journal
    719                 .prepare_delivery_attempt(request, copy(proof)?, envelope.as_ref())
    720                 .await?
    721             {
    722                 DeliveryAttemptOutcome::Claimed(attempt) => attempt,
    723                 DeliveryAttemptOutcome::Retained(_) | DeliveryAttemptOutcome::Unknown { .. } => {
    724                     continue;
    725                 }
    726             };
    727             let result = self
    728                 .io
    729                 .publish(
    730                     attempt.transport_request()?,
    731                     attempt.intent().selected_target_set()?,
    732                 )
    733                 .await;
    734             let observed = self
    735                 .io
    736                 .now()
    737                 .ok()
    738                 .and_then(|time| time.get().checked_mul(1000))
    739                 .and_then(NonZeroU64::new);
    740             let reports = match &result {
    741                 Ok(receipt) => receipt.target_receipts(),
    742                 Err(failure) => failure.partial_evidence(),
    743             };
    744             let mut entries = Vec::new();
    745             for report in reports {
    746                 let observation = match &result {
    747                     Ok(receipt) => DeliveryObservation::from_receipt(
    748                         &attempt,
    749                         receipt,
    750                         report.target().fingerprint(),
    751                         observed,
    752                     ),
    753                     Err(failure) => DeliveryObservation::from_failure(
    754                         &attempt,
    755                         failure,
    756                         report.target().fingerprint(),
    757                         observed,
    758                     ),
    759                 }?;
    760                 entries.push(Shared::new(PendingObservation {
    761                     journal: journal.clone(),
    762                     binding: binding.clone(),
    763                     proof: copy(proof)?,
    764                     observation,
    765                     _lease: lease.clone(),
    766                 }));
    767             }
    768             self.observations
    769                 .lock()
    770                 .unwrap_or_else(std::sync::PoisonError::into_inner)
    771                 .extend(entries.iter().cloned());
    772             for entry in entries {
    773                 self.capture_observation(&entry).await?;
    774             }
    775         }
    776         Ok(())
    777     }
    778 }
    779 fn copy(proof: &AttachmentProof) -> Result<AttachmentProof, OperationError> {
    780     proof
    781         .with_secret(|secret| AttachmentProof::from_protected_input(secret))
    782         .map_err(Into::into)
    783 }