lib

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

commit e62b84c2e03950176fdf0cd2694fc183dc453ea6
parent c95bfcdbd73c08dd3581b2c718862158314a50fc
Author: triesap <tyson@radroots.org>
Date:   Tue, 20 Oct 2026 22:41:36 +0000

execution: publish native listings through the shared command owner

- Return validated listings and scoped operation status without private placeholders.
- Share native and browser command ownership while preserving exact artifacts.
- Refuse inconsistent public snapshots and protected record projections.
- Verify real native faults, unchanged browser artifacts, APIs and coverage gates.

Diffstat:
Mcontracts/api_baselines/radroots.txt | 17++++++++++++++---
Mcontracts/api_baselines/radroots_domain.txt | 21+++++++++++++++++++++
Mcontracts/api_baselines/radroots_execution.txt | 61++++++++++++++++++++++++++++++++++++++++---------------------
Mcontracts/api_baselines/radroots_protocol.txt | 1+
Mcontracts/coverage-profiles.toml | 3++-
Mcrates/domain/src/listing.rs | 6++++++
Acrates/domain/src/listing/view.rs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/tests/listing.rs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/Cargo.toml | 2+-
Mcrates/execution/README.md | 22++++++++++++++--------
Mcrates/execution/src/lib.rs | 3++-
Mcrates/execution/src/receipt.rs | 190+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcrates/execution/src/session/client.rs | 10+++++-----
Mcrates/execution/src/session/client_commands.rs | 96++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Acrates/execution/src/session/command.rs | 678+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dcrates/execution/src/session/inquiry.rs | 592-------------------------------------------------------------------------------
Mcrates/execution/src/session/mod.rs | 2+-
Mcrates/protocol/src/listing.rs | 39+++++++++++++++------------------------
Mcrates/protocol/tests/package_boundary.rs | 9++++++++-
Mcrates/protocol/tests/public_command.rs | 37+++++++++++++++++++++++++++++++++++++
Mcrates/radroots/Cargo.toml | 4++--
Mcrates/radroots/README.md | 35+++++++++++++++++++++++++++--------
Mcrates/radroots/src/client.rs | 56++++++++++++++++++++++++++++++--------------------------
Mcrates/radroots/src/lib.rs | 6++++--
Acrates/radroots/src/listings.rs | 26++++++++++++++++++++++++++
Acrates/radroots/src/native_commands.rs | 344+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dcrates/radroots/src/native_inquiry.rs | 338-------------------------------------------------------------------------------
Mcrates/radroots/src/operations.rs | 16++++++++--------
Mcrates/radroots/tests/package_boundary.rs | 3++-
Mcrates/radroots/tests/support/receipt_delivery.rs | 12++++++++++--
Mcrates/radroots/tests/support/receipt_delivery_faults.rs | 10+++++++---
Mcrates/radroots/tests/support/receipt_installation.rs | 7++++---
Acrates/radroots/tests/support/receipt_public_snapshots.rs | 676+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/tests/support/receipt_snapshots.rs | 27++++++++++++++++++---------
Mcrates/radroots/tests/support/receipt_workflow.rs | 16++++++++++++++--
Acrates/radroots/tests/support/receipt_workflow_listing.rs | 816+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots_browser/src/client.rs | 51+++++++++++++++++++++++++++------------------------
Acrates/radroots_browser/src/commands.rs | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dcrates/radroots_browser/src/inquiry.rs | 204-------------------------------------------------------------------------------
Mcrates/radroots_browser/src/lib.rs | 6+++---
Mcrates/radroots_browser/tests/browser/src/lib.rs | 7++++++-
Mcrates/storage/src/command/snapshot.rs | 10++++------
Mcrates/storage_sqlite/src/workspace/tests/issuance_records.rs | 3+++
Acrates/storage_sqlite/src/workspace/tests/public_delivery_records.rs | 418+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
44 files changed, 3909 insertions(+), 1344 deletions(-)

diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -9,7 +9,10 @@ pub use radroots::DeliveryObservation pub use radroots::Error pub use radroots::Issuance pub use radroots::OperationId +pub use radroots::OperationKind pub use radroots::OperationReceipt +pub use radroots::OperationStatus +pub use radroots::OperationValue pub use radroots::RecoveryRequirement pub use radroots::Result pub use radroots::StartMode @@ -24,6 +27,7 @@ pub async fn radroots::client::Client::attach(&self, radroots_storage::workspace pub async fn radroots::client::Client::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::signer::SignerSession> pub async fn radroots::client::Client::close(&self) -> radroots_execution::Result<radroots::client::CloseReceipt> pub const fn radroots::client::Client::inbox(&self) -> radroots::inbox::Inbox<'_> +pub const fn radroots::client::Client::listings(&self) -> radroots::listings::Listings<'_> pub async fn radroots::client::Client::open(radroots::client::NativeConfig) -> radroots_execution::Result<Self> pub fn radroots::client::Client::operations(&self, &radroots_execution::workspace::WorkspaceSession) -> radroots::operations::Operations<'_> pub fn radroots::client::Client::preview() -> Self @@ -123,12 +127,18 @@ pub use radroots::listing::PrepareError pub use radroots::listing::PrepareErrorKind pub use radroots::listing::PrepareRequest pub use radroots::listing::prepare +pub mod radroots::listings +pub use radroots::listings::Listing +pub use radroots::listings::PublishInput +pub struct radroots::listings::Listings<'a> +impl<'a> radroots::listings::Listings<'a> +pub async fn radroots::listings::Listings<'a>::publish(&self, radroots_execution::workspace::CommandContext, radroots_protocol::listing::PublishInput) -> radroots_execution::Result<radroots_execution::receipt::OperationReceipt<radroots_domain::listing::view::Listing>> pub mod radroots::operations 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 async fn radroots::operations::Operations<'a>::get(&self, radroots_domain::identifier::OperationId) -> radroots_execution::Result<core::option::Option<radroots_execution::receipt::OperationStatus>> +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::OperationStatus>> +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::OperationStatus> pub mod radroots::signing pub use radroots::signing::ArtifactRole pub use radroots::signing::AuthorizationHeader @@ -205,6 +215,7 @@ pub async fn radroots::client::Client::attach(&self, radroots_storage::workspace pub async fn radroots::client::Client::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::signer::SignerSession> pub async fn radroots::client::Client::close(&self) -> radroots_execution::Result<radroots::client::CloseReceipt> pub const fn radroots::client::Client::inbox(&self) -> radroots::inbox::Inbox<'_> +pub const fn radroots::client::Client::listings(&self) -> radroots::listings::Listings<'_> pub async fn radroots::client::Client::open(radroots::client::NativeConfig) -> radroots_execution::Result<Self> pub fn radroots::client::Client::operations(&self, &radroots_execution::workspace::WorkspaceSession) -> radroots::operations::Operations<'_> pub fn radroots::client::Client::preview() -> Self diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -11,6 +11,7 @@ pub radroots_domain::listing::ListingError::InvalidIdentifier pub radroots_domain::listing::ListingError::InvalidOptions pub radroots_domain::listing::ListingError::InvalidQuantity pub radroots_domain::listing::ListingError::InvalidText +pub radroots_domain::listing::ListingError::InvalidTime impl core::error::Error for radroots_domain::listing::ListingError impl core::fmt::Display for radroots_domain::listing::ListingError pub fn radroots_domain::listing::ListingError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result @@ -36,6 +37,18 @@ pub struct radroots_domain::listing::LeadSeconds(_) impl radroots_domain::listing::LeadSeconds pub const fn radroots_domain::listing::LeadSeconds::get(self) -> u64 pub fn radroots_domain::listing::LeadSeconds::new(u64) -> core::result::Result<Self, radroots_domain::listing::ListingError> +pub struct radroots_domain::listing::Listing +impl radroots_domain::listing::Listing +pub const fn radroots_domain::listing::Listing::author(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::listing::Listing::created_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::listing::Listing::id(&self) -> radroots_domain::listing::ListingId +pub fn radroots_domain::listing::Listing::new(radroots_domain::listing::ListingId, radroots_identity::key::PublicKey, radroots_domain::EnvelopeEventId, radroots_domain::UnixSeconds, radroots_domain::UnixSeconds, radroots_domain::listing::ListingText, radroots_domain::listing::ListingTerms) -> core::result::Result<Self, radroots_domain::listing::ListingError> +pub const fn radroots_domain::listing::Listing::published_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::listing::Listing::revision(&self) -> radroots_domain::EnvelopeEventId +pub const fn radroots_domain::listing::Listing::terms(&self) -> &radroots_domain::listing::ListingTerms +pub const fn radroots_domain::listing::Listing::text(&self) -> &radroots_domain::listing::ListingText +impl core::fmt::Debug for radroots_domain::listing::Listing +pub fn radroots_domain::listing::Listing::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::listing::ListingId(_) impl radroots_domain::listing::ListingId pub const fn radroots_domain::listing::ListingId::as_bytes(&self) -> &[u8; 16] @@ -67,6 +80,14 @@ pub fn radroots_domain::listing::ListingTerms::options(&self) -> &[radroots_doma pub const fn radroots_domain::listing::ListingTerms::state(&self) -> radroots_domain::listing::ListingState impl core::fmt::Debug for radroots_domain::listing::ListingTerms pub fn radroots_domain::listing::ListingTerms::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::listing::ListingText +impl radroots_domain::listing::ListingText +pub fn radroots_domain::listing::ListingText::description_markdown(&self) -> &str +pub fn radroots_domain::listing::ListingText::new(&str, &str, &str) -> core::result::Result<Self, radroots_domain::listing::ListingError> +pub fn radroots_domain::listing::ListingText::summary(&self) -> &str +pub fn radroots_domain::listing::ListingText::title(&self) -> &str +impl core::fmt::Debug for radroots_domain::listing::ListingText +pub fn radroots_domain::listing::ListingText::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::listing::Product impl radroots_domain::listing::Product pub fn radroots_domain::listing::Product::name(&self) -> &str diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -3,23 +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 fn radroots_execution::session::inquiry::capture_dm_route<'a>(radroots_identity::key::PublicKey, impl core::iter::traits::collect::IntoIterator<Item = &'a str>, &radroots_transport::target::TargetSet) -> core::result::Result<radroots_protocol::chat::routes::CapturedDmRoute, radroots_storage::command::OperationError> -pub fn radroots_execution::session::inquiry::selected_dm_targets(&radroots_protocol::chat::routes::CapturedDmRoute, &radroots_transport::target::TargetSet) -> core::result::Result<radroots_transport::target::TargetSet, radroots_storage::command::OperationError> +pub mod radroots_execution::session::command +pub struct radroots_execution::session::command::CommandRuntime +impl radroots_execution::session::command::CommandRuntime +pub async fn radroots_execution::session::command::CommandRuntime::drain(&self) -> core::result::Result<(), radroots_storage::command::OperationError> +pub fn radroots_execution::session::command::CommandRuntime::new(alloc::sync::Arc<dyn radroots_execution::session::command::CommandIo>) -> Self +pub trait radroots_execution::session::command::CommandIo: radroots_execution::session::HostBound +pub fn radroots_execution::session::command::CommandIo::delivery_id(&self) -> core::result::Result<alloc::string::String, radroots_storage::command::OperationError> +pub fn radroots_execution::session::command::CommandIo::enabled(&self) -> bool +pub fn radroots_execution::session::command::CommandIo::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::command::CommandIo::now(&self) -> core::result::Result<radroots_domain::context::UnixSeconds, radroots_storage::command::OperationError> +pub fn radroots_execution::session::command::CommandIo::public_targets(&self) -> core::result::Result<radroots_transport::target::TargetSet, radroots_storage::command::OperationError> +pub fn radroots_execution::session::command::CommandIo::publication_policy(&self) -> radroots_transport::policy::SatisfactionPolicy +pub fn radroots_execution::session::command::CommandIo::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::command::CommandIo::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::command::CommandIo::seal_time(&self, radroots_domain::context::UnixSeconds) -> core::result::Result<radroots_domain::context::UnixSeconds, radroots_storage::command::OperationError> +pub fn radroots_execution::session::command::CommandIo::targets(&self, &radroots_protocol::chat::routes::CapturedDmRoute) -> core::result::Result<radroots_transport::target::TargetSet, radroots_storage::command::OperationError> +pub fn radroots_execution::session::command::capture_dm_route<'a>(radroots_identity::key::PublicKey, impl core::iter::traits::collect::IntoIterator<Item = &'a str>, &radroots_transport::target::TargetSet) -> core::result::Result<radroots_protocol::chat::routes::CapturedDmRoute, radroots_storage::command::OperationError> +pub fn radroots_execution::session::command::selected_dm_targets(&radroots_protocol::chat::routes::CapturedDmRoute, &radroots_transport::target::TargetSet) -> 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<()> @@ -35,7 +36,8 @@ pub radroots_execution::session::StartMode::Online 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>> +pub async fn radroots_execution::session::ClientSession<H>::publish_listing(&self, alloc::sync::Arc<dyn radroots_storage::command::OperationJournal>, radroots_execution::workspace::CommandContext, radroots_protocol::listing::PublishInput) -> radroots_execution::Result<radroots_execution::OperationReceipt<radroots_domain::listing::view::Listing>> +pub async fn radroots_execution::session::ClientSession<H>::resume_command(&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::OperationStatus> 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> @@ -45,9 +47,9 @@ pub fn radroots_execution::session::ClientSession<H>::new_with_task_host(H, core 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 +pub fn radroots_execution::session::ClientSession<H>::with_command_runtime(self, alloc::sync::Arc<radroots_execution::session::command::CommandRuntime>) -> Self impl<H: radroots_execution::session::SessionHost> radroots_execution::session::ClientSession<H> -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>>> +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::OperationStatus>> 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 pub struct radroots_execution::session::Session<H: radroots_execution::session::SessionHost> @@ -184,6 +186,17 @@ pub radroots_execution::Issuance::Obtained pub radroots_execution::Issuance::Pending pub radroots_execution::Issuance::ProvablyUnissued pub radroots_execution::Issuance::Unknown +#[non_exhaustive] pub enum radroots_execution::OperationKind +pub radroots_execution::OperationKind::Chat +pub radroots_execution::OperationKind::Listing +pub enum radroots_execution::OperationValue +pub radroots_execution::OperationValue::Chat(alloc::boxed::Box<radroots_domain::message::ChatMessage>) +pub radroots_execution::OperationValue::Listing(alloc::boxed::Box<radroots_domain::listing::view::Listing>) +impl radroots_execution::OperationValue +pub fn radroots_execution::OperationValue::as_chat(&self) -> core::option::Option<&radroots_domain::message::ChatMessage> +pub fn radroots_execution::OperationValue::as_listing(&self) -> core::option::Option<&radroots_domain::listing::view::Listing> +impl core::fmt::Debug for radroots_execution::OperationValue +pub fn radroots_execution::OperationValue::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_execution::Reason pub radroots_execution::Reason::Conflict pub radroots_execution::Reason::InvalidEncoding @@ -273,8 +286,12 @@ pub const fn radroots_execution::OperationContext::operation_id(self) -> core::o pub const fn radroots_execution::OperationContext::proposed(core::option::Option<radroots_domain::identifier::OperationId>) -> Self pub const fn radroots_execution::OperationContext::retained(radroots_domain::identifier::OperationId) -> Self pub struct radroots_execution::OperationReceipt<T> +impl radroots_execution::OperationReceipt<radroots_domain::listing::view::Listing> +pub fn radroots_execution::OperationReceipt<radroots_domain::listing::view::Listing>::try_from_snapshot(&radroots_storage::command::snapshot::OperationSnapshot) -> core::result::Result<Self, radroots_storage::command::OperationError> impl radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage> -pub fn radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>::from_snapshot(&radroots_storage::command::snapshot::OperationSnapshot) -> Self +pub fn radroots_execution::OperationReceipt<radroots_domain::message::ChatMessage>::try_from_snapshot(&radroots_storage::command::snapshot::OperationSnapshot) -> core::result::Result<Self, radroots_storage::command::OperationError> +impl radroots_execution::OperationReceipt<radroots_execution::OperationValue> +pub fn radroots_execution::OperationReceipt<radroots_execution::OperationValue>::try_from_snapshot(&radroots_storage::command::snapshot::OperationSnapshot) -> core::result::Result<Self, radroots_storage::command::OperationError> impl<T> radroots_execution::OperationReceipt<T> pub const fn radroots_execution::OperationReceipt<T>::admission(&self) -> radroots_execution::Admission pub const fn radroots_execution::OperationReceipt<T>::admission_transaction_id(&self) -> radroots_domain::identifier::TransactionId @@ -295,6 +312,7 @@ pub const fn radroots_execution::OperationReceipt<T>::installation_transaction_i pub const fn radroots_execution::OperationReceipt<T>::installed_at(&self) -> core::option::Option<radroots_domain::context::UnixSeconds> pub const fn radroots_execution::OperationReceipt<T>::issuance(&self) -> radroots_execution::Issuance pub const fn radroots_execution::OperationReceipt<T>::issuance_window(&self) -> radroots_domain::issuance::IssuanceWindow +pub const fn radroots_execution::OperationReceipt<T>::kind(&self) -> radroots_execution::OperationKind pub const fn radroots_execution::OperationReceipt<T>::message_id(&self) -> core::option::Option<radroots_domain::identifier::MessageId> pub fn radroots_execution::OperationReceipt<T>::missing_sources(&self) -> &[radroots_domain::identifier::SourceId] pub const fn radroots_execution::OperationReceipt<T>::observed_at(&self) -> radroots_domain::context::UnixSeconds @@ -306,4 +324,5 @@ pub const fn radroots_execution::OperationReceipt<T>::wait_termination(&self) -> pub fn radroots_execution::OperationReceipt<T>::with_wait_termination(self, radroots_execution::WaitTermination) -> Self impl<T> core::fmt::Debug for radroots_execution::OperationReceipt<T> pub fn radroots_execution::OperationReceipt<T>::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub type radroots_execution::OperationStatus = radroots_execution::OperationReceipt<radroots_execution::OperationValue> pub type radroots_execution::Result<T> = core::result::Result<T, radroots_execution::Error> diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -534,6 +534,7 @@ pub const fn radroots_protocol::listing::PublishInput::id(&self) -> radroots_dom pub fn radroots_protocol::listing::PublishInput::new(radroots_domain::listing::ListingId, &str, &str, &str, radroots_domain::context::UnixSeconds, radroots_domain::listing::ListingTerms) -> core::result::Result<Self, radroots_protocol::nip01::WireError> pub const fn radroots_protocol::listing::PublishInput::published_at(&self) -> radroots_domain::context::UnixSeconds pub const fn radroots_protocol::listing::PublishInput::terms(&self) -> &radroots_domain::listing::ListingTerms +pub const fn radroots_protocol::listing::PublishInput::text(&self) -> &radroots_domain::listing::view::ListingText impl radroots_protocol::listing::PublishInput pub fn radroots_protocol::listing::PublishInput::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> impl core::fmt::Debug for radroots_protocol::listing::PublishInput diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml @@ -10,7 +10,8 @@ test_packages = ["radroots"] test_threads = 1 [profiles.crates."radroots_protocol"] -features = ["chat", "intent"] +features = ["chat", "intent", "listing", "radroots/native"] +test_packages = ["radroots"] [profiles.crates."radroots_signing"] features = ["chat"] diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs @@ -5,6 +5,9 @@ use crate::{AuthorityRef, Decimal, ListingOptionId, PositiveDecimal, PublicKey, use alloc::{boxed::Box, string::String, vec::Vec}; use core::{fmt, str::FromStr}; +mod view; +pub use view::{Listing, ListingText}; + /// A fixed, input-free public-offer value failure. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[non_exhaustive] @@ -21,6 +24,8 @@ pub enum ListingError { InvalidFulfillment, /// A duration exceeds the cross-host exact integer bound. InvalidDuration, + /// Declared publication time follows the signed revision time. + InvalidTime, } impl fmt::Display for ListingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -31,6 +36,7 @@ impl fmt::Display for ListingError { Self::InvalidOptions => "invalid listing options", Self::InvalidFulfillment => "invalid public fulfillment", Self::InvalidDuration => "invalid listing duration", + Self::InvalidTime => "invalid listing time", }) } } diff --git a/crates/domain/src/listing/view.rs b/crates/domain/src/listing/view.rs @@ -0,0 +1,120 @@ +//! Immutable public values. Construction authenticates no source or installation. +use super::{ListingError, ListingId, ListingTerms, text}; +use crate::{EnvelopeEventId, PublicKey, UnixSeconds}; +use alloc::string::String; +use core::fmt; + +/// Bounded public presentation fields shared by authoring and retained views. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ListingText { + title: String, + summary: String, + description_markdown: String, +} +impl ListingText { + /// Validates before copying, preserving exact Unicode and whitespace. + pub fn new( + title: &str, + summary: &str, + description_markdown: &str, + ) -> Result<Self, ListingError> { + text(title, 160, false)?; + text(summary, 280, false)?; + text(description_markdown, 16_384, true)?; + Ok(Self { + title: title.into(), + summary: summary.into(), + description_markdown: description_markdown.into(), + }) + } + /// Original public title. + pub fn title(&self) -> &str { + &self.title + } + /// Original public summary. + pub fn summary(&self) -> &str { + &self.summary + } + /// Original public Markdown, without rendering or sanitization effects. + pub fn description_markdown(&self) -> &str { + &self.description_markdown + } +} +impl fmt::Debug for ListingText { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingText(<redacted>)") + } +} + +/// One immutable public listing revision. This value proves neither authenticated +/// observation, local installation, relay freshness nor stock authority. +#[derive(Clone, Eq, PartialEq)] +pub struct Listing { + id: ListingId, + author: PublicKey, + revision: EnvelopeEventId, + created_at: UnixSeconds, + published_at: UnixSeconds, + text: ListingText, + terms: ListingTerms, +} +impl Listing { + /// Captures explicit original values. Concrete execution must separately + /// authenticate the original command, signed revision and installation. + pub fn new( + id: ListingId, + author: PublicKey, + revision: EnvelopeEventId, + created_at: UnixSeconds, + published_at: UnixSeconds, + text: ListingText, + terms: ListingTerms, + ) -> Result<Self, ListingError> { + if published_at > created_at { + return Err(ListingError::InvalidTime); + } + Ok(Self { + id, + author, + revision, + created_at, + published_at, + text, + terms, + }) + } + /// Stable coordinate discriminator, separate from its signed revision. + pub const fn id(&self) -> ListingId { + self.id + } + /// Original public author. + pub const fn author(&self) -> PublicKey { + self.author + } + /// Exact signed event identity for this revision. + pub const fn revision(&self) -> EnvelopeEventId { + self.revision + } + /// Original signed event time, not local installation or current time. + pub const fn created_at(&self) -> UnixSeconds { + self.created_at + } + /// Original declared publication time. + pub const fn published_at(&self) -> UnixSeconds { + self.published_at + } + /// Original bounded presentation values. + pub const fn text(&self) -> &ListingText { + &self.text + } + /// Exact original validated offer terms; these allocate no private stock. + pub const fn terms(&self) -> &ListingTerms { + &self.terms + } +} +impl fmt::Debug for Listing { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Listing(<redacted>)") + } +} diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -1,5 +1,54 @@ use radroots_domain::{ListingOptionId, listing::*}; +#[test] +fn public_text_has_shared_unicode_bounds_and_revision_data_rejects_inverted_time() { + use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds}; + let title = "🥕".repeat(160); + let summary = "é".repeat(280); + let body = " ".repeat(16_384); + let value = ListingText::new(&title, &summary, &body).unwrap(); + assert_eq!( + serde_json::to_value(&value).unwrap(), + serde_json::json!({"title":title,"summary":summary,"description_markdown":body}) + ); + for (title, summary, body) in [ + ("🥕".repeat(161), "summary".into(), String::new()), + ("title".into(), "é".repeat(281), String::new()), + ("title".into(), "summary".into(), " ".repeat(16_385)), + ] { + assert_eq!( + ListingText::new(&title, &summary, &body).unwrap_err(), + ListingError::InvalidText + ); + } + let terms = ListingTerms::new( + ListingState::Active, + product(), + ListingOptionId::from_bytes([1; 32]), + vec![option(1, SaleUnit::measured(MeasurementUnit::Each), "1", "1", "10").unwrap()], + fulfillment(), + None, + ) + .unwrap(); + let key = + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap(); + // These are structural public data, without a signed/installed claim. + assert_eq!( + Listing::new( + ListingId::from_bytes([1; 16]), + key, + EnvelopeEventId::from_bytes([2; 32]), + UnixSeconds::new(99).unwrap(), + UnixSeconds::new(100).unwrap(), + value, + terms + ) + .unwrap_err(), + ListingError::InvalidTime + ); +} + fn product() -> Product { Product::new( "Carrots", 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", "radroots_signing/artifacts", "dep:radroots_transport"] +workspace_session = ["client_session", "receipts", "radroots_protocol/commands", "radroots_protocol/listing", "radroots_signing/artifacts", "dep:radroots_transport"] receipts = ["dep:radroots_storage", "radroots_storage/command_journal"] [dependencies] diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -94,19 +94,23 @@ Closing the attachment invalidates its contexts. A custom adapter is an explicit host trust boundary and requires its own qualification; its observation cannot establish native SQL authority. An approval descriptor is not consent proof. -`ClientSession::inquire` captures a validated inquiry from this client's own +`ClientSession::inquire` and `publish_listing` capture a validated command from this client's own authenticated context, calls the actual journal admission and queries its coherent retained graph. It does not preempt original-operation lookup with a fresh deadline check. Known failure, uncertain initial commit and a failure -after confirmed admission keep distinct original-ID dispositions. No signer or -network operation occurs in this T0 boundary. `operation` reads original progress +after confirmed admission keep distinct original-ID dispositions. T0 itself +performs no signing or network work. An explicitly online `CommandRuntime` +continues accepted work through original planning, exact signing, protected +capture, installation and publication. Public listing work uses public targets +without private routing, encryption or wrapping; private inquiry retains those +requirements. `operation` reads original progress through an explicitly selected client-owned scope, independently of the old first-issue deadline. The qualified concrete bounded worker owns accepted native admission through observer loss; its close must drain accepted work. -Package upload is not authorized. Owned signing/install/delivery continuation, -inventory authority, listing execution, browser attachment and new bindings -remain separate requirements. Revalidating a context is not durable admission; +Package upload is not authorized. Inventory authority, complete listing revision +behavior, final browser qualification and new bindings remain separate +requirements. Revalidating a context is not durable admission; the authoritative transaction must recheck its scope. @@ -116,8 +120,10 @@ It separates installation, per-recipient issuance, delivery and caller waiting. Its diagnostics contain no private command text or ciphertext. The optional `receipts` feature projects a Storage operation snapshot without I/O; the concrete adapter must qualify the underlying authenticated coherent query. -The native T2 profile projects an owned bounded `ChatMessage` when the concrete -owner reports a matching installed result. It preserves the original installation +The native T2 profile projects an owned bounded `ChatMessage` or `Listing` when +the concrete owner reports the matching installed result. `OperationStatus` +uses an explicit `OperationValue`; a public listing never projects as a message. +It preserves the original installation transaction/time separately from later recipient publication-work transactions. Pending wrapping/publication work does not establish transport acknowledgement. Newly captured recipient evidence may require T2 continuation while the original diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs @@ -9,7 +9,8 @@ extern crate alloc; mod receipt; pub use receipt::{ ArtifactObservation, BusinessInstallation, Delivery, DeliveryObservation, Issuance, - OperationReceipt, RecoveryRequirement, TargetObservation, WaitTermination, + OperationKind, OperationReceipt, OperationStatus, OperationValue, RecoveryRequirement, + TargetObservation, WaitTermination, }; #[cfg(feature = "session")] diff --git a/crates/execution/src/receipt.rs b/crates/execution/src/receipt.rs @@ -256,10 +256,54 @@ impl fmt::Debug for DeliveryObservation { } } +/// Actual retained command family, including before installation. This is an +/// observation discriminator and supplies no authority to execute a command. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum OperationKind { + /// Retained private chat command. + Chat, + /// Retained public listing command. + Listing, +} +/// Actual installed business value in an original-operation observation. +#[derive(Clone, Eq, PartialEq)] +pub enum OperationValue { + /// Original installed private message, without a public-role conversion. + Chat(Box<radroots_domain::ChatMessage>), + /// Original installed public revision, without a private participant. + Listing(Box<radroots_domain::listing::Listing>), +} +impl OperationValue { + /// Borrows an actual private result only. + pub fn as_chat(&self) -> Option<&radroots_domain::ChatMessage> { + match self { + Self::Chat(v) => Some(v), + Self::Listing(_) => None, + } + } + /// Borrows an actual public result only. + pub fn as_listing(&self) -> Option<&radroots_domain::listing::Listing> { + match self { + Self::Listing(v) => Some(v), + Self::Chat(_) => None, + } + } +} +impl fmt::Debug for OperationValue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("OperationValue(<redacted>)") + } +} +/// Common original-operation status. Querying preserves the actual family and +/// never interprets a public listing as a message, signing or dispatch right. +pub type OperationStatus = OperationReceipt<OperationValue>; + /// Owned observation of one original operation. It does not authenticate a /// principal or qualify a custom host. Business, issuance, delivery and caller /// wait dimensions remain independent; private payloads never enter diagnostics. pub struct OperationReceipt<T> { + kind: OperationKind, context: CommandContextData, command_digest: CommandDigest, admission: Admission, @@ -288,6 +332,10 @@ pub struct OperationReceipt<T> { error: Option<Error>, } impl<T> OperationReceipt<T> { + /// Actual original command family, independently of installed results. + pub const fn kind(&self) -> OperationKind { + self.kind + } /// Complete original outer/target intent references. These contain no raw /// payload and grant no dispatch permission or adapter qualification. #[cfg(feature = "receipts")] @@ -444,11 +492,15 @@ impl<T> fmt::Debug for OperationReceipt<T> { } #[cfg(feature = "receipts")] -impl OperationReceipt<ChatMessage> { +impl<T> OperationReceipt<T> { /// Projects a structurally validated retained operation report. Only the concrete /// adapter's actual authenticated coherent query qualifies the facts. This /// conversion performs no I/O, issuance, installation or publication. - pub fn from_snapshot(snapshot: &radroots_storage::command::OperationSnapshot) -> Self { + fn project( + snapshot: &radroots_storage::command::OperationSnapshot, + kind: OperationKind, + business_result: Option<T>, + ) -> Self { use alloc::{vec, vec::Vec}; let prepared = snapshot.prepared(); let mut artifacts = Vec::with_capacity(snapshot.artifacts().len()); @@ -483,8 +535,15 @@ impl OperationReceipt<ChatMessage> { publication_transaction: snapshot .publications() .iter() - .find(|value| Some(value.evidence()) == obtained) - .map(|value| value.transaction_id()), + .map(|v| (v.evidence(), v.transaction_id())) + .chain( + snapshot + .public_publications() + .iter() + .map(|v| (v.evidence(), v.transaction_id())), + ) + .find(|(e, _)| Some(*e) == obtained) + .map(|(_, tx)| tx), obtained_digest: obtained.map(|value| *value.digest()), observed_at: obtained.and_then(|value| value.observed_at_unix_ms()), }); @@ -513,9 +572,23 @@ impl OperationReceipt<ChatMessage> { let mut recovery = Vec::new(); let observations = snapshot.delivery_observations(); let attempts = snapshot.delivery_attempts(); - let delivery_pending = snapshot + let publications = snapshot .publications() .iter() + .copied() + .map(radroots_storage::command::PublicationArtifact::Private) + .chain( + snapshot + .public_publications() + .iter() + .copied() + .map(radroots_storage::command::PublicationArtifact::Public), + ) + .collect::<Vec<_>>(); + let installed = + snapshot.installation().is_some() || snapshot.listing_installation().is_some(); + let delivery_pending = publications + .iter() .any(|work| snapshot.publication_accepted(*work) != Ok(true)); let delivery_unknown = attempts.iter().any(|attempt| { attempt.intent().selected_targets().any(|target| { @@ -569,47 +642,49 @@ impl OperationReceipt<ChatMessage> { recovery.push(RecoveryRequirement::ManualReconciliation); } if recovery.is_empty() - && (snapshot.installation().is_none() - || issuance == Issuance::Pending - || issuance == Issuance::None) + && (!installed || issuance == Issuance::Pending || issuance == Issuance::None) { recovery.push(RecoveryRequirement::ContinueOriginalOperation); } Self { + kind, context: prepared.request().command().context().clone(), command_digest: prepared.identity().command_digest(), admission: Admission::Confirmed, admission_transaction: prepared.transaction_id(), plan_transaction: snapshot.bound_plan().map(|value| value.transaction_id()), - installation_transaction: snapshot.installation().map(|value| value.transaction_id()), - installed_at: snapshot.installation().map(|value| value.installed_at()), + installation_transaction: snapshot + .installation() + .map(|value| value.transaction_id()) + .or_else(|| snapshot.listing_installation().map(|v| v.transaction_id())), + installed_at: snapshot + .installation() + .map(|value| value.installed_at()) + .or_else(|| snapshot.listing_installation().map(|v| v.installed_at())), issuance_window: prepared.issuance_window(), authority_checkpoint: prepared.request().binding().input().checkpoint().clone(), operation_checkpoint: snapshot.checkpoint_digest(), conflicting_records: vec![].into_boxed_slice(), conflicting_sources: vec![].into_boxed_slice(), observed_at: snapshot.observed_at(), - business_installation: if snapshot.installation().is_some() { + business_installation: if installed { BusinessInstallation::Installed } else { BusinessInstallation::NotInstalled }, - business_result: snapshot.installed_message().cloned(), + business_result, message_id: snapshot.message_id(), record_ids: vec![].into_boxed_slice(), artifacts: artifacts.into_boxed_slice(), issuance, - delivery: if snapshot.publications().is_empty() { + delivery: if publications.is_empty() { Delivery::NotStarted } else if delivery_unknown { Delivery::Unknown } else if attempts.is_empty() - || snapshot.publications().iter().any(|work| { - !attempts.iter().any(|attempt| { - attempt.work() - == radroots_storage::command::PublicationArtifact::Private(*work) - }) - }) + || publications + .iter() + .any(|work| !attempts.iter().any(|attempt| attempt.work() == *work)) { Delivery::Pending } else { @@ -633,3 +708,80 @@ impl OperationReceipt<ChatMessage> { } } } + +#[cfg(feature = "receipts")] +fn listing_value( + snapshot: &radroots_storage::command::OperationSnapshot, +) -> Result<Option<radroots_domain::listing::Listing>, radroots_storage::command::OperationError> { + use radroots_storage::command::OperationError; + let Some(command) = snapshot.prepared().request().command().listing() else { + return Err(OperationError::UnsupportedOperation); + }; + let Some(installed) = snapshot.listing_installation() else { + return Ok(None); + }; + let bound = snapshot + .bound_plan() + .ok_or(OperationError::RecoveryRequired)?; + let input = command.input(); + radroots_domain::listing::Listing::new( + input.id(), + installed.author(), + installed.revision(), + bound.plan().created_at(), + input.published_at(), + input.text().clone(), + input.terms().clone(), + ) + .map(Some) + .map_err(|_| OperationError::RecoveryRequired) +} +#[cfg(feature = "receipts")] +impl OperationReceipt<ChatMessage> { + /// Projects only a structurally valid original private command. This checks + /// report shape; actual authenticated storage remains the adapter's duty. + pub fn try_from_snapshot( + snapshot: &radroots_storage::command::OperationSnapshot, + ) -> Result<Self, radroots_storage::command::OperationError> { + snapshot.prepared().request().chat_command()?; + Ok(Self::project( + snapshot, + OperationKind::Chat, + snapshot.installed_message().cloned(), + )) + } +} +#[cfg(feature = "receipts")] +impl OperationReceipt<radroots_domain::listing::Listing> { + /// Projects actual original public result data without inventing a message, + /// private participant, stock effect or current relay-head observation. + pub fn try_from_snapshot( + snapshot: &radroots_storage::command::OperationSnapshot, + ) -> Result<Self, radroots_storage::command::OperationError> { + Ok(Self::project( + snapshot, + OperationKind::Listing, + listing_value(snapshot)?, + )) + } +} +#[cfg(feature = "receipts")] +impl OperationStatus { + /// Observes the actual supported command family, including before any + /// installed value. This performs no authentication, issuance or dispatch. + pub fn try_from_snapshot( + snapshot: &radroots_storage::command::OperationSnapshot, + ) -> Result<Self, radroots_storage::command::OperationError> { + if snapshot.prepared().request().command().listing().is_some() { + let value = listing_value(snapshot)?.map(|v| OperationValue::Listing(Box::new(v))); + Ok(Self::project(snapshot, OperationKind::Listing, value)) + } else { + snapshot.prepared().request().chat_command()?; + let value = snapshot + .installed_message() + .cloned() + .map(|v| OperationValue::Chat(Box::new(v))); + Ok(Self::project(snapshot, OperationKind::Chat, value)) + } + } +} diff --git a/crates/execution/src/session/client.rs b/crates/execution/src/session/client.rs @@ -94,7 +94,7 @@ pub struct ClientSession<H: SessionHost> { #[cfg(feature = "workspace_session")] pub(crate) task_budget: super::tasks::TaskBudget, #[cfg(feature = "workspace_session")] - pub(crate) inquiry: Option<Shared<super::inquiry::InquiryRuntime>>, + pub(crate) commands: Option<Shared<super::command::CommandRuntime>>, } impl<H: SessionHost> Clone for ClientSession<H> { fn clone(&self) -> Self { @@ -108,7 +108,7 @@ impl<H: SessionHost> Clone for ClientSession<H> { #[cfg(feature = "workspace_session")] task_budget: self.task_budget.clone(), #[cfg(feature = "workspace_session")] - inquiry: self.inquiry.clone(), + commands: self.commands.clone(), } } } @@ -137,7 +137,7 @@ impl<H: SessionHost> ClientSession<H> { #[cfg(feature = "workspace_session")] task_budget: super::tasks::TaskBudget::new(), #[cfg(feature = "workspace_session")] - inquiry: None, + commands: None, } } /// Pairs an explicit target task host with its owning lifecycle host. The @@ -157,8 +157,8 @@ impl<H: SessionHost> ClientSession<H> { /// 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); + pub fn with_command_runtime(mut self, runtime: Shared<super::command::CommandRuntime>) -> Self { + self.commands = Some(runtime); self } /// Reports resource lifecycle independently of business authority. diff --git a/crates/execution/src/session/client_commands.rs b/crates/execution/src/session/client_commands.rs @@ -1,28 +1,33 @@ use super::{ClientSession, SessionHost, Shared}; -use crate::session::{HostBound, inquiry::InquiryRuntime}; +use crate::session::{HostBound, command::CommandRuntime}; use crate::{ - Error, OperationContext, OperationReceipt, + Error, OperationContext, OperationReceipt, OperationStatus, workspace::{CommandContext, WorkspaceSession}, }; use alloc::boxed::Box; -use radroots_domain::{ChatMessage, CommandDigest, OperationId}; -use radroots_protocol::command::{CapturedChatCommand, InquireInput}; +use radroots_domain::{ChatMessage, CommandDigest, OperationId, listing::Listing}; +use radroots_protocol::{ + command::{CapturedChatCommand, CapturedCommand, CommandError, InquireInput}, + listing::{CapturedListingCommand, PublishInput}, +}; use radroots_storage::command::{ - AdmissionOutcome, AdmissionRequest, OperationError, OperationJournal, + AdmissionOutcome, AdmissionRequest, OperationError, OperationJournal, OperationSnapshot, }; +type ReceiptProjection<T> = fn(&OperationSnapshot) -> Result<OperationReceipt<T>, OperationError>; + impl<H: SessionHost + 'static> ClientSession<H> { - /// Explicitly resumes an original inquiry under current attached access. + /// Explicitly resumes an original command 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( + pub async fn resume_command( &self, journal: Shared<dyn OperationJournal>, scope: &WorkspaceSession, operation: OperationId, expected: Option<CommandDigest>, - ) -> crate::Result<OperationReceipt<ChatMessage>> { + ) -> crate::Result<OperationStatus> { let proposed = OperationContext::proposed(Some(operation)); let permit = self .session @@ -45,7 +50,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .captured_input() .map_err(|error| Error::operation(error.into(), proposed))?; let runtime = self - .inquiry + .commands .clone() .ok_or_else(|| Error::operation(OperationError::Unauthorized, proposed))?; let host = self @@ -86,7 +91,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { &proof, signer, lease, - crate::session::inquiry::RunMode::Resume, + crate::session::command::RunMode::Resume, ) .await .map_err(|error| Error::operation(error, retained))?; @@ -95,7 +100,8 @@ impl<H: SessionHost + 'static> ClientSession<H> { .await .map_err(|error| Error::operation(error, retained))? .ok_or_else(|| Error::operation(OperationError::RecoveryRequired, retained))?; - Ok::<_, Error>(OperationReceipt::from_snapshot(&snapshot)) + OperationStatus::try_from_snapshot(&snapshot) + .map_err(|error| Error::operation(error, retained)) } .await; let _ = reply.send(result); @@ -118,13 +124,47 @@ impl<H: SessionHost + 'static> ClientSession<H> { context: CommandContext, input: InquireInput, ) -> crate::Result<OperationReceipt<ChatMessage>> { + self.submit_command( + journal, + context, + move |data| CapturedChatCommand::inquire(data, input).map(CapturedCommand::Chat), + OperationReceipt::<ChatMessage>::try_from_snapshot, + ) + .await + } + /// Captures an initial public listing under its actual attached seller + /// scope. The same owner retains T0/T1/S/T2/D after observer loss. + pub async fn publish_listing( + &self, + journal: Shared<dyn OperationJournal>, + context: CommandContext, + input: PublishInput, + ) -> crate::Result<OperationReceipt<Listing>> { + self.submit_command( + journal, + context, + move |data| CapturedListingCommand::capture(data, input).map(CapturedCommand::Listing), + OperationReceipt::<Listing>::try_from_snapshot, + ) + .await + } + async fn submit_command<T: HostBound + 'static, F>( + &self, + journal: Shared<dyn OperationJournal>, + context: CommandContext, + capture: F, + project: ReceiptProjection<T>, + ) -> crate::Result<OperationReceipt<T>> + where + F: FnOnce(radroots_domain::CommandContextData) -> Result<CapturedCommand, CommandError>, + { let operation = context.data().operation_id(); let proposed = OperationContext::proposed(Some(operation)); let permit = self .session .admit() .map_err(|error| error.with_context(proposed))?; - let budget = if self.task_host.is_some() || self.inquiry.is_some() { + let budget = if self.task_host.is_some() || self.commands.is_some() { Some( self.task_budget .reserve() @@ -145,17 +185,18 @@ impl<H: SessionHost + 'static> ClientSession<H> { let (binding, proof) = context .captured_input() .map_err(|error| Error::operation(error.into(), proposed))?; - let command = CapturedChatCommand::inquire(context.data().clone(), input) + let command = capture(context.data().clone()) .map_err(|_| Error::operation(OperationError::InvalidCommand, proposed))?; let request = AdmissionRequest::new(binding, command) .map_err(|error| Error::operation(error, proposed))?; - let runtime = self.inquiry.clone(); + let runtime = self.commands.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 result = + execute_command(journal, request, proof, runtime, signer, lease, project).await; let _ = reply.send(result); }); host.submit(task) @@ -164,7 +205,7 @@ impl<H: SessionHost + 'static> ClientSession<H> { .await .unwrap_or_else(|_| Err(Error::admission_uncertain(operation))) } else { - execute_inquiry(journal, request, proof, runtime, signer, lease).await + execute_command(journal, request, proof, runtime, signer, lease, project).await } } } @@ -179,7 +220,7 @@ impl<H: SessionHost> ClientSession<H> { scope: &WorkspaceSession, operation: OperationId, expected_digest: Option<CommandDigest>, - ) -> crate::Result<Option<OperationReceipt<ChatMessage>>> { + ) -> crate::Result<Option<OperationStatus>> { let proposed = OperationContext::proposed(Some(operation)); let _permit = self .session @@ -197,22 +238,27 @@ impl<H: SessionHost> ClientSession<H> { let (binding, proof) = scope .captured_input() .map_err(|error| Error::operation(error.into(), proposed))?; - journal + let snapshot = journal .operation_snapshot(binding, operation, expected_digest, proof) .await - .map(|snapshot| snapshot.as_ref().map(OperationReceipt::from_snapshot)) - .map_err(|error| Error::operation(error, proposed)) + .map_err(|error| Error::operation(error, proposed))?; + snapshot + .as_ref() + .map(OperationStatus::try_from_snapshot) + .transpose() + .map_err(|error| Error::operation(error, OperationContext::retained(operation))) } } -async fn execute_inquiry( +async fn execute_command<T: HostBound + 'static>( journal: Shared<dyn OperationJournal>, request: AdmissionRequest, proof: radroots_storage::workspace::AttachmentProof, - runtime: Option<Shared<InquiryRuntime>>, + runtime: Option<Shared<CommandRuntime>>, signer: Option<super::SignerSession>, lease: Shared<dyn HostBound>, -) -> crate::Result<OperationReceipt<ChatMessage>> { + project: ReceiptProjection<T>, +) -> crate::Result<OperationReceipt<T>> { let operation = request.command().context().operation_id(); let proposed = OperationContext::proposed(Some(operation)); let binding = request.binding().clone(); @@ -240,7 +286,7 @@ async fn execute_inquiry( &query_proof, signer, lease, - crate::session::inquiry::RunMode::Command, + crate::session::command::RunMode::Command, ) .await .map_err(|error| Error::operation(error, retained))?; @@ -250,7 +296,7 @@ async fn execute_inquiry( .await .map_err(|error| Error::operation(error, retained))? .ok_or_else(|| Error::operation(OperationError::RecoveryRequired, retained))?; - Ok(OperationReceipt::from_snapshot(&snapshot)) + project(&snapshot).map_err(|error| Error::operation(error, retained)) } } } diff --git a/crates/execution/src/session/command.rs b/crates/execution/src/session/command.rs @@ -0,0 +1,678 @@ +//! Owned ordinary public/private command execution over explicit host IO and protected storage. +#[path = "inquiry_routes.rs"] +mod routes; +pub use routes::{capture_dm_route, selected_dm_targets}; + +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, ChatRumor, ChatSeal, ChatSigningPlan}; +use radroots_protocol::{ + listing::PublicSigningPlan, + plan::{CapturedSigningPlan, SigningReplay, SigningTarget}, +}; +use radroots_signing::{ + issuance::{OutcomeKind, SigningIntent}, + provider::{PrivateCiphertext, PrivateText, ProviderCall}, + request::CancellationSignal, +}; +use radroots_storage::{ + command::{ + ArtifactEvidence, BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, + DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryIntent, DeliveryObservation, + EnvelopeCandidate, EvidenceCaptureOutcome, InstallationRequest, OperationError, + OperationJournal, PlanBindingOutcome, PreparedOperation, PublicationArtifact, + PublicationWork, + }, + 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 CommandIo: 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>; + /// Explicit configured public publication targets. An unsupported host must + /// refuse; public work never borrows a private participant's route. + fn public_targets(&self) -> Result<TargetSet, OperationError> { + Err(OperationError::UnsupportedOperation) + } + /// 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: ArtifactEvidence, + // 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 CommandRuntime { + io: Shared<dyn CommandIo>, + pending: Mutex<Vec<Shared<PendingCapture>>>, + observations: Mutex<Vec<Shared<PendingObservation>>>, + draining: futures::lock::Mutex<()>, +} +pub(super) enum RunMode { + Command, + Resume, +} +impl CommandRuntime { + /// Owns explicit IO without performing effects or starting a runtime. + pub fn new(io: Shared<dyn CommandIo>) -> 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 + .artifacts() + .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<CapturedSigningPlan, 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 observed = signer + .observe() + .await + .map_err(|_| OperationError::Unauthorized)?; + if observed.identity() != prepared.request().command().context().actor().participant() { + return Err(OperationError::Unauthorized); + } + let replay = match observed + .exact_issuance() + .ok_or(OperationError::Unauthorized)? + { + radroots_signing::recovery::ReplayCapability::NonReplayable => { + SigningReplay::NonReplayable + } + radroots_signing::recovery::ReplayCapability::LocalReplaySafe => { + SigningReplay::LocalReplaySafe + } + radroots_signing::recovery::ReplayCapability::ExactReplayByRequestId => { + SigningReplay::ExactReplayByRequestId + } + _ => return Err(OperationError::Unauthorized), + }; + if let Some(command) = prepared.request().command().listing() { + let targets = self.io.public_targets()?; + let urls = targets + .targets() + .iter() + .map(|target| target.uri().as_str().into()) + .collect::<Vec<String>>(); + return PublicSigningPlan::capture(command, now, &urls, replay) + .map(CapturedSigningPlan::Listing) + .map_err(|_| OperationError::InvalidCommand); + } + let command = prepared.request().chat_command()?; + if observed.encryption() != radroots_signing::provider::PrivateCryptoCapability::Nip44V2 + || observed.decryption() != radroots_signing::provider::PrivateCryptoCapability::Nip44V2 + { + 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(CapturedSigningPlan::Chat) + .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(); + let targets = match bound.plan() { + CapturedSigningPlan::Listing(_) => alloc::vec![SigningTarget::PublicEvent], + CapturedSigningPlan::Chat(plan) => plan + .seals() + .iter() + .map(|seal| SigningTarget::BusinessSeal(seal.recipient())) + .collect(), + }; + for target in targets { + let select = || { + ClaimAttemptRequest::for_artifact( + binding.clone(), + prepared.identity().operation_id(), + prepared.identity().command_digest(), + *bound.plan().digest(), + target, + ) + }; + 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_plan( + attempt.bound_plan().plan(), + attempt.target(), + ProviderCall::new( + attempt + .bound_plan() + .plan() + .artifact(attempt.target()) + .map_err(|_| OperationError::RecoveryRequired)? + .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| { + ArtifactEvidence::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)?; + let work = snapshot + .publications() + .iter() + .copied() + .map(PublicationArtifact::Private) + .chain( + snapshot + .public_publications() + .iter() + .copied() + .map(PublicationArtifact::Public), + ); + for work in work { + 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 (targets, envelope, event) = match work { + PublicationArtifact::Private(private) => { + let recipient = private.recipient(); + let route = bound + .chat_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 = if original.is_none() { + Some(self.io.envelope(private, captured.evidence().raw_json())?) + } else { + None + }; + let event = match original { + Some(v) => v.intent().event_id(), + None => envelope + .as_ref() + .ok_or(OperationError::RecoveryRequired)? + .event_id(), + }; + (targets, envelope, event) + } + PublicationArtifact::Public(public) => { + let configured = self.io.public_targets()?; + let plan = bound + .plan() + .listing() + .ok_or(OperationError::RecoveryRequired)?; + let targets = TargetSet::new( + plan.selected_targets() + .iter() + .map(|uri| radroots_transport::Target::nostr_relay(uri.as_ref())) + .collect::<Result<Vec<_>, _>>() + .map_err(|_| OperationError::RecoveryRequired)?, + ) + .map_err(|_| OperationError::RecoveryRequired)?; + if targets.targets().iter().any(|target| { + !configured + .targets() + .iter() + .any(|allowed| allowed.fingerprint() == target.fingerprint()) + }) { + return Err(OperationError::UnverifiedApproval); + } + (targets, None, public.evidence().event_id()) + } + }; + 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 => (event, 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 request_id = self.io.delivery_id()?; + let intent = match work { + PublicationArtifact::Private(_) => { + DeliveryIntent::new(&request_id, event, &targets, &policy, deadline) + } + PublicationArtifact::Public(_) => { + DeliveryIntent::public(&request_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/inquiry.rs b/crates/execution/src/session/inquiry.rs @@ -1,592 +0,0 @@ -//! Owned ordinary inquiry execution over explicit host IO and protected storage. -#[path = "inquiry_routes.rs"] -mod routes; -pub use routes::{capture_dm_route, selected_dm_targets}; - -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, ChatRumor, ChatSeal, ChatSigningPlan}; -use radroots_protocol::plan::SigningReplay; -use radroots_signing::{ - issuance::{OutcomeKind, SigningIntent}, - provider::{PrivateCiphertext, PrivateText, ProviderCall}, - request::CancellationSignal, -}; -use radroots_storage::{ - command::{ - ArtifactEvidence, BoundSigningPlan, ClaimAttemptOutcome, ClaimAttemptRequest, - DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryIntent, DeliveryObservation, - EnvelopeCandidate, EvidenceCaptureOutcome, InstallationRequest, OperationError, - OperationJournal, PlanBindingOutcome, PreparedOperation, PublicationWork, - }, - 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: ArtifactEvidence, - // 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.into(), 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 - .artifacts() - .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().chat_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 => { - SigningReplay::NonReplayable - } - radroots_signing::recovery::ReplayCapability::LocalReplaySafe => { - SigningReplay::LocalReplaySafe - } - radroots_signing::recovery::ReplayCapability::ExactReplayByRequestId => { - SigningReplay::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.chat_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_plan( - attempt.bound_plan().plan(), - attempt.target(), - 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| { - ArtifactEvidence::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() == radroots_storage::command::PublicationArtifact::Private(*work) - }); - if original.is_some() && matches!(mode, RunMode::Command) { - continue; - } - let recipient = work.recipient(); - let route = bound - .chat_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() - == radroots_storage::command::PublicationArtifact::Private(*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 @@ -8,7 +8,7 @@ pub(crate) mod host; pub mod tasks; #[cfg(feature = "workspace_session")] -pub mod inquiry; +pub mod command; #[cfg(feature = "client_session")] mod client; diff --git a/crates/protocol/src/listing.rs b/crates/protocol/src/listing.rs @@ -11,7 +11,7 @@ use alloc::{ use core::fmt; use radroots_domain::{ PublicKey, UnixSeconds, - listing::{ListingId, ListingState, ListingTerms, Price}, + listing::{ListingId, ListingState, ListingTerms, ListingText, Price}, }; use serde::Serialize; use serde_json::Value; @@ -36,9 +36,8 @@ pub const LISTING_TAG_TOTAL_ELEMENT_MAX_COUNT: usize = 16; #[derive(Clone, Serialize)] pub struct PublishInput { id: ListingId, - title: String, - summary: String, - description_markdown: String, + #[serde(flatten)] + text: ListingText, published_at: UnixSeconds, #[serde(rename = "profile", serialize_with = "serialize_profile")] terms: ListingTerms, @@ -54,23 +53,11 @@ impl PublishInput { published_at: UnixSeconds, terms: ListingTerms, ) -> Result<Self, WireError> { - for (value, limit, empty) in [ - (title, 160, false), - (summary, 280, false), - (description_markdown, 16_384, true), - ] { - if (!empty && value.is_empty()) - || value.len() > limit * 4 - || value.chars().count() > limit - { - return Err(WireError::InvalidInput); - } - } + let text = ListingText::new(title, summary, description_markdown) + .map_err(|_| WireError::InvalidInput)?; Ok(Self { id, - title: title.into(), - summary: summary.into(), - description_markdown: description_markdown.into(), + text, published_at, terms, }) @@ -87,6 +74,10 @@ impl PublishInput { pub const fn published_at(&self) -> UnixSeconds { self.published_at } + /// Exact domain-owned public presentation values. + pub const fn text(&self) -> &ListingText { + &self.text + } } impl fmt::Debug for PublishInput { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -157,16 +148,16 @@ impl ListingEvent { ListingState::Withdrawn => Some("Withdrawn: unavailable"), }; let summary = match inactive { - Some(label) => format!("[{label}] {}", input.summary), - None => input.summary.clone(), + Some(label) => format!("[{label}] {}", input.text.summary()), + None => input.text.summary().into(), }; let content = match inactive { - Some(label) => format!("[{label}]\n\n{}", input.description_markdown), - None => input.description_markdown.clone(), + Some(label) => format!("[{label}]\n\n{}", input.text.description_markdown()), + None => input.text.description_markdown().into(), }; let mut tags = vec![ vec!["d".into(), input.id.to_string()], - vec!["title".into(), input.title.clone()], + vec!["title".into(), input.text.title().into()], vec!["summary".into(), summary], vec!["published_at".into(), input.published_at.to_string()], vec!["location".into(), input.terms.fulfillment().area().into()], diff --git a/crates/protocol/tests/package_boundary.rs b/crates/protocol/tests/package_boundary.rs @@ -20,6 +20,11 @@ const VERSIONED_SOURCES: &[&str] = &[ include_str!("../src/chat.rs"), include_str!("../src/chat/routes.rs"), include_str!("../src/chat/plan.rs"), + include_str!("../src/listing.rs"), + include_str!("../src/listing/input.rs"), + include_str!("../src/listing/command.rs"), + include_str!("../src/listing/plan.rs"), + include_str!("../src/plan.rs"), ]; #[test] @@ -32,7 +37,7 @@ fn manifest_has_approved_data_only_features_and_dependencies() { assert_eq!( table_keys(MANIFEST, "[features]"), BTreeSet::from([ - "chat", "commands", "default", "intent", "nip01", "serde", "std" + "chat", "commands", "default", "intent", "listing", "nip01", "serde", "std" ]) ); assert_eq!( @@ -65,6 +70,8 @@ fn crate_root_exposes_only_the_approved_versioned_skeleton() { "event", "nip01", "intent", + "listing", + "plan", "radrootsd", "runtime", "schema" diff --git a/crates/protocol/tests/public_command.rs b/crates/protocol/tests/public_command.rs @@ -320,3 +320,40 @@ fn artifact_selection_has_no_public_participant_and_preserves_private_keys() { assert!(SigningTarget::from_key(invalid).is_err()); } } + +#[test] +fn public_plans_require_bounded_explicit_targets_without_scheme_or_whitespace_fallback() { + use radroots_protocol::{listing::PublicSigningPlan, plan::SigningReplay}; + let command = CapturedListingCommand::capture( + context(), + PublishInput::parse(&serde_json::to_vec(&input()).unwrap()).unwrap(), + ) + .unwrap(); + let capture = |targets: &[String]| { + PublicSigningPlan::capture( + &command, + UnixSeconds::new(100).unwrap(), + targets, + SigningReplay::NonReplayable, + ) + }; + assert!(capture(&["wss://route.example/".into()]).is_ok()); + let maximum = format!("wss://{}", "x".repeat(2048 - "wss://".len())); + assert_eq!(maximum.len(), 2048); + assert!(capture(std::slice::from_ref(&maximum)).is_ok()); + let excessive = (0..17) + .map(|i| format!("wss://route.example/{i}")) + .collect::<Vec<_>>(); + assert!(capture(&excessive).is_err()); + for target in [ + format!("{maximum}x"), + "https://route.example/".into(), + "wss://route.example/a ".into(), + "wss://route.example/a\nb".into(), + ] { + assert!( + capture(std::slice::from_ref(&target)).is_err(), + "{target:?}" + ); + } +} diff --git a/crates/radroots/Cargo.toml b/crates/radroots/Cargo.toml @@ -40,7 +40,7 @@ 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_protocol = { workspace = true, default-features = false, features = ["chat", "listing"] } radroots_event = { workspace = true } radroots_identity = { workspace = true, features = ["std"] } radroots_sdk = { workspace = true } @@ -67,7 +67,7 @@ knowledge = ["client", "radroots_sdk/knowledge"] full = ["native", "radroots_sdk/full"] [dev-dependencies] -radroots_protocol = { workspace = true, default-features = false, features = ["chat"] } +radroots_protocol = { workspace = true, default-features = false, features = ["chat", "listing"] } radroots_signing = { workspace = true, features = ["chat"] } nostr = { workspace = true, default-features = false, features = ["std", "nip44", "nip59"] } sqlx = { workspace = true, features = ["runtime-tokio", "sqlite-bundled"] } diff --git a/crates/radroots/README.md b/crates/radroots/README.md @@ -33,8 +33,9 @@ without I/O or a clock read; admission must recheck current rights and expiry. A context does not submit a command or prove user consent. After explicit start, `client.inbox().inquire(context, input)` durably captures a known-kind inquiry through the actual protected journal. -The returned coherent receipt reports pending preparation without claiming a -signature, installed message or relay acceptance. `client.operations(&scope)` +Local-only submission returns a coherent receipt for retained preparation; +online submission owns continuation through signing, installation and delivery. +Each dimension reports its actual independent facts. `client.operations(&scope)` selects an explicitly authenticated attachment for `get(operation_id)` and matching-digest reads. Every call enforces this client's attachment ownership and current persisted grant. An expired retained inquiry remains queryable and @@ -43,8 +44,8 @@ new expired input and conflicting reuse are refused. The existing bounded native worker owns accepted admission after observer loss; client close drains it before releasing storage. Unpolled calls do nothing. -Network pairing, seller authority, owned signing/install/delivery continuation, -listing execution and browser qualification remain separate requirements. +Network pairing, complete seller authority and final browser qualification +remain separate requirements. `attach_signer` observes the concrete provider only after retaining its callback scope. The first successful key freezes and later drift invalidates that scope. @@ -70,7 +71,7 @@ An explicitly opened protected workspace can be supplied with 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. +`LocalOnly` keeps commands 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 @@ -85,6 +86,23 @@ 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. +## Native initial listings + +`client.listings().publish(context, input)` uses the same owned command runtime +and protected journal for an authenticated seller's initial public listing. +Its `OperationReceipt<domain::Listing>` contains a business result only after +actual installation. Text and exact terms come from the captured command; +author, revision and event time come from its retained public signing plan and +obtained evidence. An existing coordinate cannot be replaced by publishing it +again. Revision editing, pause/withdraw and stock remain separate requirements. + +Public planning uses the configured public relay targets and exact-event +signing. It performs no private-route query, encryption or wrapping. Delivery +sends the original signed event. Scoped queries and explicit resume return +`OperationStatus`, whose `OperationValue` distinguishes Listing from Chat. +Reopening, reading and command replay do not redispatch retained work; explicit +resume preserves the original bytes, criterion, targets and retry budget. + ## Values and retained capabilities `radroots::domain` provides exact decimals and distinct order, thread, workspace, @@ -123,6 +141,7 @@ coherent retained snapshot for this projection. Native T2 can install a bounded logical chat result and retain independent recipient publication work; its original installation time/transaction remain separate from later work and unknown issuance. `domain::ChatMessage` is the owned private business view. -The ordinary inquiry boundary admits and queries T0. Owned continuation through -exact signing, native T2, wrapping and delivery remains required before the -complete native submission workflow is available. +The ordinary native inquiry and initial-listing boundaries continue accepted +online work through exact signing, protected capture, installation and delivery. +Full commerce behavior, final cross-platform acceptance and generated binding +qualification remain separate requirements. diff --git a/crates/radroots/src/client.rs b/crates/radroots/src/client.rs @@ -70,7 +70,7 @@ 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>>, + commands: Option<Shared<crate::native_commands::NativeCommands>>, } #[cfg(feature = "native")] impl NativeConfig { @@ -81,7 +81,7 @@ impl NativeConfig { options, workspace: None, #[cfg(not(target_arch = "wasm32"))] - inquiry: None, + commands: None, } } /// Adds an explicitly opened protected local outbox. A public cache alone @@ -102,8 +102,8 @@ impl NativeConfig { 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) + self.commands = Some(Shared::new( + crate::native_commands::NativeCommands::new(config, policy) .map_err(|error| Error::operation(error, OperationContext::proposed(None)))?, )); Ok(self) @@ -132,9 +132,9 @@ pub(crate) struct StoreHost { closed: Shared<Mutex<Option<CloseReceipt>>>, runtime: TargetRuntime, #[cfg(all(feature = "native", not(target_arch = "wasm32")))] - inquiry: Option<Shared<radroots_execution::session::inquiry::InquiryRuntime>>, + commands: Option<Shared<radroots_execution::session::command::CommandRuntime>>, #[cfg(all(feature = "native", not(target_arch = "wasm32")))] - native_inquiry: Option<Shared<crate::native_inquiry::NativeInquiry>>, + native_commands: Option<Shared<crate::native_commands::NativeCommands>>, } impl SessionHost for StoreHost { fn start(&self) -> HostFuture<'_, crate::Result<()>> { @@ -159,13 +159,13 @@ impl SessionHost for StoreHost { Box::pin(async move { #[cfg(all(feature = "native", not(target_arch = "wasm32")))] if let TargetRuntime::Native(tasks) = &self.runtime { - let inquiry = self.inquiry.clone(); + let commands = self.commands.clone(); tasks .control( crate::native_tasks::ControlKind::Drain, Box::pin(async move { - if let Some(inquiry) = inquiry { - inquiry.drain().await.map_err(|error| { + if let Some(commands) = commands { + commands.drain().await.map_err(|error| { Error::operation(error, OperationContext::proposed(None)) })?; } @@ -181,13 +181,13 @@ impl SessionHost for StoreHost { 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(); + let commands = self.native_commands.clone(); tasks .control( crate::native_tasks::ControlKind::Disconnect, Box::pin(async move { - if let Some(inquiry) = inquiry { - inquiry.disconnect().await; + if let Some(commands) = commands { + commands.disconnect().await; } Ok(()) }), @@ -234,7 +234,7 @@ pub struct Client { 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>>, + native_commands: Option<Shared<crate::native_commands::NativeCommands>>, } impl Client { #[cfg(any(feature = "client", feature = "native"))] @@ -242,29 +242,29 @@ impl Client { 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>, + #[cfg(all(feature = "native", not(target_arch = "wasm32")))] native_commands: Option< + Shared<crate::native_commands::NativeCommands>, >, ) -> Self { let closed = Shared::new(Mutex::new(None)); 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( + let commands = native_commands.as_ref().map(|io| { + Shared::new(radroots_execution::session::command::CommandRuntime::new( io.clone(), )) }); #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))] - let inquiry: Option<Shared<radroots_execution::session::inquiry::InquiryRuntime>> = None; + let commands: Option<Shared<radroots_execution::session::command::CommandRuntime>> = 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(), + commands: commands.clone(), #[cfg(all(feature = "native", not(target_arch = "wasm32")))] - native_inquiry: native_inquiry.clone(), + native_commands: native_commands.clone(), }; const MAX_RESOURCES: NonZeroU16 = match NonZeroU16::new(32) { Some(limit) => limit, @@ -274,8 +274,8 @@ impl Client { 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), + let session = match commands { + Some(commands) => session.with_command_runtime(commands), None => session, }; Self { @@ -284,7 +284,7 @@ impl Client { workspace, closed, #[cfg(all(feature = "native", not(target_arch = "wasm32")))] - native_inquiry, + native_commands, } } /// Creates a deterministic in-memory preview with no filesystem, network, @@ -320,7 +320,7 @@ impl Client { config.workspace, runtime, #[cfg(not(target_arch = "wasm32"))] - config.inquiry, + config.commands, )) } /// Observes resource lifecycle without probing signer, store or network. @@ -336,6 +336,10 @@ impl Client { pub const fn inbox(&self) -> crate::inbox::Inbox<'_> { crate::inbox::Inbox::new(self) } + /// Accesses initial public listing publication. Access alone has no effects. + pub const fn listings(&self) -> crate::listings::Listings<'_> { + crate::listings::Listings::new(self) + } /// Selects an explicitly authenticated scope for original-operation reads. /// Every query checks that this client owns the attachment and current grant. pub fn operations( @@ -348,8 +352,8 @@ impl Client { /// transport, command writer or stock authority is implicitly constructed. pub async fn start(&self, mode: StartMode) -> crate::Result<SessionStatus> { #[cfg(all(feature = "native", not(target_arch = "wasm32")))] - if let Some(inquiry) = &self.native_inquiry { - inquiry + if let Some(commands) = &self.native_commands { + commands .select(mode == StartMode::Online) .map_err(|error| Error::operation(error, OperationContext::proposed(None)))?; } else if mode == StartMode::Online { diff --git a/crates/radroots/src/lib.rs b/crates/radroots/src/lib.rs @@ -11,6 +11,7 @@ pub mod identity; pub mod inbox; pub mod knowledge; pub mod listing; +pub mod listings; pub mod operations; pub mod signing; pub mod storage; @@ -22,7 +23,7 @@ pub mod transport; mod native_tasks; #[cfg(all(feature = "native", not(target_arch = "wasm32")))] -mod native_inquiry; +mod native_commands; #[cfg(feature = "native")] pub use client::NativeConfig; @@ -31,7 +32,8 @@ pub use radroots_domain::OperationId; pub use radroots_execution::workspace::{CommandContext, WorkspaceSession}; pub use radroots_execution::{ ArtifactObservation, BusinessInstallation, Delivery, DeliveryObservation, Issuance, - OperationReceipt, RecoveryRequirement, TargetObservation, WaitTermination, + OperationKind, OperationReceipt, OperationStatus, OperationValue, RecoveryRequirement, + TargetObservation, WaitTermination, }; pub use radroots_execution::{Error, Result}; pub use radroots_storage::workspace::{AttachmentInput, AttachmentProof}; diff --git a/crates/radroots/src/listings.rs b/crates/radroots/src/listings.rs @@ -0,0 +1,26 @@ +//! Initial public listing commands through the shared protected execution owner. +use crate::{Client, CommandContext, OperationReceipt, Result}; +pub use radroots_domain::listing::Listing; +pub use radroots_protocol::listing::PublishInput; + +/// Borrowed public-listing access. Construction performs no host effects. +pub struct Listings<'a> { + client: &'a Client, +} +impl<'a> Listings<'a> { + pub(crate) const fn new(client: &'a Client) -> Self { + Self { client } + } + /// Publishes an initial coordinate through actual T0/T1/S/T2/D. Current + /// seller authority is required; another publish cannot act as an edit. + pub async fn publish( + &self, + context: CommandContext, + input: PublishInput, + ) -> Result<OperationReceipt<Listing>> { + self.client + .session + .publish_listing(self.client.journal()?, context, input) + .await + } +} diff --git a/crates/radroots/src/native_commands.rs b/crates/radroots/src/native_commands.rs @@ -0,0 +1,344 @@ +use core::num::NonZeroU64; +use radroots_domain::{PublicKey, UnixSeconds}; +use radroots_execution::session::{ + HostFuture, + command::{CommandIo, capture_dm_route, selected_dm_targets}, +}; +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}; +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 NativeCommands { + transport: NostrTransport, + read: TargetSet, + write: TargetSet, + policy: SatisfactionPolicy, + mode: AtomicU8, +} +impl NativeCommands { + 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: radroots_transport_nostr_native::create_transport(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> { + capture_dm_route(recipient, raw_sources, &self.write) + } +} +impl CommandIo for NativeCommands { + 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 public_targets(&self) -> Result<TargetSet, OperationError> { + if !self.enabled() { + return Err(OperationError::Unauthorized); + } + Ok(self.write.clone()) + } + 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> { + selected_dm_targets(route, &self.write) + } + 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.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::NativeCommands; + use futures::executor::block_on; + use nostr::JsonUtil; + use radroots_domain::PublicKey; + use radroots_execution::session::command::CommandIo; + 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() -> NativeCommands { + NativeCommands::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!( + NativeCommands::new( + config(RelayAccess::ReadOnly), + SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()) + ) + .is_err() + ); + assert!( + NativeCommands::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(), [older.as_str(), newer.as_str(), newer.as_str()]), + Err(OperationError::InvalidEvidence) + )); + 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 changed = radroots_transport::TargetSet::new(vec![ + radroots_transport::Target::nostr_relay("wss://changed.example").unwrap(), + ]) + .unwrap(); + assert!(matches!( + radroots_execution::session::command::selected_dm_targets(&route, &changed), + Err(OperationError::UnverifiedApproval) + )); + 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_inquiry.rs b/crates/radroots/src/native_inquiry.rs @@ -1,338 +0,0 @@ -use core::num::NonZeroU64; -use radroots_domain::{PublicKey, UnixSeconds}; -use radroots_execution::session::{ - HostFuture, - inquiry::{InquiryIo, capture_dm_route, selected_dm_targets}, -}; -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}; -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: radroots_transport_nostr_native::create_transport(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> { - capture_dm_route(recipient, raw_sources, &self.write) - } -} -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> { - selected_dm_targets(route, &self.write) - } - 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.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(), [older.as_str(), newer.as_str(), newer.as_str()]), - Err(OperationError::InvalidEvidence) - )); - 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 changed = radroots_transport::TargetSet::new(vec![ - radroots_transport::Target::nostr_relay("wss://changed.example").unwrap(), - ]) - .unwrap(); - assert!(matches!( - radroots_execution::session::inquiry::selected_dm_targets(&route, &changed), - Err(OperationError::UnverifiedApproval) - )); - 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/operations.rs b/crates/radroots/src/operations.rs @@ -1,6 +1,6 @@ //! Current authenticated reads of original retained operations. -use crate::{Client, OperationId, OperationReceipt, Result, WorkspaceSession}; -use radroots_domain::{ChatMessage, CommandDigest}; +use crate::{Client, OperationId, Result, WorkspaceSession}; +use radroots_domain::CommandDigest; /// Reads are scoped to one explicit client-owned authenticated attachment. pub struct Operations<'a> { @@ -8,17 +8,17 @@ 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 + /// Explicitly resumes one original command. Retained signing claims never + /// permit reissuance. Delivery retries use the original exact artifact and /// criterion, preserving accepted targets and the original business result. pub async fn resume( &self, operation: OperationId, expected: Option<CommandDigest>, - ) -> Result<OperationReceipt<ChatMessage>> { + ) -> Result<radroots_execution::OperationStatus> { self.client .session - .resume_inquiry(self.client.journal()?, &self.scope, operation, expected) + .resume_command(self.client.journal()?, &self.scope, operation, expected) .await } pub(crate) const fn new(client: &'a Client, scope: WorkspaceSession) -> Self { @@ -28,7 +28,7 @@ impl<'a> Operations<'a> { pub async fn get( &self, operation: OperationId, - ) -> Result<Option<OperationReceipt<ChatMessage>>> { + ) -> Result<Option<radroots_execution::OperationStatus>> { self.get_matching(operation, None).await } /// Additionally requires the original semantic command commitment. @@ -36,7 +36,7 @@ impl<'a> Operations<'a> { &self, operation: OperationId, expected: Option<CommandDigest>, - ) -> Result<Option<OperationReceipt<ChatMessage>>> { + ) -> Result<Option<radroots_execution::OperationStatus>> { self.client .session .operation(self.client.journal()?, &self.scope, operation, expected) diff --git a/crates/radroots/tests/package_boundary.rs b/crates/radroots/tests/package_boundary.rs @@ -70,8 +70,9 @@ fn root_has_exact_exports_and_no_sdk_namespace() { ROOT.contains("pub use radroots_storage::workspace::{AttachmentInput, AttachmentProof};") ); assert!(ROOT.contains( - "pub use radroots_execution::{\n ArtifactObservation, BusinessInstallation, Delivery, DeliveryObservation, Issuance,\n OperationReceipt, RecoveryRequirement, TargetObservation, WaitTermination,\n};" + "pub use radroots_execution::{\n ArtifactObservation, BusinessInstallation, Delivery, DeliveryObservation, Issuance,\n OperationKind, OperationReceipt, OperationStatus, OperationValue, RecoveryRequirement,\n TargetObservation, WaitTermination,\n};" )); + assert!(ROOT.contains("pub mod listings;")); assert_eq!(ROOT.matches("pub use ").count(), 7); assert!(README.contains("```compile_fail\nuse radroots::sdk;\n```")); } diff --git a/crates/radroots/tests/support/receipt_delivery.rs b/crates/radroots/tests/support/receipt_delivery.rs @@ -310,7 +310,11 @@ async fn native_delivery_retains_exact_outer_before_loopback_and_reopen_preserve .unwrap(); assert_eq!(pending.delivery_attempts().len(), 1); assert!(pending.delivery_observations().is_empty()); - let projected = radroots_execution::OperationReceipt::from_snapshot(&pending); + let projected = + radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot( + &pending, + ) + .unwrap(); assert_eq!(projected.delivery(), radroots_execution::Delivery::Unknown); assert_eq!( projected.delivery_attempts()[0].envelope_digest(), @@ -383,7 +387,11 @@ async fn native_delivery_retains_exact_outer_before_loopback_and_reopen_preserve .unwrap() .unwrap(); assert_ne!(complete.checkpoint_digest(), pending.checkpoint_digest()); - let projected = radroots_execution::OperationReceipt::from_snapshot(&complete); + let projected = + radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot( + &complete, + ) + .unwrap(); assert_eq!( projected.business_installation(), radroots_execution::BusinessInstallation::Installed diff --git a/crates/radroots/tests/support/receipt_delivery_faults.rs b/crates/radroots/tests/support/receipt_delivery_faults.rs @@ -164,7 +164,11 @@ async fn exhausted_optional_endpoint_does_not_starve_required_endpoint_or_weaken .unwrap() .unwrap(); assert_eq!(snapshot.publication_accepted(ready.work), Ok(true)); - let receipt = radroots_execution::OperationReceipt::from_snapshot(&snapshot); + let receipt = + radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot( + &snapshot, + ) + .unwrap(); assert_eq!(receipt.delivery(), radroots_execution::Delivery::Unknown); assert!( !receipt @@ -228,7 +232,7 @@ async fn original_quorum_accumulates_acceptance_across_independent_selected_atte .unwrap() .unwrap(); assert_eq!(snapshot.publication_accepted(ready.work), Ok(index == 1)); - let receipt = radroots_execution::OperationReceipt::from_snapshot(&snapshot); + let receipt = radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert_eq!( receipt .recovery() @@ -388,7 +392,7 @@ async fn actual_loopback_wrong_ack_timeout_disconnect_and_rejection_remain_disti .unwrap() .unwrap(); assert!(snapshot.installed_message().is_some()); - let view = radroots_execution::OperationReceipt::from_snapshot(&snapshot); + let view = radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert!( view.recovery() .contains(&radroots_execution::RecoveryRequirement::ResumeDelivery) diff --git a/crates/radroots/tests/support/receipt_installation.rs b/crates/radroots/tests/support/receipt_installation.rs @@ -183,7 +183,7 @@ async fn actual_peer_installation_and_late_self_capture_keep_one_original_messag assert_eq!(state.publications().len(), 1); assert_eq!(state.publications()[0].evidence(), peer_capture); assert_ne!(before.checkpoint_digest(), state.checkpoint_digest()); - let view = OperationReceipt::from_snapshot(&state); + let view = OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&state).unwrap(); assert_eq!( view.business_installation(), BusinessInstallation::Installed @@ -232,7 +232,7 @@ async fn actual_peer_installation_and_late_self_capture_keep_one_original_messag .unwrap(); assert!(matches!(captured, EvidenceCaptureOutcome::Committed(_))); let late = snapshot(&reopened, &binding, &prepared, &proof).await; - let late = OperationReceipt::from_snapshot(&late); + let late = OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&late).unwrap(); assert_eq!( late.business_installation(), BusinessInstallation::Installed @@ -273,7 +273,8 @@ async fn actual_peer_installation_and_late_self_capture_keep_one_original_messag assert_eq!(peer_work.transaction_id(), first.transaction_id()); assert_ne!(self_work.transaction_id(), first.transaction_id()); assert_eq!(self_work.queued_at().get(), 151); - let receipt = OperationReceipt::from_snapshot(&complete); + let receipt = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&complete).unwrap(); assert_eq!(receipt.installed_at(), Some(first.installed_at())); assert_eq!(receipt.business_result(), Some(&message)); assert_eq!(receipt.recovery(), &[RecoveryRequirement::ResumeDelivery]); diff --git a/crates/radroots/tests/support/receipt_public_snapshots.rs b/crates/radroots/tests/support/receipt_public_snapshots.rs @@ -0,0 +1,676 @@ +//! Structural report consistency over actual retained public command facts. +//! These transformations neither alter the journal nor grant dispatch rights. +use super::*; +use radroots_domain::TransactionId; +use radroots_storage::command::{ + ArtifactSnapshot, BoundSigningPlan, CapturedArtifact, ChatInstallation, ClaimAttemptRequest, + DeliveryAttempt, DeliveryAttemptRequest, DeliveryAttemptSummary, DeliveryIntent, + ListingInstallation, OperationSnapshot, PublicPublicationWork, PublicationArtifact, + RetainedOperation, SigningTarget, +}; + +async fn original_plan(ready: &Ready, id: u8) -> BoundSigningPlan { + let snapshot = ready.snapshot(id).await; + ready + .store + .signing_plan( + ready.scope.binding().clone(), + OperationId::from_bytes([id; 32]), + snapshot.prepared().identity().command_digest(), + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap() +} + +async fn bare(ready: &Ready, id: u8) -> OperationSnapshot { + let snapshot = ready.snapshot(id).await; + OperationSnapshot::from_store_report( + RetainedOperation::Planned(Box::new(original_plan(ready, id).await)), + snapshot.artifacts().to_vec(), + snapshot.observed_at(), + ) + .unwrap() +} + +async fn installed(ready: &Ready, id: u8) -> OperationSnapshot { + let snapshot = ready.snapshot(id).await; + bare(ready, id) + .await + .with_public_installation( + snapshot.listing_installation(), + snapshot.public_publications().to_vec(), + ) + .unwrap() +} + +async fn original_capture(ready: &Ready, id: u8) -> CapturedArtifact { + let plan = original_plan(ready, id).await; + ready + .store + .obtained_evidence( + ClaimAttemptRequest::for_artifact( + ready.scope.binding().clone(), + OperationId::from_bytes([id; 32]), + plan.prepared().identity().command_digest(), + *plan.plan().digest(), + SigningTarget::PublicEvent, + ), + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +async fn public_reports_cannot_cross_actual_authenticated_workspaces_for_the_same_signer() { + let relay = Relay::new().await; + let first = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + let second = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + assert_ne!(first.input.workspace_id(), second.input.workspace_id()); + for ready in [&first, &second] { + ready + .client + .listings() + .publish(ready.context(224, now() + 120), input(224)) + .await + .unwrap(); + } + let original = first.snapshot(224).await; + let foreign = second.snapshot(224).await; + let work = original.public_publications()[0]; + let intent = original.delivery_attempts()[0].intent().clone(); + assert!(DeliveryAttemptRequest::new(second.scope.binding().clone(), work, intent).is_err()); + assert!( + ListingInstallation::from_committed_store( + &original_plan(&first, 224).await, + foreign.public_publications()[0].evidence(), + original.listing_installation().unwrap().transaction_id(), + original.listing_installation().unwrap().installed_at(), + ) + .is_err() + ); + let captured = original_capture(&first, 224).await; + let foreign_capture = original_capture(&second, 224).await; + let foreign_attempt = second + .store + .signing_attempt( + ClaimAttemptRequest::for_artifact( + second.scope.binding().clone(), + OperationId::from_bytes([224; 32]), + foreign.prepared().identity().command_digest(), + *foreign_capture.attempt().bound_plan().plan().digest(), + SigningTarget::PublicEvent, + ), + copy(&second.proof), + ) + .await + .unwrap() + .unwrap(); + assert!(!captured.evidence().matches_attempt(&foreign_attempt)); + assert!( + CapturedArtifact::from_committed_store( + foreign_attempt, + captured.evidence().retained_copy(), + captured.receipt().transaction_id(), + ) + .is_err() + ); + assert_eq!( + first.snapshot(224).await.checkpoint_digest(), + original.checkpoint_digest() + ); + assert_eq!( + second.snapshot(224).await.checkpoint_digest(), + foreign.checkpoint_digest() + ); + assert_eq!(relay.count.load(Ordering::SeqCst), 2); + for ready in [&first, &second] { + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0); + ready.client.close().await.unwrap(); + } + stop(relay).await; +} + +#[tokio::test] +async fn public_reports_require_original_plan_obtained_basis_and_atomic_installation_links() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + for id in [220, 221] { + ready + .client + .listings() + .publish(ready.context(id, now() + 120), input(id)) + .await + .unwrap(); + } + let original = ready.snapshot(220).await; + let other = ready.snapshot(221).await; + let installation = original.listing_installation().unwrap(); + let work = original.public_publications()[0]; + let before = original.checkpoint_digest(); + assert!( + bare(&ready, 220) + .await + .with_public_installation(None, vec![work]) + .is_err() + ); + for works in [ + vec![], + vec![work, work], + other.public_publications().to_vec(), + ] { + assert!( + bare(&ready, 220) + .await + .with_public_installation(Some(installation), works) + .is_err() + ); + } + assert!( + bare(&ready, 220) + .await + .with_public_installation(other.listing_installation(), vec![work],) + .is_err() + ); + + // Work may describe a later transaction, but cannot masquerade as the + // initial atomic T2 pair required by this snapshot profile. + for (transaction, time) in [ + ( + TransactionId::from_bytes([222; 32]), + installation.installed_at(), + ), + ( + installation.transaction_id(), + UnixSeconds::new(installation.installed_at().get() + 1).unwrap(), + ), + ] { + let changed = PublicPublicationWork::from_committed_store( + &original_plan(&ready, 220).await, + installation, + work.evidence(), + transaction, + time, + ) + .unwrap(); + assert!( + bare(&ready, 220) + .await + .with_public_installation(Some(installation), vec![changed]) + .is_err() + ); + } + let artifact = original.artifacts()[0]; + let unknown = ArtifactSnapshot::from_store_report( + SigningTarget::PublicEvent, + artifact.expected_event(), + artifact.claim(), + None, + ); + let incomplete = OperationSnapshot::from_store_report( + RetainedOperation::Planned(Box::new(original_plan(&ready, 220).await)), + vec![unknown], + original.observed_at(), + ) + .unwrap(); + assert!( + incomplete + .with_public_installation(Some(installation), vec![work]) + .is_err() + ); + let preparation = ready + .store + .operation( + ready.scope.binding().clone(), + OperationId::from_bytes([220; 32]), + None, + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + let unplanned = OperationSnapshot::from_store_report( + RetainedOperation::Prepared(preparation), + vec![ArtifactSnapshot::from_store_report( + SigningTarget::PublicEvent, + None, + None, + None, + )], + original.observed_at(), + ) + .unwrap(); + assert!( + unplanned + .with_public_installation(Some(installation), vec![work]) + .is_err() + ); + + // An independently verified public signature supplies no private subject, + // business seal or chat installation through any retained projection. + assert!(artifact.recipient().is_err()); + assert!(artifact.claim().unwrap().recipient().is_err()); + assert!(artifact.obtained().unwrap().recipient().is_err()); + assert!(PublicationArtifact::Public(work).private().is_err()); + let plan = original_plan(&ready, 220).await; + let selector = ClaimAttemptRequest::for_artifact( + ready.scope.binding().clone(), + OperationId::from_bytes([220; 32]), + original.prepared().identity().command_digest(), + *plan.plan().digest(), + SigningTarget::PublicEvent, + ); + assert!(selector.recipient().is_err()); + let attempt = ready + .store + .signing_attempt(selector, copy(&ready.proof)) + .await + .unwrap() + .unwrap(); + assert!(attempt.seal().is_err()); + assert!( + ListingInstallation::from_committed_store( + &plan, + other.public_publications()[0].evidence(), + installation.transaction_id(), + installation.installed_at(), + ) + .is_err() + ); + let other_plan = original_plan(&ready, 221).await; + let other_attempt = ready + .store + .signing_attempt( + ClaimAttemptRequest::for_artifact( + ready.scope.binding().clone(), + OperationId::from_bytes([221; 32]), + other.prepared().identity().command_digest(), + *other_plan.plan().digest(), + SigningTarget::PublicEvent, + ), + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + let captured = ready + .store + .obtained_evidence( + ClaimAttemptRequest::for_artifact( + ready.scope.binding().clone(), + OperationId::from_bytes([220; 32]), + original.prepared().identity().command_digest(), + *plan.plan().digest(), + SigningTarget::PublicEvent, + ), + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert!( + CapturedArtifact::from_committed_store( + other_attempt, + captured.evidence().retained_copy(), + captured.receipt().transaction_id(), + ) + .is_err() + ); + assert!( + ListingInstallation::from_committed_store( + &plan, + work.evidence(), + installation.transaction_id(), + UnixSeconds::new(plan.bound_at().get() - 1).unwrap(), + ) + .is_err() + ); + assert!( + ChatInstallation::from_committed_store( + &plan, + work.evidence(), + installation.transaction_id(), + installation.installed_at(), + ) + .is_err() + ); + let earlier = UnixSeconds::new(installation.installed_at().get() - 1).unwrap(); + assert!( + PublicPublicationWork::from_committed_store( + &plan, + installation, + work.evidence(), + installation.transaction_id(), + earlier, + ) + .is_err() + ); + assert!( + installed(&ready, 220) + .await + .with_installation(None, vec![]) + .is_err() + ); + assert_eq!(ready.snapshot(220).await.checkpoint_digest(), before); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2); + assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 2); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +fn descriptor( + original: &DeliveryAttempt, + id: &str, + transaction: TransactionId, + ordinal: u8, + policy: &SatisfactionPolicy, +) -> DeliveryAttemptSummary { + let intent = DeliveryIntent::public( + id, + original.intent().event_id(), + original.intent().targets(), + policy, + original.intent().deadline_unix_ms(), + ) + .unwrap() + .with_selection(&original.intent().selected_target_set().unwrap()) + .unwrap(); + let report = DeliveryAttempt::from_store_report( + original.work(), + intent, + original.raw_json(), + transaction, + original.retained_at(), + vec![ordinal], + ) + .unwrap(); + DeliveryAttemptSummary::from_attempt(&report) +} + +#[tokio::test] +async fn public_delivery_reports_refuse_unbacked_duplicate_renumbered_or_redefined_history() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + ready + .client + .listings() + .publish(ready.context(222, now() + 120), input(222)) + .await + .unwrap(); + let snapshot = ready.snapshot(222).await; + let summary = &snapshot.delivery_attempts()[0]; + let original = ready + .store + .delivery_attempt( + ready.scope.binding().clone(), + OperationId::from_bytes([222; 32]), + snapshot.prepared().identity().command_digest(), + SigningTarget::PublicEvent, + summary.intent().request_id().clone(), + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + let observations = snapshot.delivery_observations().to_vec(); + assert_eq!(observations.len(), 1); + assert!( + bare(&ready, 222) + .await + .publication_accepted(original.work()) + .is_err() + ); + + // Re-encoding even an authentic event cannot replace its original retained + // bytes. Corrupted signed fields and an oversized carrier refuse too. + let spaced = format!(" {}", original.raw_json()); + nostr::Event::from_json(&spaced).unwrap().verify().unwrap(); + let signed = nostr::Event::from_json(original.raw_json()).unwrap(); + let keys = route_key(1); + assert_eq!(signed.pubkey, keys.public_key()); + for (kind, content) in [ + (nostr::Kind::TextNote, signed.content.clone()), + (signed.kind, "Another authentic event".to_owned()), + ] { + let foreign = nostr::UnsignedEvent { + id: None, + pubkey: signed.pubkey, + created_at: signed.created_at, + kind, + tags: signed.tags.clone(), + content, + } + .sign_with_keys(&keys) + .unwrap(); + foreign.verify().unwrap(); + assert!( + DeliveryAttempt::from_store_report( + original.work(), + original.intent().clone(), + &foreign.as_json(), + original.transaction_id(), + original.retained_at(), + vec![1], + ) + .is_err() + ); + } + let mut wrong_kind: serde_json::Value = serde_json::from_str(original.raw_json()).unwrap(); + wrong_kind["kind"] = json!(1); + let mut wrong_id: serde_json::Value = serde_json::from_str(original.raw_json()).unwrap(); + wrong_id["id"] = json!("00".repeat(32)); + for raw in [ + spaced, + wrong_kind.to_string(), + wrong_id.to_string(), + " ".repeat(65_537), + "{".to_owned(), + ] { + assert!( + DeliveryAttempt::from_store_report( + original.work(), + original.intent().clone(), + &raw, + original.transaction_id(), + original.retained_at(), + vec![1], + ) + .is_err() + ); + } + let private_intent = DeliveryIntent::new( + original.intent().request_id().as_str(), + original.intent().event_id(), + original.intent().targets(), + original.intent().policy(), + original.intent().deadline_unix_ms(), + ) + .unwrap(); + assert!( + DeliveryAttempt::from_store_report( + original.work(), + private_intent, + original.raw_json(), + original.transaction_id(), + original.retained_at(), + vec![1], + ) + .is_err() + ); + let id = if summary.intent().request_id().as_str() == "01".repeat(32) { + "02".repeat(32) + } else { + "01".repeat(32) + }; + let tx = TransactionId::from_bytes([223; 32]); + assert_ne!(tx, summary.transaction_id()); + let second = descriptor(&original, &id, tx, 2, summary.intent().policy()); + let alternate = SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::any()); + let cases = [ + vec![summary.clone(), summary.clone()], + vec![ + summary.clone(), + descriptor( + &original, + &id, + summary.transaction_id(), + 2, + summary.intent().policy(), + ), + ], + vec![ + summary.clone(), + descriptor(&original, &id, tx, 1, summary.intent().policy()), + ], + vec![second.clone()], + vec![ + summary.clone(), + descriptor(&original, &id, tx, 2, &alternate), + ], + vec![summary.clone(); 385], + ]; + for attempts in cases { + assert!( + installed(&ready, 222) + .await + .with_delivery(attempts, observations.clone()) + .is_err() + ); + } + assert!( + bare(&ready, 222) + .await + .with_delivery(vec![summary.clone()], observations.clone()) + .is_err() + ); + assert!( + installed(&ready, 222) + .await + .with_delivery(vec![], observations.clone()) + .is_err() + ); + assert!( + installed(&ready, 222) + .await + .with_delivery(vec![summary.clone()], vec![observations[0].clone(); 2]) + .is_err() + ); + assert!( + installed(&ready, 222) + .await + .with_delivery(vec![summary.clone()], vec![observations[0].clone(); 2305]) + .is_err() + ); + let renumbered = [ + descriptor( + &original, + summary.intent().request_id().as_str(), + summary.transaction_id(), + 2, + summary.intent().policy(), + ), + descriptor(&original, &id, tx, 1, summary.intent().policy()), + ]; + assert!( + installed(&ready, 222) + .await + .with_delivery(renumbered.into(), observations.clone()) + .is_err() + ); + let valid = installed(&ready, 222) + .await + .with_delivery(vec![summary.clone(), second], observations) + .unwrap(); + assert!(valid.publication_accepted(original.work()).unwrap()); + assert_eq!( + ready.snapshot(222).await.checkpoint_digest(), + snapshot.checkpoint_digest() + ); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn public_delivery_queries_require_exact_bounded_request_and_artifact_selectors() { + use radroots_transport::sink::DeliveryRequestId; + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + ready + .client + .listings() + .publish(ready.context(223, now() + 120), input(223)) + .await + .unwrap(); + let snapshot = ready.snapshot(223).await; + let summary = &snapshot.delivery_attempts()[0]; + let operation = OperationId::from_bytes([223; 32]); + let digest = snapshot.prepared().identity().command_digest(); + let query = |target, request| { + ready.store.delivery_attempt( + ready.scope.binding().clone(), + operation, + digest, + target, + request, + copy(&ready.proof), + ) + }; + let actual = query( + SigningTarget::PublicEvent, + summary.intent().request_id().clone(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(actual.work(), summary.work()); + assert_eq!(actual.envelope_digest(), summary.envelope_digest()); + for id in ["short".to_owned(), "GG".repeat(32)] { + assert!(matches!( + query( + SigningTarget::PublicEvent, + DeliveryRequestId::parse(id).unwrap() + ) + .await, + Err(OperationError::InvalidCommand) + )); + } + let missing = if summary.intent().request_id().as_str() == "00".repeat(32) { + "11".repeat(32) + } else { + "00".repeat(32) + }; + assert!( + query( + SigningTarget::PublicEvent, + DeliveryRequestId::parse(missing).unwrap() + ) + .await + .unwrap() + .is_none() + ); + assert!( + query( + SigningTarget::BusinessSeal(key()), + summary.intent().request_id().clone() + ) + .await + .unwrap() + .is_none() + ); + assert_eq!( + ready.snapshot(223).await.checkpoint_digest(), + snapshot.checkpoint_digest() + ); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + ready.client.close().await.unwrap(); + stop(relay).await; +} diff --git a/crates/radroots/tests/support/receipt_snapshots.rs b/crates/radroots/tests/support/receipt_snapshots.rs @@ -215,7 +215,8 @@ async fn expiry_blocks_remaining_first_issuance_without_erasing_obtained_or_unkn .await .unwrap() .unwrap(); - let receipt = OperationReceipt::from_snapshot(&snapshot); + let receipt = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert!(receipt.durable()); assert_eq!( receipt.admission_transaction_id(), @@ -304,7 +305,8 @@ async fn full_receipts_keep_obtained_and_unknown_recipients_separate_and_bind_or .await .unwrap() .unwrap(); - let view = OperationReceipt::from_snapshot(&snapshot); + let view = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert_eq!(view.command_digest(), prepared.identity().command_digest()); assert_eq!(view.artifacts()[0].issuance(), Issuance::Obtained); assert_eq!(view.artifacts()[1].issuance(), Issuance::Unknown); @@ -372,7 +374,8 @@ async fn full_receipts_keep_obtained_and_unknown_recipients_separate_and_bind_or .await .unwrap() .unwrap(); - let completed = OperationReceipt::from_snapshot(&snapshot); + let completed = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert_eq!(completed.issuance(), Issuance::Obtained); assert_eq!(completed.error(), None); assert_eq!( @@ -395,7 +398,8 @@ async fn full_receipts_keep_obtained_and_unknown_recipients_separate_and_bind_or .await .unwrap() .unwrap(); - let later = OperationReceipt::from_snapshot(&later); + let later = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&later).unwrap(); assert_eq!(later.observed_at().get(), 110); assert_eq!(later.operation_checkpoint(), checkpoint); assert_eq!(later.artifacts()[1].attempt_id(), Some(second.attempt_id())); @@ -434,7 +438,8 @@ async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_cap prepared.transaction_id() ); assert!(snapshot.bound_plan().is_none()); - let receipt = OperationReceipt::from_snapshot(&snapshot); + let receipt = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert!(receipt.durable()); assert_eq!(receipt.issuance(), Issuance::None); assert_eq!( @@ -477,7 +482,8 @@ async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_cap .unwrap() .unwrap(); assert_eq!(snapshot.message_id(), Some(message)); - let receipt = OperationReceipt::from_snapshot(&snapshot); + let receipt = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert_eq!(receipt.issuance(), Issuance::Pending); assert_ne!(receipt.operation_checkpoint(), initial_checkpoint); assert_eq!( @@ -511,7 +517,8 @@ async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_cap attempt.attempt_id() ); assert!(snapshot.artifacts()[0].obtained().is_none()); - let receipt = OperationReceipt::from_snapshot(&snapshot); + let receipt = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert_eq!(receipt.issuance(), Issuance::Unknown); assert_eq!(receipt.artifacts()[0].issuance(), Issuance::Unknown); assert_eq!(receipt.artifacts()[1].issuance(), Issuance::Pending); @@ -540,7 +547,8 @@ async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_cap .unwrap() .unwrap(); assert_eq!(snapshot.artifacts()[0].obtained(), Some(receipt)); - let view = OperationReceipt::from_snapshot(&snapshot); + let view = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert_eq!(view.issuance(), Issuance::Pending); assert_eq!(view.artifacts()[0].issuance(), Issuance::Obtained); assert_eq!(view.artifacts()[1].issuance(), Issuance::Pending); @@ -590,7 +598,8 @@ async fn coherent_snapshots_retain_t0_t1_and_independent_recipient_claim_and_cap assert_eq!(snapshot.prepared().identity(), prepared.identity()); assert_eq!(snapshot.message_id(), Some(message)); assert_eq!(snapshot.artifacts()[0].obtained(), Some(receipt)); - let view = OperationReceipt::from_snapshot(&snapshot); + let view = + OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot(&snapshot).unwrap(); assert_eq!(view.operation_checkpoint(), captured_checkpoint); assert_eq!(view.message_id(), Some(message)); assert!(snapshot.artifacts()[1].obtained().is_none()); diff --git a/crates/radroots/tests/support/receipt_workflow.rs b/crates/radroots/tests/support/receipt_workflow.rs @@ -28,6 +28,8 @@ use tokio_tungstenite::{accept_async, tungstenite::Message}; #[path = "receipt_workflow_faults.rs"] mod faults; +#[path = "receipt_workflow_listing.rs"] +mod listing; struct Callbacks; impl SignerCallbacks for Callbacks { @@ -70,6 +72,7 @@ struct Relay { url: String, events: channel::UnboundedReceiver<String>, count: Arc<AtomicU64>, + requests: Arc<AtomicU64>, accepting: Arc<AtomicBool>, stop: oneshot::Sender<()>, task: tokio::task::JoinHandle<()>, @@ -81,6 +84,8 @@ impl Relay { let sources = Arc::new([advertisement(1, &url), advertisement(2, &url)]); let count = Arc::new(AtomicU64::new(0)); let counter = count.clone(); + let requests = Arc::new(AtomicU64::new(0)); + let read_counter = requests.clone(); let accepting = Arc::new(AtomicBool::new(true)); let acceptance = accepting.clone(); let (send, events) = channel::unbounded_channel(); @@ -92,7 +97,7 @@ impl Relay { _ = &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(); + let sources = sources.clone(); let send = send.clone(); let count = counter.clone(); let acceptance = acceptance.clone();let requests=read_counter.clone(); clients.spawn(async move { let mut socket = accept_async(tcp).await.unwrap(); while let Some(Ok(message)) = socket.next().await { @@ -100,6 +105,7 @@ impl Relay { let value: serde_json::Value = serde_json::from_str(&raw).unwrap(); match value[0].as_str().unwrap() { "REQ" => { + requests.fetch_add(1,Ordering::SeqCst); 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(); @@ -130,6 +136,7 @@ impl Relay { url, events, count, + requests, accepting, stop, task, @@ -262,6 +269,7 @@ async fn ordinary_online_inquiry_runs_t0_t1_sign_install_and_exact_peer_self_del .iter() .all(|work| snapshot.publication_accepted(*work).unwrap()) ); + assert!(relay.requests.load(Ordering::SeqCst) > 0); let original = receipt.operation_checkpoint(); let replay = client.inbox().inquire(context(), inquire()).await.unwrap(); assert_eq!(replay.operation_checkpoint(), original); @@ -274,7 +282,11 @@ async fn ordinary_online_inquiry_runs_t0_t1_sign_install_and_exact_peer_self_del .unwrap() .unwrap(); assert_eq!( - radroots_execution::OperationReceipt::from_snapshot(&snapshot).operation_checkpoint(), + radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot( + &snapshot + ) + .unwrap() + .operation_checkpoint(), original ); reopened.close_workspace().await.unwrap(); diff --git a/crates/radroots/tests/support/receipt_workflow_listing.rs b/crates/radroots/tests/support/receipt_workflow_listing.rs @@ -0,0 +1,816 @@ +//! Ordinary public commands with a signing-only provider and measured relay reads. +#[path = "receipt_public_snapshots.rs"] +mod snapshots; + +use super::*; +use radroots::listings::PublishInput; +use radroots::{BusinessInstallation, Delivery, Issuance, OperationKind}; +use radroots_execution::{Admission, Code}; +use radroots_signing::{ + issuance::{SigningIntent, SigningOutcome}, + provider::{ + PrivateCiphertext, PrivateCryptoCapability, PrivateText, ProviderCall, ProviderState, + }, +}; + +type SigningPause = (oneshot::Sender<()>, oneshot::Receiver<()>); +struct PublicSigner { + local: LocalSigner, + calls: AtomicU64, + private_calls: AtomicU64, + unknown: AtomicBool, + pause: Mutex<Option<SigningPause>>, +} +impl PublicSigner { + fn new() -> Arc<Self> { + Arc::new(Self { + local: LocalSigner::new( + parse_secret_key( + "0000000000000000000000000000000000000000000000000000000000000001", + ) + .unwrap(), + ) + .unwrap() + .with_nonce_source(Arc::new(OsNonceSource)), + calls: AtomicU64::new(0), + private_calls: AtomicU64::new(0), + unknown: AtomicBool::new(false), + pause: Mutex::new(None), + }) + } +} +impl Signer for PublicSigner { + 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 PublicSigner { + fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> { + Box::pin(async move { + let state = self.local.provider_state().await?; + Ok(ProviderState::new( + state.identity(), + PrivateCryptoCapability::Unavailable, + PrivateCryptoCapability::Unavailable, + state.signing_replay(), + ) + .with_exact_issuance(state.exact_issuance())) + }) + } + fn sign_exact(&self, intent: SigningIntent) -> BoxFuture<'_, SigningOutcome> { + Box::pin(async move { + assert_eq!(intent.recipient(), None); + self.calls.fetch_add(1, Ordering::SeqCst); + if self.unknown.load(Ordering::SeqCst) { + return SigningOutcome::unknown(intent.binding(), ProviderError::ProviderFailure); + } + let actual = 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(); + } + actual + }) + } + fn encrypt_private( + &self, + _call: ProviderCall, + _recipient: PublicKey, + _text: PrivateText, + ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> { + self.private_calls.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) + } + fn decrypt_private( + &self, + _call: ProviderCall, + _sender: PublicKey, + _text: PrivateCiphertext, + ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> { + self.private_calls.fetch_add(1, Ordering::SeqCst); + Box::pin(async { Err(ProviderError::CapabilityUnavailable) }) + } +} +fn input(id: u8) -> PublishInput { + let wire = json!({"id":format!("{id:02x}").repeat(16),"title":" Native carrots 🥕 ","summary":"Quote required","description_markdown":"Exact public terms", + "published_at":now().to_string(),"profile":{"profile":"radroots.listing","version":1,"state":"active", + "product":{"name":"Carrots","description":"x".repeat(4096),"producer":null,"origin_summary":null}, + "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"Bunch","unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}}, + "increment":"1","minimum":"1","price":{"type":"quote_required"},"supply":{"type":"available","amount":"10"},"lead_seconds":"0"}], + "fulfillment":{"modes":["pickup"],"area":"Example","lead_seconds":"0"},"authority":null,"media":[]}}); + PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap() +} +fn config(relay: &Relay) -> Config { + Config::from_profile( + RelayProfile::explicit( + RelayProfileKind::Simulator, + [ + RelayEndpoint::new(&relay.url, RelayUrlPolicy::Local, RelayAccess::ReadWrite) + .unwrap(), + ], + ) + .unwrap(), + ) + .with_timeouts(2000, 2000, 2000) + .unwrap() +} +struct Ready { + fixture: Fixture, + store: Arc<NativeWorkspace>, + client: Client, + scope: radroots::WorkspaceSession, + input: AttachmentInput, + proof: AttachmentProof, + signer: Arc<PublicSigner>, +} +async fn open( + fixture: &Fixture, + store: &NativeWorkspace, + relay: &Relay, + name: &str, + signer: Arc<PublicSigner>, + credential: (&AttachmentInput, &AttachmentProof), + mode: StartMode, +) -> (Client, radroots::WorkspaceSession) { + let (input, proof) = credential; + let cache = fixture.path.parent().unwrap().join(name); + std::fs::create_dir(&cache).unwrap(); + let options = OpenOptions::new(Paths::from_directory(cache).unwrap(), OpenMode::Create) + .with_source_generation(SourceGeneration::new([41; 32]).unwrap(), 1) + .unwrap(); + let client = Client::open( + NativeConfig::public_read(options) + .with_workspace(store.clone()) + .with_nostr( + config(relay), + 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, Arc::new(Callbacks))) + .await + .unwrap(); + client.start(mode).await.unwrap(); + (client, scope) +} +impl Ready { + async fn new(relay: &Relay, mode: StartMode, signer: Arc<PublicSigner>, seller: bool) -> Self { + let fixture = Fixture::new(); + fixture.clock.live.store(true, Ordering::SeqCst); + let cfg = if seller { + LocalOutboxConfig::seller( + key(), + key(), + "public-workflow", + UnixSeconds::new(now() + 600).unwrap(), + ) + } else { + LocalOutboxConfig::new( + key(), + key(), + "public-workflow", + UnixSeconds::new(now() + 600).unwrap(), + ) + } + .unwrap(); + let (store, input, proof) = NativeWorkspace::initialize_local_outbox( + &fixture.path, + cfg, + fixture.crypto(), + fixture.clock.clone(), + ) + .await + .unwrap(); + let store = Arc::new(store); + let (client, scope) = open( + &fixture, + &store, + relay, + "cache", + signer.clone(), + (&input, &proof), + mode, + ) + .await; + Self { + fixture, + store, + client, + scope, + input, + proof, + signer, + } + } + fn context(&self, id: u8, deadline: u64) -> radroots::CommandContext { + self.scope + .command_context( + OperationId::from_bytes([id; 32]), + None, + None, + UnixSeconds::new(deadline).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 stop(relay: Relay) { + relay.stop.send(()).unwrap(); + relay.task.await.unwrap(); +} + +#[tokio::test] +async fn ordinary_public_publish_uses_no_private_capability_and_queries_the_actual_listing_after_reopen() + { + let mut relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + let captured = input(211); + let deadline = now() + 120; + let receipt = ready + .client + .listings() + .publish(ready.context(211, deadline), captured.clone()) + .await + .unwrap(); + assert_eq!(receipt.kind(), OperationKind::Listing); + assert_eq!( + receipt.business_installation(), + BusinessInstallation::Installed + ); + assert_eq!(receipt.issuance(), Issuance::Obtained); + assert_eq!(receipt.delivery(), Delivery::Observed); + assert_eq!(receipt.message_id(), None); + assert!(receipt.record_ids().is_empty()); + let listing = receipt.business_result().unwrap(); + assert_eq!(listing.id(), captured.id()); + assert_eq!(listing.author(), key()); + assert_eq!(listing.text(), captured.text()); + assert_eq!(listing.terms(), captured.terms()); + assert_eq!(listing.published_at(), captured.published_at()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.requests.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + let raw = tokio::time::timeout(Duration::from_secs(5), relay.events.recv()) + .await + .unwrap() + .unwrap(); + let independent = nostr::Event::from_json(&raw).unwrap(); + independent.verify().unwrap(); + assert_eq!(independent.kind.as_u16(), 30402); + assert_eq!(independent.id.as_bytes(), listing.revision().as_bytes()); + assert!( + independent + .tags + .iter() + .any(|tag| tag.as_slice().iter().any(|v| v.len() > 4096)) + ); + let snapshot = ready.snapshot(211).await; + assert!(snapshot.publications().is_empty()); + assert!(snapshot.installed_message().is_none()); + assert!( + snapshot + .publication_accepted(snapshot.public_publications()[0]) + .unwrap() + ); + assert!(matches!( + radroots_execution::OperationReceipt::<radroots_domain::ChatMessage>::try_from_snapshot( + &snapshot + ), + Err(OperationError::UnsupportedOperation) + )); + let status = ready + .client + .operations(&ready.scope) + .get(OperationId::from_bytes([211; 32])) + .await + .unwrap() + .unwrap(); + assert_eq!(status.kind(), OperationKind::Listing); + assert_eq!(status.message_id(), None); + assert_eq!( + status.business_result().unwrap().as_listing().unwrap(), + listing + ); + assert!(status.business_result().unwrap().as_chat().is_none()); + let replay = ready + .client + .listings() + .publish(ready.context(211, deadline), captured) + .await + .unwrap(); + assert_eq!( + replay.operation_checkpoint(), + receipt.operation_checkpoint() + ); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + ready.client.close().await.unwrap(); + let store = ready.fixture.reopen(ready.input.clone()).await; + let (client, scope) = open( + &ready.fixture, + &store, + &relay, + "cache-reopened", + ready.signer.clone(), + (&ready.input, &ready.proof), + StartMode::Online, + ) + .await; + let restored = client + .operations(&scope) + .get(OperationId::from_bytes([211; 32])) + .await + .unwrap() + .unwrap(); + assert_eq!( + restored.operation_checkpoint(), + receipt.operation_checkpoint() + ); + assert_eq!( + restored.business_result().unwrap().as_listing().unwrap(), + listing + ); + let resumed = client + .operations(&scope) + .resume( + OperationId::from_bytes([211; 32]), + Some(receipt.command_digest()), + ) + .await + .unwrap(); + assert_eq!( + resumed.operation_checkpoint(), + receipt.operation_checkpoint() + ); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn ordinary_local_public_admission_returns_listing_family_without_signing_or_network() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::LocalOnly, PublicSigner::new(), true).await; + let receipt = ready + .client + .listings() + .publish(ready.context(212, now() + 120), input(212)) + .await + .unwrap(); + assert!(receipt.durable()); + assert_eq!(receipt.kind(), OperationKind::Listing); + assert!(receipt.business_result().is_none()); + assert_eq!(receipt.issuance(), Issuance::None); + assert_eq!(receipt.message_id(), None); + let status = ready + .client + .operations(&ready.scope) + .get(OperationId::from_bytes([212; 32])) + .await + .unwrap() + .unwrap(); + assert_eq!(status.kind(), OperationKind::Listing); + assert!(status.business_result().is_none()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 0); + assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn ordinary_public_explicit_retry_after_first_issue_expiry_preserves_original_bytes_and_policy() + { + let mut relay = Relay::new().await; + relay.accepting.store(false, Ordering::SeqCst); + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + let deadline = now() + 10; + let captured = input(213); + let receipt = ready + .client + .listings() + .publish(ready.context(213, deadline), captured.clone()) + .await + .unwrap(); + assert!(receipt.business_result().is_some()); + let original = relay.events.recv().await.unwrap(); + let before = ready.snapshot(213).await; + let policy = *before.delivery_attempts()[0] + .intent() + .publication_policy_digest(); + assert!( + !before + .publication_accepted(before.public_publications()[0]) + .unwrap() + ); + let replay = ready + .client + .listings() + .publish(ready.context(213, deadline), captured) + .await + .unwrap(); + assert_eq!( + replay.operation_checkpoint(), + receipt.operation_checkpoint() + ); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + tokio::time::sleep(Duration::from_secs(deadline.saturating_sub(now()) + 1)).await; + relay.accepting.store(true, Ordering::SeqCst); + let resumed = ready + .client + .operations(&ready.scope) + .resume( + OperationId::from_bytes([213; 32]), + Some(receipt.command_digest()), + ) + .await + .unwrap(); + assert_eq!(resumed.issuance_window(), receipt.issuance_window()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!( + tokio::time::timeout(Duration::from_secs(5), relay.events.recv()) + .await + .unwrap() + .unwrap(), + original + ); + let after = ready.snapshot(213).await; + assert_eq!(after.delivery_attempts().len(), 2); + assert!( + after + .publication_accepted(after.public_publications()[0]) + .unwrap() + ); + assert!( + after + .delivery_attempts() + .iter() + .all(|v| v.intent().publication_policy_digest() == &policy) + ); + assert!( + after + .delivery_attempts() + .iter() + .any(|attempt| attempt.target_ordinals() == [2]) + ); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn ordinary_public_resume_requires_original_targets_to_remain_configured() { + let mut original_relay = Relay::new().await; + original_relay.accepting.store(false, Ordering::SeqCst); + let replacement = Relay::new().await; + let ready = Ready::new( + &original_relay, + StartMode::Online, + PublicSigner::new(), + true, + ) + .await; + let receipt = ready + .client + .listings() + .publish(ready.context(218, now() + 120), input(218)) + .await + .unwrap(); + let original_bytes = original_relay.events.recv().await.unwrap(); + let before = ready.snapshot(218).await; + assert_eq!(before.delivery_attempts().len(), 1); + ready.client.close().await.unwrap(); + + let store = ready.fixture.reopen(ready.input.clone()).await; + let (client, scope) = open( + &ready.fixture, + &store, + &replacement, + "cache-reconfigured", + ready.signer.clone(), + (&ready.input, &ready.proof), + StartMode::Online, + ) + .await; + let observed = client + .operations(&scope) + .get(OperationId::from_bytes([218; 32])) + .await + .unwrap() + .unwrap(); + assert_eq!( + observed.operation_checkpoint(), + receipt.operation_checkpoint() + ); + let error = client + .operations(&scope) + .resume( + OperationId::from_bytes([218; 32]), + Some(receipt.command_digest()), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Unauthorized); + assert_eq!(error.context().admission(), Admission::Confirmed); + assert_eq!( + error.context().operation_id(), + Some(OperationId::from_bytes([218; 32])) + ); + let after = store + .operation_snapshot( + scope.binding().clone(), + OperationId::from_bytes([218; 32]), + Some(receipt.command_digest()), + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(after.checkpoint_digest(), before.checkpoint_digest()); + assert_eq!(after.delivery_attempts().len(), 1); + assert_eq!(replacement.count.load(Ordering::SeqCst), 0); + assert_eq!(replacement.requests.load(Ordering::SeqCst), 0); + assert_eq!(original_relay.count.load(Ordering::SeqCst), 1); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + client.close().await.unwrap(); + + original_relay.accepting.store(true, Ordering::SeqCst); + let store = ready.fixture.reopen(ready.input.clone()).await; + let (client, scope) = open( + &ready.fixture, + &store, + &original_relay, + "cache-original-restored", + ready.signer.clone(), + (&ready.input, &ready.proof), + StartMode::Online, + ) + .await; + let resumed = client + .operations(&scope) + .resume( + OperationId::from_bytes([218; 32]), + Some(receipt.command_digest()), + ) + .await + .unwrap(); + assert_eq!(resumed.business_result(), observed.business_result()); + assert!( + resumed + .delivery_observations() + .iter() + .any(|observation| { observation.outcome() == radroots::TargetObservation::Accepted }) + ); + assert_eq!( + tokio::time::timeout(Duration::from_secs(5), original_relay.events.recv()) + .await + .unwrap() + .unwrap(), + original_bytes + ); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0); + client.close().await.unwrap(); + stop(replacement).await; + stop(original_relay).await; +} + +#[tokio::test] +async fn public_snapshot_cannot_remove_installation_beneath_retained_delivery() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + ready + .client + .listings() + .publish(ready.context(219, now() + 120), input(219)) + .await + .unwrap(); + let snapshot = ready.snapshot(219).await; + assert!(snapshot.listing_installation().is_some()); + assert!(!snapshot.delivery_attempts().is_empty()); + assert!(!snapshot.delivery_observations().is_empty()); + let changed = snapshot.with_public_installation(None, vec![]); + ready.client.close().await.unwrap(); + stop(relay).await; + assert!(matches!(changed, Err(OperationError::RecoveryRequired))); +} + +#[tokio::test] +async fn ordinary_unknown_public_issuance_is_never_reissued_by_query_or_explicit_resume() { + let relay = Relay::new().await; + let signer = PublicSigner::new(); + signer.unknown.store(true, Ordering::SeqCst); + let ready = Ready::new(&relay, StartMode::Online, signer, true).await; + let receipt = ready + .client + .listings() + .publish(ready.context(214, now() + 120), input(214)) + .await + .unwrap(); + assert_eq!(receipt.issuance(), Issuance::Unknown); + assert!(receipt.business_result().is_none()); + assert_eq!(receipt.message_id(), None); + let resumed = ready + .client + .operations(&ready.scope) + .resume( + OperationId::from_bytes([214; 32]), + Some(receipt.command_digest()), + ) + .await + .unwrap(); + assert_eq!(resumed.issuance(), Issuance::Unknown); + assert!(resumed.business_result().is_none()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + ready.client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn ordinary_public_observer_loss_retains_actual_obtained_output_until_close_drains() { + let relay = Relay::new().await; + let signer = PublicSigner::new(); + 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, true).await; + let context = ready.context(215, now() + 120); + let client = ready.client.clone(); + let value = input(215); + let observer = tokio::spawn(async move { client.listings().publish(context, value).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!(matches!( + NativeWorkspace::open_existing( + &ready.fixture.path, + ready.input.clone(), + ready.fixture.crypto(), + ready.fixture.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + 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.clone()).await; + let snapshot = reopened + .operation_snapshot( + ready.scope.binding().clone(), + OperationId::from_bytes([215; 32]), + None, + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert!(snapshot.artifacts()[0].obtained().is_some()); + assert!(snapshot.listing_installation().is_some()); + assert!(snapshot.installed_message().is_none()); + reopened.close_workspace().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn ordinary_public_capture_failure_retains_writer_and_recovers_original_without_new_signature() + { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + let mut db = ready.fixture.database().await; + sqlx::query("CREATE TRIGGER public_capture_fault BEFORE INSERT ON artifact_evidence BEGIN SELECT RAISE(ABORT,'public_capture_fault'); END").execute(&mut db).await.unwrap(); + assert!( + ready + .client + .listings() + .publish(ready.context(216, now() + 120), input(216)) + .await + .is_err() + ); + assert!(ready.client.close().await.is_err()); + assert!(matches!( + NativeWorkspace::open_existing( + &ready.fixture.path, + ready.input.clone(), + ready.fixture.crypto(), + ready.fixture.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + sqlx::query("DROP TRIGGER public_capture_fault") + .execute(&mut db) + .await + .unwrap(); + db.close().await.unwrap(); + ready.client.close().await.unwrap(); + let reopened = ready.fixture.reopen(ready.input.clone()).await; + let snapshot = reopened + .operation_snapshot( + ready.scope.binding().clone(), + OperationId::from_bytes([216; 32]), + None, + copy(&ready.proof), + ) + .await + .unwrap() + .unwrap(); + assert!(snapshot.artifacts()[0].obtained().is_some()); + assert!(snapshot.listing_installation().is_none()); + let (client, scope) = open( + &ready.fixture, + &reopened, + &relay, + "cache-recovery", + ready.signer.clone(), + (&ready.input, &ready.proof), + StartMode::Online, + ) + .await; + let resumed = client + .operations(&scope) + .resume( + OperationId::from_bytes([216; 32]), + Some(snapshot.prepared().identity().command_digest()), + ) + .await + .unwrap(); + assert_eq!( + resumed.business_installation(), + BusinessInstallation::Installed + ); + assert!(resumed.business_result().unwrap().as_listing().is_some()); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 1); + assert_eq!(relay.count.load(Ordering::SeqCst), 1); + client.close().await.unwrap(); + stop(relay).await; +} + +#[tokio::test] +async fn ordinary_publication_never_upgrades_an_actual_buyer_outbox_to_seller_authority() { + let relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), false).await; + assert!( + ready + .client + .listings() + .publish(ready.context(217, now() + 120), input(217)) + .await + .is_err() + ); + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 0); + assert!( + ready + .store + .operation( + ready.scope.binding().clone(), + OperationId::from_bytes([217; 32]), + None, + copy(&ready.proof) + ) + .await + .unwrap() + .is_none() + ); + ready.client.close().await.unwrap(); + stop(relay).await; +} diff --git a/crates/radroots_browser/src/client.rs b/crates/radroots_browser/src/client.rs @@ -4,13 +4,13 @@ use crate::{ WorkspaceSession, }; use crate::{ - inquiry::{BrowserInquiry, unix_seconds}, + commands::{BrowserCommands, unix_seconds}, tasks::OwnedTasks, }; use radroots_domain::{ChatMessage, CommandDigest, UnixSeconds}; use radroots_execution::{ Code, Error, OperationContext, RetryClass, - session::{ClientSession, HostFuture, SessionHost, SignerSession, inquiry::InquiryRuntime}, + session::{ClientSession, HostFuture, SessionHost, SignerSession, command::CommandRuntime}, }; use radroots_secrets::{SecretId, SecretRef, browser::BrowserProvider, provider::AccessPolicy}; use radroots_signing::provider::SignerHandle; @@ -43,7 +43,7 @@ pub struct BrowserConfig { input: AttachmentInput, proof: AttachmentProof, policy: AccessPolicy, - inquiry: Option<Rc<BrowserInquiry>>, + commands: Option<Rc<BrowserCommands>>, } impl BrowserConfig { /// Selects an existing key and workspace only. Missing/damaged state is an @@ -63,7 +63,7 @@ impl BrowserConfig { input, proof, policy, - inquiry: None, + commands: None, } } /// Adds explicit destinations and a relay acceptance criterion. No I/O. @@ -72,8 +72,8 @@ impl BrowserConfig { config: radroots_transport_nostr::Config, policy: radroots_transport::policy::SatisfactionPolicy, ) -> Result<Self> { - self.inquiry = Some(Rc::new( - BrowserInquiry::new(config, policy).map_err(operation)?, + self.commands = Some(Rc::new( + BrowserCommands::new(config, policy).map_err(operation)?, )); Ok(self) } @@ -88,8 +88,8 @@ struct Resources { workspace: Rc<BrowserWorkspace>, provider: Rc<BrowserProvider>, tasks: Rc<OwnedTasks>, - inquiry: Option<Rc<InquiryRuntime>>, - io: Option<Rc<BrowserInquiry>>, + commands: Option<Rc<CommandRuntime>>, + io: Option<Rc<BrowserCommands>>, storage_closed: Rc<Cell<bool>>, } impl SessionHost for Resources { @@ -102,8 +102,8 @@ impl SessionHost for Resources { fn drain(&self) -> HostFuture<'_, Result<()>> { Box::pin(async move { self.tasks.drain().await?; - if let Some(inquiry) = &self.inquiry { - inquiry.drain().await.map_err(operation)?; + if let Some(commands) = &self.commands { + commands.drain().await.map_err(operation)?; } Ok(()) }) @@ -154,7 +154,7 @@ impl CloseReceipt { pub struct Client { session: ClientSession<Resources>, workspace: Rc<BrowserWorkspace>, - io: Option<Rc<BrowserInquiry>>, + io: Option<Rc<BrowserCommands>>, storage_closed: Rc<Cell<bool>>, } impl Client { @@ -191,17 +191,17 @@ impl Client { } }; let tasks = Rc::new(OwnedTasks::default()); - let inquiry = config - .inquiry + let commands = config + .commands .as_ref() - .map(|io| Rc::new(InquiryRuntime::new(io.clone()))); + .map(|io| Rc::new(CommandRuntime::new(io.clone()))); let storage_closed = Rc::new(Cell::new(false)); let host = Resources { workspace: workspace.clone(), provider, tasks: tasks.clone(), - inquiry: inquiry.clone(), - io: config.inquiry.clone(), + commands: commands.clone(), + io: config.commands.clone(), storage_closed: storage_closed.clone(), }; const MAX: NonZeroU16 = match NonZeroU16::new(32) { @@ -209,14 +209,14 @@ impl Client { None => panic!("nonzero constant"), }; let session = ClientSession::new_with_task_host(host, MAX, tasks); - let session = match inquiry { - Some(inquiry) => session.with_inquiry_runtime(inquiry), + let session = match commands { + Some(commands) => session.with_command_runtime(commands), None => session, }; Ok(Self { session, workspace, - io: config.inquiry, + io: config.commands, storage_closed, }) } @@ -253,7 +253,7 @@ impl Client { self.session.start().await?; Ok(self.state()) } - /// Borrows the ordinary shared inquiry entry point without performing I/O. + /// Borrows the ordinary private inquiry entry point without performing I/O. pub const fn inbox(&self) -> Inbox<'_> { Inbox { client: self } } @@ -301,7 +301,10 @@ pub struct Operations<'a> { } impl Operations<'_> { /// Reads original retained progress; absence proves no safe nonissuance. - pub async fn get(&self, id: OperationId) -> Result<Option<OperationReceipt<ChatMessage>>> { + pub async fn get( + &self, + id: OperationId, + ) -> Result<Option<radroots_execution::OperationStatus>> { self.get_matching(id, None).await } /// Requires the original command digest in addition to operation identity. @@ -309,7 +312,7 @@ impl Operations<'_> { &self, id: OperationId, expected: Option<CommandDigest>, - ) -> Result<Option<OperationReceipt<ChatMessage>>> { + ) -> Result<Option<radroots_execution::OperationStatus>> { self.client .session .operation(self.client.workspace.clone(), &self.scope, id, expected) @@ -320,10 +323,10 @@ impl Operations<'_> { &self, id: OperationId, expected: Option<CommandDigest>, - ) -> Result<OperationReceipt<ChatMessage>> { + ) -> Result<radroots_execution::OperationStatus> { self.client .session - .resume_inquiry(self.client.workspace.clone(), &self.scope, id, expected) + .resume_command(self.client.workspace.clone(), &self.scope, id, expected) .await } } diff --git a/crates/radroots_browser/src/commands.rs b/crates/radroots_browser/src/commands.rs @@ -0,0 +1,204 @@ +use core::num::NonZeroU64; +use radroots_domain::{PublicKey, UnixSeconds}; +use radroots_execution::session::{ + HostFuture, + command::{CommandIo, capture_dm_route, selected_dm_targets}, +}; +use radroots_nostr::signing::gift_wrap::{randomized_past_time, wrap_retained_seal}; +use radroots_protocol::chat::CapturedDmRoute; +use radroots_signing::provider::{NonceSource, ProviderError}; +use radroots_storage::command::{EnvelopeCandidate, OperationError, PublicationWork}; +use radroots_transport::{ + EventSink, EventSource, TargetSet, + policy::{SatisfactionClass, SatisfactionPolicy}, + source::{FetchBounds, FetchRequest, FetchSelector}, +}; +use radroots_transport_nostr::{Config, NostrTransport}; +use radroots_transport_nostr_browser::BrowserConnector; +use std::{ + sync::Arc, + sync::atomic::{AtomicU8, Ordering}, +}; +use wasm_bindgen::JsCast; + +pub(crate) struct BrowserCommands { + transport: NostrTransport, + connector: Arc<BrowserConnector>, + read: TargetSet, + write: TargetSet, + policy: SatisfactionPolicy, + mode: AtomicU8, +} +impl BrowserCommands { + 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)?; + let connector = Arc::new(BrowserConnector::default()); + Ok(Self { + transport: NostrTransport::new(config, connector.clone()), + connector, + 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; + } + pub(crate) async fn dispose(&self) -> Result<(), OperationError> { + self.connector + .close() + .await + .map_err(|_| OperationError::RecoveryRequired) + } + fn capture_route<'a>( + &self, + recipient: PublicKey, + raw_sources: impl IntoIterator<Item = &'a str>, + ) -> Result<CapturedDmRoute, OperationError> { + capture_dm_route(recipient, raw_sources, &self.write) + } +} +impl CommandIo for BrowserCommands { + fn enabled(&self) -> bool { + self.mode.load(Ordering::Acquire) == 2 + } + fn now(&self) -> Result<UnixSeconds, OperationError> { + unix_seconds() + } + fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError> { + let time = randomized_past_time( + NonZeroU64::new(now.get()).ok_or(OperationError::RecoveryRequired)?, + &BrowserNonceSource, + ) + .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> { + selected_dm_targets(route, &self.write) + } + 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.recipient(); + let wrapped = wrap_retained_seal(raw_seal, recipient, now, &BrowserNonceSource) + .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 = BrowserNonceSource + .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) + } +} + +pub(crate) fn unix_seconds() -> Result<UnixSeconds, OperationError> { + let millis = js_sys::Date::now(); + if !millis.is_finite() || millis < 1000.0 { + return Err(OperationError::RecoveryRequired); + } + UnixSeconds::new((millis / 1000.0) as u64).map_err(|_| OperationError::RecoveryRequired) +} + +/// Explicit origin-thread WebCrypto CSPRNG. Construction is inert; failed +/// entropy acquisition never returns a partial nonce or falls back to a clock. +pub struct BrowserNonceSource; +impl NonceSource for BrowserNonceSource { + fn next_nonce(&self) -> Result<[u8; 32], ProviderError> { + let crypto = js_sys::Reflect::get(&js_sys::global(), &"crypto".into()) + .map_err(|_| ProviderError::CapabilityUnavailable)? + .dyn_into::<web_sys::Crypto>() + .map_err(|_| ProviderError::CapabilityUnavailable)?; + let mut nonce = [0; 32]; + crypto + .get_random_values_with_u8_array(&mut nonce) + .map_err(|_| ProviderError::CapabilityUnavailable)?; + Ok(nonce) + } +} diff --git a/crates/radroots_browser/src/inquiry.rs b/crates/radroots_browser/src/inquiry.rs @@ -1,204 +0,0 @@ -use core::num::NonZeroU64; -use radroots_domain::{PublicKey, UnixSeconds}; -use radroots_execution::session::{ - HostFuture, - inquiry::{InquiryIo, capture_dm_route, selected_dm_targets}, -}; -use radroots_nostr::signing::gift_wrap::{randomized_past_time, wrap_retained_seal}; -use radroots_protocol::chat::CapturedDmRoute; -use radroots_signing::provider::{NonceSource, ProviderError}; -use radroots_storage::command::{EnvelopeCandidate, OperationError, PublicationWork}; -use radroots_transport::{ - EventSink, EventSource, TargetSet, - policy::{SatisfactionClass, SatisfactionPolicy}, - source::{FetchBounds, FetchRequest, FetchSelector}, -}; -use radroots_transport_nostr::{Config, NostrTransport}; -use radroots_transport_nostr_browser::BrowserConnector; -use std::{ - sync::Arc, - sync::atomic::{AtomicU8, Ordering}, -}; -use wasm_bindgen::JsCast; - -pub(crate) struct BrowserInquiry { - transport: NostrTransport, - connector: Arc<BrowserConnector>, - read: TargetSet, - write: TargetSet, - policy: SatisfactionPolicy, - mode: AtomicU8, -} -impl BrowserInquiry { - 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)?; - let connector = Arc::new(BrowserConnector::default()); - Ok(Self { - transport: NostrTransport::new(config, connector.clone()), - connector, - 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; - } - pub(crate) async fn dispose(&self) -> Result<(), OperationError> { - self.connector - .close() - .await - .map_err(|_| OperationError::RecoveryRequired) - } - fn capture_route<'a>( - &self, - recipient: PublicKey, - raw_sources: impl IntoIterator<Item = &'a str>, - ) -> Result<CapturedDmRoute, OperationError> { - capture_dm_route(recipient, raw_sources, &self.write) - } -} -impl InquiryIo for BrowserInquiry { - fn enabled(&self) -> bool { - self.mode.load(Ordering::Acquire) == 2 - } - fn now(&self) -> Result<UnixSeconds, OperationError> { - unix_seconds() - } - fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError> { - let time = randomized_past_time( - NonZeroU64::new(now.get()).ok_or(OperationError::RecoveryRequired)?, - &BrowserNonceSource, - ) - .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> { - selected_dm_targets(route, &self.write) - } - 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.recipient(); - let wrapped = wrap_retained_seal(raw_seal, recipient, now, &BrowserNonceSource) - .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 = BrowserNonceSource - .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) - } -} - -pub(crate) fn unix_seconds() -> Result<UnixSeconds, OperationError> { - let millis = js_sys::Date::now(); - if !millis.is_finite() || millis < 1000.0 { - return Err(OperationError::RecoveryRequired); - } - UnixSeconds::new((millis / 1000.0) as u64).map_err(|_| OperationError::RecoveryRequired) -} - -/// Explicit origin-thread WebCrypto CSPRNG. Construction is inert; failed -/// entropy acquisition never returns a partial nonce or falls back to a clock. -pub struct BrowserNonceSource; -impl NonceSource for BrowserNonceSource { - fn next_nonce(&self) -> Result<[u8; 32], ProviderError> { - let crypto = js_sys::Reflect::get(&js_sys::global(), &"crypto".into()) - .map_err(|_| ProviderError::CapabilityUnavailable)? - .dyn_into::<web_sys::Crypto>() - .map_err(|_| ProviderError::CapabilityUnavailable)?; - let mut nonce = [0; 32]; - crypto - .get_random_values_with_u8_array(&mut nonce) - .map_err(|_| ProviderError::CapabilityUnavailable)?; - Ok(nonce) - } -} diff --git a/crates/radroots_browser/src/lib.rs b/crates/radroots_browser/src/lib.rs @@ -10,15 +10,15 @@ mod client; #[cfg(all(target_arch = "wasm32", feature = "artifact_clock"))] mod clock; #[cfg(target_arch = "wasm32")] -mod inquiry; +mod commands; #[cfg(target_arch = "wasm32")] pub use client::{BrowserConfig, Client, CloseReceipt, Inbox, Operations}; #[cfg(target_arch = "wasm32")] -pub use inquiry::BrowserNonceSource; +pub use commands::BrowserNonceSource; pub use radroots_domain::{CommandDigest, OperationId}; pub use radroots_execution::{ - OperationReceipt, + OperationKind, OperationReceipt, OperationStatus, OperationValue, inbox::InquireInput, session::{SessionState, StartMode}, workspace::{CommandContext, WorkspaceSession}, diff --git a/crates/radroots_browser/tests/browser/src/lib.rs b/crates/radroots_browser/tests/browser/src/lib.rs @@ -359,7 +359,12 @@ pub async fn verify_client(base: String, label: String) -> Result<String, JsValu completed.durable() && completed.business_result().is_some(), "explicit resume must finish original inquiry", )?; - let resumed_message = completed.business_result().unwrap().id().to_string(); + let resumed_message = completed + .business_result() + .and_then(|value| value.as_chat()) + .ok_or_else(|| JsValue::from_str("resumed inquiry must retain its actual chat result"))? + .id() + .to_string(); resumed.close().await.map_err(fail)?; storage_callbacks_closed()?; require(callbacks.closed.get() == 1, "resumed signer scope disposed")?; diff --git a/crates/storage/src/command/snapshot.rs b/crates/storage/src/command/snapshot.rs @@ -537,6 +537,9 @@ impl OperationSnapshot { installation: Option<ListingInstallation>, publications: Vec<PublicPublicationWork>, ) -> Result<Self, OperationError> { + if !self.deliveries.is_empty() || !self.observations.is_empty() { + return Err(OperationError::RecoveryRequired); + } let Some(installed) = installation else { if !publications.is_empty() { return Err(OperationError::RecoveryRequired); @@ -545,12 +548,7 @@ impl OperationSnapshot { self.public_publications = Vec::new().into_boxed_slice(); return Ok(self); }; - if self.installation.is_some() - || self.message.is_some() - || !self.publications.is_empty() - || !self.deliveries.is_empty() - || !self.observations.is_empty() - { + if self.installation.is_some() || self.message.is_some() || !self.publications.is_empty() { return Err(OperationError::RecoveryRequired); } let bound = self.bound_plan().ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/tests/issuance_records.rs b/crates/storage_sqlite/src/workspace/tests/issuance_records.rs @@ -19,6 +19,9 @@ use radroots_storage::command::{ }; use serde_json::{Value, json}; use sqlx::{Connection, SqliteConnection}; +#[path = "public_delivery_records.rs"] +mod public_delivery_records; + struct Issued { fixture: CryptoFixture, selected: AttachmentInput, diff --git a/crates/storage_sqlite/src/workspace/tests/public_delivery_records.rs b/crates/storage_sqlite/src/workspace/tests/public_delivery_records.rs @@ -0,0 +1,418 @@ +//! Actual synthetic native T0/T1/S/T2/D records, without network dispatch. +//! Codec-only report fixtures retain their separate, narrower claims. +use super::*; +use crate::workspace::{listing_installation, snapshot::RetainedGraph}; +use radroots_protocol::listing::PublicSigningPlan; +use radroots_storage::command::{ + DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryIntent, InstallationOutcome, + InstallationRequest, OperationError, SigningTarget, +}; +use radroots_transport::{ + Target, TargetSet, + policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}, +}; + +async fn actual() -> (DeliveryData, WorkspaceBinding) { + let fixture = CryptoFixture::new(); + let path = fixture + ._temp + .path() + .canonicalize() + .unwrap() + .join("actual-public"); + let (store, selected, proof) = NativeWorkspace::initialize_local_outbox( + &path, + LocalOutboxConfig::seller( + participant(), + participant(), + "public-records", + UnixSeconds::new(200).unwrap(), + ) + .unwrap(), + fixture.crypto(), + Arc::new(FixedClock(100)), + ) + .await + .unwrap(); + let binding = store.authenticate(selected.clone(), &proof).await.unwrap(); + let copied = || proof.with_secret(|raw| AttachmentProof::from_protected_input(raw).unwrap()); + let time = UnixSeconds::new(100).unwrap(); + let context = CommandContextData::new( + OperationId::from_bytes([91; 32]), + binding.actor(), + selected.workspace_id(), + selected.authority(), + selected.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let wire = json!({"type":"listing.publish","context":context,"input":{ + "id":"04".repeat(16),"title":"Actual public records","summary":"Quote required", + "description_markdown":"Retained public terms","published_at":"100", + "profile":{"profile":"radroots.listing","version":1,"state":"active", + "product":{"name":"Carrots","description":"Public description","producer":null,"origin_summary":null}, + "default_option":"02".repeat(32),"options":[{"id":"02".repeat(32),"label":"Bunch", + "unit":{"type":"package","label":"bunch","contents":{"type":"unspecified"}}, + "increment":"1","minimum":"1","price":{"type":"quote_required"}, + "supply":{"type":"available","amount":"10"},"lead_seconds":"0"}], + "fulfillment":{"modes":["pickup"],"area":"Example","lead_seconds":"0"},"authority":null,"media":[]}}}); + let request = + AdmissionRequest::from_protected_wire(binding.clone(), &serde_json::to_vec(&wire).unwrap()) + .unwrap(); + let plan = PublicSigningPlan::capture( + request.command().listing().unwrap(), + time, + &["wss://route.example/".into()], + SigningReplay::NonReplayable, + ) + .unwrap(); + let plan_digest = *plan.digest(); + let command_digest = request.command().digest(); + assert!(matches!( + store + .admit_command_and_hold(request, copied()) + .await + .unwrap(), + AdmissionOutcome::Committed(_) + )); + assert!(matches!( + store + .bind_signing_intents(binding.clone(), plan.into(), copied()) + .await + .unwrap(), + PlanBindingOutcome::Committed(_) + )); + let attempt = match store + .claim_attempt( + ClaimAttemptRequest::for_artifact( + binding.clone(), + OperationId::from_bytes([91; 32]), + command_digest, + plan_digest, + SigningTarget::PublicEvent, + ), + copied(), + ) + .await + .unwrap() + { + ClaimAttemptOutcome::Claimed(value) => value, + _ => panic!("actual public signing claim"), + }; + let artifact = attempt.artifact().unwrap(); + let fields = artifact.fields(); + let mut scalar = [0; 32]; + scalar[31] = 1; + let keys = nostr::Keys::new(nostr::SecretKey::from_slice(&scalar).unwrap()); + let signed = nostr::UnsignedEvent { + id: None, + pubkey: keys.public_key(), + created_at: nostr::Timestamp::from_secs(fields.created_at), + kind: nostr::Kind::Custom(fields.kind.try_into().unwrap()), + tags: nostr::Tags::from_list( + fields + .tags + .iter() + .map(|v| nostr::Tag::parse(v).unwrap()) + .collect(), + ), + content: fields.content.into(), + } + .sign_with_keys(&keys) + .unwrap(); + signed.verify().unwrap(); + let evidence = ArtifactEvidence::verify(&attempt, &signed.as_json(), None).unwrap(); + assert!(matches!( + store + .capture_evidence(selected.clone(), &proof, &evidence) + .await + .unwrap(), + EvidenceCaptureOutcome::Committed(_) + )); + assert!(matches!( + store + .install_transition_and_outbox( + InstallationRequest::new( + binding.clone(), + OperationId::from_bytes([91; 32]), + command_digest, + plan_digest + ), + copied() + ) + .await + .unwrap(), + InstallationOutcome::ListingCommitted(_) + )); + let snapshot = store + .operation_snapshot( + binding.clone(), + OperationId::from_bytes([91; 32]), + Some(command_digest), + copied(), + ) + .await + .unwrap() + .unwrap(); + let work = snapshot.public_publications()[0]; + let targets = + TargetSet::new(vec![Target::nostr_relay("wss://route.example/").unwrap()]).unwrap(); + let intent = DeliveryIntent::public( + &"ab".repeat(32), + work.evidence().event_id(), + &targets, + &SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), + core::num::NonZeroU64::new(110_000).unwrap(), + ) + .unwrap(); + let report = match store + .prepare_delivery_attempt( + DeliveryAttemptRequest::new(binding.clone(), work, intent).unwrap(), + copied(), + None, + ) + .await + .unwrap() + { + DeliveryAttemptOutcome::Claimed(value) => *value, + _ => panic!("actual public delivery claim"), + }; + store.close().await.unwrap(); + let issued = Issued { + fixture, + selected, + attempt, + evidence, + proof, + path, + }; + let database = issued.database().await; + let crypto = issued.fixture.crypto(); + ( + DeliveryData { + _issued: issued, + database, + crypto, + report, + }, + binding, + ) +} + +#[tokio::test] +async fn actual_public_records_refuse_reencoded_scope_and_nonatomic_initial_work() { + let (mut data, binding) = actual().await; + let selected = data.selection(); + let e = data.report.work().evidence(); + let graph = RetainedGraph::read( + &mut data.database, + &selected, + &binding, + e.operation_id(), + Some(e.command_digest()), + &data.crypto, + ) + .await + .unwrap(); + let retained = listing_installation::Records::read( + &mut data.database, + &selected, + e.operation_id(), + &graph, + &data.crypto, + ) + .await + .unwrap(); + let scope = crate::workspace::crypto::IssuanceScope { + workspace: e.workspace_id(), + operation: e.operation_id(), + plan_digest: *data.report.work().plan_digest(), + attempt: e.attempt_id(), + target: SigningTarget::PublicEvent, + }; + for (table, payload, changes) in [ + ( + "listing_installations", + IssuancePayload::ListingInstallation, + vec![ + ("/version", json!(2)), + ("/plan", json!(vec![9u8; 32])), + ("/preparation", json!("99".repeat(32))), + ("/plan_transaction", json!("99".repeat(32))), + ("/evidence/operation", json!("99".repeat(32))), + ], + ), + ( + "public_publication_work", + IssuancePayload::Publication, + vec![ + ("/version", json!(2)), + ("/installation", json!("99".repeat(32))), + ("/plan", json!(vec![9u8; 32])), + ("/evidence/attempt", json!("99".repeat(32))), + ("/queued_at", json!("101")), + ], + ), + ] { + let (read, update) = match table { + "listing_installations" => ( + "SELECT protected FROM listing_installations", + "UPDATE listing_installations SET protected=?", + ), + "public_publication_work" => ( + "SELECT protected FROM public_publication_work", + "UPDATE public_publication_work SET protected=?", + ), + _ => unreachable!("fixed fixture tables"), + }; + let original: Vec<u8> = sqlx::query_scalar(read) + .fetch_one(&mut data.database) + .await + .unwrap(); + let decoded: Value = data + .crypto + .open_issuance(scope, payload, 0, &original) + .await + .unwrap() + .expose_secret(|raw| serde_json::from_slice(raw).unwrap()); + for (pointer, value) in changes { + let mut changed = decoded.clone(); + *changed.pointer_mut(pointer).unwrap() = value; + let protected = data + .crypto + .seal_issuance(scope, payload, 0, &serde_json::to_vec(&changed).unwrap()) + .await + .unwrap(); + sqlx::query(update) + .bind(&protected) + .execute(&mut data.database) + .await + .unwrap(); + assert!( + matches!( + listing_installation::Records::read( + &mut data.database, + &selected, + e.operation_id(), + &graph, + &data.crypto + ) + .await, + Err(OperationError::RecoveryRequired) + ), + "{table}: {pointer}" + ); + assert!( + retained + .unchanged(&mut data.database, &selected, e.operation_id()) + .await + .is_err() + ); + let untouched: Vec<u8> = sqlx::query_scalar(read) + .fetch_one(&mut data.database) + .await + .unwrap(); + assert_eq!( + untouched, protected, + "validation must not repair persisted data" + ); + sqlx::query(update) + .bind(&original) + .execute(&mut data.database) + .await + .unwrap(); + } + // Equivalent plaintext with a new protected representation still + // invalidates an already observed exact-fact fence. + let different = data + .crypto + .seal_issuance(scope, payload, 0, &serde_json::to_vec(&decoded).unwrap()) + .await + .unwrap(); + assert_ne!(different, original); + sqlx::query(update) + .bind(&different) + .execute(&mut data.database) + .await + .unwrap(); + assert!( + listing_installation::Records::read( + &mut data.database, + &selected, + e.operation_id(), + &graph, + &data.crypto + ) + .await + .is_ok() + ); + assert!( + retained + .unchanged(&mut data.database, &selected, e.operation_id()) + .await + .is_err() + ); + sqlx::query(update) + .bind(&original) + .execute(&mut data.database) + .await + .unwrap(); + } + let original: Vec<u8> = sqlx::query_scalar("SELECT protected FROM public_publication_work") + .fetch_one(&mut data.database) + .await + .unwrap(); + let mut changed: Value = data + .crypto + .open_issuance(scope, IssuancePayload::Publication, 0, &original) + .await + .unwrap() + .expose_secret(|raw| serde_json::from_slice(raw).unwrap()); + changed["transaction"] = json!("99".repeat(32)); + let protected = data + .crypto + .seal_issuance( + scope, + IssuancePayload::Publication, + 0, + &serde_json::to_vec(&changed).unwrap(), + ) + .await + .unwrap(); + sqlx::query("UPDATE public_publication_work SET transaction_id=?,protected=?") + .bind([0x99u8; 32].as_slice()) + .bind(protected) + .execute(&mut data.database) + .await + .unwrap(); + assert!(matches!( + listing_installation::Records::read( + &mut data.database, + &selected, + e.operation_id(), + &graph, + &data.crypto + ) + .await, + Err(OperationError::RecoveryRequired) + )); + sqlx::query("UPDATE public_publication_work SET transaction_id=?,protected=?") + .bind(data.report.work().transaction_id().as_bytes().as_slice()) + .bind(original) + .execute(&mut data.database) + .await + .unwrap(); + retained + .unchanged(&mut data.database, &selected, e.operation_id()) + .await + .unwrap(); + assert!( + listing_installation::absent(&mut data.database, &selected, e.operation_id()) + .await + .is_err() + ); + data.database.close().await.unwrap(); +}