lib

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

commit b004dcaaa0672e397f0b00da4ee81ee175e06d33
parent a146bf147961815f8d196e840c51a87891bf862b
Author: triesap <tyson@radroots.org>
Date:   Sun, 18 Oct 2026 19:43:35 +0000

execution: complete owned native inquiry workflows

- Run accepted inquiries on a bounded native task owner through exact retained delivery.
- Compose scoped private crypto, original signing plans, installation and explicit resume.
- Retain obtained evidence and writer ownership across capture failure and cancelled close.
- Cover peer and self decrypt, exact retries, partial outcomes and native lifecycle faults.

Diffstat:
Mcontracts/api_baselines/radroots.txt | 5+++++
Mcontracts/api_baselines/radroots_execution.txt | 28+++++++++++++++++++++++++++-
Mcontracts/api_baselines/radroots_nostr.txt | 1+
Mcontracts/api_baselines/radroots_storage.txt | 12++++++++++++
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 1+
Mcrates/execution/Cargo.toml | 3++-
Mcrates/execution/src/error.rs | 4+++-
Mcrates/execution/src/session/client.rs | 42++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/session/client_commands.rs | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcrates/execution/src/session/host.rs | 8++++++++
Acrates/execution/src/session/inquiry.rs | 588+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/session/mod.rs | 11++++++++++-
Mcrates/execution/src/session/signer.rs | 81++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Acrates/execution/src/session/tasks.rs | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/tests/session.rs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/tests/signer_session.rs | 151+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcrates/nostr/src/signing/gift_wrap.rs | 12++++++++++++
Mcrates/nostr/src/signing/gift_wrap/tests.rs | 24++++++++++++++++++++++++
Mcrates/radroots/Cargo.toml | 7++++++-
Mcrates/radroots/README.md | 29+++++++++++++++++++++++++----
Mcrates/radroots/src/client.rs | 179++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcrates/radroots/src/lib.rs | 6++++++
Acrates/radroots/src/native_inquiry.rs | 372+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots/src/native_tasks.rs | 652+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/src/operations.rs | 13+++++++++++++
Mcrates/radroots/tests/native_client.rs | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/tests/package_boundary.rs | 7++++++-
Mcrates/radroots/tests/receipts.rs | 17+++++++++++++++--
Mcrates/radroots/tests/support/receipt_client.rs | 144+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/tests/support/receipt_issuance.rs | 2++
Acrates/radroots/tests/support/receipt_recovery.rs | 221+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots/tests/support/receipt_workflow.rs | 283+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/radroots/tests/support/receipt_workflow_faults.rs | 654+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage/src/command.rs | 15+++++++++++++++
Acrates/storage/src/command/dm_source.rs | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/delivery/graph.rs | 61++++++++-----------------------------------------------------
Mcrates/storage_sqlite/src/workspace/mod.rs | 15+++++++++++++++
Acrates/storage_sqlite/src/workspace/recovery.rs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/worker.rs | 151+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
39 files changed, 4364 insertions(+), 129 deletions(-)

diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -18,6 +18,7 @@ pub use radroots::WorkspaceSession pub mod radroots::client #[non_exhaustive] pub enum radroots::client::StartMode pub radroots::client::StartMode::LocalOnly +pub radroots::client::StartMode::Online pub struct radroots::client::Client impl radroots::client::Client pub async fn radroots::client::Client::attach(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<radroots_execution::workspace::WorkspaceSession> @@ -37,6 +38,7 @@ pub const fn radroots::client::CloseReceipt::storage(self) -> radroots_storage:: pub struct radroots::client::NativeConfig impl radroots::client::NativeConfig pub fn radroots::client::NativeConfig::public_read(radroots_storage_sqlite::config::OpenOptions) -> Self +pub fn radroots::client::NativeConfig::with_nostr(self, radroots_transport_nostr::client::Config, radroots_transport::policy::SatisfactionPolicy) -> radroots_execution::Result<Self> pub fn radroots::client::NativeConfig::with_workspace(self, radroots_storage_sqlite::workspace::NativeWorkspace) -> Self pub struct radroots::client::SessionStatus impl radroots::client::SessionStatus @@ -127,6 +129,7 @@ pub struct radroots::operations::Operations<'a> impl<'a> radroots::operations::Operations<'a> pub async fn radroots::operations::Operations<'a>::get(&self, radroots_domain::identifier::OperationId) -> radroots_execution::Result<core::option::Option<radroots_execution::receipt::OperationReceipt<radroots_domain::message::ChatMessage>>> pub async fn radroots::operations::Operations<'a>::get_matching(&self, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<core::option::Option<radroots_execution::receipt::OperationReceipt<radroots_domain::message::ChatMessage>>> +pub async fn radroots::operations::Operations<'a>::resume(&self, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<radroots_execution::receipt::OperationReceipt<radroots_domain::message::ChatMessage>> pub mod radroots::signing pub use radroots::signing::ArtifactRole pub use radroots::signing::AuthorizationHeader @@ -199,6 +202,7 @@ pub use radroots::transport::TargetSet pub use radroots::transport::TransportId #[non_exhaustive] pub enum radroots::StartMode pub radroots::StartMode::LocalOnly +pub radroots::StartMode::Online pub struct radroots::Client impl radroots::client::Client pub async fn radroots::client::Client::attach(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<radroots_execution::workspace::WorkspaceSession> @@ -218,6 +222,7 @@ pub const fn radroots::client::CloseReceipt::storage(self) -> radroots_storage:: pub struct radroots::NativeConfig impl radroots::client::NativeConfig pub fn radroots::client::NativeConfig::public_read(radroots_storage_sqlite::config::OpenOptions) -> Self +pub fn radroots::client::NativeConfig::with_nostr(self, radroots_transport_nostr::client::Config, radroots_transport::policy::SatisfactionPolicy) -> radroots_execution::Result<Self> pub fn radroots::client::NativeConfig::with_workspace(self, radroots_storage_sqlite::workspace::NativeWorkspace) -> Self pub struct radroots::SessionStatus impl radroots::client::SessionStatus diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -3,6 +3,24 @@ pub mod radroots_execution::inbox pub use radroots_execution::inbox::InquireInput pub use radroots_execution::inbox::ListingRevisionRef pub mod radroots_execution::session +pub mod radroots_execution::session::inquiry +pub struct radroots_execution::session::inquiry::InquiryRuntime +impl radroots_execution::session::inquiry::InquiryRuntime +pub async fn radroots_execution::session::inquiry::InquiryRuntime::drain(&self) -> core::result::Result<(), radroots_storage::command::OperationError> +pub fn radroots_execution::session::inquiry::InquiryRuntime::new(alloc::sync::Arc<dyn radroots_execution::session::inquiry::InquiryIo>) -> Self +pub trait radroots_execution::session::inquiry::InquiryIo: radroots_execution::session::HostBound +pub fn radroots_execution::session::inquiry::InquiryIo::delivery_id(&self) -> core::result::Result<alloc::string::String, radroots_storage::command::OperationError> +pub fn radroots_execution::session::inquiry::InquiryIo::enabled(&self) -> bool +pub fn radroots_execution::session::inquiry::InquiryIo::envelope(&self, radroots_storage::command::installation::PublicationWork, &str) -> core::result::Result<radroots_storage::command::delivery::EnvelopeCandidate, radroots_storage::command::OperationError> +pub fn radroots_execution::session::inquiry::InquiryIo::now(&self) -> core::result::Result<radroots_domain::context::UnixSeconds, radroots_storage::command::OperationError> +pub fn radroots_execution::session::inquiry::InquiryIo::publication_policy(&self) -> radroots_transport::policy::SatisfactionPolicy +pub fn radroots_execution::session::inquiry::InquiryIo::publish(&self, radroots_transport::sink::DeliveryRequest, radroots_transport::target::TargetSet) -> radroots_execution::session::HostFuture<'_, core::result::Result<radroots_transport::sink::DeliveryReceipt, radroots_transport::sink::SinkFailure>> +pub fn radroots_execution::session::inquiry::InquiryIo::route(&self, radroots_identity::key::PublicKey, core::num::nonzero::NonZeroU64) -> radroots_execution::session::HostFuture<'_, core::result::Result<radroots_protocol::chat::routes::CapturedDmRoute, radroots_storage::command::OperationError>> +pub fn radroots_execution::session::inquiry::InquiryIo::seal_time(&self, radroots_domain::context::UnixSeconds) -> core::result::Result<radroots_domain::context::UnixSeconds, radroots_storage::command::OperationError> +pub fn radroots_execution::session::inquiry::InquiryIo::targets(&self, &radroots_protocol::chat::routes::CapturedDmRoute) -> core::result::Result<radroots_transport::target::TargetSet, radroots_storage::command::OperationError> +pub mod radroots_execution::session::tasks +pub trait radroots_execution::session::tasks::TaskHost: radroots_execution::session::HostBound +pub fn radroots_execution::session::tasks::TaskHost::submit(&self, radroots_execution::session::HostFuture<'static, ()>) -> radroots_execution::Result<()> pub enum radroots_execution::session::SessionState pub radroots_execution::session::SessionState::Closed pub radroots_execution::session::SessionState::Closing @@ -10,16 +28,20 @@ pub radroots_execution::session::SessionState::Ready pub radroots_execution::session::SessionState::Running pub radroots_execution::session::SessionState::Starting pub struct radroots_execution::session::ClientSession<H: radroots_execution::session::SessionHost> +impl<H: radroots_execution::session::SessionHost + 'static> radroots_execution::session::ClientSession<H> +pub async fn radroots_execution::session::ClientSession<H>::inquire(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, radroots_execution::workspace::CommandContext, radroots_protocol::command::InquireInput) -> radroots_execution::Result<radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>> +pub async fn radroots_execution::session::ClientSession<H>::resume_inquiry(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, &radroots_execution::workspace::WorkspaceSession, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>> impl<H: radroots_execution::session::SessionHost> radroots_execution::session::ClientSession<H> pub async fn radroots_execution::session::ClientSession<H>::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::SignerSession> pub async fn radroots_execution::session::ClientSession<H>::attach_workspace(&self, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceStore>, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_execution::Result<radroots_execution::workspace::WorkspaceSession> pub async fn radroots_execution::session::ClientSession<H>::close(&self) -> radroots_execution::Result<()> pub fn radroots_execution::session::ClientSession<H>::new(H, core::num::nonzero::NonZeroU16) -> Self +pub fn radroots_execution::session::ClientSession<H>::new_with_task_host(H, core::num::nonzero::NonZeroU16, alloc::sync::Arc<dyn radroots_execution::session::tasks::TaskHost>) -> Self pub fn radroots_execution::session::ClientSession<H>::signer_session(&self) -> core::option::Option<radroots_execution::session::SignerSession> pub async fn radroots_execution::session::ClientSession<H>::start(&self) -> radroots_execution::Result<()> pub fn radroots_execution::session::ClientSession<H>::state(&self) -> radroots_execution::session::SessionState +pub fn radroots_execution::session::ClientSession<H>::with_inquiry_runtime(self, alloc::sync::Arc<radroots_execution::session::inquiry::InquiryRuntime>) -> Self impl<H: radroots_execution::session::SessionHost> radroots_execution::session::ClientSession<H> -pub async fn radroots_execution::session::ClientSession<H>::inquire(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, radroots_execution::workspace::CommandContext, radroots_protocol::command::InquireInput) -> radroots_execution::Result<radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>> pub async fn radroots_execution::session::ClientSession<H>::operation(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, &radroots_execution::workspace::WorkspaceSession, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>) -> radroots_execution::Result<core::option::Option<radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>>> impl<H: radroots_execution::session::SessionHost> core::clone::Clone for radroots_execution::session::ClientSession<H> pub fn radroots_execution::session::ClientSession<H>::clone(&self) -> Self @@ -36,6 +58,8 @@ pub fn radroots_execution::session::Session<H>::clone(&self) -> Self pub struct radroots_execution::session::SignerSession impl radroots_execution::session::SignerSession pub async fn radroots_execution::session::SignerSession::close(&self) -> radroots_execution::Result<()> +pub async fn radroots_execution::session::SignerSession::decrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateCiphertext) -> core::result::Result<radroots_signing::provider::PrivateText, radroots_signing::provider::ProviderError> +pub async fn radroots_execution::session::SignerSession::encrypt_private(&self, radroots_signing::provider::ProviderCall, radroots_identity::key::PublicKey, radroots_signing::provider::PrivateText) -> core::result::Result<radroots_signing::provider::PrivateCiphertext, radroots_signing::provider::ProviderError> pub fn radroots_execution::session::SignerSession::identity_changed(&self) -> bool pub fn radroots_execution::session::SignerSession::new(radroots_signing::provider::SignerHandle) -> Self pub async fn radroots_execution::session::SignerSession::observe(&self) -> core::result::Result<radroots_signing::provider::ProviderState, radroots_signing::provider::ProviderError> @@ -54,6 +78,7 @@ pub trait radroots_execution::session::SessionHost: radroots_execution::session: pub fn radroots_execution::session::SessionHost::close_storage(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> pub fn radroots_execution::session::SessionHost::disconnect(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> pub fn radroots_execution::session::SessionHost::dispose_callbacks(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> +pub fn radroots_execution::session::SessionHost::drain(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> pub fn radroots_execution::session::SessionHost::quiesce(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> pub fn radroots_execution::session::SessionHost::start(&self) -> radroots_execution::session::HostFuture<'_, radroots_execution::Result<()>> pub type radroots_execution::session::HostFuture<'a, T> = core::pin::Pin<alloc::boxed::Box<(dyn core::future::future::Future<Output = T> + core::marker::Send + 'a)>> @@ -230,6 +255,7 @@ pub const fn radroots_execution::Error::code(self) -> radroots_execution::Code pub const fn radroots_execution::Error::context(self) -> radroots_execution::OperationContext pub const fn radroots_execution::Error::detail(self) -> core::option::Option<radroots_execution::Detail> pub const fn radroots_execution::Error::new(radroots_execution::Code, radroots_execution::OperationContext, radroots_execution::RetryClass, core::option::Option<radroots_execution::Detail>) -> core::result::Result<Self, radroots_execution::InvalidErrorContext> +pub const fn radroots_execution::Error::operation(radroots_storage::command::OperationError, radroots_execution::OperationContext) -> Self pub const fn radroots_execution::Error::retry(self) -> radroots_execution::RetryClass impl core::error::Error for radroots_execution::Error impl core::fmt::Display for radroots_execution::Error diff --git a/contracts/api_baselines/radroots_nostr.txt b/contracts/api_baselines/radroots_nostr.txt @@ -284,6 +284,7 @@ pub fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::signed_json(&self) - pub fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::with_wrapping_key<T>(&self, impl core::ops::function::FnOnce(&[u8; 32]) -> T) -> T impl core::fmt::Debug for radroots_nostr::signing::gift_wrap::PendingGiftWrap pub fn radroots_nostr::signing::gift_wrap::PendingGiftWrap::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub fn radroots_nostr::signing::gift_wrap::randomized_past_time(core::num::nonzero::NonZeroU64, &dyn radroots_signing::provider::NonceSource) -> core::result::Result<core::num::nonzero::NonZeroU64, radroots_nostr::signing::gift_wrap::WrapError> pub fn radroots_nostr::signing::gift_wrap::wrap_retained_seal(&str, radroots_identity::key::PublicKey, core::num::nonzero::NonZeroU64, &dyn radroots_signing::provider::NonceSource) -> core::result::Result<radroots_nostr::signing::gift_wrap::PendingGiftWrap, radroots_nostr::signing::gift_wrap::WrapError> pub struct radroots_nostr::signing::LocalSigner impl radroots_nostr::signing::LocalSigner diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -1072,6 +1072,17 @@ pub fn radroots_storage::command::SealEvidence::verify(&radroots_storage::comman pub const fn radroots_storage::command::SealEvidence::workspace_id(&self) -> radroots_domain::identifier::WorkspaceId impl core::fmt::Debug for radroots_storage::command::SealEvidence pub fn radroots_storage::command::SealEvidence::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::command::SignedDmRelaySource +impl radroots_storage::command::SignedDmRelaySource +pub const fn radroots_storage::command::SignedDmRelaySource::created_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage::command::SignedDmRelaySource::event_id(&self) -> radroots_domain::identifier::EnvelopeEventId +pub const fn radroots_storage::command::SignedDmRelaySource::participant(&self) -> radroots_identity::key::PublicKey +pub fn radroots_storage::command::SignedDmRelaySource::raw_json(&self) -> &str +pub fn radroots_storage::command::SignedDmRelaySource::relay_uris(&self) -> impl core::iter::traits::iterator::Iterator<Item = &str> +pub fn radroots_storage::command::SignedDmRelaySource::validate_capture(&self, &radroots_protocol::chat::routes::CapturedDmRoute) -> core::result::Result<(), radroots_storage::command::OperationError> +pub fn radroots_storage::command::SignedDmRelaySource::verify(&str) -> core::result::Result<Self, radroots_storage::command::OperationError> +impl core::fmt::Debug for radroots_storage::command::SignedDmRelaySource +pub fn radroots_storage::command::SignedDmRelaySource::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::command::SigningAttempt impl radroots_storage::command::SigningAttempt pub const fn radroots_storage::command::SigningAttempt::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId @@ -1098,6 +1109,7 @@ pub fn radroots_storage::command::OperationJournal::obtained_evidence(&self, rad pub fn radroots_storage::command::OperationJournal::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::operation_snapshot(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::OperationSnapshot>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::prepare_delivery_attempt<'a>(&'a self, radroots_storage::command::DeliveryAttemptRequest, radroots_storage::workspace::AttachmentProof, core::option::Option<&'a radroots_storage::command::EnvelopeCandidate>) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::DeliveryAttemptOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::command::OperationJournal::reconcile_unknown<'a>(&'a self, radroots_storage::workspace::AttachmentInput, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::SealEvidence) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::EvidenceCaptureOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::record_delivery_observation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::AttachmentProof, radroots_storage::command::DeliveryObservation) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::DeliveryObservationOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::signing_attempt(&self, radroots_storage::command::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::SigningAttempt>, radroots_storage::command::OperationError>> pub fn radroots_storage::command::OperationJournal::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>> diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -391,6 +391,7 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::obtained_evidence(&s pub fn radroots_storage_sqlite::workspace::NativeWorkspace::operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::PreparedOperation>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::operation_snapshot(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::snapshot::OperationSnapshot>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::prepare_delivery_attempt<'a>(&'a self, radroots_storage::command::delivery::DeliveryAttemptRequest, radroots_storage::workspace::AttachmentProof, core::option::Option<&'a radroots_storage::command::delivery::EnvelopeCandidate>) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::delivery::DeliveryAttemptOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::reconcile_unknown<'a>(&'a self, radroots_storage::workspace::AttachmentInput, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::issuance::SealEvidence) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::command::issuance::EvidenceCaptureOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::record_delivery_observation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::AttachmentProof, radroots_storage::command::observation::DeliveryObservation) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::command::observation::DeliveryObservationOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::issuance::SigningAttempt>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>> diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml @@ -17,7 +17,7 @@ default = [] session = ["dep:futures"] signer_session = ["session", "dep:radroots_signing"] client_session = ["signer_session"] -workspace_session = ["client_session", "receipts", "radroots_protocol/commands"] +workspace_session = ["client_session", "receipts", "radroots_protocol/commands", "radroots_signing/chat", "dep:radroots_transport"] receipts = ["dep:radroots_storage", "radroots_storage/command_journal"] [dependencies] @@ -26,6 +26,7 @@ radroots_protocol = { workspace = true, default-features = false, features = ["i futures = { workspace = true, optional = true } radroots_signing = { workspace = true, default-features = false, optional = true } radroots_storage = { workspace = true, default-features = false, optional = true } +radroots_transport = { workspace = true, default-features = false, optional = true } [dev-dependencies] radroots_transport = { workspace = true } diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs @@ -209,7 +209,9 @@ impl Error { } #[cfg(feature = "workspace_session")] - pub(crate) const fn operation( + /// Projects a typed journal refusal with its observed admission context. + /// This data conversion performs no transaction or authorization check. + pub const fn operation( error: radroots_storage::command::OperationError, context: OperationContext, ) -> Self { diff --git a/crates/execution/src/session/client.rs b/crates/execution/src/session/client.rs @@ -63,6 +63,9 @@ impl<H: SessionHost> SessionHost for Resources<H> { fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> { self.host.disconnect() } + fn drain(&self) -> HostFuture<'_, crate::Result<()>> { + self.host.drain() + } fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> { Box::pin(async move { let signer = signer_lock(&self.signer).clone(); @@ -86,6 +89,12 @@ pub struct ClientSession<H: SessionHost> { signer: Shared<Mutex<Option<SignerSession>>>, #[cfg(feature = "workspace_session")] workspaces: WorkspaceScopes, + #[cfg(feature = "workspace_session")] + pub(crate) task_host: Option<Shared<dyn super::tasks::TaskHost>>, + #[cfg(feature = "workspace_session")] + pub(crate) task_budget: super::tasks::TaskBudget, + #[cfg(feature = "workspace_session")] + pub(crate) inquiry: Option<Shared<super::inquiry::InquiryRuntime>>, } impl<H: SessionHost> Clone for ClientSession<H> { fn clone(&self) -> Self { @@ -94,6 +103,12 @@ impl<H: SessionHost> Clone for ClientSession<H> { signer: self.signer.clone(), #[cfg(feature = "workspace_session")] workspaces: self.workspaces.clone(), + #[cfg(feature = "workspace_session")] + task_host: self.task_host.clone(), + #[cfg(feature = "workspace_session")] + task_budget: self.task_budget.clone(), + #[cfg(feature = "workspace_session")] + inquiry: self.inquiry.clone(), } } } @@ -117,8 +132,35 @@ impl<H: SessionHost> ClientSession<H> { signer, #[cfg(feature = "workspace_session")] workspaces, + #[cfg(feature = "workspace_session")] + task_host: None, + #[cfg(feature = "workspace_session")] + task_budget: super::tasks::TaskBudget::new(), + #[cfg(feature = "workspace_session")] + inquiry: None, } } + /// Pairs an explicit target task host with its owning lifecycle host. The + /// lifecycle must drain accepted tasks and retain failed captures through + /// recovery before allowing storage disposal. This is a host trust boundary; + /// supplying an implementation is not execution qualification. + #[cfg(feature = "workspace_session")] + pub fn new_with_task_host( + host: H, + maximum_in_flight: NonZeroU16, + task_host: Shared<dyn super::tasks::TaskHost>, + ) -> Self { + let mut client = Self::new(host, maximum_in_flight); + client.task_host = Some(task_host); + client + } + /// Pairs the workflow's obtained-material owner with the lifecycle host + /// which must drain that same owner before closing resources. + #[cfg(feature = "workspace_session")] + pub fn with_inquiry_runtime(mut self, runtime: Shared<super::inquiry::InquiryRuntime>) -> Self { + self.inquiry = Some(runtime); + self + } /// Reports resource lifecycle independently of business authority. pub fn state(&self) -> SessionState { self.session.state() diff --git a/crates/execution/src/session/client_commands.rs b/crates/execution/src/session/client_commands.rs @@ -1,15 +1,113 @@ use super::{ClientSession, SessionHost, Shared}; +use crate::session::{HostBound, inquiry::InquiryRuntime}; use crate::{ Error, OperationContext, OperationReceipt, workspace::{CommandContext, WorkspaceSession}, }; +use alloc::boxed::Box; use radroots_domain::{ChatMessage, CommandDigest, OperationId}; use radroots_protocol::command::{CapturedChatCommand, InquireInput}; use radroots_storage::command::{ AdmissionOutcome, AdmissionRequest, OperationError, OperationJournal, }; -impl<H: SessionHost> ClientSession<H> { +impl<H: SessionHost + 'static> ClientSession<H> { + /// Explicitly resumes an original inquiry under current attached access. + /// Original claims are never signed again; delivery retries preserve exact + /// retained outer bytes and the first publication criterion, selecting only + /// targets without recorded acceptance. No first-issue deadline is renewed. + pub async fn resume_inquiry( + &self, + journal: Shared<dyn OperationJournal>, + scope: &WorkspaceSession, + operation: OperationId, + expected: Option<CommandDigest>, + ) -> crate::Result<OperationReceipt<ChatMessage>> { + let proposed = OperationContext::proposed(Some(operation)); + let permit = self + .session + .admit() + .map_err(|error| error.with_context(proposed))?; + let budget = self + .task_budget + .reserve() + .map_err(|error| error.with_context(proposed))?; + { + let scopes = self + .workspaces + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if !scopes.iter().any(|owned| owned.same_scope(scope)) { + return Err(Error::operation(OperationError::Unauthorized, proposed)); + } + } + let (binding, proof) = scope + .captured_input() + .map_err(|error| Error::operation(error.into(), proposed))?; + let runtime = self + .inquiry + .clone() + .ok_or_else(|| Error::operation(OperationError::Unauthorized, proposed))?; + let host = self + .task_host + .as_ref() + .ok_or_else(|| Error::operation(OperationError::Unauthorized, proposed))?; + let signer = self.signer_session(); + let lease: Shared<dyn HostBound> = Shared::new((permit, budget)); + let (reply, observed) = futures::channel::oneshot::channel(); + host.submit(Box::pin(async move { + let result = async { + runtime + .drain() + .await + .map_err(|error| Error::operation(error, proposed))?; + let prepared = journal + .operation( + binding.clone(), + operation, + expected, + proof + .with_secret(|secret| { + radroots_storage::workspace::AttachmentProof::from_protected_input( + secret, + ) + }) + .map_err(|error| Error::operation(error.into(), proposed))?, + ) + .await + .map_err(|error| Error::operation(error, proposed))? + .ok_or_else(|| Error::operation(OperationError::MissingHistory, proposed))?; + let retained = OperationContext::retained(operation); + let digest = prepared.identity().command_digest(); + runtime + .run( + journal.clone(), + prepared, + &proof, + signer, + lease, + crate::session::inquiry::RunMode::Resume, + ) + .await + .map_err(|error| Error::operation(error, retained))?; + let snapshot = journal + .operation_snapshot(binding, operation, Some(digest), proof) + .await + .map_err(|error| Error::operation(error, retained))? + .ok_or_else(|| Error::operation(OperationError::RecoveryRequired, retained))?; + Ok::<_, Error>(OperationReceipt::from_snapshot(&snapshot)) + } + .await; + let _ = reply.send(result); + })) + .map_err(|error| error.with_context(proposed))?; + observed.await.unwrap_or_else(|_| { + Err(Error::operation( + OperationError::RecoveryRequired, + OperationContext::admission_unknown(operation), + )) + }) + } /// Captures and durably admits one inquiry through the configured journal. /// The concrete bounded worker owns accepted T0 work after observer loss. /// A pending receipt does not claim signing, installation or publication. @@ -22,10 +120,19 @@ impl<H: SessionHost> ClientSession<H> { ) -> crate::Result<OperationReceipt<ChatMessage>> { let operation = context.data().operation_id(); let proposed = OperationContext::proposed(Some(operation)); - let _permit = self + let permit = self .session .admit() .map_err(|error| error.with_context(proposed))?; + let budget = if self.task_host.is_some() || self.inquiry.is_some() { + Some( + self.task_budget + .reserve() + .map_err(|error| error.with_context(proposed))?, + ) + } else { + None + }; { let scopes = self .workspaces @@ -40,34 +147,29 @@ impl<H: SessionHost> ClientSession<H> { .map_err(|error| Error::operation(error.into(), proposed))?; let command = CapturedChatCommand::inquire(context.data().clone(), input) .map_err(|_| Error::operation(OperationError::InvalidCommand, proposed))?; - let digest = command.digest(); - let request = AdmissionRequest::new(binding.clone(), command) - .map_err(|error| Error::operation(error, proposed))?; - // The actual admission checks the original identity before fresh - // deadline/planning; context.revalidate would reject retained replays. - let query_proof = proof - .with_secret(|secret| { - radroots_storage::workspace::AttachmentProof::from_protected_input(secret) - }) - .map_err(|error| Error::operation(error.into(), proposed))?; - let result = journal - .admit_command_and_hold(request, proof) - .await + let request = AdmissionRequest::new(binding, command) .map_err(|error| Error::operation(error, proposed))?; - match result { - AdmissionOutcome::Unknown(_) => Err(Error::admission_uncertain(operation)), - AdmissionOutcome::Committed(_) => { - let retained = OperationContext::retained(operation); - let snapshot = journal - .operation_snapshot(binding, operation, Some(digest), query_proof) - .await - .map_err(|error| Error::operation(error, retained))? - .ok_or_else(|| Error::operation(OperationError::RecoveryRequired, retained))?; - Ok(OperationReceipt::from_snapshot(&snapshot)) - } + let runtime = self.inquiry.clone(); + let signer = self.signer_session(); + let lease: Shared<dyn HostBound> = Shared::new((permit, budget)); + if let Some(host) = &self.task_host { + let (reply, observed) = futures::channel::oneshot::channel(); + let task = Box::pin(async move { + let result = execute_inquiry(journal, request, proof, runtime, signer, lease).await; + let _ = reply.send(result); + }); + host.submit(task) + .map_err(|error| error.with_context(proposed))?; + observed + .await + .unwrap_or_else(|_| Err(Error::admission_uncertain(operation))) + } else { + execute_inquiry(journal, request, proof, runtime, signer, lease).await } } +} +impl<H: SessionHost> ClientSession<H> { /// Reads the original complete operation through a scope attached to this /// client. Query time never renews the original first-issue deadline and /// absence never proves an uncertain invocation was safely unissued. @@ -102,3 +204,53 @@ impl<H: SessionHost> ClientSession<H> { .map_err(|error| Error::operation(error, proposed)) } } + +async fn execute_inquiry( + journal: Shared<dyn OperationJournal>, + request: AdmissionRequest, + proof: radroots_storage::workspace::AttachmentProof, + runtime: Option<Shared<InquiryRuntime>>, + signer: Option<super::SignerSession>, + lease: Shared<dyn HostBound>, +) -> crate::Result<OperationReceipt<ChatMessage>> { + let operation = request.command().context().operation_id(); + let proposed = OperationContext::proposed(Some(operation)); + let binding = request.binding().clone(); + let digest = request.command().digest(); + // Original lookup precedes fresh deadline/planning. Authentication of the + // actual transaction remains native; a captured descriptor grants nothing. + let query_proof = proof + .with_secret(|secret| { + radroots_storage::workspace::AttachmentProof::from_protected_input(secret) + }) + .map_err(|error| Error::operation(error.into(), proposed))?; + let result = journal + .admit_command_and_hold(request, proof) + .await + .map_err(|error| Error::operation(error, proposed))?; + match result { + AdmissionOutcome::Unknown(_) => Err(Error::admission_uncertain(operation)), + AdmissionOutcome::Committed(prepared) => { + let retained = OperationContext::retained(operation); + if let Some(runtime) = runtime { + runtime + .run( + journal.clone(), + prepared, + &query_proof, + signer, + lease, + crate::session::inquiry::RunMode::Command, + ) + .await + .map_err(|error| Error::operation(error, retained))?; + } + let snapshot = journal + .operation_snapshot(binding, operation, Some(digest), query_proof) + .await + .map_err(|error| Error::operation(error, retained))? + .ok_or_else(|| Error::operation(OperationError::RecoveryRequired, retained))?; + Ok(OperationReceipt::from_snapshot(&snapshot)) + } + } +} diff --git a/crates/execution/src/session/host.rs b/crates/execution/src/session/host.rs @@ -42,6 +42,14 @@ pub trait SessionHost: HostBound { /// Existing permitted work must remain able to reach its safe boundary. fn quiesce(&self) -> HostFuture<'_, crate::Result<()>>; + /// Drains the host's owned jobs after dispatch has been quiesced. A failed + /// protected capture must keep its original material and resource permits; + /// return recovery rather than claiming successful disposal. Repeated calls + /// resume the same retained work. Hosts without an owned job set do nothing. + fn drain(&self) -> HostFuture<'_, crate::Result<()>> { + Box::pin(async { Ok(()) }) + } + /// Disconnects every owned transport and its authentication state. fn disconnect(&self) -> HostFuture<'_, crate::Result<()>>; diff --git a/crates/execution/src/session/inquiry.rs b/crates/execution/src/session/inquiry.rs @@ -0,0 +1,588 @@ +//! Owned ordinary inquiry execution over explicit host IO and protected storage. +use super::{HostBound, HostFuture, Shared, SignerSession}; +use alloc::{string::String, vec::Vec}; +use core::num::NonZeroU64; +use radroots_domain::{PublicKey, UnixSeconds}; +use radroots_protocol::chat::{CapturedDmRoute, ChatReplay, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_signing::{ + issuance::{OutcomeKind, SigningIntent}, + provider::{PrivateCiphertext, PrivateText, ProviderCall}, + request::CancellationSignal, +}; +use radroots_storage::{ + command::{ + BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, DeliveryAttemptOutcome, + DeliveryAttemptRequest, DeliveryIntent, DeliveryObservation, EnvelopeCandidate, + EvidenceCaptureOutcome, InstallationRequest, OperationError, OperationJournal, + PlanBindingOutcome, PreparedOperation, PublicationWork, SealEvidence, + }, + workspace::{AttachmentProof, WorkspaceBinding}, +}; +use radroots_transport::{DeliveryReceipt, SinkFailure, TargetSet}; +use std::sync::Mutex; + +/// Target IO, not command authority. Construction/start/query must not perform +/// network work or replay an outbox. Implementations must enforce their explicit +/// destination policy and bound every actual request. +pub trait InquiryIo: HostBound { + /// Whether explicit online startup permits this workflow's network work. + fn enabled(&self) -> bool; + /// Current positive supported time; never renews a first-issue window. + fn now(&self) -> Result<UnixSeconds, OperationError>; + /// CSPRNG-backed NIP-59 past time within the supported two-day interval. + fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError>; + /// Authenticates a bounded current kind-10050 head and captures only its + /// explicitly approved write endpoints, preserving original signed bytes. + fn route( + &self, + recipient: PublicKey, + deadline: NonZeroU64, + ) -> HostFuture<'_, Result<CapturedDmRoute, OperationError>>; + /// Resolves only the original captured route against current write policy. + fn targets(&self, route: &CapturedDmRoute) -> Result<TargetSet, OperationError>; + /// Explicit relay acceptance criterion, frozen by the first retained D. + fn publication_policy(&self) -> radroots_transport::policy::SatisfactionPolicy; + /// Wraps the original obtained seal with a fresh temporary envelope key. + fn envelope( + &self, + work: PublicationWork, + raw_seal: &str, + ) -> Result<EnvelopeCandidate, OperationError>; + /// Fresh full-width transport-attempt identity from qualified entropy. + fn delivery_id(&self) -> Result<String, OperationError>; + /// Dispatches only an actual freshly committed original delivery claim. + fn publish( + &self, + request: radroots_transport::sink::DeliveryRequest, + selected: TargetSet, + ) -> HostFuture<'_, Result<DeliveryReceipt, SinkFailure>>; +} + +struct PendingCapture { + journal: Shared<dyn OperationJournal>, + binding: WorkspaceBinding, + proof: AttachmentProof, + evidence: SealEvidence, + // Keeps both the resource permit and conservative live-byte reservation. + _lease: Shared<dyn HostBound>, +} +struct PendingObservation { + journal: Shared<dyn OperationJournal>, + binding: WorkspaceBinding, + proof: AttachmentProof, + observation: DeliveryObservation, + _lease: Shared<dyn HostBound>, +} + +/// Shared workflow and obtained-material owner. Its lifecycle host must call +/// `drain` before releasing work permits, callbacks or protected storage. +pub struct InquiryRuntime { + io: Shared<dyn InquiryIo>, + pending: Mutex<Vec<Shared<PendingCapture>>>, + observations: Mutex<Vec<Shared<PendingObservation>>>, + draining: futures::lock::Mutex<()>, +} +pub(super) enum RunMode { + Command, + Resume, +} +impl InquiryRuntime { + /// Owns explicit IO without performing effects or starting a runtime. + pub fn new(io: Shared<dyn InquiryIo>) -> Self { + Self { + io, + pending: Mutex::new(Vec::new()), + observations: Mutex::new(Vec::new()), + draining: futures::lock::Mutex::new(()), + } + } + /// Retries only already obtained original evidence. Failure retains its + /// exact bytes and resource ownership, including when this wait is dropped. + pub async fn drain(&self) -> Result<(), OperationError> { + let _serial = self.draining.lock().await; + loop { + let next = self + .pending + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .first() + .cloned(); + let Some(next) = next else { + break; + }; + match next + .journal + .reconcile_unknown(next.binding.input().clone(), &next.proof, &next.evidence) + .await + .map_err(|_| OperationError::RecoveryRequired)? + { + EvidenceCaptureOutcome::Committed(_) => self.remove(&next), + EvidenceCaptureOutcome::Unknown(_) => return Err(OperationError::RecoveryRequired), + } + } + loop { + let next = self + .observations + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .first() + .cloned(); + let Some(next) = next else { + return Ok(()); + }; + self.capture_observation(&next) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + } + } + async fn capture_observation( + &self, + entry: &Shared<PendingObservation>, + ) -> Result<(), OperationError> { + match entry + .journal + .record_delivery_observation( + entry.binding.clone(), + copy(&entry.proof)?, + entry.observation.clone(), + ) + .await? + { + radroots_storage::command::DeliveryObservationOutcome::Committed(_) => { + let removed = { + let mut pending = self + .observations + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + pending + .iter() + .position(|value| Shared::ptr_eq(value, entry)) + .map(|index| pending.remove(index)) + }; + drop(removed); + Ok(()) + } + radroots_storage::command::DeliveryObservationOutcome::Unknown(_) => { + Err(OperationError::RecoveryRequired) + } + } + } + fn remove(&self, entry: &Shared<PendingCapture>) { + let removed = { + let mut pending = self + .pending + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + pending + .iter() + .position(|value| Shared::ptr_eq(value, entry)) + .map(|index| pending.remove(index)) + }; + drop(removed); + } + pub(super) async fn run( + &self, + journal: Shared<dyn OperationJournal>, + prepared: PreparedOperation, + proof: &AttachmentProof, + signer: Option<SignerSession>, + lease: Shared<dyn HostBound>, + mode: RunMode, + ) -> Result<(), OperationError> { + if !self.io.enabled() { + return Ok(()); + } + self.drain().await?; + let binding = prepared.request().binding().clone(); + let operation = prepared.identity().operation_id(); + let digest = prepared.identity().command_digest(); + let original = journal + .signing_plan(binding.clone(), operation, digest, copy(proof)?) + .await?; + let bound = match original { + Some(bound) => bound, + None => { + let signer = signer.as_ref().ok_or(OperationError::Unauthorized)?; + let plan = self.plan(&prepared, signer).await?; + match journal + .bind_signing_intents(binding.clone(), plan, copy(proof)?) + .await? + { + PlanBindingOutcome::Committed(bound) => bound, + PlanBindingOutcome::Unknown(_) => return Err(OperationError::RecoveryRequired), + } + } + }; + self.issue( + journal.clone(), + &bound, + proof, + signer.as_ref(), + lease.clone(), + ) + .await?; + let snapshot = journal + .operation_snapshot(binding.clone(), operation, Some(digest), copy(proof)?) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if snapshot + .recipients() + .iter() + .any(|recipient| recipient.obtained().is_some()) + { + journal + .install_transition_and_outbox( + InstallationRequest::new( + binding.clone(), + operation, + digest, + *bound.plan().digest(), + ), + copy(proof)?, + ) + .await?; + } + self.deliver(journal, &bound, proof, lease, mode).await + } + async fn plan( + &self, + prepared: &PreparedOperation, + signer: &SignerSession, + ) -> Result<ChatSigningPlan, OperationError> { + let now = self.io.now()?; + let deadline = NonZeroU64::new( + prepared + .issuance_window() + .first_issue_not_after() + .get() + .checked_mul(1000) + .ok_or(OperationError::RecoveryRequired)?, + ) + .ok_or(OperationError::RecoveryRequired)?; + if now >= prepared.issuance_window().first_issue_not_after() { + return Err(OperationError::DeadlineExceeded); + } + let command = prepared.request().command(); + let observed = signer + .observe() + .await + .map_err(|_| OperationError::Unauthorized)?; + if observed.identity() != command.context().actor().participant() + || observed.encryption() != radroots_signing::provider::PrivateCryptoCapability::Nip44V2 + || observed.decryption() != radroots_signing::provider::PrivateCryptoCapability::Nip44V2 + { + return Err(OperationError::Unauthorized); + } + let replay = match observed + .exact_issuance() + .ok_or(OperationError::Unauthorized)? + { + radroots_signing::recovery::ReplayCapability::NonReplayable => { + ChatReplay::NonReplayable + } + radroots_signing::recovery::ReplayCapability::LocalReplaySafe => { + ChatReplay::LocalReplaySafe + } + radroots_signing::recovery::ReplayCapability::ExactReplayByRequestId => { + ChatReplay::ExactReplayByRequestId + } + _ => return Err(OperationError::Unauthorized), + }; + let rumor = + ChatRumor::from_command(command, now).map_err(|_| OperationError::InvalidCommand)?; + let mut routes = Vec::new(); + // Resolve every original route before provider encryption or T1. + for recipient in rumor.recipients() { + routes.push(self.io.route(*recipient, deadline).await?); + } + let mut seals = Vec::new(); + for recipient in rumor.recipients() { + let call = || ProviderCall::new(rumor.author(), deadline, CancellationSignal::new()); + let text = + PrivateText::new(rumor.json()).map_err(|_| OperationError::InvalidCommand)?; + let encrypted = signer + .encrypt_private(call(), *recipient, text) + .await + .map_err(|_| OperationError::Unauthorized)?; + let check = PrivateCiphertext::parse(encrypted.as_str()) + .map_err(|_| OperationError::InvalidEvidence)?; + let decrypted = signer + .decrypt_private(call(), *recipient, check) + .await + .map_err(|_| OperationError::InvalidEvidence)?; + if decrypted.expose() != rumor.json() { + return Err(OperationError::InvalidEvidence); + } + seals.push( + ChatSeal::new( + &rumor, + *recipient, + self.io.seal_time(now)?, + encrypted.as_str(), + ) + .map_err(|_| OperationError::InvalidCommand)?, + ); + } + ChatSigningPlan::new(command, now, seals, routes, replay) + .map_err(|_| OperationError::InvalidCommand) + } + async fn issue( + &self, + journal: Shared<dyn OperationJournal>, + bound: &BoundSigningPlan, + proof: &AttachmentProof, + signer: Option<&SignerSession>, + lease: Shared<dyn HostBound>, + ) -> Result<(), OperationError> { + let prepared = bound.prepared(); + let binding = prepared.request().binding(); + for seal in bound.plan().seals() { + let select = || { + ClaimAttemptRequest::new( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + *bound.plan().digest(), + seal.recipient(), + ) + }; + if journal + .signing_attempt(select(), copy(proof)?) + .await? + .is_some() + { + continue; + } + let Some(signer) = signer else { + continue; + }; + if signer.state() != super::SessionState::Running + || !self + .io + .now() + .is_ok_and(|now| now < prepared.issuance_window().first_issue_not_after()) + { + continue; + } + let attempt = match journal.claim_attempt(select(), copy(proof)?).await { + Err(OperationError::DeadlineExceeded) => continue, + Err(error) => return Err(error), + Ok(outcome) => match outcome { + ClaimAttemptOutcome::Claimed(attempt) => attempt, + ClaimAttemptOutcome::Retained(_) | ClaimAttemptOutcome::Unknown(_) => continue, + }, + }; + let intent = SigningIntent::from_chat_seal( + prepared.identity().operation_id(), + prepared.identity().command_digest(), + attempt.seal(), + ProviderCall::new( + attempt.seal().fields().author, + attempt.deadline_unix_ms(), + CancellationSignal::new(), + ), + ) + .map_err(|_| OperationError::InvalidCommand)?; + if intent.binding() != attempt.binding() { + return Err(OperationError::RecoveryRequired); + } + let outcome = signer.sign_exact(intent).await; + let (_, kind) = outcome.into_parts(); + if let OutcomeKind::Obtained(artifact) = kind { + let evidence = artifact.with_json(|raw| { + SealEvidence::verify(&attempt, raw, artifact.observed_at_unix_ms()) + })?; + let entry = Shared::new(PendingCapture { + journal: journal.clone(), + binding: binding.clone(), + proof: copy(proof)?, + evidence, + _lease: lease.clone(), + }); + self.pending + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(entry.clone()); + match journal + .capture_evidence(binding.input().clone(), &entry.proof, &entry.evidence) + .await + .map_err(|_| OperationError::RecoveryRequired)? + { + EvidenceCaptureOutcome::Committed(_) => self.remove(&entry), + EvidenceCaptureOutcome::Unknown(_) => { + return Err(OperationError::RecoveryRequired); + } + } + } + } + Ok(()) + } + async fn deliver( + &self, + journal: Shared<dyn OperationJournal>, + bound: &BoundSigningPlan, + proof: &AttachmentProof, + lease: Shared<dyn HostBound>, + mode: RunMode, + ) -> Result<(), OperationError> { + let prepared = bound.prepared(); + let binding = prepared.request().binding(); + let snapshot = journal + .operation_snapshot( + binding.clone(), + prepared.identity().operation_id(), + Some(prepared.identity().command_digest()), + copy(proof)?, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + for work in snapshot.publications() { + if snapshot.publication_accepted(*work)? { + continue; + } + // Replaying a command never dispatches a previously claimed attempt. + let original = snapshot + .delivery_attempts() + .iter() + .find(|attempt| attempt.work() == *work); + if original.is_some() && matches!(mode, RunMode::Command) { + continue; + } + let recipient = work.evidence().recipient(); + let route = bound + .plan() + .routes() + .iter() + .find(|route| route.participant() == recipient) + .ok_or(OperationError::RecoveryRequired)?; + let targets = self.io.targets(route)?; + let captured = journal + .obtained_evidence( + ClaimAttemptRequest::new( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + *bound.plan().digest(), + recipient, + ), + copy(proof)?, + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let envelope = match original { + Some(_) => None, + None => Some(self.io.envelope(*work, captured.evidence().raw_json())?), + }; + let deadline = NonZeroU64::new( + self.io + .now()? + .get() + .checked_add(30) + .and_then(|time| time.checked_mul(1000)) + .ok_or(OperationError::RecoveryRequired)?, + ) + .ok_or(OperationError::RecoveryRequired)?; + let (event, targets, policy) = match original { + Some(original) => ( + original.intent().event_id(), + original.intent().targets().clone(), + original.intent().policy().clone(), + ), + None => ( + envelope + .as_ref() + .ok_or(OperationError::RecoveryRequired)? + .event_id(), + targets, + self.io.publication_policy(), + ), + }; + let selected = targets + .targets() + .iter() + .filter(|target| { + !snapshot.delivery_observations().iter().any(|observation| { + observation.work() == *work + && observation.target_receipt().target().fingerprint() + == target.fingerprint() + && observation.kind() + == radroots_storage::command::DeliveryObservationKind::Accepted + }) + }) + .cloned() + .collect::<Vec<_>>(); + if selected.is_empty() { + continue; + } + let selected = + TargetSet::new(selected).map_err(|_| OperationError::RecoveryRequired)?; + let intent = + DeliveryIntent::new(&self.io.delivery_id()?, event, &targets, &policy, deadline)? + .with_selection(&selected)?; + let request = DeliveryAttemptRequest::new(binding.clone(), *work, intent)?; + let attempt = match journal + .prepare_delivery_attempt(request, copy(proof)?, envelope.as_ref()) + .await? + { + DeliveryAttemptOutcome::Claimed(attempt) => attempt, + DeliveryAttemptOutcome::Retained(_) | DeliveryAttemptOutcome::Unknown { .. } => { + continue; + } + }; + let result = self + .io + .publish( + attempt.transport_request()?, + attempt.intent().selected_target_set()?, + ) + .await; + let observed = self + .io + .now() + .ok() + .and_then(|time| time.get().checked_mul(1000)) + .and_then(NonZeroU64::new); + let reports = match &result { + Ok(receipt) => receipt.target_receipts(), + Err(failure) => failure.partial_evidence(), + }; + let mut entries = Vec::new(); + for report in reports { + let observation = match &result { + Ok(receipt) => DeliveryObservation::from_receipt( + &attempt, + receipt, + report.target().fingerprint(), + observed, + ), + Err(failure) => DeliveryObservation::from_failure( + &attempt, + failure, + report.target().fingerprint(), + observed, + ), + }?; + entries.push(Shared::new(PendingObservation { + journal: journal.clone(), + binding: binding.clone(), + proof: copy(proof)?, + observation, + _lease: lease.clone(), + })); + } + self.observations + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .extend(entries.iter().cloned()); + for entry in entries { + self.capture_observation(&entry).await?; + } + } + Ok(()) + } +} +fn copy(proof: &AttachmentProof) -> Result<AttachmentProof, OperationError> { + proof + .with_secret(|secret| AttachmentProof::from_protected_input(secret)) + .map_err(Into::into) +} diff --git a/crates/execution/src/session/mod.rs b/crates/execution/src/session/mod.rs @@ -5,6 +5,10 @@ //! A permit is resource ownership, never proof of durable command admission. pub(crate) mod host; +pub mod tasks; + +#[cfg(feature = "workspace_session")] +pub mod inquiry; #[cfg(feature = "client_session")] mod client; @@ -49,6 +53,7 @@ pub enum SessionState { #[derive(Clone, Copy)] enum CloseStage { Quiesce, + DrainOwned, Drain, Disconnect, Callbacks, @@ -220,7 +225,7 @@ impl<H: SessionHost> Session<H> { let mut stage = self.inner.control.lock().await; if matches!(*stage, CloseStage::Quiesce) { self.inner.host.quiesce().await?; - *stage = CloseStage::Drain; + *stage = CloseStage::DrainOwned; } Ok(()) } @@ -238,6 +243,10 @@ impl<H: SessionHost> Session<H> { *stage = match *stage { CloseStage::Quiesce => { self.inner.host.quiesce().await?; + CloseStage::DrainOwned + } + CloseStage::DrainOwned => { + self.inner.host.drain().await?; CloseStage::Drain } CloseStage::Drain => { diff --git a/crates/execution/src/session/signer.rs b/crates/execution/src/session/signer.rs @@ -1,6 +1,7 @@ use core::num::NonZeroU16; use radroots_signing::provider::{ - ParticipantProvider, ProviderError, ProviderState, SignerCallbacks, SignerHandle, + ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText, ProviderCall, + ProviderError, ProviderState, SignerCallbacks, SignerHandle, }; use std::{ boxed::Box, @@ -122,6 +123,70 @@ impl Clone for SignerSession { } impl SignerSession { + async fn private_provider( + &self, + call: &ProviderCall, + encrypt: bool, + ) -> Result<Binding, ProviderError> { + if self.state() != SessionState::Running || self.observed().is_none() { + return Err(ProviderError::CapabilityUnavailable); + } + let observed = self.observe().await?; + if observed.identity() != call.identity() { + return Err(ProviderError::IdentityChanged); + } + let capability = if encrypt { + observed.encryption() + } else { + observed.decryption() + }; + if capability != PrivateCryptoCapability::Nip44V2 { + return Err(ProviderError::CapabilityUnavailable); + } + self.resources + .retain_binding() + .ok_or(ProviderError::CapabilityUnavailable) + } + + /// Encrypts only with the already attached participant's current NIP-44 v2 + /// provider. It reobserves identity/capability before dispatch and retains + /// the callback scope through the call. No signing or persistence occurs. + pub async fn encrypt_private( + &self, + call: ProviderCall, + recipient: radroots_domain::PublicKey, + plaintext: PrivateText, + ) -> Result<PrivateCiphertext, ProviderError> { + let provider = self.private_provider(&call, true).await?; + let _permit = self + .session + .admit() + .map_err(|_| ProviderError::CapabilityUnavailable)?; + provider + .provider + .encrypt_private(call, recipient, plaintext) + .await + } + + /// Decrypts through the current attached NIP-44 v2 provider. The composing + /// executor must first authenticate the carrier and bind its actual author. + /// Plaintext remains zeroizing and grants no history/command authority. + pub async fn decrypt_private( + &self, + call: ProviderCall, + sender: radroots_domain::PublicKey, + ciphertext: PrivateCiphertext, + ) -> Result<PrivateText, ProviderError> { + let provider = self.private_provider(&call, false).await?; + let _permit = self + .session + .admit() + .map_err(|_| ProviderError::CapabilityUnavailable)?; + provider + .provider + .decrypt_private(call, sender, ciphertext) + .await + } /// Issues only through an already observed, live exact-intent provider. /// The executor must retain its own work permit through durable capture; /// this scoped future owns resources but supplies no admission receipt. @@ -131,9 +196,9 @@ impl SignerSession { ) -> radroots_signing::issuance::SigningOutcome { use radroots_signing::issuance::SigningOutcome; let binding = intent.binding(); - let Ok(_permit) = self.session.admit() else { + if self.state() != SessionState::Running { return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable); - }; + } if self.identity_changed() { return SigningOutcome::not_dispatched(binding, ProviderError::IdentityChanged); } @@ -146,6 +211,16 @@ impl SignerSession { if observed.exact_issuance().is_none() { return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable); } + let observed = match self.observe().await { + Ok(observed) => observed, + Err(error) => return SigningOutcome::not_dispatched(binding, error), + }; + if observed.identity() != intent.author() || observed.exact_issuance().is_none() { + return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable); + } + let Ok(_permit) = self.session.admit() else { + return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable); + }; let Some(provider) = self.resources.retain_binding() else { return SigningOutcome::not_dispatched(binding, ProviderError::CapabilityUnavailable); }; diff --git a/crates/execution/src/session/tasks.rs b/crates/execution/src/session/tasks.rs @@ -0,0 +1,50 @@ +//! Mechanical ownership of already bounded execution tasks. +use super::{HostBound, HostFuture}; + +#[cfg(feature = "workspace_session")] +use super::host::Shared; +#[cfg(feature = "workspace_session")] +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[cfg(feature = "workspace_session")] +const LIVE_MAX_BYTES: usize = 4 * 1024 * 1024; +#[cfg(feature = "workspace_session")] +const INQUIRY_RESERVATION_BYTES: usize = 2 * 1024 * 1024; + +#[cfg(feature = "workspace_session")] +#[derive(Clone)] +pub(crate) struct TaskBudget(Shared<AtomicUsize>); +#[cfg(feature = "workspace_session")] +impl TaskBudget { + pub(crate) fn new() -> Self { + Self(Shared::new(AtomicUsize::new(0))) + } + pub(crate) fn reserve(&self) -> crate::Result<TaskReservation> { + self.0 + .try_update(Ordering::AcqRel, Ordering::Acquire, |used| { + used.checked_add(INQUIRY_RESERVATION_BYTES) + .filter(|next| *next <= LIVE_MAX_BYTES) + }) + .map_err(|_| crate::Error::session_unavailable(crate::Reason::OutOfRange))?; + Ok(TaskReservation(self.0.clone())) + } +} +#[cfg(feature = "workspace_session")] +pub(crate) struct TaskReservation(Shared<AtomicUsize>); +#[cfg(feature = "workspace_session")] +impl Drop for TaskReservation { + fn drop(&mut self) { + self.0 + .fetch_sub(INQUIRY_RESERVATION_BYTES, Ordering::AcqRel); + } +} + +/// Target-host task admission. The execution owner reserves input/result budget +/// and moves its resource permit into the task before submitting it. Success +/// transfers ownership: losing the observer must not cancel the accepted task. +/// This port confers no command, signer, journal or adapter qualification. +pub trait TaskHost: HostBound { + /// Accepts an unpolled owned task. Refusal executes no part of the task. + /// Implementations must bound their accepted task set. + fn submit(&self, task: HostFuture<'static, ()>) -> crate::Result<()>; +} diff --git a/crates/execution/tests/session.rs b/crates/execution/tests/session.rs @@ -581,3 +581,91 @@ fn explicit_quiesce_stops_admission_without_draining_or_disposing_resources() { ] ); } + +struct RetainedJobsHost { + host: Host, + drains: Arc<AtomicUsize>, + retained: Arc<AtomicBool>, +} +impl SessionHost for RetainedJobsHost { + fn start(&self) -> HostFuture<'_, Result<()>> { + self.host.start() + } + fn quiesce(&self) -> HostFuture<'_, Result<()>> { + self.host.quiesce() + } + fn drain(&self) -> HostFuture<'_, Result<()>> { + Box::pin(async move { + self.drains.fetch_add(1, Ordering::SeqCst); + if self.retained.load(Ordering::SeqCst) { + return Err(Error::new( + Code::RecoveryRequired, + OperationContext::proposed(None), + RetryClass::ManualReconciliation, + None, + ) + .unwrap()); + } + Ok(()) + }) + } + fn disconnect(&self) -> HostFuture<'_, Result<()>> { + self.host.disconnect() + } + fn dispose_callbacks(&self) -> HostFuture<'_, Result<()>> { + self.host.dispose_callbacks() + } + fn close_storage(&self) -> HostFuture<'_, Result<()>> { + self.host.close_storage() + } +} +#[test] +fn owned_drain_failure_preserves_close_stage_and_resources_until_safe_completion() { + let observations = Arc::new(Observations::default()); + let drains = Arc::new(AtomicUsize::new(0)); + let retained = Arc::new(AtomicBool::new(true)); + let session = Session::new( + RetainedJobsHost { + host: Host(observations.clone()), + drains: drains.clone(), + retained: retained.clone(), + }, + NonZeroU16::MIN, + ); + block_on(session.start()).unwrap(); + let permit = session.admit().unwrap(); + assert_eq!( + block_on(session.close()).unwrap_err().code(), + Code::RecoveryRequired + ); + assert_eq!(session.state(), SessionState::Closing); + assert_eq!( + *observations.calls.lock().unwrap(), + vec![Hook::Start, Hook::Quiesce] + ); + assert!(session.admit().is_err()); + assert_eq!( + block_on(session.close()).unwrap_err().code(), + Code::RecoveryRequired + ); + assert_eq!(drains.load(Ordering::SeqCst), 2); + retained.store(false, Ordering::SeqCst); + let mut wait = Box::pin(session.close()); + assert!(poll(wait.as_mut()).is_pending()); + drop(wait); + assert_eq!(drains.load(Ordering::SeqCst), 3); + drop(permit); + block_on(session.close()).unwrap(); + assert_eq!(drains.load(Ordering::SeqCst), 3); + assert_eq!( + *observations.calls.lock().unwrap(), + vec![ + Hook::Start, + Hook::Quiesce, + Hook::Disconnect, + Hook::Callbacks, + Hook::Storage + ] + ); + assert_eq!(session.state(), SessionState::Closed); +} diff --git a/crates/execution/tests/signer_session.rs b/crates/execution/tests/signer_session.rs @@ -49,6 +49,8 @@ struct Control { current: Mutex<ProviderState>, calls: AtomicUsize, sign_calls: AtomicUsize, + crypto_calls: AtomicUsize, + crypto_response: Mutex<Option<oneshot::Receiver<()>>>, sign_response: Mutex<Option<oneshot::Receiver<radroots_signing::issuance::SigningOutcome>>>, sign_binding: Mutex<Option<radroots_signing::issuance::IntentBinding>>, response: Mutex<Option<oneshot::Receiver<()>>>, @@ -123,7 +125,14 @@ impl ParticipantProvider for Provider { _: PublicKey, _: PrivateText, ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> { - Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) + Box::pin(async move { + self.0.crypto_calls.fetch_add(1, Ordering::SeqCst); + let response = self.0.crypto_response.lock().unwrap().take(); + if let Some(response) = response { + response.await.map_err(|_| ProviderError::Cancelled)?; + } + Err(ProviderError::ProviderFailure) + }) } fn decrypt_private( &self, @@ -131,7 +140,10 @@ impl ParticipantProvider for Provider { _: PublicKey, _: PrivateCiphertext, ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> { - Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) + Box::pin(async move { + self.0.crypto_calls.fetch_add(1, Ordering::SeqCst); + Err(ProviderError::ProviderFailure) + }) } } @@ -193,6 +205,8 @@ fn control() -> Shared<Control> { current: Mutex::new(state(false, false)), calls: AtomicUsize::new(0), sign_calls: AtomicUsize::new(0), + crypto_calls: AtomicUsize::new(0), + crypto_response: Mutex::new(None), sign_response: Mutex::new(None), sign_binding: Mutex::new(None), response: Mutex::new(None), @@ -603,3 +617,136 @@ fn exact_callback_binding_cannot_claim_another_operations_result() { assert!(rejected.fingerprint().is_none()); block_on(session.close()).unwrap(); } + +fn crypto_call(second: bool) -> ProviderCall { + ProviderCall::new( + key(second), + core::num::NonZeroU64::new(1_700_000_010_000).unwrap(), + radroots_signing::request::CancellationSignal::new(), + ) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn private_crypto_reobserves_the_attached_identity_and_capability_without_fallback() { + let Fixture { + session, control, .. + } = scope(); + assert_eq!( + block_on(session.encrypt_private( + crypto_call(false), + key(true), + PrivateText::new("private model").unwrap() + )) + .unwrap_err(), + ProviderError::CapabilityUnavailable + ); + assert_eq!(control.calls.load(Ordering::SeqCst), 0); + block_on(session.observe()).unwrap(); + assert_eq!( + block_on(session.encrypt_private( + crypto_call(false), + key(true), + PrivateText::new("private model").unwrap() + )) + .unwrap_err(), + ProviderError::CapabilityUnavailable + ); + assert_eq!(control.crypto_calls.load(Ordering::SeqCst), 0); + *control.current.lock().unwrap() = state(false, true); + assert_eq!( + block_on(session.encrypt_private( + crypto_call(true), + key(true), + PrivateText::new("private model").unwrap() + )) + .unwrap_err(), + ProviderError::IdentityChanged + ); + assert!(!session.identity_changed()); + assert_eq!( + block_on(session.encrypt_private( + crypto_call(false), + key(true), + PrivateText::new("private model").unwrap() + )) + .unwrap_err(), + ProviderError::ProviderFailure + ); + // This is structural port data, not authenticated NIP-44 ciphertext. + assert_eq!( + block_on(session.decrypt_private( + crypto_call(false), + key(true), + PrivateCiphertext::parse(&"A".repeat(132)).unwrap() + )) + .unwrap_err(), + ProviderError::ProviderFailure + ); + assert_eq!(control.crypto_calls.load(Ordering::SeqCst), 2); + *control.current.lock().unwrap() = state(true, true); + assert_eq!( + block_on(session.encrypt_private( + crypto_call(false), + key(true), + PrivateText::new("private model").unwrap() + )) + .unwrap_err(), + ProviderError::IdentityChanged + ); + *control.current.lock().unwrap() = state(false, true); + assert_eq!( + block_on(session.decrypt_private( + crypto_call(false), + key(true), + PrivateCiphertext::parse(&"A".repeat(132)).unwrap() + )) + .unwrap_err(), + ProviderError::IdentityChanged + ); + assert_eq!(control.crypto_calls.load(Ordering::SeqCst), 2); + block_on(session.close()).unwrap(); + assert_eq!( + block_on(session.encrypt_private( + crypto_call(false), + key(true), + PrivateText::new("private model").unwrap() + )) + .unwrap_err(), + ProviderError::CapabilityUnavailable + ); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn scoped_private_crypto_retains_callbacks_until_the_issued_call_finishes() { + let Fixture { + session, + control, + provider, + callbacks, + } = scope(); + *control.current.lock().unwrap() = state(false, true); + block_on(session.observe()).unwrap(); + let (send, receive) = oneshot::channel(); + *control.crypto_response.lock().unwrap() = Some(receive); + let mut encrypt = Box::pin(session.encrypt_private( + crypto_call(false), + key(true), + PrivateText::new("private model").unwrap(), + )); + let mut cx = Context::from_waker(noop_waker_ref()); + assert!(encrypt.as_mut().poll(&mut cx).is_pending()); + let mut close = Box::pin(session.close()); + assert!(close.as_mut().poll(&mut cx).is_pending()); + assert_eq!(session.state(), SessionState::Closing); + assert_eq!(control.close_attempts.load(Ordering::SeqCst), 0); + assert!(provider.upgrade().is_some() && callbacks.upgrade().is_some()); + send.send(()).unwrap(); + assert!(matches!( + encrypt.as_mut().poll(&mut cx), + Poll::Ready(Err(ProviderError::ProviderFailure)) + )); + assert!(matches!(close.as_mut().poll(&mut cx), Poll::Ready(Ok(())))); + assert!(provider.upgrade().is_none() && callbacks.upgrade().is_none()); +} diff --git a/crates/nostr/src/signing/gift_wrap.rs b/crates/nostr/src/signing/gift_wrap.rs @@ -114,6 +114,18 @@ fn past_time(now: u64, source: &dyn NonceSource) -> Result<u64, WrapError> { Err(WrapError::EntropyUnavailable) } +/// Draws a positive timestamp within the NIP-59 two-day past interval using +/// bounded unbiased sampling. The injected source must be a qualified CSPRNG. +pub fn randomized_past_time( + now: NonZeroU64, + source: &dyn NonceSource, +) -> Result<NonZeroU64, WrapError> { + if now.get() > MAX_TIME { + return Err(WrapError::InvalidTime); + } + NonZeroU64::new(past_time(now.get(), source)?).ok_or(WrapError::InvalidTime) +} + fn wrapping_keys( source: &dyn NonceSource, author: PublicKey, diff --git a/crates/nostr/src/signing/gift_wrap/tests.rs b/crates/nostr/src/signing/gift_wrap/tests.rs @@ -11,6 +11,30 @@ const NOW: u64 = 1_700_200_000; fn time(value: u64) -> NonZeroU64 { NonZeroU64::new(value).unwrap() } + +#[test] +fn public_past_time_boundary_is_positive_bounded_and_refuses_invalid_time_or_entropy() { + for now in [1, 2, PAST_SECONDS, NOW, MAX_TIME] { + let selected = randomized_past_time(time(now), &Entropy::default()) + .unwrap() + .get(); + assert!((now.saturating_sub(PAST_SECONDS).max(1)..=now).contains(&selected)); + } + let source = Entropy::default(); + assert_eq!( + randomized_past_time(time(MAX_TIME + 1), &source), + Err(WrapError::InvalidTime) + ); + assert_eq!(source.calls.load(Ordering::SeqCst), 0); + let source = Entropy { + fail_at: Some(0), + ..Default::default() + }; + assert_eq!( + randomized_past_time(time(NOW), &source), + Err(WrapError::EntropyUnavailable) + ); +} fn keys(value: u8) -> nostr::Keys { let mut key = [0; 32]; key[31] = value; diff --git a/crates/radroots/Cargo.toml b/crates/radroots/Cargo.toml @@ -36,22 +36,27 @@ name = "radroots" path = "src/lib.rs" [dependencies] +futures = { workspace = true, optional = true } radroots_core = { workspace = true } radroots_domain = { workspace = true, features = ["std", "serde"] } radroots_execution = { workspace = true, features = ["client_session", "workspace_session"] } +radroots_protocol = { workspace = true, default-features = false, features = ["chat"] } radroots_event = { workspace = true } radroots_identity = { workspace = true, features = ["std"] } radroots_sdk = { workspace = true } radroots_signing = { workspace = true } radroots_storage = { workspace = true } radroots_storage_sqlite = { workspace = true, optional = true } +radroots_nostr = { workspace = true, features = ["signing", "nip17"], optional = true } +radroots_transport_nostr = { workspace = true, optional = true } radroots_trade = { workspace = true, features = ["json", "std"] } radroots_transport = { workspace = true } +tokio = { workspace = true, features = ["rt", "sync"], optional = true } [features] default = ["client"] client = ["radroots_sdk/default", "radroots_storage/memory"] -native = ["client", "radroots_sdk/native", "dep:radroots_storage_sqlite"] +native = ["client", "radroots_sdk/native", "dep:radroots_storage_sqlite", "dep:futures", "dep:tokio", "dep:radroots_nostr", "dep:radroots_transport_nostr"] nostr = ["client", "radroots_sdk/nostr"] blossom = ["client", "radroots_sdk/blossom"] nip46 = ["nostr", "radroots_sdk/nip46"] diff --git a/crates/radroots/README.md b/crates/radroots/README.md @@ -63,6 +63,28 @@ Errors come from `radroots_execution`: fixed codes, bounded redacted details, explicit admission/retry disposition and optional exact operation identity. Backend prose, private payloads and paths are not retained in the error. +## Native inquiries + +An explicitly opened protected workspace can be supplied with +`NativeConfig::with_workspace`. Attach its authenticated scope and a scoped +participant signer to the Client. `with_nostr` additionally selects exact relay +destinations, directional access and a relay-acceptance criterion. +`StartMode::Online` permits command IO without querying or replaying on startup; +`LocalOnly` keeps inquiries at durable admission without network or signing. +A started session cannot silently escalate from local to online mode. + +`client.inbox().inquire(context, input)` owns accepted native work through +planning, exact participant signing, protected capture, logical installation +and retained-envelope publication. Peer and self copies have independent +progress. Relay acceptance proves neither recipient delivery nor acceptance +of an agreement. Original operation queries never dispatch work. +`client.operations(&scope).resume(operation, digest)` explicitly continues an +original inquiry: retained signing claims cannot be reissued, and publication +retries preserve exact original bytes, the full criterion and prior accepted +targets. A dropped observer does not cancel the native job. Obtained material +whose capture fails stays owned; close reports recovery until its protected +capture can be confirmed. + ## Values and retained capabilities `radroots::domain` provides exact decimals and distinct order, thread, workspace, @@ -71,10 +93,9 @@ retained identity. These values alone perform no authorization or transaction. Farm, listing, trade, event, identity, transport, geographic and knowledge modules retain their source-owned values/planners and advanced capability -paths. The advanced `radroots_sdk` still owns its existing explicit transport -composition while concrete ordinary network integration is unfinished; the -new Client does not wrap that engine or report its writes as new durable -commerce. Optional capabilities remain governed by their actual host/target +paths. The advanced `radroots_sdk` retains its existing explicit transport +composition. The ordinary Client composes the shared execution owner directly. +Optional capabilities remain governed by their actual host/target qualification and do not become available because a feature compiles. The former root `ClientBuilder` and builder-returning memory/native helpers diff --git a/crates/radroots/src/client.rs b/crates/radroots/src/client.rs @@ -37,6 +37,9 @@ const MISSING_WORKSPACE: Error = match Error::new( pub enum StartMode { /// Enables local resource work without opening sockets or replaying writes. LocalOnly, + /// Permits explicit commands to use the configured transport. Startup + /// itself performs no query, publication or automatic outbox replay. + Online, } /// A passive resource-start observation, independent of business authority. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -75,6 +78,8 @@ impl CloseReceipt { pub struct NativeConfig { options: radroots_storage_sqlite::OpenOptions, workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, + #[cfg(not(target_arch = "wasm32"))] + inquiry: Option<Shared<crate::native_inquiry::NativeInquiry>>, } #[cfg(feature = "native")] impl NativeConfig { @@ -84,6 +89,8 @@ impl NativeConfig { Self { options, workspace: None, + #[cfg(not(target_arch = "wasm32"))] + inquiry: None, } } /// Adds an explicitly opened protected local outbox. A public cache alone @@ -96,28 +103,118 @@ impl NativeConfig { self.workspace = Some(Shared::new(workspace)); self } + /// Selects explicit relay destinations and a relay-acceptance criterion. + /// Construction opens no socket. Actual command IO requires Online start. + #[cfg(not(target_arch = "wasm32"))] + pub fn with_nostr( + mut self, + config: radroots_transport_nostr::Config, + policy: radroots_transport::policy::SatisfactionPolicy, + ) -> crate::Result<Self> { + self.inquiry = Some(Shared::new( + crate::native_inquiry::NativeInquiry::new(config, policy) + .map_err(|error| Error::operation(error, OperationContext::proposed(None)))?, + )); + Ok(self) + } } +#[derive(Clone, Default)] +enum TargetRuntime { + #[default] + Preview, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + Native(Shared<crate::native_tasks::NativeTasks>), +} +impl TargetRuntime { + fn task_host(&self) -> Option<Shared<dyn radroots_execution::session::tasks::TaskHost>> { + match self { + Self::Preview => None, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + Self::Native(tasks) => Some(tasks.clone()), + } + } +} pub(crate) struct StoreHost { store: Shared<dyn Storage>, workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, closed: Shared<Mutex<Option<CloseReceipt>>>, + runtime: TargetRuntime, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + inquiry: Option<Shared<radroots_execution::session::inquiry::InquiryRuntime>>, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + native_inquiry: Option<Shared<crate::native_inquiry::NativeInquiry>>, } impl SessionHost for StoreHost { fn start(&self) -> HostFuture<'_, crate::Result<()>> { - Box::pin(async { Ok(()) }) + Box::pin(async move { + match &self.runtime { + TargetRuntime::Preview => Ok(()), + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + TargetRuntime::Native(tasks) => tasks.start().await, + } + }) } fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> { - Box::pin(async { Ok(()) }) + Box::pin(async move { + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + if let TargetRuntime::Native(tasks) = &self.runtime { + tasks.quiesce(); + } + Ok(()) + }) + } + fn drain(&self) -> HostFuture<'_, crate::Result<()>> { + Box::pin(async move { + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + if let TargetRuntime::Native(tasks) = &self.runtime { + let inquiry = self.inquiry.clone(); + tasks + .control( + crate::native_tasks::ControlKind::Drain, + Box::pin(async move { + if let Some(inquiry) = inquiry { + inquiry.drain().await.map_err(|error| { + Error::operation(error, OperationContext::proposed(None)) + })?; + } + Ok(()) + }), + ) + .await?; + } + Ok(()) + }) } fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> { - Box::pin(async { Ok(()) }) + Box::pin(async move { + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + if let TargetRuntime::Native(tasks) = &self.runtime { + let inquiry = self.native_inquiry.clone(); + tasks + .control( + crate::native_tasks::ControlKind::Disconnect, + Box::pin(async move { + if let Some(inquiry) = inquiry { + inquiry.disconnect().await; + } + Ok(()) + }), + ) + .await?; + } + Ok(()) + }) } fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> { Box::pin(async { Ok(()) }) } fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> { Box::pin(async move { + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + if let TargetRuntime::Native(tasks) = &self.runtime { + tasks.close().await?; + } if let Some(workspace) = &self.workspace { workspace .close_workspace() @@ -145,27 +242,58 @@ pub struct Client { store: Shared<dyn Storage>, workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, closed: Shared<Mutex<Option<CloseReceipt>>>, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + native_inquiry: Option<Shared<crate::native_inquiry::NativeInquiry>>, } impl Client { #[cfg(any(feature = "client", feature = "native"))] fn from_store( store: Shared<dyn Storage>, workspace: Option<Shared<dyn radroots_storage::command::OperationJournal>>, + runtime: TargetRuntime, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] native_inquiry: Option< + Shared<crate::native_inquiry::NativeInquiry>, + >, ) -> Self { let closed = Shared::new(Mutex::new(None)); - let session = ClientSession::new( - StoreHost { - store: store.clone(), - workspace: workspace.clone(), - closed: closed.clone(), - }, - NonZeroU16::MIN, - ); + let task_host = runtime.task_host(); + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + let inquiry = native_inquiry.as_ref().map(|io| { + Shared::new(radroots_execution::session::inquiry::InquiryRuntime::new( + io.clone(), + )) + }); + #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))] + let inquiry: Option<Shared<radroots_execution::session::inquiry::InquiryRuntime>> = None; + let host = StoreHost { + store: store.clone(), + workspace: workspace.clone(), + closed: closed.clone(), + runtime, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + inquiry: inquiry.clone(), + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + native_inquiry: native_inquiry.clone(), + }; + const MAX_RESOURCES: NonZeroU16 = match NonZeroU16::new(32) { + Some(limit) => limit, + None => panic!("invalid constant resource bound"), + }; + let session = match task_host { + Some(tasks) => ClientSession::new_with_task_host(host, MAX_RESOURCES, tasks), + None => ClientSession::new(host, MAX_RESOURCES), + }; + let session = match inquiry { + Some(inquiry) => session.with_inquiry_runtime(inquiry), + None => session, + }; Self { session, store, workspace, closed, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + native_inquiry, } } /// Creates a deterministic in-memory preview with no filesystem, network, @@ -180,6 +308,9 @@ impl Client { Self::from_store( Shared::new(radroots_storage::memory::MemoryStorage::new(GENERATION)), None, + TargetRuntime::Preview, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + None, ) } /// Opens the actual native SQLite cache using explicit host options. This @@ -189,7 +320,17 @@ impl Client { let store = radroots_storage_sqlite::SqliteStorage::open(config.options) .await .map_err(|_| STORAGE_FAILURE)?; - Ok(Self::from_store(Shared::new(store), config.workspace)) + #[cfg(not(target_arch = "wasm32"))] + let runtime = TargetRuntime::Native(Shared::new(crate::native_tasks::NativeTasks::new())); + #[cfg(target_arch = "wasm32")] + let runtime = TargetRuntime::Preview; + Ok(Self::from_store( + Shared::new(store), + config.workspace, + runtime, + #[cfg(not(target_arch = "wasm32"))] + config.inquiry, + )) } /// Observes resource lifecycle without probing signer, store or network. pub fn state(&self) -> SessionState { @@ -215,9 +356,19 @@ impl Client { /// Enables the selected local resource host. No background runtime, /// transport, command writer or stock authority is implicitly constructed. pub async fn start(&self, mode: StartMode) -> crate::Result<SessionStatus> { - match mode { - StartMode::LocalOnly => self.session.start().await?, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] + if let Some(inquiry) = &self.native_inquiry { + inquiry + .select(mode == StartMode::Online) + .map_err(|error| Error::operation(error, OperationContext::proposed(None)))?; + } else if mode == StartMode::Online { + return Err(MISSING_WORKSPACE); + } + #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))] + if mode == StartMode::Online { + return Err(MISSING_WORKSPACE); } + self.session.start().await?; Ok(SessionStatus { state: self.state(), }) diff --git a/crates/radroots/src/lib.rs b/crates/radroots/src/lib.rs @@ -18,6 +18,12 @@ pub mod sync; pub mod trade; pub mod transport; +#[cfg(all(feature = "native", not(target_arch = "wasm32")))] +mod native_tasks; + +#[cfg(all(feature = "native", not(target_arch = "wasm32")))] +mod native_inquiry; + #[cfg(feature = "native")] pub use client::NativeConfig; pub use client::{Client, CloseReceipt, SessionStatus, StartMode}; diff --git a/crates/radroots/src/native_inquiry.rs b/crates/radroots/src/native_inquiry.rs @@ -0,0 +1,372 @@ +use core::num::NonZeroU64; +use radroots_domain::{PublicKey, UnixSeconds}; +use radroots_execution::session::{HostFuture, inquiry::InquiryIo}; +use radroots_nostr::signing::{ + OsNonceSource, + gift_wrap::{randomized_past_time, wrap_retained_seal}, +}; +use radroots_protocol::chat::CapturedDmRoute; +use radroots_signing::provider::NonceSource; +use radroots_storage::command::{ + EnvelopeCandidate, OperationError, PublicationWork, SignedDmRelaySource, +}; +use radroots_transport::{ + EventSink, EventSource, TargetSet, + policy::{SatisfactionClass, SatisfactionPolicy}, + source::{FetchBounds, FetchRequest, FetchSelector}, +}; +use radroots_transport_nostr::{Config, NostrTransport}; +use std::{ + sync::atomic::{AtomicU8, Ordering}, + time::{SystemTime, UNIX_EPOCH}, +}; + +pub(crate) struct NativeInquiry { + transport: NostrTransport, + read: TargetSet, + write: TargetSet, + policy: SatisfactionPolicy, + mode: AtomicU8, +} +impl NativeInquiry { + pub(crate) fn new(config: Config, policy: SatisfactionPolicy) -> Result<Self, OperationError> { + let read = TargetSet::new( + config + .read_relays() + .map(|relay| relay.to_target()) + .collect::<Result<_, _>>() + .map_err(|_| OperationError::InvalidCommand)?, + ) + .map_err(|_| OperationError::InvalidCommand)?; + let write = TargetSet::new( + config + .write_relays() + .map(|relay| relay.to_target()) + .collect::<Result<_, _>>() + .map_err(|_| OperationError::InvalidCommand)?, + ) + .map_err(|_| OperationError::InvalidCommand)?; + if policy.class() != SatisfactionClass::Accepted { + return Err(OperationError::InvalidCommand); + } + policy + .validate_for(&write) + .map_err(|_| OperationError::InvalidCommand)?; + Ok(Self { + transport: NostrTransport::new(config), + read, + write, + policy, + mode: AtomicU8::new(0), + }) + } + pub(crate) fn select(&self, online: bool) -> Result<(), OperationError> { + let mode = if online { 2 } else { 1 }; + match self + .mode + .compare_exchange(0, mode, Ordering::AcqRel, Ordering::Acquire) + { + Ok(_) => Ok(()), + Err(current) if current == mode => Ok(()), + Err(_) => Err(OperationError::Unauthorized), + } + } + pub(crate) async fn disconnect(&self) { + self.transport.shutdown().await; + } + fn capture_route<'a>( + &self, + recipient: PublicKey, + raw_sources: impl IntoIterator<Item = &'a str>, + ) -> Result<CapturedDmRoute, OperationError> { + let mut head: Option<SignedDmRelaySource> = None; + for raw in raw_sources { + let source = SignedDmRelaySource::verify(raw)?; + if source.participant() != recipient { + return Err(OperationError::InvalidEvidence); + } + // NIP-01 replaceable head: latest time, then lowest event ID. + if head.as_ref().is_none_or(|old| { + source.created_at() > old.created_at() + || (source.created_at() == old.created_at() + && source.event_id() < old.event_id()) + }) { + head = Some(source); + } + } + let head = head.ok_or(OperationError::MissingHistory)?; + let mut selected = Vec::new(); + for uri in head.relay_uris() { + if self + .write + .targets() + .iter() + .any(|target| target.matches_nostr_relay(uri).unwrap_or(false)) + && !selected.iter().any(|old| old == uri) + { + selected.push(uri.to_owned()); + } + } + CapturedDmRoute::from_observed_descriptor( + recipient, + head.event_id(), + head.raw_json(), + &selected, + ) + .map_err(|_| OperationError::UnverifiedApproval) + } +} +impl InquiryIo for NativeInquiry { + fn enabled(&self) -> bool { + self.mode.load(Ordering::Acquire) == 2 + } + fn now(&self) -> Result<UnixSeconds, OperationError> { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| OperationError::RecoveryRequired)? + .as_secs(); + UnixSeconds::new(now).map_err(|_| OperationError::RecoveryRequired) + } + fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError> { + let time = randomized_past_time( + NonZeroU64::new(now.get()).ok_or(OperationError::RecoveryRequired)?, + &OsNonceSource, + ) + .map_err(|_| OperationError::RecoveryRequired)?; + UnixSeconds::new(time.get()).map_err(|_| OperationError::RecoveryRequired) + } + fn route( + &self, + recipient: PublicKey, + deadline: NonZeroU64, + ) -> HostFuture<'_, Result<CapturedDmRoute, OperationError>> { + Box::pin(async move { + if !self.enabled() { + return Err(OperationError::Unauthorized); + } + let selector = FetchSelector::all() + .with_kinds(vec![10050]) + .and_then(|selector| selector.with_authors(vec![recipient])) + .map_err(|_| OperationError::InvalidCommand)?; + let bounds = + FetchBounds::new(2, deadline.get()).map_err(|_| OperationError::InvalidCommand)?; + let request = FetchRequest::new(self.delivery_id()?, self.read.clone(), bounds) + .map_err(|_| OperationError::InvalidCommand)? + .with_selector(selector); + let page = self + .transport + .fetch(request) + .await + .map_err(|_| OperationError::MissingHistory)?; + self.capture_route( + recipient, + page.events() + .iter() + .map(|observed| observed.event().raw_json()), + ) + }) + } + fn targets(&self, route: &CapturedDmRoute) -> Result<TargetSet, OperationError> { + SignedDmRelaySource::verify(route.raw_json())?.validate_capture(route)?; + let mut selected = Vec::new(); + for uri in route.selected_relays() { + let target = self + .write + .targets() + .iter() + .find(|target| target.matches_nostr_relay(uri).unwrap_or(false)) + .ok_or(OperationError::UnverifiedApproval)?; + if !selected.iter().any(|old| old == target) { + selected.push(target.clone()); + } + } + TargetSet::new(selected).map_err(|_| OperationError::UnverifiedApproval) + } + fn publication_policy(&self) -> SatisfactionPolicy { + self.policy.clone() + } + fn envelope( + &self, + work: PublicationWork, + raw_seal: &str, + ) -> Result<EnvelopeCandidate, OperationError> { + let now = NonZeroU64::new(self.now()?.get()).ok_or(OperationError::RecoveryRequired)?; + let recipient = work.evidence().recipient(); + let wrapped = wrap_retained_seal(raw_seal, recipient, now, &OsNonceSource) + .map_err(|_| OperationError::InvalidEvidence)?; + wrapped.with_wrapping_key(|key| { + EnvelopeCandidate::from_obtained(work, wrapped.signed_json(), key) + }) + } + fn delivery_id(&self) -> Result<String, OperationError> { + let bytes = OsNonceSource + .next_nonce() + .map_err(|_| OperationError::RecoveryRequired)?; + let mut output = String::with_capacity(64); + const HEX: &[u8; 16] = b"0123456789abcdef"; + for byte in bytes { + output.push(HEX[usize::from(byte >> 4)] as char); + output.push(HEX[usize::from(byte & 15)] as char); + } + Ok(output) + } + fn publish( + &self, + request: radroots_transport::sink::DeliveryRequest, + selected: TargetSet, + ) -> HostFuture<'_, Result<radroots_transport::DeliveryReceipt, radroots_transport::SinkFailure>> + { + self.transport.deliver_selected(request, selected) + } +} + +#[cfg(test)] +mod tests { + use super::NativeInquiry; + use futures::executor::block_on; + use nostr::JsonUtil; + use radroots_domain::PublicKey; + use radroots_execution::session::inquiry::InquiryIo; + use radroots_storage::command::{OperationError, SignedDmRelaySource}; + use radroots_transport::policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}; + use radroots_transport_nostr::{ + Config, RelayAccess, RelayEndpoint, RelayProfile, RelayProfileKind, RelayUrlPolicy, + }; + use std::num::NonZeroU64; + + const URI: &str = "ws://127.0.0.1:1"; + fn config(access: RelayAccess) -> Config { + Config::from_profile( + RelayProfile::explicit( + RelayProfileKind::Simulator, + [RelayEndpoint::new(URI, RelayUrlPolicy::Local, access).unwrap()], + ) + .unwrap(), + ) + } + fn io() -> NativeInquiry { + NativeInquiry::new( + config(RelayAccess::ReadWrite), + SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), + ) + .unwrap() + } + fn source(author: u8, time: u64, content: &str, relays: &[&str]) -> String { + let mut key = [0; 32]; + key[31] = author; + let keys = nostr::Keys::new(nostr::SecretKey::from_slice(&key).unwrap()); + nostr::EventBuilder::new(nostr::Kind::Custom(10050), content) + .tags( + relays + .iter() + .map(|uri| nostr::Tag::parse(["relay", *uri]).unwrap()), + ) + .custom_created_at(nostr::Timestamp::from_secs(time)) + .sign_with_keys(&keys) + .unwrap() + .as_json() + } + fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap() + } + + #[tokio::test] + async fn explicit_io_configuration_and_repeated_start_modes_never_imply_network_admission() { + assert!( + NativeInquiry::new( + config(RelayAccess::ReadOnly), + SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()) + ) + .is_err() + ); + assert!( + NativeInquiry::new( + config(RelayAccess::ReadWrite), + SatisfactionPolicy::new(SatisfactionClass::Delivered, TargetPolicy::all()) + ) + .is_err() + ); + let local = io(); + assert!(matches!( + local.route(key(), NonZeroU64::new(1000).unwrap()).await, + Err(OperationError::Unauthorized) + )); + local.select(false).unwrap(); + local.select(false).unwrap(); + assert!(local.select(true).is_err()); + let online = io(); + online.select(true).unwrap(); + online.select(true).unwrap(); + assert!(online.select(false).is_err()); + local.disconnect().await; + online.disconnect().await; + let preview = crate::Client::preview(); + assert!(preview.start(crate::StartMode::Online).await.is_err()); + preview.close().await.unwrap(); + } + + #[test] + fn exact_signed_route_heads_are_order_independent_and_ties_use_the_original_event_id() { + let io = io(); + let older = source(1, 100, "old", &[URI]); + let newer = source(1, 101, "new", &[URI]); + let expected = SignedDmRelaySource::verify(&newer).unwrap().event_id(); + for values in [ + [older.as_str(), newer.as_str()], + [newer.as_str(), older.as_str()], + ] { + let route = io.capture_route(key(), values).unwrap(); + assert_eq!(route.source_id(), expected); + assert_eq!(route.raw_json(), newer); + } + let a = source(1, 101, "a", &[URI]); + let b = source(1, 101, "b", &[URI]); + let a_id = SignedDmRelaySource::verify(&a).unwrap().event_id(); + let b_id = SignedDmRelaySource::verify(&b).unwrap().event_id(); + for values in [[a.as_str(), b.as_str()], [b.as_str(), a.as_str()]] { + assert_eq!( + io.capture_route(key(), values).unwrap().source_id(), + a_id.min(b_id) + ); + } + assert!(matches!( + io.capture_route(key(), []), + Err(OperationError::MissingHistory) + )); + assert!(matches!( + io.capture_route(key(), [source(2, 100, "foreign", &[URI]).as_str()]), + Err(OperationError::InvalidEvidence) + )); + } + + #[test] + fn signed_route_selection_keeps_exact_sources_and_deduplicates_only_approved_targets() { + let io = io(); + let raw = format!( + " \n{}\t", + source( + 1, + 100, + "original", + &[URI, URI, "ws://127.0.0.1:1/", "wss://other.example"] + ) + ); + let route = io.capture_route(key(), [raw.as_str()]).unwrap(); + assert_eq!(route.raw_json(), raw); + assert_eq!(route.selected_relays().len(), 2); + assert_eq!(io.targets(&route).unwrap().len(), 1); + let refused = source(1, 100, "no approved target", &["wss://other.example"]); + assert!(matches!( + io.capture_route(key(), [refused.as_str()]), + Err(OperationError::UnverifiedApproval) + )); + let no_targets = source(1, 100, "no advertised fallback", &[]); + assert!(matches!( + io.capture_route(key(), [no_targets.as_str()]), + Err(OperationError::UnverifiedApproval) + )); + // The actual IO gate refuses before opening the configured local port. + assert!(block_on(io.route(key(), NonZeroU64::new(1000).unwrap())).is_err()); + } +} diff --git a/crates/radroots/src/native_tasks.rs b/crates/radroots/src/native_tasks.rs @@ -0,0 +1,652 @@ +//! One explicitly started native executor for library-owned command futures. +use futures::{FutureExt, future::Shared}; +use radroots_execution::{ + Code, Error, OperationContext, RetryClass, + session::{HostFuture, tasks::TaskHost}, +}; +use std::{sync::Mutex, thread::JoinHandle}; +use tokio::sync::{mpsc, oneshot}; + +const CAPACITY: usize = 32; +const UNAVAILABLE: Error = match Error::new( + Code::CapabilityUnavailable, + OperationContext::proposed(None), + RetryClass::Never, + None, +) { + Ok(error) => error, + Err(_) => panic!("invalid constant task-host error"), +}; +type Completion = Shared<HostFuture<'static, crate::Result<()>>>; +enum Job { + Work(HostFuture<'static, ()>), + Control( + HostFuture<'static, crate::Result<()>>, + oneshot::Sender<crate::Result<()>>, + ), + Stop, +} +#[derive(Clone, Copy, Eq, PartialEq)] +pub(crate) enum ControlKind { + Drain, + Disconnect, +} +struct Control { + id: u64, + kind: ControlKind, + completed: Completion, +} +struct Running { + sender: mpsc::Sender<Job>, + ready: Completion, + done: Completion, + thread: Option<JoinHandle<()>>, + stop_sent: bool, +} +#[derive(Default)] +struct State { + running: Option<Running>, + accepting: bool, + quiesced: bool, + closed: bool, + control: Option<Control>, + next_control: u64, +} +#[derive(Default)] +pub(crate) struct NativeTasks { + state: Mutex<State>, + closing: futures::lock::Mutex<()>, +} +fn completion(receiver: oneshot::Receiver<crate::Result<()>>) -> Completion { + let future: HostFuture<'static, crate::Result<()>> = + Box::pin(async move { receiver.await.unwrap_or(Err(UNAVAILABLE)) }); + future.shared() +} +fn run_worker( + mut receiver: mpsc::Receiver<Job>, + ready: oneshot::Sender<crate::Result<()>>, + done: oneshot::Sender<crate::Result<()>>, + build: impl FnOnce() -> std::io::Result<tokio::runtime::Runtime>, +) { + let runtime = match build() { + Ok(runtime) => runtime, + Err(_) => { + let _ = ready.send(Err(UNAVAILABLE)); + let _ = done.send(Err(UNAVAILABLE)); + return; + } + }; + let _ = ready.send(Ok(())); + runtime.block_on(async move { + while let Some(job) = receiver.recv().await { + match job { + Job::Work(task) => task.await, + Job::Control(task, reply) => { + let result = task.await; + let _ = reply.send(result); + } + Job::Stop => break, + } + } + }); + drop(runtime); + let _ = done.send(Ok(())); +} +impl NativeTasks { + pub(crate) fn new() -> Self { + Self::default() + } + + pub(crate) async fn start(&self) -> crate::Result<()> { + let ready = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.quiesced || state.closed { + return Err(UNAVAILABLE); + } + if state.running.is_none() { + let (sender, receiver) = mpsc::channel::<Job>(CAPACITY); + let (ready, ready_receiver) = oneshot::channel(); + let (done, done_receiver) = oneshot::channel(); + let thread = std::thread::Builder::new() + .name("radroots_commands".into()) + .spawn(move || { + run_worker(receiver, ready, done, || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + }) + }) + .map_err(|_| UNAVAILABLE)?; + state.running = Some(Running { + sender, + ready: completion(ready_receiver), + done: completion(done_receiver), + thread: Some(thread), + stop_sent: false, + }); + } + state.running.as_ref().ok_or(UNAVAILABLE)?.ready.clone() + }; + ready.await?; + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.quiesced || state.closed { + return Err(UNAVAILABLE); + } + state.accepting = true; + Ok(()) + } + + pub(crate) fn quiesce(&self) { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.accepting = false; + state.quiesced = true; + } + + pub(crate) async fn control( + &self, + kind: ControlKind, + task: HostFuture<'static, crate::Result<()>>, + ) -> crate::Result<()> { + let ready = { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.closed { + return Err(UNAVAILABLE); + } + state.running.as_ref().map(|running| running.ready.clone()) + }; + let Some(ready) = ready else { + return Ok(()); + }; + if ready.await.is_err() { + return Ok(()); + } + let (id, completed) = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.closed { + return Err(UNAVAILABLE); + } + if let Some(control) = &state.control { + if control.kind != kind { + return Err(UNAVAILABLE); + } + (control.id, control.completed.clone()) + } else { + let id = state.next_control.checked_add(1).ok_or(UNAVAILABLE)?; + let Some(running) = state.running.as_ref() else { + return Ok(()); + }; + if running.stop_sent { + return Err(UNAVAILABLE); + } + let (reply, wait) = oneshot::channel(); + if let Err(error) = running.sender.try_send(Job::Control(task, reply)) { + drop(state); + drop(error); + return Err(UNAVAILABLE); + } + let completed = completion(wait); + state.next_control = id; + state.control = Some(Control { + id, + kind, + completed: completed.clone(), + }); + (id, completed) + } + }; + let result = completed.await; + let retired = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state + .control + .as_ref() + .is_some_and(|control| control.id == id) + { + state.control.take() + } else { + None + } + }; + drop(retired); + result + } + + pub(crate) async fn close(&self) -> crate::Result<()> { + self.quiesce(); + let _closing = self.closing.lock().await; + let ready = { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.running.as_ref().map(|running| running.ready.clone()) + }; + let failed_start = match ready { + Some(ready) => ready.await.is_err(), + None => false, + }; + let done = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if state.closed { + return Ok(()); + } + let Some(running) = state.running.as_mut() else { + state.closed = true; + return Ok(()); + }; + if !failed_start && !running.stop_sent { + running + .sender + .try_send(Job::Stop) + .map_err(|_| UNAVAILABLE)?; + running.stop_sent = true; + } + running.done.clone() + }; + let result = done.await; + if !failed_start { + result?; + } + let thread = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state + .running + .as_mut() + .and_then(|running| running.thread.take()) + }; + if let Some(thread) = thread { + let result = thread.join().map_err(|_| UNAVAILABLE); + if !failed_start { + result?; + } + } + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .closed = true; + Ok(()) + } +} +impl TaskHost for NativeTasks { + fn submit(&self, task: HostFuture<'static, ()>) -> crate::Result<()> { + let state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if !state.accepting || state.quiesced || state.closed { + return Err(UNAVAILABLE); + } + let running = state.running.as_ref().ok_or(UNAVAILABLE)?; + let result = running.sender.try_send(Job::Work(task)); + drop(state); + result.map_err(|_| UNAVAILABLE) + } +} + +#[cfg(test)] +mod tests { + use super::{CAPACITY, ControlKind, NativeTasks, Running, UNAVAILABLE, completion, run_worker}; + use futures::{FutureExt, executor::block_on, task::noop_waker_ref}; + use radroots_execution::session::{HostFuture, tasks::TaskHost}; + use std::{ + future::Future, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + task::{Context, Poll}, + time::Duration, + }; + use tokio::sync::{mpsc, oneshot}; + + fn pending<F: Future>(future: Pin<&mut F>) { + assert!( + future + .poll(&mut Context::from_waker(noop_waker_ref())) + .is_pending() + ); + } + fn gate_ready(tasks: &NativeTasks) -> oneshot::Sender<()> { + let mut state = tasks.state.lock().unwrap(); + let running = state.running.as_mut().unwrap(); + let original = running.ready.clone(); + let (release, wait) = oneshot::channel(); + let gated: HostFuture<'static, crate::Result<()>> = Box::pin(async move { + original.await?; + wait.await.map_err(|_| UNAVAILABLE) + }); + running.ready = gated.shared(); + release + } + + #[test] + fn never_started_driver_quiesces_and_closes_without_dispatch() { + let tasks = NativeTasks::new(); + block_on(tasks.control( + ControlKind::Drain, + Box::pin(async { panic!("unstarted control dispatched") }), + )) + .unwrap(); + tasks.quiesce(); + assert!(block_on(tasks.start()).is_err()); + block_on(tasks.close()).unwrap(); + assert!(block_on(tasks.control(ControlKind::Drain, Box::pin(async { Ok(()) }))).is_err()); + block_on(tasks.close()).unwrap(); + } + + #[test] + fn cancelled_close_retains_stop_progress_and_refuses_late_control() { + let tasks = NativeTasks::new(); + block_on(tasks.start()).unwrap(); + let (release, wait) = oneshot::channel(); + tasks + .submit(Box::pin(async move { + wait.await.unwrap(); + })) + .unwrap(); + let mut closing = Box::pin(tasks.close()); + pending(closing.as_mut()); + drop(closing); + assert!(block_on(tasks.control(ControlKind::Drain, Box::pin(async { Ok(()) }))).is_err()); + release.send(()).unwrap(); + block_on(tasks.close()).unwrap(); + assert!( + tasks + .state + .lock() + .unwrap() + .running + .as_ref() + .unwrap() + .thread + .is_none() + ); + } + + #[test] + fn coalesced_control_failure_retry_and_stale_observer_keep_the_current_generation() { + let tasks = NativeTasks::new(); + block_on(tasks.start()).unwrap(); + block_on(tasks.start()).unwrap(); + let (release, wait) = oneshot::channel(); + let mut first = Box::pin(tasks.control( + ControlKind::Drain, + Box::pin(async move { + wait.await.unwrap(); + Err(UNAVAILABLE) + }), + )); + pending(first.as_mut()); + let mut stale = Box::pin(tasks.control( + ControlKind::Drain, + Box::pin(async { panic!("coalesced work dispatched twice") }), + )); + pending(stale.as_mut()); + assert!( + block_on(tasks.control(ControlKind::Disconnect, Box::pin(async { Ok(()) }))).is_err() + ); + release.send(()).unwrap(); + assert!(block_on(first).is_err()); + let (release, wait) = oneshot::channel(); + let mut current = Box::pin(tasks.control( + ControlKind::Drain, + Box::pin(async move { + wait.await.unwrap(); + Ok(()) + }), + )); + pending(current.as_mut()); + let generation = tasks.state.lock().unwrap().control.as_ref().unwrap().id; + assert!(block_on(stale).is_err()); + assert_eq!( + tasks.state.lock().unwrap().control.as_ref().unwrap().id, + generation + ); + release.send(()).unwrap(); + block_on(current).unwrap(); + block_on(tasks.close()).unwrap(); + } + + #[test] + fn delayed_ready_observation_cannot_reopen_a_closed_driver_or_dispatch_control() { + let tasks = NativeTasks::new(); + block_on(tasks.start()).unwrap(); + let release = gate_ready(&tasks); + let mut start = Box::pin(tasks.start()); + pending(start.as_mut()); + let mut control = Box::pin(tasks.control( + ControlKind::Drain, + Box::pin(async { panic!("closed control dispatched") }), + )); + pending(control.as_mut()); + release.send(()).unwrap(); + block_on(tasks.close()).unwrap(); + assert!(block_on(start).is_err()); + assert!(block_on(control).is_err()); + } + + fn injected_driver(bootstrap_failure: bool, panic_after_drain: bool) -> NativeTasks { + let tasks = NativeTasks::new(); + let (sender, receiver) = mpsc::channel(CAPACITY); + let (ready, ready_receiver) = oneshot::channel(); + let (done, done_receiver) = oneshot::channel(); + let thread = std::thread::spawn(move || { + run_worker(receiver, ready, done, || { + if bootstrap_failure { + Err(std::io::Error::other("injected bootstrap failure")) + } else { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + } + }); + assert!(!panic_after_drain, "injected post-drain worker failure"); + }); + tasks.state.lock().unwrap().running = Some(Running { + sender, + ready: completion(ready_receiver), + done: completion(done_receiver), + thread: Some(thread), + stop_sent: false, + }); + tasks + } + + #[test] + fn injected_bootstrap_failure_and_post_drain_join_failure_preserve_actual_close_progress() { + let failed = injected_driver(true, false); + assert!(block_on(failed.start()).is_err()); + block_on(failed.control( + ControlKind::Drain, + Box::pin(async { panic!("failed bootstrap dispatched") }), + )) + .unwrap(); + block_on(failed.close()).unwrap(); + let failed = injected_driver(false, true); + block_on(failed.start()).unwrap(); + assert!(block_on(failed.close()).is_err()); + assert!(!failed.state.lock().unwrap().closed); + block_on(failed.close()).unwrap(); + } + + #[test] + fn dropping_an_empty_driver_ends_its_actual_channel_without_claiming_close() { + let tasks = NativeTasks::new(); + block_on(tasks.start()).unwrap(); + let (done, thread) = { + let mut state = tasks.state.lock().unwrap(); + let running = state.running.as_mut().unwrap(); + (running.done.clone(), running.thread.take().unwrap()) + }; + drop(tasks); + block_on(done).unwrap(); + thread.join().unwrap(); + } + + #[test] + fn accepted_tasks_and_control_survive_lost_observation_on_the_actual_native_executor() { + let tasks = NativeTasks::new(); + let count = Arc::new(AtomicUsize::new(0)); + assert!(tasks.submit(Box::pin(async {})).is_err()); + drop(tasks.start()); + assert!(tasks.state.lock().unwrap().running.is_none()); + block_on(tasks.start()).unwrap(); + let (ready, observed) = std::sync::mpsc::sync_channel(1); + let (release, wait) = oneshot::channel(); + let calls = count.clone(); + tasks + .submit(Box::pin(async move { + ready.send(std::thread::current().id()).unwrap(); + wait.await.unwrap(); + calls.fetch_add(1, Ordering::SeqCst); + })) + .unwrap(); + assert_ne!( + observed.recv_timeout(Duration::from_secs(10)).unwrap(), + std::thread::current().id() + ); + let calls = count.clone(); + tasks + .submit(Box::pin(async move { + calls.fetch_add(10, Ordering::SeqCst); + })) + .unwrap(); + tasks.quiesce(); + assert!(tasks.submit(Box::pin(async {})).is_err()); + let calls = count.clone(); + let mut drain = Box::pin(tasks.control( + ControlKind::Drain, + Box::pin(async move { + calls.fetch_add(100, Ordering::SeqCst); + Ok(()) + }), + )); + assert!(matches!( + drain + .as_mut() + .poll(&mut Context::from_waker(noop_waker_ref())), + Poll::Pending + )); + drop(drain); + release.send(()).unwrap(); + let calls = count.clone(); + block_on(tasks.control( + ControlKind::Drain, + Box::pin(async move { + calls.fetch_add(1000, Ordering::SeqCst); + Ok(()) + }), + )) + .unwrap(); + assert_eq!(count.load(Ordering::SeqCst), 111); + block_on(tasks.control(ControlKind::Disconnect, Box::pin(async { Ok(()) }))).unwrap(); + block_on(tasks.close()).unwrap(); + block_on(tasks.close()).unwrap(); + assert!(block_on(tasks.start()).is_err()); + assert!( + tasks + .state + .lock() + .unwrap() + .running + .as_ref() + .unwrap() + .thread + .is_none() + ); + } + + struct ReentrantDrop(Arc<NativeTasks>, Arc<AtomicUsize>); + impl Drop for ReentrantDrop { + fn drop(&mut self) { + assert!(self.0.state.try_lock().is_ok()); + self.1.fetch_add(1, Ordering::SeqCst); + } + } + #[test] + fn native_queue_refusal_drops_captured_roots_outside_the_gate_and_close_drains_accepted_tasks() + { + let tasks = Arc::new(NativeTasks::new()); + block_on(tasks.start()).unwrap(); + let (ready, observed) = std::sync::mpsc::sync_channel(1); + let (release, wait) = oneshot::channel(); + tasks + .submit(Box::pin(async move { + ready.send(()).unwrap(); + wait.await.unwrap(); + })) + .unwrap(); + observed.recv_timeout(Duration::from_secs(10)).unwrap(); + let count = Arc::new(AtomicUsize::new(0)); + let (finished, completed) = oneshot::channel(); + let mut finished = Some(finished); + for index in 0..CAPACITY { + let count = count.clone(); + let finished = if index + 1 == CAPACITY { + finished.take() + } else { + None + }; + tasks + .submit(Box::pin(async move { + count.fetch_add(1, Ordering::SeqCst); + if let Some(finished) = finished { + let _ = finished.send(()); + } + })) + .unwrap(); + } + let drops = Arc::new(AtomicUsize::new(0)); + let probe = ReentrantDrop(tasks.clone(), drops.clone()); + assert!( + tasks + .submit(Box::pin(async move { + let _probe = probe; + })) + .is_err() + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); + assert!(block_on(tasks.control(ControlKind::Drain, Box::pin(async { Ok(()) }))).is_err()); + assert!(block_on(tasks.close()).is_err()); + tasks.quiesce(); + let probe = ReentrantDrop(tasks.clone(), drops.clone()); + assert!( + tasks + .submit(Box::pin(async move { + let _probe = probe; + })) + .is_err() + ); + assert_eq!(drops.load(Ordering::SeqCst), 2); + release.send(()).unwrap(); + block_on(completed).unwrap(); + block_on(tasks.control(ControlKind::Drain, Box::pin(async { Ok(()) }))).unwrap(); + block_on(tasks.close()).unwrap(); + assert_eq!(count.load(Ordering::SeqCst), CAPACITY); + } +} diff --git a/crates/radroots/src/operations.rs b/crates/radroots/src/operations.rs @@ -8,6 +8,19 @@ pub struct Operations<'a> { scope: WorkspaceSession, } impl<'a> Operations<'a> { + /// Explicitly resumes one original inquiry. Retained signing claims never + /// permit reissuance. Delivery retries use the original exact envelope and + /// criterion, preserving accepted targets and the original business result. + pub async fn resume( + &self, + operation: OperationId, + expected: Option<CommandDigest>, + ) -> Result<OperationReceipt<ChatMessage>> { + self.client + .session + .resume_inquiry(self.client.journal()?, &self.scope, operation, expected) + .await + } pub(crate) const fn new(client: &'a Client, scope: WorkspaceSession) -> Self { Self { client, scope } } diff --git a/crates/radroots/tests/native_client.rs b/crates/radroots/tests/native_client.rs @@ -255,3 +255,104 @@ async fn ordinary_native_signer_scope_returns_real_full_identity_signature_facts // primitive fact alone does not claim a durable command or publication. artifact.with_json(|raw| assert!(!raw.is_empty())); } + +#[tokio::test] +async fn ordinary_scoped_private_crypto_uses_actual_custody_and_nip44() { + use radroots_nostr::signing::OsNonceSource; + use radroots_signing::provider::{ + ParticipantProvider, PrivateText, ProviderCall, ProviderError, + }; + use radroots_signing::request::CancellationSignal; + fn checked_clock() -> Result<u64, radroots_signing::Error> { + Ok(1_700_000_000_001) + } + let root = tempfile::tempdir().unwrap(); + let options = options(root.path()); + let client = Client::open(NativeConfig::public_read(options.clone())) + .await + .unwrap(); + let owner = Arc::new( + LocalSigner::with_clock( + parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") + .unwrap(), + checked_clock, + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)), + ); + let peer = LocalSigner::with_clock( + parse_secret_key("0000000000000000000000000000000000000000000000000000000000000002") + .unwrap(), + checked_clock, + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)); + let call = |identity| { + ProviderCall::new( + identity, + std::num::NonZeroU64::new(1_700_000_010_000).unwrap(), + CancellationSignal::new(), + ) + }; + let scope = client + .attach_signer(SignerHandle::new(owner.clone(), callbacks(options, true))) + .await + .unwrap(); + let text = "scoped private inquiry: apples 🍎 and exact original text"; + let ciphertext = scope + .encrypt_private( + call(owner.public_key()), + peer.public_key(), + PrivateText::new(text).unwrap(), + ) + .await + .unwrap(); + assert_eq!( + peer.decrypt_private(call(peer.public_key()), owner.public_key(), ciphertext) + .await + .unwrap() + .expose(), + text + ); + let ciphertext = peer + .encrypt_private( + call(peer.public_key()), + owner.public_key(), + PrivateText::new("independent peer response").unwrap(), + ) + .await + .unwrap(); + let plaintext = scope + .decrypt_private(call(owner.public_key()), peer.public_key(), ciphertext) + .await + .unwrap(); + assert_eq!(plaintext.expose(), "independent peer response"); + assert!(!format!("{plaintext:?}").contains("independent peer response")); + let cancelled = CancellationSignal::new(); + cancelled.cancel(); + let denied = scope + .encrypt_private( + ProviderCall::new( + owner.public_key(), + std::num::NonZeroU64::new(1_700_000_010_000).unwrap(), + cancelled, + ), + peer.public_key(), + PrivateText::new(text).unwrap(), + ) + .await + .unwrap_err(); + assert_eq!(denied, ProviderError::Cancelled); + client.close().await.unwrap(); + assert_eq!( + scope + .encrypt_private( + call(owner.public_key()), + peer.public_key(), + PrivateText::new(text).unwrap() + ) + .await + .unwrap_err(), + ProviderError::CapabilityUnavailable + ); +} diff --git a/crates/radroots/tests/package_boundary.rs b/crates/radroots/tests/package_boundary.rs @@ -12,17 +12,22 @@ fn package_has_final_identity_and_exact_dependencies() { assert_eq!( dependency_names(MANIFEST), BTreeSet::from([ + "futures", "radroots_core", "radroots_domain", "radroots_event", "radroots_execution", "radroots_identity", + "radroots_nostr", + "radroots_protocol", "radroots_sdk", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_trade", "radroots_transport", + "radroots_transport_nostr", + "tokio", ]) ); assert!(WORKSPACE.contains( @@ -35,7 +40,7 @@ fn features_forward_the_exact_user_oriented_graph() { for forwarding in [ "default = [\"client\"]", "client = [\"radroots_sdk/default\", \"radroots_storage/memory\"]", - "native = [\"client\", \"radroots_sdk/native\", \"dep:radroots_storage_sqlite\"]", + "native = [\"client\", \"radroots_sdk/native\", \"dep:radroots_storage_sqlite\", \"dep:futures\", \"dep:tokio\", \"dep:radroots_nostr\", \"dep:radroots_transport_nostr\"]", "nostr = [\"client\", \"radroots_sdk/nostr\"]", "nip46 = [\"nostr\", \"radroots_sdk/nip46\"]", "radrootsd = [\"client\", \"radroots_sdk/radrootsd\"]", diff --git a/crates/radroots/tests/receipts.rs b/crates/radroots/tests/receipts.rs @@ -6,6 +6,9 @@ mod plans; #[path = "support/receipt_client.rs"] mod ordinary; +#[path = "support/receipt_workflow.rs"] +mod workflow; + use radroots_domain::{ CommandContextData, CommandDigest, CorrelationId, OperationId, PublicKey, UnixSeconds, }; @@ -32,7 +35,7 @@ use std::{ path::PathBuf, sync::{ Arc, Mutex, - atomic::{AtomicU64, Ordering}, + atomic::{AtomicBool, AtomicU64, Ordering}, mpsc, }, time::Duration, @@ -45,6 +48,7 @@ struct Pause { } struct Clock { now: AtomicU64, + live: AtomicBool, pause: Mutex<Option<Pause>>, } impl Clock { @@ -84,7 +88,15 @@ impl WorkspaceClock for Clock { .recv_timeout(Duration::from_secs(10)) .map_err(|_| WorkspaceError::Unavailable)?; } - UnixSeconds::new(self.now.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + let now = if self.live.load(Ordering::SeqCst) { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| WorkspaceError::Unavailable)? + .as_secs() + } else { + self.now.load(Ordering::SeqCst) + }; + UnixSeconds::new(now).map_err(|_| WorkspaceError::Unavailable) } } struct Fixture { @@ -118,6 +130,7 @@ impl Fixture { provider, clock: Arc::new(Clock { now: AtomicU64::new(100), + live: AtomicBool::new(false), pause: Mutex::new(None), }), } diff --git a/crates/radroots/tests/support/receipt_client.rs b/crates/radroots/tests/support/receipt_client.rs @@ -428,3 +428,147 @@ async fn unpolled_ordinary_inquiry_and_post_close_admission_have_no_effect() { .is_err() ); } + +#[tokio::test] +async fn ordinary_owned_budget_survives_lost_observers_and_all_accepted_commands_drain() { + use std::{ + future::Future, + task::{Context, Poll}, + }; + let ready = Ordinary::new().await; + ready.start().await; + let inbox = ready.client.inbox(); + let (paused, release) = ready.fixture.clock.arm(0); + let mut first = Box::pin(inbox.inquire( + ready.context(97, "first owned"), + input("first owned command"), + )); + assert!(matches!( + first + .as_mut() + .poll(&mut Context::from_waker(futures::task::noop_waker_ref())), + Poll::Pending + )); + reached(paused).await; + let mut second = Box::pin(inbox.inquire( + ready.context(98, "second owned"), + input("second owned command"), + )); + assert!(matches!( + second + .as_mut() + .poll(&mut Context::from_waker(futures::task::noop_waker_ref())), + Poll::Pending + )); + drop(first); + drop(second); + let copy_client = ready.client.clone(); + let error = copy_client + .inbox() + .inquire(ready.context(99, "over quota"), input("not accepted")) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::CapabilityUnavailable); + assert_eq!( + error.context().operation_id(), + Some(OperationId::from_bytes([99; 32])) + ); + assert_eq!(error.context().admission(), Admission::NotAdmitted); + let mut close = Box::pin(ready.client.close()); + assert!(matches!( + close + .as_mut() + .poll(&mut Context::from_waker(futures::task::noop_waker_ref())), + Poll::Pending + )); + release.send(()).unwrap(); + close.await.unwrap(); + let reopened = ready.fixture.reopen(ready.input.clone()).await; + let binding = reopened + .authenticate(ready.input.clone(), &ready.proof) + .await + .unwrap(); + for (id, body) in [(97, "first owned command"), (98, "second owned command")] { + let snapshot = reopened + .operation_snapshot( + binding.clone(), + OperationId::from_bytes([id; 32]), + None, + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(snapshot.prepared().request().command().text(), body); + } + assert!( + reopened + .operation_snapshot( + binding, + OperationId::from_bytes([99; 32]), + None, + copy(&ready.proof) + ) + .await + .unwrap() + .is_none() + ); + reopened.close().await.unwrap(); +} + +#[tokio::test] +async fn owned_inquiry_continues_to_its_coherent_query_after_the_caller_disappears() { + use std::{ + future::Future, + task::{Context, Poll}, + }; + let ready = Ordinary::new().await; + ready.start().await; + let inbox = ready.client.inbox(); + let (first_paused, release_first) = ready.fixture.clock.arm(0); + let mut wait = Box::pin(inbox.inquire( + ready.context(100, "lost before admission reply"), + input("independent owner continuation"), + )); + assert!(matches!( + wait.as_mut() + .poll(&mut Context::from_waker(futures::task::noop_waker_ref())), + Poll::Pending + )); + reached(first_paused).await; + drop(wait); + // After the first access observation, T0's fence consumes one clock read; + // the coherent query's access is the next actual boundary. + let (query_paused, release_query) = ready.fixture.clock.arm(1); + release_first.send(()).unwrap(); + reached(query_paused).await; + let mut close = Box::pin(ready.client.close()); + assert!(matches!( + close + .as_mut() + .poll(&mut Context::from_waker(futures::task::noop_waker_ref())), + Poll::Pending + )); + release_query.send(()).unwrap(); + close.await.unwrap(); + let reopened = ready.fixture.reopen(ready.input.clone()).await; + let binding = reopened + .authenticate(ready.input.clone(), &ready.proof) + .await + .unwrap(); + let snapshot = reopened + .operation_snapshot( + binding, + OperationId::from_bytes([100; 32]), + None, + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + snapshot.prepared().request().command().text(), + "independent owner continuation" + ); + reopened.close().await.unwrap(); +} diff --git a/crates/radroots/tests/support/receipt_issuance.rs b/crates/radroots/tests/support/receipt_issuance.rs @@ -1,4 +1,6 @@ use super::*; +#[path = "receipt_recovery.rs"] +mod recovery; use core::cell::Cell; use radroots_nostr::{ key::parse_secret_key, diff --git a/crates/radroots/tests/support/receipt_recovery.rs b/crates/radroots/tests/support/receipt_recovery.rs @@ -0,0 +1,221 @@ +use super::*; +use radroots_storage::command::EvidenceCaptureOutcome; + +struct Issued { + fixture: Fixture, + store: Arc<NativeWorkspace>, + input: AttachmentInput, + proof: AttachmentProof, + binding: WorkspaceBinding, + attempt: SigningAttempt, + evidence: SealEvidence, +} +impl Issued { + async fn new(id: u8, large: bool) -> Self { + let fixture = Fixture::new(); + let (store, input, proof, binding) = fixture.create().await; + let (prepared, digest, recipients) = + prepare(&fixture, &store, &binding, &proof, id, large).await; + let attempt = claim( + store + .claim_attempt( + selection(&binding, &prepared, digest, recipients[0]), + copy(&proof), + ) + .await + .unwrap(), + ); + let original = obtain(&attempt, true).await; + let raw = format!(" \n{}\t", original.raw_json()); + let evidence = + SealEvidence::verify(&attempt, &raw, original.observed_at_unix_ms()).unwrap(); + Self { + fixture, + store, + input, + proof, + binding, + attempt, + evidence, + } + } + async fn assert_same_writer(&self) { + assert!(matches!( + NativeWorkspace::open_existing( + &self.fixture.path, + self.input.clone(), + self.fixture.crypto(), + self.fixture.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + } +} +fn confirmed(outcome: EvidenceCaptureOutcome) -> radroots_storage::command::EvidenceReceipt { + match outcome { + EvidenceCaptureOutcome::Committed(receipt) => receipt, + _ => panic!("actual original capture must confirm"), + } +} + +#[tokio::test] +async fn original_capture_recovery_retries_known_rollback_without_reissuing_and_preserves_exact_bytes() + { + let issued = Issued::new(101, false).await; + let original = issued.evidence.raw_json().to_owned(); + let mut database = issued.fixture.database().await; + sqlx::query("CREATE TRIGGER capture_insert_fault BEFORE INSERT ON seal_evidence BEGIN SELECT RAISE(ABORT,'synthetic capture fault'); END").execute(&mut database).await.unwrap(); + assert!( + issued + .store + .capture_evidence(issued.input.clone(), &issued.proof, &issued.evidence) + .await + .is_err() + ); + assert!( + issued + .store + .reconcile_unknown(issued.input.clone(), &issued.proof, &issued.evidence) + .await + .is_err() + ); + issued.assert_same_writer().await; + sqlx::query("DROP TRIGGER capture_insert_fault") + .execute(&mut database) + .await + .unwrap(); + let first = confirmed( + issued + .store + .reconcile_unknown(issued.input.clone(), &issued.proof, &issued.evidence) + .await + .unwrap(), + ); + assert_eq!(first.observed_at_unix_ms(), None); + let replay = confirmed( + issued + .store + .reconcile_unknown(issued.input.clone(), &issued.proof, &issued.evidence) + .await + .unwrap(), + ); + assert_eq!(first, replay); + let retained = issued + .store + .obtained_evidence( + selection( + &issued.binding, + issued.attempt.bound_plan().prepared(), + *issued.attempt.bound_plan().plan().digest(), + issued.attempt.seal().recipient(), + ), + copy(&issued.proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.evidence().raw_json(), original); + assert_eq!(retained.evidence().observed_at_unix_ms(), None); + database.close().await.unwrap(); + issued.store.close().await.unwrap(); +} + +#[tokio::test] +async fn unknown_capture_recovery_preserves_writer_during_refused_preflight_and_resumes_exact_original() + { + let issued = Issued::new(102, true).await; + let original = issued.evidence.raw_json().to_owned(); + let mut database = issued.fixture.database().await; + sqlx::raw_sql("CREATE TABLE capture_commit_fault (parent INTEGER REFERENCES workspace_grant(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER capture_commit_fault_trigger AFTER INSERT ON seal_evidence BEGIN INSERT INTO capture_commit_fault VALUES(2); END").execute(&mut database).await.unwrap(); + assert!(matches!( + issued + .store + .capture_evidence(issued.input.clone(), &issued.proof, &issued.evidence) + .await, + Ok(EvidenceCaptureOutcome::Unknown(_)) + )); + assert!( + issued + .store + .operation_snapshot( + issued.binding.clone(), + issued.evidence.operation_id(), + None, + copy(&issued.proof) + ) + .await + .is_err() + ); + // The extra fault objects are deliberately outside the exact real schema. + // Recovery closes the old connection but must retain namespace authority. + assert!( + issued + .store + .reconcile_unknown(issued.input.clone(), &issued.proof, &issued.evidence) + .await + .is_err() + ); + issued.assert_same_writer().await; + let wrong = AttachmentProof::from_protected_input(&[0; 32]).unwrap(); + assert_eq!( + issued + .store + .reconcile_unknown(issued.input.clone(), &wrong, &issued.evidence) + .await + .unwrap_err() + .code(), + "unauthorized" + ); + sqlx::raw_sql("DROP TRIGGER capture_commit_fault_trigger; DROP TABLE capture_commit_fault") + .execute(&mut database) + .await + .unwrap(); + issued.fixture.clock.now.store(0, Ordering::SeqCst); + let captured = confirmed( + issued + .store + .reconcile_unknown(issued.input.clone(), &issued.proof, &issued.evidence) + .await + .unwrap(), + ); + assert_eq!(captured.observed_at_unix_ms(), None); + assert_eq!(captured.digest(), issued.evidence.digest()); + issued.fixture.clock.now.store(160, Ordering::SeqCst); + let snapshot = issued + .store + .operation_snapshot( + issued.binding.clone(), + issued.evidence.operation_id(), + Some(issued.evidence.command_digest()), + copy(&issued.proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + snapshot.prepared().issuance_window(), + issued.attempt.bound_plan().prepared().issuance_window() + ); + assert!(snapshot.installation().is_none()); + assert!(snapshot.delivery_attempts().is_empty()); + let retained = issued + .store + .obtained_evidence( + selection( + &issued.binding, + issued.attempt.bound_plan().prepared(), + *issued.attempt.bound_plan().plan().digest(), + issued.attempt.seal().recipient(), + ), + copy(&issued.proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.evidence().raw_json(), original); + assert_eq!(retained.evidence().observed_at_unix_ms(), None); + issued.assert_same_writer().await; + database.close().await.unwrap(); + issued.store.close().await.unwrap(); +} diff --git a/crates/radroots/tests/support/receipt_workflow.rs b/crates/radroots/tests/support/receipt_workflow.rs @@ -0,0 +1,283 @@ +use super::*; +use futures::{SinkExt, StreamExt}; +use nostr::JsonUtil; +use radroots::{Client, NativeConfig, StartMode, inbox::InquireInput}; +use radroots_domain::ThreadId; +use radroots_nostr::{ + key::parse_secret_key, + signing::{LocalSigner, OsNonceSource}, +}; +use radroots_signing::{ + Signer, + provider::{ParticipantProvider, ProviderError, SignerCallbacks, SignerHandle}, + signer::BoxFuture, +}; +use radroots_storage::event::SourceGeneration; +use radroots_storage::workspace::WorkspaceStore; +use radroots_storage_sqlite::{OpenMode, OpenOptions, Paths}; +use radroots_transport::policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}; +use radroots_transport_nostr::{ + Config, RelayAccess, RelayEndpoint, RelayProfile, RelayProfileKind, RelayUrlPolicy, +}; +use tokio::{ + net::TcpListener, + sync::{mpsc as channel, oneshot}, + task::JoinSet, +}; +use tokio_tungstenite::{accept_async, tungstenite::Message}; + +#[path = "receipt_workflow_faults.rs"] +mod faults; + +struct Callbacks; +impl SignerCallbacks for Callbacks { + fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> { + Box::pin(async { Ok(()) }) + } + fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> { + Box::pin(async { Ok(()) }) + } +} +fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() +} +fn route_key(last: u8) -> nostr::Keys { + let mut bytes = [0; 32]; + bytes[31] = last; + nostr::Keys::new(nostr::SecretKey::from_slice(&bytes).unwrap()) +} +fn advertisement(last: u8, url: &str) -> String { + let keys = route_key(last); + nostr::UnsignedEvent { + id: None, + pubkey: keys.public_key(), + created_at: nostr::Timestamp::from_secs(now() - 1), + kind: nostr::Kind::Custom(10050), + tags: nostr::Tags::from_list(vec![ + nostr::Tag::parse(["relay", url]).unwrap(), + nostr::Tag::parse(["client", "ordinary-test"]).unwrap(), + ]), + content: String::new(), + } + .sign_with_keys(&keys) + .unwrap() + .as_json() +} +struct Relay { + url: String, + events: channel::UnboundedReceiver<String>, + count: Arc<AtomicU64>, + accepting: Arc<AtomicBool>, + stop: oneshot::Sender<()>, + task: tokio::task::JoinHandle<()>, +} +impl Relay { + async fn new() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let sources = Arc::new([advertisement(1, &url), advertisement(2, &url)]); + let count = Arc::new(AtomicU64::new(0)); + let counter = count.clone(); + let accepting = Arc::new(AtomicBool::new(true)); + let acceptance = accepting.clone(); + let (send, events) = channel::unbounded_channel(); + let (stop, mut stopping) = oneshot::channel(); + let task = tokio::spawn(async move { + let mut clients = JoinSet::new(); + loop { + tokio::select! { + _ = &mut stopping => break, + accepted = listener.accept() => { + let (tcp, _) = accepted.unwrap(); + let sources = sources.clone(); let send = send.clone(); let count = counter.clone(); let acceptance = acceptance.clone(); + clients.spawn(async move { + let mut socket = accept_async(tcp).await.unwrap(); + while let Some(Ok(message)) = socket.next().await { + let Message::Text(raw) = message else {continue}; + let value: serde_json::Value = serde_json::from_str(&raw).unwrap(); + match value[0].as_str().unwrap() { + "REQ" => { + let author = value[2]["authors"][0].as_str().unwrap(); + for source in sources.iter() { + let event: serde_json::Value = serde_json::from_str(source).unwrap(); + if event["pubkey"].as_str() == Some(author) { + socket.send(Message::Text(format!("[\"EVENT\",{}, {} ]", value[1], source).into())).await.unwrap(); + } + } + socket.send(Message::Text(json!(["EOSE", value[1]]).to_string().into())).await.unwrap(); + } + "EVENT" => { + let event = raw.strip_prefix("[\"EVENT\",").and_then(|raw| raw.strip_suffix(']')).unwrap().to_owned(); + nostr::Event::from_json(&event).unwrap().verify().unwrap(); + count.fetch_add(1, Ordering::SeqCst); + send.send(event).unwrap(); + socket.send(Message::Text(json!(["OK", value[1]["id"], acceptance.load(Ordering::SeqCst), ""]).to_string().into())).await.unwrap(); + } + "CLOSE" => {}, + other => panic!("unexpected relay command {other}"), + } + } + }); + } + } + } + clients.shutdown().await; + }); + Self { + url, + events, + count, + accepting, + stop, + task, + } + } + fn config(&self) -> Config { + Config::from_profile( + RelayProfile::explicit( + RelayProfileKind::Simulator, + [ + RelayEndpoint::new(&self.url, RelayUrlPolicy::Local, RelayAccess::ReadWrite) + .unwrap(), + ], + ) + .unwrap(), + ) + .with_timeouts(2_000, 2_000, 2_000) + .unwrap() + } +} + +#[tokio::test] +async fn ordinary_online_inquiry_runs_t0_t1_sign_install_and_exact_peer_self_delivery_then_reopens() +{ + let mut relay = Relay::new().await; + let fixture = Fixture::new(); + fixture.clock.live.store(true, Ordering::SeqCst); + let (store, input, proof, _) = fixture.create_with_expiry(now() + 600).await; + let cache = fixture.path.parent().unwrap().join("ordinary-cache"); + std::fs::create_dir(&cache).unwrap(); + let options = OpenOptions::new(Paths::from_directory(cache).unwrap(), OpenMode::Create) + .with_source_generation(SourceGeneration::new([18; 32]).unwrap(), 1) + .unwrap(); + let policy = SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()); + let client = Client::open( + NativeConfig::public_read(options) + .with_workspace(store.as_ref().clone()) + .with_nostr(relay.config(), policy) + .unwrap(), + ) + .await + .unwrap(); + let scope = client.attach(input.clone(), copy(&proof)).await.unwrap(); + let signer = LocalSigner::new( + parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001") + .unwrap(), + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)); + client + .attach_signer(SignerHandle::new(Arc::new(signer), Arc::new(Callbacks))) + .await + .unwrap(); + client.start(StartMode::Online).await.unwrap(); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + let operation = OperationId::from_bytes([201; 32]); + let not_after = now() + 120; + let context = || { + scope + .command_context_with_correlation( + operation, + None, + None, + UnixSeconds::new(not_after).unwrap(), + Some(CorrelationId::new("ordinary-online").unwrap()), + ) + .unwrap() + }; + let inquire = || { + InquireInput::new( + ThreadId::from_bytes([33; 32]), + PublicKey::from_bytes(route_key(2).public_key().to_bytes()).unwrap(), + None, + "ordinary complete inquiry", + ) + .unwrap() + }; + let receipt = client.inbox().inquire(context(), inquire()).await.unwrap(); + assert!(receipt.durable()); + assert!(receipt.business_result().is_some(), "{receipt:?}"); + assert_eq!(relay.count.load(Ordering::SeqCst), 2); + let mut recipients = Vec::new(); + for _ in 0..2 { + let raw = tokio::time::timeout(Duration::from_secs(5), relay.events.recv()) + .await + .unwrap() + .unwrap(); + let outer = nostr::Event::from_json(raw).unwrap(); + let target = outer + .tags + .iter() + .find(|tag| tag.as_slice()[0] == "p") + .unwrap() + .as_slice()[1] + .clone(); + let key = if target == route_key(1).public_key().to_hex() { + 1 + } else { + 2 + }; + let message = nostr::nips::nip59::extract_rumor(&route_key(key), &outer) + .await + .unwrap(); + assert_eq!(message.sender, route_key(1).public_key()); + assert_eq!(message.rumor.content, "ordinary complete inquiry"); + assert_eq!( + message.rumor.id.unwrap().as_bytes(), + receipt.business_result().unwrap().id().as_bytes() + ); + recipients.push(key); + } + recipients.sort_unstable(); + assert_eq!(recipients, [1, 2]); + let snapshot = store + .operation_snapshot(scope.binding().clone(), operation, None, copy(&proof)) + .await + .unwrap() + .unwrap(); + assert!( + snapshot + .recipients() + .iter() + .all(|recipient| recipient.obtained().is_some()) + ); + assert_eq!(snapshot.publications().len(), 2); + assert_eq!(snapshot.delivery_attempts().len(), 2); + assert!( + snapshot + .publications() + .iter() + .all(|work| snapshot.publication_accepted(*work).unwrap()) + ); + let original = receipt.operation_checkpoint(); + let replay = client.inbox().inquire(context(), inquire()).await.unwrap(); + assert_eq!(replay.operation_checkpoint(), original); + assert_eq!(relay.count.load(Ordering::SeqCst), 2); + client.close().await.unwrap(); + let reopened = fixture.reopen(input).await; + let snapshot = reopened + .operation_snapshot(scope.binding().clone(), operation, None, copy(&proof)) + .await + .unwrap() + .unwrap(); + assert_eq!( + radroots_execution::OperationReceipt::from_snapshot(&snapshot).operation_checkpoint(), + original + ); + reopened.close_workspace().await.unwrap(); + relay.stop.send(()).unwrap(); + relay.task.await.unwrap(); +} diff --git a/crates/radroots/tests/support/receipt_workflow_faults.rs b/crates/radroots/tests/support/receipt_workflow_faults.rs @@ -0,0 +1,654 @@ +use super::*; +use radroots_execution::{Admission, Code, session::SessionState}; +use radroots_signing::{ + issuance::{SigningIntent, SigningOutcome}, + provider::{PrivateCiphertext, PrivateText, ProviderCall, ProviderState}, +}; + +type SigningPause = (oneshot::Sender<()>, oneshot::Receiver<()>); +#[derive(Clone, Copy, Default)] +enum CryptoFault { + #[default] + None, + EncryptionUnavailable, + DecryptionUnavailable, + WrongPlaintext, +} +struct RecordedSigner { + local: LocalSigner, + calls: AtomicU64, + uncertain: Option<PublicKey>, + pause: Mutex<Option<SigningPause>>, + crypto_fault: Mutex<CryptoFault>, + crypto_calls: AtomicU64, +} +impl RecordedSigner { + fn new(uncertain: Option<PublicKey>) -> Arc<Self> { + Arc::new(Self { + local: LocalSigner::new( + parse_secret_key( + "0000000000000000000000000000000000000000000000000000000000000001", + ) + .unwrap(), + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)), + calls: AtomicU64::new(0), + uncertain, + pause: Mutex::new(None), + crypto_fault: Mutex::new(CryptoFault::None), + crypto_calls: AtomicU64::new(0), + }) + } +} +impl Signer for RecordedSigner { + fn status( + &self, + ) -> BoxFuture<'_, Result<radroots_signing::SignerStatus, radroots_signing::Error>> { + self.local.status() + } + fn sign( + &self, + request: radroots_signing::SignRequest, + ) -> BoxFuture<'_, Result<radroots_signing::SignReceipt, radroots_signing::Error>> { + self.local.sign(request) + } +} +impl ParticipantProvider for RecordedSigner { + fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> { + Box::pin(async move { + use radroots_signing::provider::PrivateCryptoCapability::Unavailable; + let state = self.local.provider_state().await?; + let fault = *self.crypto_fault.lock().unwrap(); + let (encryption, decryption) = match fault { + CryptoFault::EncryptionUnavailable => (Unavailable, state.decryption()), + CryptoFault::DecryptionUnavailable => (state.encryption(), Unavailable), + CryptoFault::None | CryptoFault::WrongPlaintext => return Ok(state), + }; + Ok(ProviderState::new( + state.identity(), + encryption, + decryption, + state.signing_replay(), + ) + .with_exact_issuance(state.exact_issuance())) + }) + } + fn encrypt_private( + &self, + call: ProviderCall, + recipient: PublicKey, + text: PrivateText, + ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> { + self.crypto_calls.fetch_add(1, Ordering::SeqCst); + self.local.encrypt_private(call, recipient, text) + } + fn decrypt_private( + &self, + call: ProviderCall, + sender: PublicKey, + text: PrivateCiphertext, + ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> { + self.crypto_calls.fetch_add(1, Ordering::SeqCst); + Box::pin(async move { + let actual = self.local.decrypt_private(call, sender, text).await?; + if matches!( + *self.crypto_fault.lock().unwrap(), + CryptoFault::WrongPlaintext + ) { + PrivateText::new("injected post-decryption mismatch") + } else { + Ok(actual) + } + }) + } + fn sign_exact(&self, intent: SigningIntent) -> BoxFuture<'_, SigningOutcome> { + Box::pin(async move { + self.calls.fetch_add(1, Ordering::SeqCst); + if intent.recipient() == self.uncertain { + return SigningOutcome::unknown(intent.binding(), ProviderError::ProviderFailure); + } + let outcome = self.local.sign_exact(intent).await; + let pause = self.pause.lock().unwrap().take(); + if let Some((reached, resume)) = pause { + reached.send(()).unwrap(); + resume.await.unwrap(); + } + outcome + }) + } +} +struct Ready { + fixture: Fixture, + store: Arc<NativeWorkspace>, + client: Client, + scope: radroots::WorkspaceSession, + input: AttachmentInput, + proof: AttachmentProof, + signer: Arc<RecordedSigner>, +} +impl Ready { + async fn new(relay: &Relay, mode: StartMode, signer: Arc<RecordedSigner>) -> Self { + let fixture = Fixture::new(); + fixture.clock.live.store(true, Ordering::SeqCst); + let (store, input, proof, _) = fixture.create_with_expiry(now() + 600).await; + let cache = fixture.path.parent().unwrap().join("cache"); + std::fs::create_dir(&cache).unwrap(); + let options = OpenOptions::new(Paths::from_directory(cache).unwrap(), OpenMode::Create) + .with_source_generation(SourceGeneration::new([19; 32]).unwrap(), 1) + .unwrap(); + let client = Client::open( + NativeConfig::public_read(options) + .with_workspace(store.as_ref().clone()) + .with_nostr( + relay.config(), + SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), + ) + .unwrap(), + ) + .await + .unwrap(); + let scope = client.attach(input.clone(), copy(&proof)).await.unwrap(); + client + .attach_signer(SignerHandle::new(signer.clone(), Arc::new(Callbacks))) + .await + .unwrap(); + client.start(mode).await.unwrap(); + Self { + fixture, + store, + client, + scope, + input, + proof, + signer, + } + } + fn context(&self, id: u8, not_after: u64) -> radroots::CommandContext { + self.scope + .command_context_with_correlation( + OperationId::from_bytes([id; 32]), + None, + None, + UnixSeconds::new(not_after).unwrap(), + Some(CorrelationId::new("workflow-fault").unwrap()), + ) + .unwrap() + } + async fn snapshot(&self, id: u8) -> radroots_storage::command::OperationSnapshot { + self.store + .operation_snapshot( + self.scope.binding().clone(), + OperationId::from_bytes([id; 32]), + None, + copy(&self.proof), + ) + .await + .unwrap() + .unwrap() + } + async fn writer_is_retained(&self) { + assert!(matches!( + NativeWorkspace::open_existing( + &self.fixture.path, + self.input.clone(), + self.fixture.crypto(), + self.fixture.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + } +} +fn inquiry() -> InquireInput { + InquireInput::new( + ThreadId::from_bytes([34; 32]), + PublicKey::from_bytes(route_key(2).public_key().to_bytes()).unwrap(), + None, + "ordinary fault path", + ) + .unwrap() +} +async fn stop(relay: Relay) { + relay.stop.send(()).unwrap(); + relay.task.await.unwrap(); +} + +#[tokio::test] +async fn planning_refuses_wrong_participant_missing_private_methods_and_altered_decryption_before_t1() + { + let relay = Relay::new().await; + for (index, fault) in [ + CryptoFault::None, + CryptoFault::EncryptionUnavailable, + CryptoFault::DecryptionUnavailable, + CryptoFault::WrongPlaintext, + ] + .into_iter() + .enumerate() + { + let mut signer = RecordedSigner::new(None); + if index == 0 { + Arc::get_mut(&mut signer).unwrap().local = LocalSigner::new( + parse_secret_key( + "0000000000000000000000000000000000000000000000000000000000000002", + ) + .unwrap(), + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)); + } + *signer.crypto_fault.lock().unwrap() = fault; + let ready = Ready::new(&relay, StartMode::Online, signer).await; + let id = 210 + index as u8; + let error = ready + .client + .inbox() + .inquire(ready.context(id, now() + 120), inquiry()) + .await + .unwrap_err(); + assert_eq!(error.context().admission(), Admission::Confirmed); + assert_eq!( + error.code(), + if index == 3 { + Code::RecoveryRequired + } else { + Code::Unauthorized + } + ); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 0); + assert_eq!( + ready.signer.crypto_calls.load(Ordering::SeqCst), + if index == 3 { 2 } else { 0 } + ); + assert!(ready.snapshot(id).await.bound_plan().is_none()); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + ready.client.close().await.unwrap(); + } + stop(relay).await; +} + +#[tokio::test] +async fn explicit_resume_refuses_foreign_and_closed_attachments_before_read_or_dispatch() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, RecordedSigner::new(None)).await; + let foreign = Ready::new(&relay, StartMode::Online, RecordedSigner::new(None)).await; + let operation = OperationId::from_bytes([214; 32]); + let error = ready + .client + .operations(&foreign.scope) + .resume(operation, None) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Unauthorized); + assert_eq!(error.context().admission(), Admission::NotAdmitted); + ready.scope.close(); + let error = ready + .client + .operations(&ready.scope) + .resume(operation, None) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::CapabilityUnavailable); + assert_eq!(error.context().admission(), Admission::NotAdmitted); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + ready.client.close().await.unwrap(); + foreign.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn local_only_admits_without_crypto_network_or_mode_escalation() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::LocalOnly, RecordedSigner::new(None)).await; + let absent = ready + .client + .operations(&ready.scope) + .resume(OperationId::from_bytes([202; 32]), None) + .await + .unwrap_err(); + assert_eq!(absent.code(), Code::MissingHistory); + assert_eq!(absent.context().admission(), Admission::NotAdmitted); + let receipt = ready + .client + .inbox() + .inquire(ready.context(202, now() + 120), inquiry()) + .await + .unwrap(); + assert!(receipt.durable()); + assert!(receipt.business_result().is_none()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + assert!(ready.client.start(StartMode::Online).await.is_err()); + assert!( + ready + .client + .operations(&ready.scope) + .get(OperationId::from_bytes([202; 32])) + .await + .unwrap() + .is_some() + ); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn explicit_delivery_retry_after_first_issue_expiry_preserves_original_bytes_and_criterion() { + let mut relay = Relay::new().await; + relay.accepting.store(false, Ordering::SeqCst); + let ready = Ready::new(&relay, StartMode::Online, RecordedSigner::new(None)).await; + let not_after = now() + 10; + let first = ready + .client + .inbox() + .inquire(ready.context(203, not_after), inquiry()) + .await + .unwrap(); + assert!(first.business_result().is_some()); + let initial_count = relay.count.load(Ordering::SeqCst); + assert!((1..=2).contains(&initial_count)); + let snapshot = ready.snapshot(203).await; + assert!( + snapshot + .publications() + .iter() + .all(|work| !snapshot.publication_accepted(*work).unwrap()) + ); + let mut original = Vec::new(); + assert_eq!(snapshot.delivery_attempts().len(), 2); + for attempt in snapshot.delivery_attempts() { + let retained = ready + .store + .delivery_attempt( + ready.scope.binding().clone(), + OperationId::from_bytes([203; 32]), + first.command_digest(), + attempt.work().evidence().recipient(), + attempt.intent().request_id().clone(), + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + original.push(retained.raw_json().to_owned()); + } + while relay.events.try_recv().is_ok() {} + let replay = ready + .client + .inbox() + .inquire(ready.context(203, not_after), inquiry()) + .await + .unwrap(); + assert_eq!(replay.operation_checkpoint(), first.operation_checkpoint()); + assert_eq!(relay.count.load(Ordering::SeqCst), initial_count); + tokio::time::sleep(Duration::from_secs(not_after.saturating_sub(now()) + 1)).await; + relay.accepting.store(true, Ordering::SeqCst); + let resumed = ready + .client + .operations(&ready.scope) + .resume( + OperationId::from_bytes([203; 32]), + Some(first.command_digest()), + ) + .await + .unwrap(); + assert_eq!(resumed.issuance_window(), first.issuance_window()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2); + let mut retried = Vec::new(); + for _ in 0..2 { + retried.push(relay.events.recv().await.unwrap()); + } + retried.sort(); + original.sort(); + assert!( + retried == original, + "retry changed the exact original outer representation" + ); + let snapshot = ready.snapshot(203).await; + assert_eq!(snapshot.delivery_attempts().len(), 4); + assert!( + snapshot + .publications() + .iter() + .all(|work| snapshot.publication_accepted(*work).unwrap()) + ); + for work in snapshot.publications() { + let attempts: Vec<_> = snapshot + .delivery_attempts() + .iter() + .filter(|attempt| attempt.work() == *work) + .collect(); + assert_eq!( + attempts[0].intent().publication_policy_digest(), + attempts[1].intent().publication_policy_digest() + ); + assert_eq!(attempts[0].envelope_digest(), attempts[1].envelope_digest()); + } + ready + .client + .operations(&ready.scope) + .resume(OperationId::from_bytes([203; 32]), None) + .await + .unwrap(); + assert_eq!(relay.count.load(Ordering::SeqCst), initial_count + 2); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn uncertain_second_recipient_never_reissues_and_preserves_actual_first_copy_installation() { + let relay = Relay::new().await; + let uncertain = PublicKey::from_bytes(route_key(2).public_key().to_bytes()).unwrap(); + let ready = Ready::new( + &relay, + StartMode::Online, + RecordedSigner::new(Some(uncertain)), + ) + .await; + let first = ready + .client + .inbox() + .inquire(ready.context(204, now() + 120), inquiry()) + .await + .unwrap(); + assert!(first.business_result().is_some()); + let snapshot = ready.snapshot(204).await; + assert_eq!( + snapshot + .recipients() + .iter() + .filter(|recipient| recipient.obtained().is_some()) + .count(), + 1 + ); + assert_eq!(snapshot.publications().len(), 1); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + ready + .client + .operations(&ready.scope) + .resume(OperationId::from_bytes([204; 32]), None) + .await + .unwrap(); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn failed_obtained_capture_blocks_close_retains_writer_and_retries_without_signing_again() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, RecordedSigner::new(None)).await; + let mut db = ready.fixture.database().await; + sqlx::query("CREATE TRIGGER capture_insert_fault BEFORE INSERT ON seal_evidence BEGIN SELECT RAISE(ABORT, 'capture_insert_fault'); END").execute(&mut db).await.unwrap(); + let error = ready + .client + .inbox() + .inquire(ready.context(205, now() + 120), inquiry()) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::RecoveryRequired); + assert_eq!(error.context().admission(), Admission::Confirmed); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + let error = ready.client.close().await.unwrap_err(); + assert_eq!(error.code(), Code::RecoveryRequired); + assert_eq!(ready.client.state(), SessionState::Closing); + ready.writer_is_retained().await; + sqlx::query("DROP TRIGGER capture_insert_fault") + .execute(&mut db) + .await + .unwrap(); + db.close().await.unwrap(); + ready.client.close().await.unwrap(); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + let reopened = ready.fixture.reopen(ready.input).await; + let snapshot = reopened + .operation_snapshot( + ready.scope.binding().clone(), + OperationId::from_bytes([205; 32]), + None, + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!( + snapshot + .recipients() + .iter() + .filter(|recipient| recipient.obtained().is_some()) + .count(), + 1 + ); + reopened.close_workspace().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn explicit_resume_recovers_unknown_capture_under_same_writer_before_continuing_original() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, RecordedSigner::new(None)).await; + let mut db = ready.fixture.database().await; + sqlx::query("PRAGMA foreign_keys=ON") + .execute(&mut db) + .await + .unwrap(); + sqlx::query("CREATE TABLE capture_commit_fault (parent INTEGER REFERENCES workspace_grant(singleton) DEFERRABLE INITIALLY DEFERRED)").execute(&mut db).await.unwrap(); + sqlx::query("CREATE TRIGGER capture_commit_fault AFTER INSERT ON seal_evidence BEGIN INSERT INTO capture_commit_fault(parent) VALUES(2); END").execute(&mut db).await.unwrap(); + let error = ready + .client + .inbox() + .inquire(ready.context(207, now() + 120), inquiry()) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::RecoveryRequired); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert!( + ready + .store + .operation_snapshot( + ready.scope.binding().clone(), + OperationId::from_bytes([207; 32]), + None, + copy(&ready.proof) + ) + .await + .is_err() + ); + assert_eq!( + ready + .client + .operations(&ready.scope) + .resume(OperationId::from_bytes([207; 32]), None) + .await + .unwrap_err() + .code(), + Code::RecoveryRequired + ); + ready.writer_is_retained().await; + sqlx::query("DROP TRIGGER capture_commit_fault") + .execute(&mut db) + .await + .unwrap(); + sqlx::query("DROP TABLE capture_commit_fault") + .execute(&mut db) + .await + .unwrap(); + db.close().await.unwrap(); + let receipt = ready + .client + .operations(&ready.scope) + .resume(OperationId::from_bytes([207; 32]), None) + .await + .unwrap(); + assert!(receipt.business_result().is_some()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2); + let snapshot = ready.snapshot(207).await; + assert!( + snapshot + .recipients() + .iter() + .all(|recipient| recipient.obtained().is_some()) + ); + assert!( + snapshot + .publications() + .iter() + .all(|work| snapshot.publication_accepted(*work).unwrap()) + ); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn lost_observer_and_cancelled_close_preserve_actual_obtained_signature_until_capture() { + let relay = Relay::new().await; + let signer = RecordedSigner::new(None); + let (reached, produced) = oneshot::channel(); + let (resume, released) = oneshot::channel(); + *signer.pause.lock().unwrap() = Some((reached, released)); + let ready = Ready::new(&relay, StartMode::Online, signer).await; + let context = ready.context(206, now() + 120); + let client = ready.client.clone(); + let observer = tokio::spawn(async move { client.inbox().inquire(context, inquiry()).await }); + tokio::time::timeout(Duration::from_secs(5), produced) + .await + .unwrap() + .unwrap(); + observer.abort(); + assert!(observer.await.unwrap_err().is_cancelled()); + { + let mut close = Box::pin(ready.client.close()); + assert!(futures::poll!(&mut close).is_pending()); + } + assert_eq!(ready.client.state(), SessionState::Closing); + ready.writer_is_retained().await; + resume.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(5), ready.client.close()) + .await + .unwrap() + .unwrap(); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + let reopened = ready.fixture.reopen(ready.input).await; + let snapshot = reopened + .operation_snapshot( + ready.scope.binding().clone(), + OperationId::from_bytes([206; 32]), + None, + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert!( + snapshot + .recipients() + .iter() + .any(|recipient| recipient.obtained().is_some()) + ); + reopened.close_workspace().await.unwrap(); + stop(relay).await; +} diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -13,6 +13,7 @@ use radroots_transport::BoxFuture; mod delivery; mod delivery_summary; +mod dm_source; mod installation; mod issuance; mod observation; @@ -22,6 +23,7 @@ pub use delivery::{ EnvelopeCandidate, }; pub use delivery_summary::DeliveryAttemptSummary; +pub use dm_source::SignedDmRelaySource; pub use installation::{ ChatInstallation, InstallationOutcome, InstallationRequest, PublicationWork, }; @@ -272,6 +274,19 @@ impl fmt::Debug for AdmissionOutcome { /// Typed transaction port, implemented by actual shared storage adapters. /// Applications do not implement a second orchestration or stock engine here. pub trait OperationJournal: WorkspaceStore { + /// Reconciles a failed/unknown capture of already obtained original seal + /// bytes. A qualified host must retain its namespace/writer identity, + /// verify the existing schema and original claim, and confirm capture before + /// clearing uncertainty. This grants no fresh issuance or replacement + /// authority. The current profile covers obtained chat evidence only. + fn reconcile_unknown<'a>( + &'a self, + _input: crate::workspace::AttachmentInput, + _proof: &'a AttachmentProof, + _evidence: &'a SealEvidence, + ) -> BoxFuture<'a, Result<EvidenceCaptureOutcome, OperationError>> { + Box::pin(async { Err(OperationError::RecoveryRequired) }) + } /// Appends obtained target evidence against the actual original retained /// attempt. Original credential authentication is required; late capture /// does not acquire a fresh lease, deadline, grant or dispatch permission. diff --git a/crates/storage/src/command/dm_source.rs b/crates/storage/src/command/dm_source.rs @@ -0,0 +1,125 @@ +//! Shared authentication of original signed DM route sources. +use super::OperationError; +use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds}; +use radroots_event::{ + SignedEvent, + wire::{EventWireLimits, Nip01EventWire}, +}; +use radroots_event_codec::verify::{self, Nip01SignatureVerifier, RawEvent}; +use radroots_protocol::chat::CapturedDmRoute; +use radroots_transport::target::EndpointUri; +use std::fmt; + +/// Authenticated kind-10050 source with its exact original representation. +/// This proves neither current access, target approval, availability nor a +/// dispatch right. Selected targets require their independent host policy. +pub struct SignedDmRelaySource { + event: SignedEvent, + participant: PublicKey, + event_id: EnvelopeEventId, + created_at: UnixSeconds, +} +impl SignedDmRelaySource { + /// Bounds and verifies the actual NIP-01 ID/signature before exposing + /// source fields. Additional signed non-relay tags remain intact. + pub fn verify(raw: &str) -> Result<Self, OperationError> { + let invalid = |_| OperationError::InvalidEvidence; + let limits = EventWireLimits { + max_raw_json_bytes: 65536, + max_tag_element_bytes: 32768, + max_total_tag_bytes: 65536, + max_extra_fields: 0, + max_total_extra_json_bytes: 0, + ..Default::default() + }; + let wire = Nip01EventWire::parse_json_exact_with_limits(raw, limits).map_err(invalid)?; + let participant = + PublicKey::from_hex(&wire.pubkey).map_err(|_| OperationError::InvalidEvidence)?; + let event_id = wire + .id + .parse() + .map_err(|_| OperationError::InvalidEvidence)?; + if wire.kind != 10050 + || wire.pubkey != participant.to_hex() + || wire.created_at == 0 + || wire.created_at > 253_402_300_799 + { + return Err(OperationError::InvalidEvidence); + } + for tag in &wire.tags { + if tag.first().is_some_and(|v| v == "relay") && (tag.len() != 2 || tag[1].len() > 2048) + { + return Err(OperationError::InvalidEvidence); + } + } + let created_at = + UnixSeconds::new(wire.created_at).map_err(|_| OperationError::InvalidEvidence)?; + let event = SignedEvent::from_wire_verified_id(wire, raw) + .map_err(|_| OperationError::InvalidEvidence)?; + let checked = verify::id(RawEvent::new(event.envelope().clone())) + .map_err(|_| OperationError::InvalidEvidence)?; + verify::signature(checked, &Nip01SignatureVerifier) + .map_err(|_| OperationError::InvalidEvidence)?; + Ok(Self { + event, + participant, + event_id, + created_at, + }) + } + /// Actual signed author, without workspace or route authority. + pub const fn participant(&self) -> PublicKey { + self.participant + } + /// Actual signed event identity, separate from a logical chat message. + pub const fn event_id(&self) -> EnvelopeEventId { + self.event_id + } + /// Author-claimed time; it is not an independent clock observation. + pub const fn created_at(&self) -> UnixSeconds { + self.created_at + } + /// Exact original signed source bytes. + pub fn raw_json(&self) -> &str { + self.event.raw_json() + } + /// Original relay-tag strings. Only actual transport matching/policy may + /// select an active endpoint; unrelated signed tags authorize none. + pub fn relay_uris(&self) -> impl Iterator<Item = &str> { + self.event + .wire() + .tags + .iter() + .filter(|tag| tag.first().is_some_and(|value| value == "relay") && tag.len() == 2) + .map(|tag| tag[1].as_str()) + } + /// Checks a retained exact capture against its actual signed source. This + /// does not approve another target or weaken the original target policy. + pub fn validate_capture(&self, route: &CapturedDmRoute) -> Result<(), OperationError> { + if route.participant() != self.participant + || route.source_id() != self.event_id + || route.raw_json() != self.raw_json() + { + return Err(OperationError::InvalidEvidence); + } + if route.selected_relays().is_empty() { + return Err(OperationError::InvalidCommand); + } + for selected in route.selected_relays() { + if !self.relay_uris().any(|value| value == selected.as_ref()) { + return Err(OperationError::UnverifiedApproval); + } + let endpoint = EndpointUri::parse(selected.as_ref()) + .map_err(|_| OperationError::InvalidCommand)?; + if endpoint.as_str().len() > 2048 { + return Err(OperationError::InvalidCommand); + } + } + Ok(()) + } +} +impl fmt::Debug for SignedDmRelaySource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SignedDmRelaySource(<redacted>)") + } +} diff --git a/crates/storage_sqlite/src/workspace/delivery/graph.rs b/crates/storage_sqlite/src/workspace/delivery/graph.rs @@ -6,15 +6,9 @@ use super::{ codec::{self, Fact}, }; use radroots_domain::{OperationId, PublicKey}; -use radroots_event::{ - SignedEvent, - wire::{EventWireLimits, Nip01EventWire}, -}; -use radroots_event_codec::verify::{self, Nip01SignatureVerifier, RawEvent}; use radroots_storage::command::{ - BoundSigningPlan, DeliveryAttempt, DeliveryIntent, OperationError, + BoundSigningPlan, DeliveryAttempt, DeliveryIntent, OperationError, SignedDmRelaySource, }; -use radroots_transport::target::EndpointUri; use sqlx::{Row, SqliteConnection}; use std::collections::{BTreeMap, BTreeSet}; @@ -51,52 +45,13 @@ fn allowed_routes( .iter() .filter(|route| route.participant() == recipient) { - let limits = EventWireLimits { - max_raw_json_bytes: 65536, - max_tag_element_bytes: 32768, - max_total_tag_bytes: 65536, - max_extra_fields: 0, - max_total_extra_json_bytes: 0, - ..Default::default() - }; - let wire = Nip01EventWire::parse_json_exact_with_limits(route.raw_json(), limits) - .map_err(|_| OperationError::InvalidEvidence)?; - if wire.kind != 10050 - || wire.pubkey != route.participant().to_hex() - || wire.id != route.source_id().to_string() - || wire.created_at == 0 - || wire.created_at > 253_402_300_799 - { - return Err(OperationError::InvalidEvidence); - } - for tag in &wire.tags { - if tag.first().is_some_and(|v| v == "relay") && (tag.len() != 2 || tag[1].len() > 2048) - { - return Err(OperationError::InvalidEvidence); - } - } - let mut selected = BTreeSet::new(); - for target in route.selected_relays() { - if !wire - .tags - .iter() - .any(|tag| tag.len() == 2 && tag[0] == "relay" && tag[1] == target.as_ref()) - { - return Err(OperationError::UnverifiedApproval); - } - let endpoint = - EndpointUri::parse(target.as_ref()).map_err(|_| OperationError::InvalidCommand)?; - if endpoint.as_str().len() > 2048 { - return Err(OperationError::InvalidCommand); - } - selected.insert(target.as_ref().to_owned()); - } - let event = SignedEvent::from_wire_verified_id(wire, route.raw_json()) - .map_err(|_| OperationError::InvalidEvidence)?; - let checked = verify::id(RawEvent::new(event.envelope().clone())) - .map_err(|_| OperationError::InvalidEvidence)?; - verify::signature(checked, &Nip01SignatureVerifier) - .map_err(|_| OperationError::InvalidEvidence)?; + let source = SignedDmRelaySource::verify(route.raw_json())?; + source.validate_capture(route)?; + let selected = route + .selected_relays() + .iter() + .map(|target| target.as_ref().to_owned()) + .collect::<BTreeSet<_>>(); if selected.is_empty() || result.insert(route.participant(), selected).is_some() { return Err(OperationError::InvalidCommand); } diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -16,6 +16,7 @@ mod issuance; mod operation; mod plan; mod record; +mod recovery; mod snapshot; mod worker; @@ -220,6 +221,20 @@ impl WorkspaceStore for NativeWorkspace { } } impl radroots_storage::command::OperationJournal for NativeWorkspace { + fn reconcile_unknown<'a>( + &'a self, + input: AttachmentInput, + proof: &'a AttachmentProof, + evidence: &'a radroots_storage::command::SealEvidence, + ) -> BoxFuture< + 'a, + Result< + radroots_storage::command::EvidenceCaptureOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.reconcile_unknown(input, proof, evidence)) + } fn record_delivery_observation( &self, binding: WorkspaceBinding, diff --git a/crates/storage_sqlite/src/workspace/recovery.rs b/crates/storage_sqlite/src/workspace/recovery.rs @@ -0,0 +1,126 @@ +//! Original obtained-evidence recovery on the same namespace owner. +use super::{ + AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceCrypto, admission::Journal, + fs::Namespace, record::GrantRecord, worker, +}; +use radroots_storage::command::{EvidenceCaptureOutcome, OperationError, SealEvidence}; +use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions}; + +pub(super) struct RecoveryAuthorization { + grant: GrantRecord, + close_confirmed: bool, +} +pub(super) struct RecoveryTurn<'a> { + pub connection: &'a mut Option<SqliteConnection>, + pub cached_grant: &'a mut Option<RecoveryAuthorization>, + pub namespace: &'a Namespace, + pub selected: &'a AttachmentInput, + pub crypto: &'a WorkspaceCrypto, + pub clock: &'a dyn WorkspaceClock, + pub uncertain: &'a mut bool, + pub options: &'a SqliteConnectOptions, +} +impl RecoveryTurn<'_> { + pub(super) async fn capture( + &mut self, + input: AttachmentInput, + proof: AttachmentProof, + evidence: SealEvidence, + ) -> Result<EvidenceCaptureOutcome, OperationError> { + if input != *self.selected { + return Err(OperationError::Unauthorized); + } + if !*self.uncertain { + let connection = self + .connection + .as_mut() + .ok_or(OperationError::RecoveryRequired)?; + return Journal { + connection, + namespace: self.namespace, + selected: self.selected, + crypto: self.crypto, + clock: self.clock, + uncertain: self.uncertain, + } + .capture_issuance(input, proof, evidence) + .await; + } + + self.namespace.validate()?; + // Authenticate original capture ownership before disposing any existing + // connection. No current lease, clock or fresh command grant is acquired. + if let Some(connection) = self.connection.as_mut() { + let protected = worker::read(connection, self.selected).await?; + let plaintext = self + .crypto + .open( + self.selected.workspace_id(), + self.selected.grant_id(), + &protected, + ) + .await?; + let record = plaintext.expose_secret(GrantRecord::decode)?; + record.authenticate_retained_capture(&input, &proof)?; + *self.cached_grant = Some(RecoveryAuthorization { + grant: record, + close_confirmed: false, + }); + } else { + let cached = self + .cached_grant + .as_ref() + .ok_or(OperationError::RecoveryRequired)?; + cached.grant.authenticate_retained_capture(&input, &proof)?; + if !cached.close_confirmed { + return Err(OperationError::RecoveryRequired); + } + } + + // Namespace authority stays owned throughout the close, read-only + // preflight and replacement connection. Missing/foreign schemas are + // refused; there is no initialization, migration or restored dispatch. + if let Some(connection) = self.connection.take() { + connection + .close() + .await + .map_err(|_| OperationError::RecoveryRequired)?; + self.cached_grant + .as_mut() + .ok_or(OperationError::RecoveryRequired)? + .close_confirmed = true; + } + worker::preflight_existing(self.namespace, self.selected, self.crypto).await?; + let connection = SqliteConnection::connect_with(self.options) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + *self.connection = Some(connection); + self.cached_grant + .as_mut() + .ok_or(OperationError::RecoveryRequired)? + .close_confirmed = false; + let connection = self + .connection + .as_mut() + .ok_or(OperationError::RecoveryRequired)?; + // A failed validation retains this replacement connection. Its close + // must be confirmed by the same owner before any subsequent replacement. + worker::initialize(connection, self.namespace, self.selected, None, self.crypto).await?; + let mut capture_uncertain = false; + let result = Journal { + connection, + namespace: self.namespace, + selected: self.selected, + crypto: self.crypto, + clock: self.clock, + uncertain: &mut capture_uncertain, + } + .capture_issuance(input, proof, evidence) + .await; + if matches!(&result, Ok(EvidenceCaptureOutcome::Committed(_))) { + *self.uncertain = false; + self.cached_grant.take(); + } + result + } +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -94,6 +94,12 @@ enum Job { Box<SealEvidence>, Reply<EvidenceCaptureOutcome, OperationError>, ), + RecoverCapture( + Box<AttachmentInput>, + AttachmentProof, + Box<SealEvidence>, + Reply<EvidenceCaptureOutcome, OperationError>, + ), Captured( Box<ClaimAttemptRequest>, AttachmentProof, @@ -127,6 +133,60 @@ enum Job { Reply<Option<PreparedOperation>, OperationError>, ), } +impl Job { + fn reject_recovery(self) { + match self { + Self::CaptureDeliveryObservation(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::QueryDeliveryObservations(_, _, _, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::PrepareDelivery(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::QueryDelivery(_, _, _, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Install(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Snapshot(_, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Claim(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Attempt(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Capture(_, _, _, reply) | Self::RecoverCapture(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Captured(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::BindPlan(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::SigningPlan(_, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Authenticate(_, _, reply) => { + let _ = reply.send(Err(WorkspaceError::RecoveryRequired)); + } + Self::Revoke(_, _, reply) => { + let _ = reply.send(Err(WorkspaceError::RecoveryRequired)); + } + Self::Admit(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::Operation(_, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + } + } +} struct Budget { used: Arc<AtomicUsize>, bytes: usize, @@ -214,9 +274,35 @@ impl Handle { return Err(error); } let mut uncertain = false; + let mut cached_grant = None; + let mut connection = Some(connection); if ready.send(Ok(())).is_ok() { while let Ok(Queued { job, _budget }) = requests.recv() { + let job = match job { + Job::RecoverCapture(selected, proof, evidence, reply) => { + let result = super::recovery::RecoveryTurn { + connection: &mut connection, + cached_grant: &mut cached_grant, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + options: &options, + } + .capture(*selected, proof, *evidence) + .await; + let _ = reply.send(result); + continue; + } + job => job, + }; + let Some(connection) = connection.as_mut() else { + job.reject_recovery(); + continue; + }; match job { + job @ Job::RecoverCapture(..) => job.reject_recovery(), Job::CaptureDeliveryObservation( binding, proof, @@ -224,7 +310,7 @@ impl Handle { reply, ) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -245,7 +331,7 @@ impl Handle { reply, ) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -260,7 +346,7 @@ impl Handle { } Job::PrepareDelivery(request, proof, candidate, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -285,7 +371,7 @@ impl Handle { reply, ) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -300,7 +386,7 @@ impl Handle { } Job::Install(request, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -313,7 +399,7 @@ impl Handle { } Job::Snapshot(binding, operation, digest, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -326,7 +412,7 @@ impl Handle { } Job::Claim(request, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -339,7 +425,7 @@ impl Handle { } Job::Attempt(request, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -352,7 +438,7 @@ impl Handle { } Job::Capture(selected, proof, evidence, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -365,7 +451,7 @@ impl Handle { } Job::Captured(request, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -378,7 +464,7 @@ impl Handle { } Job::BindPlan(binding, plan, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -391,7 +477,7 @@ impl Handle { } Job::SigningPlan(binding, operation_id, digest, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -404,7 +490,7 @@ impl Handle { } Job::Authenticate(selected, proof, reply) => { let result = authenticate( - &mut connection, + connection, &namespace, &input, &crypto, @@ -418,7 +504,7 @@ impl Handle { } Job::Revoke(selected, proof, reply) => { let result = revoke( - &mut connection, + connection, &namespace, &input, &crypto, @@ -431,7 +517,7 @@ impl Handle { } Job::Admit(request, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -444,7 +530,7 @@ impl Handle { } Job::Operation(binding, operation_id, digest, proof, reply) => { let result = Journal { - connection: &mut connection, + connection, namespace: &namespace, selected: &input, crypto: &crypto, @@ -459,6 +545,9 @@ impl Handle { } } // The admission sender is gone. All admitted work has drained. + let Some(mut connection) = connection else { + return Err(WorkspaceError::RecoveryRequired); + }; let checkpoint = sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)") .fetch_one(&mut connection) .await; @@ -499,7 +588,7 @@ impl Handle { Job::CaptureDeliveryObservation(..) => 96 * 1024, Job::PrepareDelivery(..) => 1024 * 1024, Job::BindPlan(..) => 1024 * 1024, - Job::Capture(..) => 256 * 1024, + Job::Capture(..) | Job::RecoverCapture(..) => 256 * 1024, Job::Admit(..) => 96 * 1024, _ => 16 * 1024, }; @@ -687,6 +776,30 @@ impl Handle { Err(_) => Ok(EvidenceCaptureOutcome::Unknown(anchor)), } } + pub(super) async fn reconcile_unknown( + &self, + input: AttachmentInput, + proof: &AttachmentProof, + evidence: &SealEvidence, + ) -> Result<EvidenceCaptureOutcome, OperationError> { + let anchor = CommitAttempt::new( + evidence.workspace_id(), + evidence.operation_id(), + evidence.command_digest(), + None, + ); + let copied = proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?; + let (reply, result) = oneshot::channel(); + self.send(Job::RecoverCapture( + Box::new(input), + copied, + Box::new(evidence.retained_copy()), + reply, + ))?; + result + .await + .unwrap_or(Ok(EvidenceCaptureOutcome::Unknown(anchor))) + } pub(super) async fn obtained_evidence( &self, request: ClaimAttemptRequest, @@ -814,7 +927,7 @@ impl Handle { } } -async fn preflight_existing( +pub(super) async fn preflight_existing( namespace: &Namespace, expected: &AttachmentInput, crypto: &WorkspaceCrypto, @@ -838,7 +951,7 @@ async fn preflight_existing( inspected.and(closed) } -async fn initialize( +pub(super) async fn initialize( connection: &mut SqliteConnection, namespace: &Namespace, expected: &AttachmentInput,