commit 5517ffee7f45989c5645fc4537137b2708ed6196 parent 25e93b2f03cb807d68ea61cdf60851f5ebf16060 Author: triesap <tyson@radroots.org> Date: Wed, 28 Oct 2026 23:17:57 +0000 storage: persist original stock delivery attempts and outcomes - Add protected stock dispatch and per-target observations to catalog 17. - Authenticate original plans, installation, outers, consent and transaction witnesses. - Bound retries and queries while retaining obtained material through owner reconciliation. - Isolate worker polling frames and expose coherent status with generated API baselines. Diffstat:
80 files changed, 5836 insertions(+), 1264 deletions(-)
diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -60,6 +60,7 @@ impl radroots_execution::session::commerce::AcceptanceStatus pub const fn radroots_execution::session::commerce::AcceptanceStatus::aborted(&self) -> bool pub const fn radroots_execution::session::commerce::AcceptanceStatus::attempt(&self) -> radroots_storage::command::CommitAttempt pub const fn radroots_execution::session::commerce::AcceptanceStatus::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_execution::session::commerce::AcceptanceStatus::delivery(&self) -> core::option::Option<&[radroots_storage::inventory::delivery_state::StockDeliverySummary; 2]> pub const fn radroots_execution::session::commerce::AcceptanceStatus::installation(&self) -> core::option::Option<radroots_execution::session::commerce::InstalledAcceptance> pub const fn radroots_execution::session::commerce::AcceptanceStatus::plan_bound(&self) -> bool pub const fn radroots_execution::session::commerce::AcceptanceStatus::recipients(&self) -> &[radroots_execution::session::commerce::AcceptanceRecipient; 2] @@ -85,6 +86,7 @@ pub fn radroots_execution::session::commerce::AcceptanceDispatch::dispatch<'a>(a pub trait radroots_execution::session::commerce::AcceptanceSnapshot: radroots_execution::session::HostBound pub fn radroots_execution::session::commerce::AcceptanceSnapshot::aborted(&self) -> bool pub fn radroots_execution::session::commerce::AcceptanceSnapshot::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_execution::session::commerce::AcceptanceSnapshot::delivery(&self) -> core::option::Option<&[radroots_storage::inventory::delivery_state::StockDeliverySummary; 2]> pub fn radroots_execution::session::commerce::AcceptanceSnapshot::installation(&self) -> core::option::Option<radroots_execution::session::commerce::InstalledAcceptance> pub fn radroots_execution::session::commerce::AcceptanceSnapshot::plan(&self) -> core::option::Option<&radroots_protocol::commerce::signing_plan::CommerceSigningPlan> pub fn radroots_execution::session::commerce::AcceptanceSnapshot::preparation(&self) -> &radroots_storage::inventory::acceptance::StockAcceptanceReceipt @@ -94,6 +96,7 @@ pub fn radroots_execution::session::commerce::AcceptanceStore::bind<'a>(&'a self pub fn radroots_execution::session::commerce::AcceptanceStore::claim<'a>(&'a self, radroots_execution::session::commerce::AcceptanceSelection, radroots_identity::key::PublicKey, &'a radroots_storage::workspace::AttachmentProof) -> radroots_execution::session::HostFuture<'a, core::result::Result<radroots_execution::session::commerce::AcceptanceClaimOutcome, radroots_storage::command::OperationError>> pub fn radroots_execution::session::commerce::AcceptanceStore::exact_replay<'a>(&'a self, radroots_execution::session::commerce::AcceptanceSelection, radroots_identity::key::PublicKey, radroots_signing::provider::ProviderCall, &'a radroots_storage::workspace::AttachmentProof) -> radroots_execution::session::HostFuture<'a, core::result::Result<(radroots_signing::issuance::exact_recovery::ExactRecoveryRequest, radroots_execution::session::commerce::AcceptanceClaim), radroots_storage::command::OperationError>> pub fn radroots_execution::session::commerce::AcceptanceStore::install<'a>(&'a self, radroots_execution::session::commerce::AcceptanceSelection, &'a radroots_storage::workspace::AttachmentProof) -> radroots_execution::session::HostFuture<'a, core::result::Result<radroots_execution::session::commerce::AcceptanceInstallationOutcome, radroots_storage::command::OperationError>> +pub fn radroots_execution::session::commerce::AcceptanceStore::signing_evidence<'a>(&'a self, radroots_execution::session::commerce::AcceptanceSelection, radroots_storage::inventory::evidence::StockEvidenceReceipt, &'a radroots_storage::workspace::AttachmentProof) -> radroots_execution::session::HostFuture<'a, core::result::Result<core::option::Option<radroots_storage::inventory::evidence::StockEvidenceSource>, radroots_storage::command::OperationError>> pub fn radroots_execution::session::commerce::AcceptanceStore::snapshot<'a>(&'a self, radroots_execution::session::commerce::AcceptanceSelection, &'a radroots_storage::workspace::AttachmentProof) -> radroots_execution::session::HostFuture<'a, core::result::Result<alloc::boxed::Box<dyn radroots_execution::session::commerce::AcceptanceSnapshot>, radroots_storage::command::OperationError>> pub trait radroots_execution::session::commerce::AcceptanceUnissued: radroots_execution::session::HostBound pub fn radroots_execution::session::commerce::AcceptanceUnissued::capture(&self) -> radroots_execution::session::HostFuture<'_, core::result::Result<radroots_execution::session::commerce::AcceptanceUnissuedOutcome, radroots_storage::command::OperationError>> diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -1390,6 +1390,19 @@ pub enum radroots_storage::inventory::StockAcceptanceOutcome pub radroots_storage::inventory::StockAcceptanceOutcome::Aborted(alloc::boxed::Box<radroots_storage::inventory::StockAbortReceipt>) pub radroots_storage::inventory::StockAcceptanceOutcome::Prepared(alloc::boxed::Box<radroots_storage::inventory::StockAcceptanceReceipt>) pub radroots_storage::inventory::StockAcceptanceOutcome::Unknown(radroots_storage::command::CommitAttempt) +pub enum radroots_storage::inventory::StockDeliveryAttemptOutcome +pub radroots_storage::inventory::StockDeliveryAttemptOutcome::Claimed(alloc::boxed::Box<radroots_storage::inventory::StockDeliveryAttempt>) +pub radroots_storage::inventory::StockDeliveryAttemptOutcome::Retained(alloc::boxed::Box<radroots_storage::inventory::StockDeliveryAttempt>) +pub radroots_storage::inventory::StockDeliveryAttemptOutcome::Unknown +pub radroots_storage::inventory::StockDeliveryAttemptOutcome::Unknown::operation: radroots_storage::command::CommitAttempt +pub radroots_storage::inventory::StockDeliveryAttemptOutcome::Unknown::request: radroots_transport::sink::DeliveryRequestId +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryAttemptOutcome +pub fn radroots_storage::inventory::StockDeliveryAttemptOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_storage::inventory::StockDeliveryObservationOutcome +pub radroots_storage::inventory::StockDeliveryObservationOutcome::Committed(alloc::boxed::Box<radroots_storage::inventory::StockDeliveryObservationReceipt>) +pub radroots_storage::inventory::StockDeliveryObservationOutcome::Unknown(radroots_storage::command::CommitAttempt) +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryObservationOutcome +pub fn radroots_storage::inventory::StockDeliveryObservationOutcome::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub enum radroots_storage::inventory::StockEnvelopeOutcome pub radroots_storage::inventory::StockEnvelopeOutcome::Committed(alloc::boxed::Box<radroots_storage::inventory::StockEnvelopeReceipt>) pub radroots_storage::inventory::StockEnvelopeOutcome::Unknown(radroots_storage::command::CommitAttempt) @@ -1475,6 +1488,79 @@ pub const fn radroots_storage::inventory::StockAcceptanceRequest::minimum_checkp pub const fn radroots_storage::inventory::StockAcceptanceRequest::source_checkpoint(&self) -> radroots_storage::workspace::seller_stock::StockSourceCheckpointRef impl core::fmt::Debug for radroots_storage::inventory::StockAcceptanceRequest pub fn radroots_storage::inventory::StockAcceptanceRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockDeliveryAttempt +impl radroots_storage::inventory::StockDeliveryAttempt +pub const fn radroots_storage::inventory::StockDeliveryAttempt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage::inventory::StockDeliveryAttempt::from_store_report(alloc::sync::Arc<radroots_storage::inventory::StockEnvelopeSource>, radroots_storage::command::DeliveryIntent, radroots_domain::identifier::TransactionId, radroots_domain::context::UnixSeconds, radroots_storage::inventory::InventoryCheckpointRef, alloc::vec::Vec<u8>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliveryAttempt::intent(&self) -> &radroots_storage::command::DeliveryIntent +pub const fn radroots_storage::inventory::StockDeliveryAttempt::retained_at(&self) -> radroots_domain::context::UnixSeconds +pub fn radroots_storage::inventory::StockDeliveryAttempt::source(&self) -> &radroots_storage::inventory::StockEnvelopeSource +pub fn radroots_storage::inventory::StockDeliveryAttempt::target_ordinals(&self) -> &[u8] +pub const fn radroots_storage::inventory::StockDeliveryAttempt::transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub fn radroots_storage::inventory::StockDeliveryAttempt::transport_request(&self) -> core::result::Result<radroots_transport::sink::DeliveryRequest, radroots_storage::command::OperationError> +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryAttempt +pub fn radroots_storage::inventory::StockDeliveryAttempt::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockDeliveryObservation +impl radroots_storage::inventory::StockDeliveryObservation +pub const fn radroots_storage::inventory::StockDeliveryObservation::attempt_checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub const fn radroots_storage::inventory::StockDeliveryObservation::attempt_transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub const fn radroots_storage::inventory::StockDeliveryObservation::event_id(&self) -> radroots_domain::identifier::EnvelopeEventId +pub fn radroots_storage::inventory::StockDeliveryObservation::from_failure(&radroots_storage::inventory::StockDeliveryAttempt, &radroots_transport::sink::SinkFailure, &radroots_transport::target::TargetFingerprint, core::option::Option<core::num::nonzero::NonZeroU64>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::inventory::StockDeliveryObservation::from_receipt(&radroots_storage::inventory::StockDeliveryAttempt, &radroots_transport::sink::DeliveryReceipt, &radroots_transport::target::TargetFingerprint, core::option::Option<core::num::nonzero::NonZeroU64>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::inventory::StockDeliveryObservation::from_store_report(&radroots_storage::inventory::StockDeliveryAttempt, &radroots_transport::sink::DeliveryTargetReceipt, core::option::Option<core::num::nonzero::NonZeroU64>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliveryObservation::kind(&self) -> radroots_storage::command::DeliveryObservationKind +pub const fn radroots_storage::inventory::StockDeliveryObservation::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub const fn radroots_storage::inventory::StockDeliveryObservation::request_id(&self) -> &radroots_transport::sink::DeliveryRequestId +pub const fn radroots_storage::inventory::StockDeliveryObservation::source(&self) -> radroots_storage::inventory::StockEnvelopeReceipt +pub const fn radroots_storage::inventory::StockDeliveryObservation::target_ordinal(&self) -> u8 +pub const fn radroots_storage::inventory::StockDeliveryObservation::target_receipt(&self) -> &radroots_transport::sink::DeliveryTargetReceipt +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryObservation +pub fn radroots_storage::inventory::StockDeliveryObservation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockDeliveryObservationPage +impl radroots_storage::inventory::StockDeliveryObservationPage +pub const fn radroots_storage::inventory::StockDeliveryObservationPage::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage::inventory::StockDeliveryObservationPage::entries(&self) -> &[radroots_storage::inventory::StockDeliveryObservationReceipt] +pub fn radroots_storage::inventory::StockDeliveryObservationPage::from_store_report(&radroots_storage::inventory::StockEnvelopeRequest, alloc::vec::Vec<radroots_storage::inventory::StockDeliveryObservationReceipt>, bool, radroots_storage::inventory::InventoryCheckpointRef) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliveryObservationPage::next_after(&self) -> core::option::Option<radroots_domain::context::Sequence> +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryObservationPage +pub fn radroots_storage::inventory::StockDeliveryObservationPage::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockDeliveryObservationReceipt +impl radroots_storage::inventory::StockDeliveryObservationReceipt +pub const fn radroots_storage::inventory::StockDeliveryObservationReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage::inventory::StockDeliveryObservationReceipt::from_store_report(radroots_storage::inventory::StockDeliveryObservation, radroots_domain::identifier::TransactionId, radroots_storage::inventory::InventoryCheckpointRef) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliveryObservationReceipt::observation(&self) -> &radroots_storage::inventory::StockDeliveryObservation +pub const fn radroots_storage::inventory::StockDeliveryObservationReceipt::transaction_id(&self) -> radroots_domain::identifier::TransactionId +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryObservationReceipt +pub fn radroots_storage::inventory::StockDeliveryObservationReceipt::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockDeliveryRequest +impl radroots_storage::inventory::StockDeliveryRequest +pub fn radroots_storage::inventory::StockDeliveryRequest::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage::inventory::StockDeliveryRequest::intent(&self) -> &radroots_storage::command::DeliveryIntent +pub fn radroots_storage::inventory::StockDeliveryRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_storage::command::DeliveryIntent) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliveryRequest::source(&self) -> &radroots_storage::inventory::StockEnvelopeRequest +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryRequest +pub fn radroots_storage::inventory::StockDeliveryRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockDeliverySummary +impl radroots_storage::inventory::StockDeliverySummary +pub fn radroots_storage::inventory::StockDeliverySummary::acceptance_satisfied(&self) -> core::result::Result<bool, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliverySummary::attempt_count(&self) -> u16 +pub const fn radroots_storage::inventory::StockDeliverySummary::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage::inventory::StockDeliverySummary::from_store_report(&radroots_storage::inventory::StockEnvelopeRequest, core::option::Option<radroots_storage::inventory::StockEnvelopeReceipt>, core::option::Option<radroots_storage::command::DeliveryIntent>, u16, alloc::vec::Vec<radroots_storage::inventory::StockDeliveryTargetProgress>, radroots_storage::inventory::InventoryCheckpointRef) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliverySummary::original_intent(&self) -> core::option::Option<&radroots_storage::command::DeliveryIntent> +pub const fn radroots_storage::inventory::StockDeliverySummary::source(&self) -> core::option::Option<radroots_storage::inventory::StockEnvelopeReceipt> +pub fn radroots_storage::inventory::StockDeliverySummary::targets(&self) -> &[radroots_storage::inventory::StockDeliveryTargetProgress] +impl core::fmt::Debug for radroots_storage::inventory::StockDeliverySummary +pub fn radroots_storage::inventory::StockDeliverySummary::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockDeliveryTargetProgress +impl radroots_storage::inventory::StockDeliveryTargetProgress +pub const fn radroots_storage::inventory::StockDeliveryTargetProgress::accepted(&self) -> bool +pub fn radroots_storage::inventory::StockDeliveryTargetProgress::from_store_report(radroots_transport::target::TargetFingerprint, u8, bool, core::option::Option<radroots_storage::command::DeliveryObservationKind>, core::option::Option<core::num::nonzero::NonZeroU64>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockDeliveryTargetProgress::last_observation_kind(&self) -> core::option::Option<radroots_storage::command::DeliveryObservationKind> +pub const fn radroots_storage::inventory::StockDeliveryTargetProgress::last_observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub const fn radroots_storage::inventory::StockDeliveryTargetProgress::potential_attempts(&self) -> u8 +pub const fn radroots_storage::inventory::StockDeliveryTargetProgress::target(&self) -> &radroots_transport::target::TargetFingerprint +impl core::fmt::Debug for radroots_storage::inventory::StockDeliveryTargetProgress +pub fn radroots_storage::inventory::StockDeliveryTargetProgress::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage::inventory::StockEnvelopeReceipt impl radroots_storage::inventory::StockEnvelopeReceipt pub const fn radroots_storage::inventory::StockEnvelopeReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt @@ -1531,6 +1617,13 @@ pub const fn radroots_storage::inventory::StockEvidenceRequest::signing_attempt_ pub fn radroots_storage::inventory::StockEvidenceRequest::with_json<T>(&self, impl core::ops::function::FnOnce(&str) -> T) -> T impl core::fmt::Debug for radroots_storage::inventory::StockEvidenceRequest pub fn radroots_storage::inventory::StockEvidenceRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage::inventory::StockEvidenceSource +impl radroots_storage::inventory::StockEvidenceSource +pub fn radroots_storage::inventory::StockEvidenceSource::from_retained_wire(radroots_storage::inventory::StockEvidenceReceipt, &str) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockEvidenceSource::receipt(&self) -> radroots_storage::inventory::StockEvidenceReceipt +pub fn radroots_storage::inventory::StockEvidenceSource::with_json<T>(&self, impl core::ops::function::FnOnce(&str) -> T) -> T +impl core::fmt::Debug for radroots_storage::inventory::StockEvidenceSource +pub fn radroots_storage::inventory::StockEvidenceSource::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub trait radroots_storage::inventory::InventoryStore: radroots_storage::workspace::WorkspaceStore pub fn radroots_storage::inventory::InventoryStore::abort_proven_unissued(&self, radroots_storage::inventory::StockAbortRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::StockAbortOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::inventory::InventoryStore::capture_stock_envelope<'a>(&'a self, radroots_storage::inventory::StockEnvelopeRequest, radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::PrivateEnvelopeCandidate) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::StockEnvelopeOutcome, radroots_storage::command::OperationError>> @@ -1540,7 +1633,14 @@ pub fn radroots_storage::inventory::InventoryStore::inventory_operation(&self, r pub fn radroots_storage::inventory::InventoryStore::option_mapping(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::stock::mapping::OptionMappingKey, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::mapping::OptionPoolMapping>, radroots_storage::command::OperationError>> pub fn radroots_storage::inventory::InventoryStore::pool(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::PoolId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::PoolView>, radroots_storage::command::OperationError>> pub fn radroots_storage::inventory::InventoryStore::prepare_stock_acceptance(&self, radroots_storage::inventory::StockAcceptanceRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::StockAcceptanceOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::prepare_stock_delivery_attempt(&self, radroots_storage::inventory::StockDeliveryRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::StockDeliveryAttemptOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::reconcile_stock_delivery_observation<'a>(&'a self, &'a radroots_storage::workspace::WorkspaceBinding, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::inventory::StockDeliveryObservation) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::StockDeliveryObservationOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::reconcile_stock_envelope<'a>(&'a self, radroots_storage::inventory::StockEnvelopeRequest, radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::PrivateEnvelopeCandidate) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::StockEnvelopeOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage::inventory::InventoryStore::reconcile_stock_evidence<'a>(&'a self, &'a radroots_storage::inventory::StockEvidenceRequest, &'a radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::StockEvidenceOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::record_stock_delivery_observation<'a>(&'a self, &'a radroots_storage::workspace::WorkspaceBinding, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::inventory::StockDeliveryObservation) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::StockDeliveryObservationOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::stock_delivery_attempt(&self, radroots_storage::inventory::StockEnvelopeRequest, radroots_transport::sink::DeliveryRequestId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::StockDeliveryAttempt>, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::stock_delivery_observations(&self, radroots_storage::inventory::StockEnvelopeRequest, core::option::Option<radroots_domain::context::Sequence>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::StockDeliveryObservationPage, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::stock_delivery_summary(&self, radroots_storage::inventory::StockEnvelopeRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::StockDeliverySummary, radroots_storage::command::OperationError>> pub fn radroots_storage::inventory::InventoryStore::stock_envelope(&self, radroots_storage::inventory::StockEnvelopeRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::StockEnvelopeSource>, radroots_storage::command::OperationError>> pub fn radroots_storage::inventory::InventoryStore::stock_preparation_abort(&self, radroots_storage::inventory::StockAbortRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::StockAbortReceipt>, radroots_storage::command::OperationError>> pub mod radroots_storage::journal diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -504,7 +504,14 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::inventory_operation( pub fn radroots_storage_sqlite::workspace::NativeWorkspace::option_mapping(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::stock::mapping::OptionMappingKey, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::mapping::OptionPoolMapping>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::pool(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::PoolId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::PoolView>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::prepare_stock_acceptance(&self, radroots_storage::inventory::acceptance::StockAcceptanceRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::acceptance::StockAcceptanceOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::prepare_stock_delivery_attempt(&self, radroots_storage::inventory::delivery::StockDeliveryRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::delivery::StockDeliveryAttemptOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::reconcile_stock_delivery_observation<'a>(&'a self, &'a radroots_storage::workspace::WorkspaceBinding, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::inventory::delivery::StockDeliveryObservation) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::delivery::StockDeliveryObservationOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::reconcile_stock_envelope<'a>(&'a self, radroots_storage::inventory::envelope::StockEnvelopeRequest, radroots_storage::workspace::AttachmentProof, &'a radroots_storage::command::delivery::private::PrivateEnvelopeCandidate) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::envelope::StockEnvelopeOutcome, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::reconcile_stock_evidence<'a>(&'a self, &'a radroots_storage::inventory::evidence::StockEvidenceRequest, &'a radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::evidence::StockEvidenceOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::record_stock_delivery_observation<'a>(&'a self, &'a radroots_storage::workspace::WorkspaceBinding, &'a radroots_storage::workspace::AttachmentProof, &'a radroots_storage::inventory::delivery::StockDeliveryObservation) -> radroots_transport::source::BoxFuture<'a, core::result::Result<radroots_storage::inventory::delivery::StockDeliveryObservationOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_delivery_attempt(&self, radroots_storage::inventory::envelope::StockEnvelopeRequest, radroots_transport::sink::DeliveryRequestId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::delivery::StockDeliveryAttempt>, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_delivery_observations(&self, radroots_storage::inventory::envelope::StockEnvelopeRequest, core::option::Option<radroots_domain::context::Sequence>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::delivery_state::StockDeliveryObservationPage, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_delivery_summary(&self, radroots_storage::inventory::envelope::StockEnvelopeRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::delivery_state::StockDeliverySummary, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_envelope(&self, radroots_storage::inventory::envelope::StockEnvelopeRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::envelope::StockEnvelopeSource>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_preparation_abort(&self, radroots_storage::inventory::abort::StockAbortRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::abort::StockAbortReceipt>, radroots_storage::command::OperationError>> impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace @@ -672,6 +679,7 @@ pub struct radroots_storage_sqlite::workspace::StockOperationSnapshot impl radroots_storage_sqlite::workspace::StockOperationSnapshot pub fn radroots_storage_sqlite::workspace::StockOperationSnapshot::aborted(&self) -> core::option::Option<&radroots_storage::inventory::abort::StockAbortReceipt> pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage_sqlite::workspace::StockOperationSnapshot::delivery(&self) -> core::option::Option<&[radroots_storage::inventory::delivery_state::StockDeliverySummary; 2]> pub fn radroots_storage_sqlite::workspace::StockOperationSnapshot::installation(&self) -> core::option::Option<&radroots_storage_sqlite::workspace::StockInstallationReceipt> pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::preparation(&self) -> &radroots_storage::inventory::acceptance::StockAcceptanceReceipt pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::recipients(&self) -> &[radroots_storage_sqlite::workspace::StockRecipientSnapshot; 2] diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -82,7 +82,7 @@ "adapter": "radroots_nostr.signing.LocalSigner", "native_authorizer": "NativeWorkspace.authorize_stock_exact_replay", "captured_replay": "local_replay_safe", - "native_catalog": 16, + "native_catalog": 17, "worker_charge_bytes": 1048576, "existing_protected_claim_required": true, "current_execute_consent_required": true, @@ -111,7 +111,7 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 16, + "schema_version": 17, "retained_enrollment_versions": [ 1 ], @@ -129,9 +129,10 @@ 12, 13, 14, - 15 + 15, + 16 ], - "authority_payload_schema": "radroots.seller_stock.authority.v16", + "authority_payload_schema": "radroots.seller_stock.authority.v17", "public_source_payload_schemas": [ "radroots.seller_stock.public_source_event.v1", "radroots.seller_stock.public_source_head.v1", @@ -395,7 +396,8 @@ "retained_v1_requires_absent_claims": true, "claimed_cleanup_catalogs": [ 15, - 16 + 16, + 17 ], "untracked_claimed_catalogs": [ 13, @@ -414,7 +416,8 @@ "payload_version": 1, "payload_prefix_bytes": 213, "supported_catalogs": [ - 16 + 16, + 17 ], "retained_unsupported_catalogs": [ 1, @@ -448,7 +451,74 @@ "existing_original_bytes_may_be_replaced": false, "capture_grants_dispatch": false, "capture_changes_physical_stock": false, - "provider_io_inside_sql": false + "provider_io_inside_sql": false, + "recovery_port": "InventoryStore.reconcile_stock_envelope" + }, + "delivery": { + "supported_catalogs": [ + 17 + ], + "retained_unsupported_catalogs": [ + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16 + ], + "attempt_journal_family": 11, + "observation_journal_family": 12, + "attempt_payload_version": 1, + "observation_payload_version": 1, + "attempt_body_max_bytes": 65536, + "observation_body_max_bytes": 16384, + "target_max": 16, + "attempts_per_target": 12, + "attempts_per_operation_max": 384, + "observations_per_operation_max": 2304, + "observation_page_max": 16, + "summary_target_max": 16, + "worker_charge_bytes": 1048576, + "storage_ports": [ + "InventoryStore.prepare_stock_delivery_attempt", + "InventoryStore.stock_delivery_attempt", + "InventoryStore.stock_delivery_summary", + "InventoryStore.record_stock_delivery_observation", + "InventoryStore.reconcile_stock_delivery_observation", + "InventoryStore.stock_delivery_observations" + ], + "original_stock_evidence_installation_outer_required": true, + "original_captured_route_and_current_write_policy_required": true, + "fresh_current_scoped_consent_grant_clock_required": true, + "installed_original_recovery_delivery_supported": true, + "fresh_claim_requires_confirmed_commit": true, + "existing_attempt_grants_dispatch": false, + "unknown_commit_grants_dispatch": false, + "query_grants_dispatch": false, + "first_complete_targets_and_criterion_immutable": true, + "ordinary_command_replays_existing_attempt": false, + "explicit_resume_claims_bounded_new_attempt": true, + "retries_use_original_outer_bytes": true, + "observation_nullable": true, + "original_credential_capture_requires_live_clock_or_grant": false, + "same_owner_obtained_material_reconciliation_required": true, + "first_observation_per_class_immutable": true, + "wrong_event_request_target_ack_rejected": true, + "protected_refs_indexes_complete_ancestry_required": true, + "final_transaction_witnesses_required": true, + "unbounded_attempt_or_observation_collections": false, + "physical_stock_effect": false, + "transport_inside_sql": false } }, "provenance": { diff --git a/crates/execution/src/session/commerce.rs b/crates/execution/src/session/commerce.rs @@ -13,7 +13,10 @@ use radroots_signing::{ }; use radroots_storage::{ command::{CommitAttempt, OperationError}, - inventory::{InventoryCheckpointRef, StockAcceptanceReceipt, StockEvidenceReceipt}, + inventory::{ + InventoryCheckpointRef, StockAcceptanceReceipt, StockDeliverySummary, StockEvidenceReceipt, + StockEvidenceSource, + }, workspace::{AttachmentProof, WorkspaceBinding}, }; @@ -94,6 +97,9 @@ pub trait AcceptanceSnapshot: HostBound { fn installation(&self) -> Option<InstalledAcceptance>; /// Whether an actual original proven-unissued abort was observed. fn aborted(&self) -> bool; + /// Coherent bounded original per-recipient delivery progress, in the same + /// canonical order as recipients. None means unsupported by this catalog. + fn delivery(&self) -> Option<&[StockDeliverySummary; 2]>; } #[path = "commerce_dispatch.rs"] @@ -134,6 +140,16 @@ pub enum AcceptanceInstallationOutcome { /// replacement application workflow. The ordinary facade selects the same owner /// as its InventoryStore; custom hosts require their own executed qualification. pub trait AcceptanceStore: HostBound { + /// Reads the exact retained signed seal under current recovery access. + /// This cannot create signing material or confer dispatch permission. + fn signing_evidence<'a>( + &'a self, + _selection: AcceptanceSelection, + _receipt: StockEvidenceReceipt, + _proof: &'a AttachmentProof, + ) -> HostFuture<'a, Result<Option<StockEvidenceSource>, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } /// Reads original T0/T1, independent recipient S and initial T2 coherently. fn snapshot<'a>( &'a self, @@ -183,8 +199,14 @@ pub struct AcceptanceStatus { pub(crate) plan_bound: bool, pub(crate) installation: Option<InstalledAcceptance>, pub(crate) aborted: bool, + pub(crate) delivery: Option<Box<[StockDeliverySummary; 2]>>, } impl AcceptanceStatus { + /// Original per-recipient delivery progress, independently of installation + /// or buyer receipt. Absence means this catalog does not support stock D. + pub fn delivery(&self) -> Option<&[StockDeliverySummary; 2]> { + self.delivery.as_deref() + } /// Original confirmed T0 anchor. pub const fn attempt(&self) -> CommitAttempt { self.attempt diff --git a/crates/execution/src/session/commerce_run.rs b/crates/execution/src/session/commerce_run.rs @@ -117,6 +117,27 @@ pub(crate) fn observe( } } Ok(AcceptanceStatus { + delivery: match snapshot.delivery() { + Some(values) => { + for (value, recipient) in values.iter().zip(&recipients) { + if value.checkpoint() != snapshot.checkpoint() + || value.source().is_some_and(|source| { + !same(source.attempt(), selection) + || source.recipient() != recipient.recipient + || recipient.evidence != Some(source.evidence()) + || installation.is_none_or(|installed| { + Some(source.installation_transaction_id()) + != installed.attempt.transaction_id() + }) + }) + { + return Err(OperationError::RecoveryRequired); + } + } + Some(alloc::boxed::Box::new(values.clone())) + } + None => None, + }, attempt: original.attempt(), record: original.rumor().record_id(), checkpoint: snapshot.checkpoint(), diff --git a/crates/radroots/src/native_commerce.rs b/crates/radroots/src/native_commerce.rs @@ -132,6 +132,9 @@ impl AcceptanceSnapshot for Snapshot { fn aborted(&self) -> bool { self.0.aborted().is_some() } + fn delivery(&self) -> Option<&[radroots_storage::inventory::StockDeliverySummary; 2]> { + self.0.delivery() + } } impl AcceptanceDispatch for Dispatch { fn claim(&self) -> AcceptanceClaim { @@ -181,6 +184,38 @@ fn select(value: AcceptanceSelection, recipient: PublicKey) -> StockClaimRequest ) } impl AcceptanceStore for NativeCommerce { + fn signing_evidence<'a>( + &'a self, + selection: AcceptanceSelection, + receipt: radroots_storage::inventory::StockEvidenceReceipt, + proof: &'a AttachmentProof, + ) -> HostFuture< + 'a, + Result<Option<radroots_storage::inventory::StockEvidenceSource>, OperationError>, + > { + Box::pin(async move { + let source = self + .0 + .stock_signing_evidence( + select(selection, receipt.recipient()), + *receipt.digest(), + proof, + ) + .await?; + source + .map(|source| { + if source.receipt() != receipt { + return Err(OperationError::RecoveryRequired); + } + source.with_json(|raw| { + radroots_storage::inventory::StockEvidenceSource::from_retained_wire( + receipt, raw, + ) + }) + }) + .transpose() + }) + } fn snapshot<'a>( &'a self, value: AcceptanceSelection, diff --git a/crates/radroots/src/native_commerce_tests.rs b/crates/radroots/src/native_commerce_tests.rs @@ -613,6 +613,36 @@ async fn ordinary_acceptance_uses_real_t0_t1_s_t2_and_preserves_original_retry() .await .unwrap(); assert_eq!(observed.installation(), status.installation()); + // The coherent supported view reports no D; the existing workflow has + // not wrapped or invoked transport. Actual protected S is independently + // readable through the same native owner under current access. + assert!(observed.delivery().unwrap().iter().all(|value| { + value.checkpoint() == observed.checkpoint() + && value.source().is_none() + && value.attempt_count() == 0 + })); + let evidence = observed.recipients()[0].evidence.unwrap(); + let source = radroots_execution::session::commerce::AcceptanceStore::signing_evidence( + &crate::native_commerce::NativeCommerce(Arc::new(r.native.clone())), + radroots_execution::session::commerce::AcceptanceSelection { + binding: r.scope.binding().clone(), + minimum, + operation: command.context().operation_id(), + digest: command.digest(), + }, + evidence, + r.enrollment.proof(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(source.receipt(), evidence); + source.with_json(|raw| { + assert_eq!( + serde_json::from_str::<serde_json::Value>(raw).unwrap()["kind"], + 13 + ) + }); r.clock.0.store(231, Ordering::SeqCst); let refused = r .client diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -23,6 +23,8 @@ mod dm_source; mod installation; mod issuance; mod observation; +#[cfg(feature = "protected_outbox")] +pub(crate) use observation::normalize as normalize_delivery_observation; mod publication; pub use publication::PublicationArtifact; mod snapshot; diff --git a/crates/storage/src/command/observation.rs b/crates/storage/src/command/observation.rs @@ -10,6 +10,46 @@ use radroots_transport::{ target::TargetFingerprint, }; +/// Mechanical target normalization shared by independently authenticated owners. +pub(crate) fn normalize( + intent: &super::DeliveryIntent, + ordinals: &[u8], + report: &DeliveryTargetReceipt, + observed_at: Option<NonZeroU64>, +) -> Result<(DeliveryObservationKind, u8), OperationError> { + if observed_at.is_some_and(|time| time.get() > 253_402_300_799_999) + || !intent.targets().targets().contains(report.target()) + || report.outcome().kind() == DeliveryOutcomeKind::Delivered + { + return Err(OperationError::InvalidEvidence); + } + let kind = if !report.was_attempted() { + DeliveryObservationKind::NotAttempted + } else { + match report.outcome().kind() { + DeliveryOutcomeKind::Accepted => DeliveryObservationKind::Accepted, + DeliveryOutcomeKind::Rejected => DeliveryObservationKind::Rejected, + DeliveryOutcomeKind::Failed | DeliveryOutcomeKind::Unavailable => { + match report.outcome().code() { + Some("timeout" | "deadline_exceeded") => DeliveryObservationKind::TimedOut, + Some("connection_failed" | "disconnected") => { + DeliveryObservationKind::Disconnected + } + _ => DeliveryObservationKind::Unknown, + } + } + DeliveryOutcomeKind::Delivered => return Err(OperationError::InvalidEvidence), + } + }; + let index = intent + .selection() + .iter() + .position(|target| target == report.target().fingerprint()) + .ok_or(OperationError::InvalidEvidence)?; + let ordinal = *ordinals.get(index).ok_or(OperationError::InvalidEvidence)?; + Ok((kind, ordinal)) +} + /// Independent append-only outcome classes. Each actual attempt/target has at /// most one original observation of each class; a later class never erases it. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -100,44 +140,12 @@ impl DeliveryObservation { report: &DeliveryTargetReceipt, observed_at_unix_ms: Option<NonZeroU64>, ) -> Result<Self, OperationError> { - if observed_at_unix_ms.is_some_and(|time| time.get() > 253_402_300_799_999) - || !attempt - .intent() - .targets() - .targets() - .contains(report.target()) - || report.outcome().kind() == DeliveryOutcomeKind::Delivered - { - return Err(OperationError::InvalidEvidence); - } - let kind = if !report.was_attempted() { - DeliveryObservationKind::NotAttempted - } else { - match report.outcome().kind() { - DeliveryOutcomeKind::Accepted => DeliveryObservationKind::Accepted, - DeliveryOutcomeKind::Rejected => DeliveryObservationKind::Rejected, - DeliveryOutcomeKind::Failed | DeliveryOutcomeKind::Unavailable => { - match report.outcome().code() { - Some("timeout" | "deadline_exceeded") => DeliveryObservationKind::TimedOut, - Some("connection_failed" | "disconnected") => { - DeliveryObservationKind::Disconnected - } - _ => DeliveryObservationKind::Unknown, - } - } - DeliveryOutcomeKind::Delivered => return Err(OperationError::InvalidEvidence), - } - }; - let index = attempt - .intent() - .selection() - .iter() - .position(|target| target == report.target().fingerprint()) - .ok_or(OperationError::InvalidEvidence)?; - let ordinal = *attempt - .target_ordinals() - .get(index) - .ok_or(OperationError::InvalidEvidence)?; + let (kind, ordinal) = normalize( + attempt.intent(), + attempt.target_ordinals(), + report, + observed_at_unix_ms, + )?; Ok(Self { work: attempt.work(), request: attempt.intent().request_id().clone(), diff --git a/crates/storage/src/inventory.rs b/crates/storage/src/inventory.rs @@ -9,14 +9,25 @@ pub use radroots_protocol::command::{CapturedInventoryCommand, InventoryCommandK use radroots_transport::BoxFuture; mod abort; mod acceptance; +mod delivery; +mod delivery_state; mod envelope; mod evidence; pub use abort::{StockAbortOutcome, StockAbortReceipt, StockAbortRequest}; pub use acceptance::{StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest}; +pub use delivery::{ + StockDeliveryAttempt, StockDeliveryAttemptOutcome, StockDeliveryObservation, + StockDeliveryObservationOutcome, StockDeliveryObservationReceipt, StockDeliveryRequest, +}; +pub use delivery_state::{ + StockDeliveryObservationPage, StockDeliverySummary, StockDeliveryTargetProgress, +}; pub use envelope::{ StockEnvelopeOutcome, StockEnvelopeReceipt, StockEnvelopeRequest, StockEnvelopeSource, }; -pub use evidence::{StockEvidenceOutcome, StockEvidenceReceipt, StockEvidenceRequest}; +pub use evidence::{ + StockEvidenceOutcome, StockEvidenceReceipt, StockEvidenceRequest, StockEvidenceSource, +}; /// Exact captured owner-private inventory command and original authenticated observation. pub struct InventoryRequest { @@ -313,6 +324,70 @@ pub trait InventoryStore: WorkspaceStore { ) -> BoxFuture<'_, Result<Option<StockEnvelopeSource>, OperationError>> { Box::pin(async { Err(OperationError::UnsupportedOperation) }) } + /// Reconciles borrowed original outer material on the same retained owner. + /// Unsupported hosts cannot replace this with another wrap or a new writer. + fn reconcile_stock_envelope<'a>( + &'a self, + _request: StockEnvelopeRequest, + _proof: AttachmentProof, + _candidate: &'a crate::command::PrivateEnvelopeCandidate, + ) -> BoxFuture<'a, Result<StockEnvelopeOutcome, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } + /// Commits an actual potential invocation before transport. Existing or + /// uncertain attempts never confer another dispatch right. + fn prepare_stock_delivery_attempt( + &self, + _request: StockDeliveryRequest, + _proof: AttachmentProof, + ) -> BoxFuture<'_, Result<StockDeliveryAttemptOutcome, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } + /// Reads one original request without replay or deadline renewal. + fn stock_delivery_attempt( + &self, + _source: StockEnvelopeRequest, + _request_id: radroots_transport::sink::DeliveryRequestId, + _proof: AttachmentProof, + ) -> BoxFuture<'_, Result<Option<StockDeliveryAttempt>, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } + /// Reads bounded current per-endpoint progress under current recovery access. + fn stock_delivery_summary( + &self, + _source: StockEnvelopeRequest, + _proof: AttachmentProof, + ) -> BoxFuture<'_, Result<StockDeliverySummary, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } + /// Captures already obtained original outcome data without requiring a + /// fresh clock or live grant. The caller retains its original across errors. + fn record_stock_delivery_observation<'a>( + &'a self, + _binding: &'a WorkspaceBinding, + _proof: &'a AttachmentProof, + _observation: &'a StockDeliveryObservation, + ) -> BoxFuture<'a, Result<StockDeliveryObservationOutcome, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } + /// Reconciles only the borrowed obtained outcome on its original owner. + fn reconcile_stock_delivery_observation<'a>( + &'a self, + _binding: &'a WorkspaceBinding, + _proof: &'a AttachmentProof, + _observation: &'a StockDeliveryObservation, + ) -> BoxFuture<'a, Result<StockDeliveryObservationOutcome, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } + /// Pages original independent outcomes; a read never issues transport. + fn stock_delivery_observations( + &self, + _source: StockEnvelopeRequest, + _after: Option<radroots_domain::Sequence>, + _proof: AttachmentProof, + ) -> BoxFuture<'_, Result<StockDeliveryObservationPage, OperationError>> { + Box::pin(async { Err(OperationError::UnsupportedOperation) }) + } /// Prepares an original acceptance with complete atomic holds and the order /// fence. Unsupported hosts execute no fallback or simulated stock effect. fn prepare_stock_acceptance( diff --git a/crates/storage/src/inventory/delivery.rs b/crates/storage/src/inventory/delivery.rs @@ -0,0 +1,312 @@ +//! Stock-owned original delivery reports. Data construction grants no dispatch. +use super::*; +use crate::command::{DeliveryIntent, DeliveryObservationKind}; +use core::{fmt, num::NonZeroU64}; +use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds}; +use radroots_protocol::intent::ArtifactRole; +use radroots_transport::{ + DeliveryReceipt, SinkFailure, + sink::{DeliveryPayload, DeliveryRequest, DeliveryRequestId, DeliveryTargetReceipt}, + target::TargetFingerprint, +}; +use std::sync::Arc; + +/// Exact original operation/recipient selectors and one requested transport intent. +pub struct StockDeliveryRequest { + source: StockEnvelopeRequest, + intent: DeliveryIntent, +} +impl StockDeliveryRequest { + pub fn new( + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + recipient: PublicKey, + intent: DeliveryIntent, + ) -> Result<Self, OperationError> { + if intent.role() != ArtifactRole::GiftWrap { + return Err(OperationError::InvalidCommand); + } + Ok(Self { + source: StockEnvelopeRequest::new( + binding, minimum, operation, digest, recipient, None, + )?, + intent, + }) + } + pub const fn source(&self) -> &StockEnvelopeRequest { + &self.source + } + pub const fn intent(&self) -> &DeliveryIntent { + &self.intent + } + pub fn attempt(&self) -> CommitAttempt { + self.source.attempt() + } +} +impl fmt::Debug for StockDeliveryRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryRequest(<redacted>)") + } +} + +/// Original retained intent and exact outer. Queries of this report cannot +/// authorize transport; only a qualified owner's fresh confirmed claim can. +pub struct StockDeliveryAttempt { + source: Arc<StockEnvelopeSource>, + intent: DeliveryIntent, + transaction: TransactionId, + retained_at: UnixSeconds, + checkpoint: InventoryCheckpointRef, + ordinals: Box<[u8]>, +} +impl StockDeliveryAttempt { + /// Checks report shape and the actual carrier. The concrete owner must + /// authenticate the original stock graph and observe transaction completion. + pub fn from_store_report( + source: Arc<StockEnvelopeSource>, + intent: DeliveryIntent, + transaction: TransactionId, + retained_at: UnixSeconds, + checkpoint: InventoryCheckpointRef, + ordinals: Vec<u8>, + ) -> Result<Self, OperationError> { + if intent.role() != ArtifactRole::GiftWrap + || intent.event_id() != source.receipt().event_id() + || checkpoint.authority() != source.receipt().checkpoint().authority() + || checkpoint.revision() <= source.receipt().checkpoint().revision() + || ordinals.len() != intent.selection().len() + || ordinals.iter().any(|n| !(1..=12).contains(n)) + || retained_at + .get() + .checked_mul(1000) + .is_none_or(|at| at >= intent.deadline_unix_ms().get()) + { + return Err(OperationError::RecoveryRequired); + } + let outer = source.with_json(|raw| { + crate::command::verified_private_outer(raw, source.receipt().recipient()) + })?; + if outer.envelope().created_at_u64() > retained_at.get() { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + source, + intent, + transaction, + retained_at, + checkpoint, + ordinals: ordinals.into_boxed_slice(), + }) + } + pub fn source(&self) -> &StockEnvelopeSource { + &self.source + } + pub const fn intent(&self) -> &DeliveryIntent { + &self.intent + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + pub const fn retained_at(&self) -> UnixSeconds { + self.retained_at + } + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } + pub fn target_ordinals(&self) -> &[u8] { + &self.ordinals + } + /// Reconstructs the original request without supplying a dispatch permit. + pub fn transport_request(&self) -> Result<DeliveryRequest, OperationError> { + let outer = self.source.with_json(|raw| { + crate::command::verified_private_outer(raw, self.source.receipt().recipient()) + })?; + DeliveryRequest::new( + self.intent.request_id().as_str(), + DeliveryPayload::new(outer), + self.intent.targets().clone(), + self.intent.policy().clone(), + self.intent.deadline_unix_ms().get(), + ) + .map_err(|_| OperationError::RecoveryRequired) + } +} +impl fmt::Debug for StockDeliveryAttempt { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryAttempt(<redacted>)") + } +} + +/// Actual store outcome; public construction does not qualify an arbitrary host. +pub enum StockDeliveryAttemptOutcome { + /// Newly confirmed potential invocation; its qualified owner may proceed once. + Claimed(Box<StockDeliveryAttempt>), + /// Original existing request, without another dispatch right. + Retained(Box<StockDeliveryAttempt>), + /// Uncertain transaction, without any dispatch right. + Unknown { + operation: CommitAttempt, + request: DeliveryRequestId, + }, +} +impl fmt::Debug for StockDeliveryAttemptOutcome { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryAttemptOutcome(<redacted>)") + } +} + +/// Independent exact attempt/target outcome, never buyer receipt or stock effect. +#[derive(Clone, Eq, PartialEq)] +pub struct StockDeliveryObservation { + source: StockEnvelopeReceipt, + request: DeliveryRequestId, + attempt: TransactionId, + checkpoint: InventoryCheckpointRef, + target: DeliveryTargetReceipt, + kind: DeliveryObservationKind, + ordinal: u8, + observed: Option<NonZeroU64>, +} +impl StockDeliveryObservation { + pub fn from_receipt( + attempt: &StockDeliveryAttempt, + receipt: &DeliveryReceipt, + target: &TargetFingerprint, + observed: Option<NonZeroU64>, + ) -> Result<Self, OperationError> { + receipt + .validate_for_request(&attempt.transport_request()?) + .map_err(|_| OperationError::InvalidEvidence)?; + let report = receipt + .target_receipts() + .iter() + .find(|report| report.target().fingerprint() == target) + .ok_or(OperationError::InvalidEvidence)?; + Self::from_store_report(attempt, report, observed) + } + pub fn from_failure( + attempt: &StockDeliveryAttempt, + failure: &SinkFailure, + target: &TargetFingerprint, + observed: Option<NonZeroU64>, + ) -> Result<Self, OperationError> { + failure + .validate_for_request(&attempt.transport_request()?) + .map_err(|_| OperationError::InvalidEvidence)?; + let report = failure + .partial_evidence() + .iter() + .find(|report| report.target().fingerprint() == target) + .ok_or(OperationError::InvalidEvidence)?; + Self::from_store_report(attempt, report, observed) + } + /// Normalizes bounded data only. The native owner authenticates the actual + /// original attempt and preserves the first observation of each class. + pub fn from_store_report( + attempt: &StockDeliveryAttempt, + report: &DeliveryTargetReceipt, + observed: Option<NonZeroU64>, + ) -> Result<Self, OperationError> { + let (kind, ordinal) = crate::command::normalize_delivery_observation( + attempt.intent(), + attempt.target_ordinals(), + report, + observed, + )?; + Ok(Self { + source: attempt.source().receipt(), + request: attempt.intent().request_id().clone(), + attempt: attempt.transaction_id(), + checkpoint: attempt.checkpoint(), + target: report.clone(), + kind, + ordinal, + observed, + }) + } + pub const fn source(&self) -> StockEnvelopeReceipt { + self.source + } + pub const fn request_id(&self) -> &DeliveryRequestId { + &self.request + } + pub const fn event_id(&self) -> EnvelopeEventId { + self.source.event_id() + } + pub const fn attempt_transaction_id(&self) -> TransactionId { + self.attempt + } + pub const fn attempt_checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } + pub const fn target_receipt(&self) -> &DeliveryTargetReceipt { + &self.target + } + pub const fn kind(&self) -> DeliveryObservationKind { + self.kind + } + pub const fn target_ordinal(&self) -> u8 { + self.ordinal + } + pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { + self.observed + } +} +impl fmt::Debug for StockDeliveryObservation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryObservation(<redacted>)") + } +} + +/// Actual original observation append metadata, with no remote delivery claim. +#[derive(Clone, Eq, PartialEq)] +pub struct StockDeliveryObservationReceipt { + observation: StockDeliveryObservation, + transaction: TransactionId, + checkpoint: InventoryCheckpointRef, +} +impl StockDeliveryObservationReceipt { + pub fn from_store_report( + observation: StockDeliveryObservation, + transaction: TransactionId, + checkpoint: InventoryCheckpointRef, + ) -> Result<Self, OperationError> { + if checkpoint.authority() != observation.attempt_checkpoint().authority() + || checkpoint.revision() <= observation.attempt_checkpoint().revision() + { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + observation, + transaction, + checkpoint, + }) + } + pub const fn observation(&self) -> &StockDeliveryObservation { + &self.observation + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } +} +impl fmt::Debug for StockDeliveryObservationReceipt { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryObservationReceipt(<redacted>)") + } +} + +/// Confirmed original append or unresolved capture of the borrowed original. +pub enum StockDeliveryObservationOutcome { + Committed(Box<StockDeliveryObservationReceipt>), + Unknown(CommitAttempt), +} +impl fmt::Debug for StockDeliveryObservationOutcome { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryObservationOutcome(<redacted>)") + } +} diff --git a/crates/storage/src/inventory/delivery_state.rs b/crates/storage/src/inventory/delivery_state.rs @@ -0,0 +1,243 @@ +//! Bounded stock delivery projections; original outcomes remain separately paged. +use super::*; +use crate::command::{DeliveryIntent, DeliveryObservationKind}; +use core::{fmt, num::NonZeroU64}; +use radroots_domain::Sequence; +use radroots_protocol::intent::ArtifactRole; +use radroots_transport::{ + outcome::DeliveryOutcome, + policy::{SatisfactionState, evaluate_satisfaction}, + target::TargetFingerprint, +}; + +/// One original endpoint's bounded progress. Counts are potential invocations; +/// acceptance is a relay observation, never physical receipt or business state. +#[derive(Clone, Eq, PartialEq)] +pub struct StockDeliveryTargetProgress { + target: TargetFingerprint, + attempts: u8, + accepted: bool, + last: Option<DeliveryObservationKind>, + observed: Option<NonZeroU64>, +} +impl StockDeliveryTargetProgress { + pub fn from_store_report( + target: TargetFingerprint, + attempts: u8, + accepted: bool, + last: Option<DeliveryObservationKind>, + observed: Option<NonZeroU64>, + ) -> Result<Self, OperationError> { + if attempts > 12 + || (attempts == 0 && (accepted || last.is_some())) + || (accepted && last.is_none()) + || (last == Some(DeliveryObservationKind::Accepted) && !accepted) + || (last.is_none() && observed.is_some()) + || observed.is_some_and(|time| time.get() > 253_402_300_799_999) + { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + target, + attempts, + accepted, + last, + observed, + }) + } + pub const fn target(&self) -> &TargetFingerprint { + &self.target + } + pub const fn potential_attempts(&self) -> u8 { + self.attempts + } + pub const fn accepted(&self) -> bool { + self.accepted + } + pub const fn last_observation_kind(&self) -> Option<DeliveryObservationKind> { + self.last + } + pub const fn last_observed_at_unix_ms(&self) -> Option<NonZeroU64> { + self.observed + } +} +impl fmt::Debug for StockDeliveryTargetProgress { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryTargetProgress(<redacted>)") + } +} + +/// At most sixteen endpoint summaries and one original publication policy. +/// No collection duplicates the signed outer for every retained attempt. +#[derive(Clone, Eq, PartialEq)] +pub struct StockDeliverySummary { + source: Option<StockEnvelopeReceipt>, + first: Option<DeliveryIntent>, + attempts: u16, + targets: Box<[StockDeliveryTargetProgress]>, + checkpoint: InventoryCheckpointRef, +} +impl StockDeliverySummary { + /// Validates report shape only; current access and original protected history + /// must be authenticated by the concrete owner in the actual read transaction. + pub fn from_store_report( + request: &StockEnvelopeRequest, + source: Option<StockEnvelopeReceipt>, + first: Option<DeliveryIntent>, + attempts: u16, + targets: Vec<StockDeliveryTargetProgress>, + checkpoint: InventoryCheckpointRef, + ) -> Result<Self, OperationError> { + if checkpoint.authority() != request.binding().input().authority() + || checkpoint.revision().get() == 0 + || attempts > 16 * 12 + || targets.len() > 16 + { + return Err(OperationError::RecoveryRequired); + } + if let Some(source) = source { + let original = source.attempt(); + if original.workspace_id() != request.binding().input().workspace_id() + || original.operation_id() != request.operation_id() + || original.command_digest() != request.command_digest() + || source.recipient() != request.recipient() + || source.checkpoint().authority() != checkpoint.authority() + || source.checkpoint().revision() > checkpoint.revision() + { + return Err(OperationError::RecoveryRequired); + } + } + match &first { + None if attempts != 0 || !targets.is_empty() => { + return Err(OperationError::RecoveryRequired); + } + Some(intent) + if attempts == 0 + || intent.role() != ArtifactRole::GiftWrap + || source.is_none_or(|source| source.event_id() != intent.event_id()) + || intent + .targets() + .targets() + .iter() + .map(|target| target.fingerprint()) + .ne(targets.iter().map(|target| target.target())) + || targets + .iter() + .any(|target| u16::from(target.attempts) > attempts) + || targets + .iter() + .map(|target| u16::from(target.attempts)) + .sum::<u16>() + < attempts => + { + return Err(OperationError::RecoveryRequired); + } + _ => {} + } + Ok(Self { + source, + first, + attempts, + targets: targets.into_boxed_slice(), + checkpoint, + }) + } + pub const fn source(&self) -> Option<StockEnvelopeReceipt> { + self.source + } + pub const fn original_intent(&self) -> Option<&DeliveryIntent> { + self.first.as_ref() + } + pub const fn attempt_count(&self) -> u16 { + self.attempts + } + pub fn targets(&self) -> &[StockDeliveryTargetProgress] { + &self.targets + } + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } + /// Applies the shared transport-owned law to sticky original acceptances. + pub fn acceptance_satisfied(&self) -> Result<bool, OperationError> { + let Some(intent) = &self.first else { + return Ok(false); + }; + let accepted = DeliveryOutcome::accepted(); + evaluate_satisfaction( + intent.policy(), + intent.targets(), + self.targets + .iter() + .filter(|target| target.accepted) + .map(|target| (target.target(), &accepted)), + ) + .map(|state| state == SatisfactionState::Satisfied) + .map_err(|_| OperationError::RecoveryRequired) + } +} +impl fmt::Debug for StockDeliverySummary { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliverySummary(<redacted>)") + } +} + +/// A bounded original-outcome page, ordered by protected stock revision. +pub struct StockDeliveryObservationPage { + entries: Vec<StockDeliveryObservationReceipt>, + next: Option<Sequence>, + checkpoint: InventoryCheckpointRef, +} +impl StockDeliveryObservationPage { + pub fn from_store_report( + request: &StockEnvelopeRequest, + entries: Vec<StockDeliveryObservationReceipt>, + more: bool, + checkpoint: InventoryCheckpointRef, + ) -> Result<Self, OperationError> { + if entries.len() > 16 + || (entries.is_empty() && more) + || checkpoint.authority() != request.binding().input().authority() + || entries + .windows(2) + .any(|pair| pair[0].checkpoint().revision() >= pair[1].checkpoint().revision()) + { + return Err(OperationError::RecoveryRequired); + } + for entry in &entries { + let original = entry.observation().source(); + if original.attempt().workspace_id() != request.binding().input().workspace_id() + || original.attempt().operation_id() != request.operation_id() + || original.attempt().command_digest() != request.command_digest() + || original.recipient() != request.recipient() + || entry.checkpoint().authority() != checkpoint.authority() + || entry.checkpoint().revision() > checkpoint.revision() + { + return Err(OperationError::RecoveryRequired); + } + } + let next = if more { + entries.last().map(|entry| entry.checkpoint().revision()) + } else { + None + }; + Ok(Self { + entries, + next, + checkpoint, + }) + } + pub fn entries(&self) -> &[StockDeliveryObservationReceipt] { + &self.entries + } + pub const fn next_after(&self) -> Option<Sequence> { + self.next + } + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } +} +impl fmt::Debug for StockDeliveryObservationPage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("StockDeliveryObservationPage(<redacted>)") + } +} diff --git a/crates/storage/src/inventory/evidence.rs b/crates/storage/src/inventory/evidence.rs @@ -4,6 +4,42 @@ use core::num::NonZeroU64; use radroots_domain::{PublicKey, SigningAttemptId}; use zeroize::Zeroizing; +/// Bounded original signed bytes read by the qualified protected owner. +/// Construction checks representation identity, not current access or issuance. +pub struct StockEvidenceSource { + receipt: StockEvidenceReceipt, + raw: Zeroizing<String>, +} +impl StockEvidenceSource { + pub fn from_retained_wire( + receipt: StockEvidenceReceipt, + raw: &str, + ) -> Result<Self, OperationError> { + use sha2::{Digest, Sha256}; + if raw.is_empty() + || raw.len() > 64 * 1024 + || <[u8; 32]>::from(Sha256::digest(raw.as_bytes())) != *receipt.digest() + { + return Err(OperationError::InvalidEvidence); + } + Ok(Self { + receipt, + raw: Zeroizing::new(raw.to_string()), + }) + } + pub const fn receipt(&self) -> StockEvidenceReceipt { + self.receipt + } + pub fn with_json<T>(&self, use_json: impl FnOnce(&str) -> T) -> T { + use_json(&self.raw) + } +} +impl core::fmt::Debug for StockEvidenceSource { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("StockEvidenceSource(<redacted>)") + } +} + /// Obtained original wire bytes, never proof of a protected claim or authority. /// The concrete store must authenticate the actual retained claim and verify /// these bytes against it before append. Construction performs no cryptography. diff --git a/crates/storage/tests/workspace/inventory_delivery.rs b/crates/storage/tests/workspace/inventory_delivery.rs @@ -0,0 +1,200 @@ +//! Synthetic report shape only; actual stock linkage is a native-store duty. +use super::*; +use radroots_storage::{ + command::{DeliveryIntent, DeliveryObservationKind}, + inventory::{ + StockDeliveryObservationPage, StockDeliveryRequest, StockDeliverySummary, + StockDeliveryTargetProgress, + }, +}; +use radroots_transport::{ + Target, TargetSet, + policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}, +}; + +fn fixture() -> (StockEnvelopeRequest, StockEnvelopeReceipt, DeliveryIntent) { + let original = attempt(1, 7, 8, true); + let request = StockEnvelopeRequest::new( + binding(WorkspaceScope::SellerStockOwner), + checkpoint(0), + original.operation_id(), + original.command_digest(), + key(), + None, + ) + .unwrap(); + let source = StockEnvelopeReceipt::from_committed_store( + &request, + original, + evidence(original, key()), + TransactionId::from_bytes([12; 32]), + EnvelopeEventId::from_bytes([14; 32]), + [15; 32], + checkpoint(1), + ) + .unwrap(); + let targets = TargetSet::new(vec![ + Target::nostr_relay("wss://one.example").unwrap(), + Target::nostr_relay("wss://two.example").unwrap(), + ]) + .unwrap(); + let intent = DeliveryIntent::new( + &"a".repeat(64), + source.event_id(), + &targets, + &SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), + core::num::NonZeroU64::new(300000).unwrap(), + ) + .unwrap(); + (request, source, intent) +} +fn progress(intent: &DeliveryIntent, accepted: &[bool; 2]) -> Vec<StockDeliveryTargetProgress> { + intent + .targets() + .targets() + .iter() + .zip(accepted) + .map(|(target, accepted)| { + StockDeliveryTargetProgress::from_store_report( + target.fingerprint().clone(), + 1, + *accepted, + Some(if *accepted { + DeliveryObservationKind::Accepted + } else { + DeliveryObservationKind::Disconnected + }), + None, + ) + .unwrap() + }) + .collect() +} + +#[test] +fn summary_keeps_the_complete_original_transport_criterion_and_never_promotes_capture_only() { + let (request, source, intent) = fixture(); + let captured = StockDeliverySummary::from_store_report( + &request, + Some(source), + None, + 0, + vec![], + checkpoint(3), + ) + .unwrap(); + assert!(!captured.acceptance_satisfied().unwrap()); + assert!(captured.original_intent().is_none()); + for (accepted, expected) in [([true, false], false), ([true, true], true)] { + let value = StockDeliverySummary::from_store_report( + &request, + Some(source), + Some(intent.clone()), + 1, + progress(&intent, &accepted), + checkpoint(3), + ) + .unwrap(); + assert_eq!(value.acceptance_satisfied().unwrap(), expected); + assert_eq!(value.original_intent(), Some(&intent)); + assert_eq!(value.attempt_count(), 1); + assert_eq!(value.targets().len(), 2); + assert_eq!(format!("{value:?}"), "StockDeliverySummary(<redacted>)"); + } +} + +#[test] +fn endpoint_caps_and_summary_scope_reject_inconsistent_reports() { + let (request, source, intent) = fixture(); + let fp = intent.targets().targets()[0].fingerprint(); + assert!( + StockDeliveryTargetProgress::from_store_report(fp.clone(), 13, false, None, None).is_err() + ); + assert!( + StockDeliveryTargetProgress::from_store_report(fp.clone(), 0, true, None, None).is_err() + ); + assert!( + StockDeliveryTargetProgress::from_store_report( + fp.clone(), + 1, + false, + None, + core::num::NonZeroU64::new(1) + ) + .is_err() + ); + for count in [0, 3, 193] { + assert!( + StockDeliverySummary::from_store_report( + &request, + Some(source), + Some(intent.clone()), + count, + progress(&intent, &[false, false]), + checkpoint(3) + ) + .is_err() + ); + } + let mut wrong_order = progress(&intent, &[false, false]); + wrong_order.reverse(); + assert!( + StockDeliverySummary::from_store_report( + &request, + Some(source), + Some(intent.clone()), + 1, + wrong_order, + checkpoint(3) + ) + .is_err() + ); + assert!( + StockDeliverySummary::from_store_report( + &request, + None, + Some(intent.clone()), + 1, + progress(&intent, &[false, false]), + checkpoint(3) + ) + .is_err() + ); +} + +#[test] +fn stock_intent_refuses_public_artifacts_and_empty_outcome_pages_do_not_advance() { + let (request, source, intent) = fixture(); + let public = DeliveryIntent::public( + &"b".repeat(64), + source.event_id(), + intent.targets(), + intent.policy(), + intent.deadline_unix_ms(), + ) + .unwrap(); + assert!( + StockDeliveryRequest::new( + request.binding().clone(), + checkpoint(0), + request.operation_id(), + request.command_digest(), + request.recipient(), + public + ) + .is_err() + ); + assert!( + StockDeliveryObservationPage::from_store_report(&request, vec![], true, checkpoint(3)) + .is_err() + ); + let page = + StockDeliveryObservationPage::from_store_report(&request, vec![], false, checkpoint(3)) + .unwrap(); + assert!(page.entries().is_empty()); + assert!(page.next_after().is_none()); + assert_eq!( + format!("{page:?}"), + "StockDeliveryObservationPage(<redacted>)" + ); +} diff --git a/crates/storage/tests/workspace/inventory_envelope.rs b/crates/storage/tests/workspace/inventory_envelope.rs @@ -1,4 +1,6 @@ //! Shape checks remain independent of concrete persistence and permission. +#[path = "inventory_delivery.rs"] +mod delivery; use super::*; use radroots_domain::{ CommandDigest, EnvelopeEventId, OperationId, SigningAttemptId, TransactionId, diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -709,7 +709,7 @@ fn stock_root_context( input: &super::AttachmentInput, version: i64, ) -> Result<EnvelopeContext, WorkspaceError> { - if matches!(version, 4..=16) { + if matches!(version, 4..=17) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -746,8 +746,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v14\0".as_slice() } else if version == 15 { b"radroots.seller_stock.authority_context.v15\0".as_slice() - } else { + } else if version == 16 { b"radroots.seller_stock.authority_context.v16\0".as_slice() + } else { + b"radroots.seller_stock.authority_context.v17\0".as_slice() }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -780,8 +782,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v14" } else if version == 15 { "radroots.seller_stock.authority.v15" - } else { + } else if version == 16 { "radroots.seller_stock.authority.v16" + } else { + "radroots.seller_stock.authority.v17" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -899,12 +903,12 @@ fn stock_record_context_for_catalog( ) -> Result<EnvelopeContext, WorkspaceError> { let original = stock_record_context(input, kind, id)?; let schema = match (catalog, kind) { - (2, _) | (3..=16, "pool") => return Ok(original), + (2, _) | (3..=17, "pool") => return Ok(original), (3, "operation") => "radroots.seller_stock.operation.v2", (4, "operation") => "radroots.seller_stock.operation.v3", (5 | 6, "operation") => "radroots.seller_stock.operation.v4", - (7..=16, "operation") => "radroots.seller_stock.operation.v5", - (3..=16, "movement") => "radroots.seller_stock.movement.v2", + (7..=17, "operation") => "radroots.seller_stock.operation.v5", + (3..=17, "movement") => "radroots.seller_stock.movement.v2", _ => return Err(WorkspaceError::RecoveryRequired), }; Ok(EnvelopeContext::new( diff --git a/crates/storage_sqlite/src/workspace/delivery/json.rs b/crates/storage_sqlite/src/workspace/delivery/json.rs @@ -8,7 +8,7 @@ use serde_json::value::RawValue; // Allocation-free structural preflight, followed by the actual closed serde // codec. Fixed identifier arrays contain 32 bytes; descriptor lists use the // stricter sixteen-element visitor below. -pub(super) fn bounded(raw: &[u8], array_limit: usize) -> bool { +pub(in crate::workspace) fn bounded(raw: &[u8], array_limit: usize) -> bool { let mut stack = [(0u8, false, 0usize); 16]; let mut depth = 0usize; let mut quoted = false; @@ -63,7 +63,7 @@ pub(super) fn bounded(raw: &[u8], array_limit: usize) -> bool { !quoted && !escaped && depth == 0 } -pub(super) fn small_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error> +pub(in crate::workspace) fn small_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error> where D: Deserializer<'de>, T: Deserialize<'de>, @@ -88,7 +88,7 @@ where deserializer.deserialize_seq(Items(PhantomData)) } -pub(super) fn targets<'de, D: Deserializer<'de>>( +pub(in crate::workspace) fn targets<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result<radroots_transport::TargetSet, D::Error> { #[derive(Deserialize)] @@ -101,7 +101,7 @@ pub(super) fn targets<'de, D: Deserializer<'de>>( radroots_transport::TargetSet::new(wire.targets).map_err(de::Error::custom) } -pub(super) fn policy<'de, D: Deserializer<'de>>( +pub(in crate::workspace) fn policy<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result<radroots_transport::policy::SatisfactionPolicy, D::Error> { let raw = <&RawValue>::deserialize(deserializer)?; diff --git a/crates/storage_sqlite/src/workspace/delivery/mod.rs b/crates/storage_sqlite/src/workspace/delivery/mod.rs @@ -3,7 +3,7 @@ mod codec; pub(super) mod containment; pub(super) mod graph; -mod json; +pub(in crate::workspace) mod json; pub(super) mod observation; mod observation_operations; mod operations; diff --git a/crates/storage_sqlite/src/workspace/recovery.rs b/crates/storage_sqlite/src/workspace/recovery.rs @@ -8,7 +8,10 @@ use super::{ }; use radroots_storage::{ command::{ArtifactEvidence, EvidenceCaptureOutcome, OperationError}, - inventory::{StockEvidenceOutcome, StockEvidenceRequest}, + inventory::{ + StockDeliveryObservation, StockDeliveryObservationOutcome, StockEnvelopeOutcome, + StockEnvelopeRequest, StockEvidenceOutcome, StockEvidenceRequest, + }, workspace::seller_stock::SellerAuthoritySelection, }; use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions}; @@ -39,6 +42,13 @@ enum Material { Outbox(Box<(AttachmentInput, ArtifactEvidence)>), Stock(Box<StockEvidenceRequest>), Unissued(Box<stock::issuance::unissued::Request>), + Envelope( + Box<( + StockEnvelopeRequest, + radroots_storage::command::PrivateEnvelopeCandidate, + )>, + ), + Observation(Box<(super::WorkspaceBinding, StockDeliveryObservation)>), } impl Material { fn input(&self) -> &AttachmentInput { @@ -46,6 +56,8 @@ impl Material { Self::Outbox(value) => &value.0, Self::Stock(value) => value.binding().input(), Self::Unissued(value) => value.binding.input(), + Self::Envelope(value) => value.0.binding().input(), + Self::Observation(value) => value.0.input(), } } } @@ -53,6 +65,8 @@ enum Captured { Outbox(EvidenceCaptureOutcome), Stock(StockEvidenceOutcome), Unissued(stock::StockUnissuedOutcome), + Envelope(StockEnvelopeOutcome), + Observation(StockDeliveryObservationOutcome), } impl Captured { fn committed(&self) -> bool { @@ -61,6 +75,8 @@ impl Captured { Self::Outbox(EvidenceCaptureOutcome::Committed(_)) | Self::Stock(StockEvidenceOutcome::Committed(_)) | Self::Unissued(stock::StockUnissuedOutcome::Committed(_)) + | Self::Envelope(StockEnvelopeOutcome::Committed(_)) + | Self::Observation(StockDeliveryObservationOutcome::Committed(_)) ) } } @@ -116,6 +132,53 @@ impl RecoveryTurn<'_> { _ => Err(OperationError::RecoveryRequired), } } + pub(super) async fn capture_envelope( + &mut self, + request: StockEnvelopeRequest, + proof: AttachmentProof, + candidate: radroots_storage::command::PrivateEnvelopeCandidate, + ) -> Result<StockEnvelopeOutcome, OperationError> { + if self.namespace.kind() != Kind::SellerStock { + return Err(OperationError::UnsupportedOperation); + } + if !SellerAuthoritySelection::from_attachment(self.selected) + .matches_attachment(request.binding().input()) + { + return Err(OperationError::Unauthorized); + } + match self + .recover(Material::Envelope(Box::new((request, candidate))), proof) + .await? + { + Captured::Envelope(value) => Ok(value), + _ => Err(OperationError::RecoveryRequired), + } + } + pub(super) async fn capture_observation( + &mut self, + binding: super::WorkspaceBinding, + proof: AttachmentProof, + observation: StockDeliveryObservation, + ) -> Result<StockDeliveryObservationOutcome, OperationError> { + if self.namespace.kind() != Kind::SellerStock { + return Err(OperationError::UnsupportedOperation); + } + if !SellerAuthoritySelection::from_attachment(self.selected) + .matches_attachment(binding.input()) + { + return Err(OperationError::Unauthorized); + } + match self + .recover( + Material::Observation(Box::new((binding, observation))), + proof, + ) + .await? + { + Captured::Observation(value) => Ok(value), + _ => Err(OperationError::RecoveryRequired), + } + } pub(super) async fn capture_unissued( &mut self, request: stock::issuance::unissued::Request, @@ -157,6 +220,42 @@ impl RecoveryTurn<'_> { &mut *self.uncertain }; let result = match material { + Material::Envelope(value) => { + let (request, candidate) = *value; + Box::pin(stock::envelope::capture( + &mut stock::inventory::Turn { + connection, + namespace: self.namespace, + selected: self.selected, + crypto: self.crypto, + clock: self.clock, + uncertain: uncertainty, + }, + request, + proof, + candidate, + )) + .await + .map(Captured::Envelope) + } + Material::Observation(value) => { + let (binding, observation) = *value; + Box::pin(stock::delivery::capture_observation( + &mut stock::inventory::Turn { + connection, + namespace: self.namespace, + selected: self.selected, + crypto: self.crypto, + clock: self.clock, + uncertain: uncertainty, + }, + binding, + proof, + observation, + )) + .await + .map(Captured::Observation) + } Material::Outbox(value) => { let (input, evidence) = *value; Journal { diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -9,6 +9,7 @@ use radroots_storage::workspace::seller_stock::{ SellerAuthoritySelection, StockAction, StockAuthorizationRef, StockGrantRecord, StockGrantScope, }; pub(in crate::workspace) mod consent; +pub(in crate::workspace) mod delivery; pub use consent::{ StockConsentCapture, StockConsentMode, StockConsentOutcome, StockConsentReceipt, }; @@ -444,10 +445,10 @@ struct AuthorityV8 { } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { - if !matches!(self.catalog, 8..=16) && self.public_sources.is_some() { + if !matches!(self.catalog, 8..=17) && self.public_sources.is_some() { return Err(WorkspaceError::RecoveryRequired); } - if matches!(self.catalog, 8..=16) { + if matches!(self.catalog, 8..=17) { let public_sources = self .public_sources .ok_or(WorkspaceError::RecoveryRequired)?; @@ -699,7 +700,7 @@ impl Authority { public_sources: None, } } - 8..=16 => { + 8..=17 => { let value: AuthorityV8 = closed_record(bytes)?; value.public_sources.validate()?; if i64::from(value.version) != catalog @@ -830,7 +831,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=16") + sqlx::query("PRAGMA user_version=17") .execute(&mut *tx) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -1190,6 +1191,130 @@ impl radroots_storage::inventory::InventoryStore for NativeWorkspace { > { Box::pin(self.worker.stock_envelope(request, proof)) } + fn reconcile_stock_envelope<'a>( + &'a self, + request: radroots_storage::inventory::StockEnvelopeRequest, + proof: AttachmentProof, + candidate: &'a radroots_storage::command::PrivateEnvelopeCandidate, + ) -> radroots_transport::BoxFuture< + 'a, + Result< + radroots_storage::inventory::StockEnvelopeOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(async move { + self.worker + .reconcile_stock_envelope(request, proof, candidate.retained_copy()) + .await + }) + } + fn prepare_stock_delivery_attempt( + &self, + request: radroots_storage::inventory::StockDeliveryRequest, + proof: AttachmentProof, + ) -> radroots_transport::BoxFuture< + '_, + Result< + radroots_storage::inventory::StockDeliveryAttemptOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.prepare_stock_delivery_attempt(request, proof)) + } + fn stock_delivery_attempt( + &self, + source: radroots_storage::inventory::StockEnvelopeRequest, + request_id: radroots_transport::sink::DeliveryRequestId, + proof: AttachmentProof, + ) -> radroots_transport::BoxFuture< + '_, + Result< + Option<radroots_storage::inventory::StockDeliveryAttempt>, + radroots_storage::command::OperationError, + >, + > { + Box::pin( + self.worker + .stock_delivery_attempt(source, request_id, proof), + ) + } + fn stock_delivery_summary( + &self, + source: radroots_storage::inventory::StockEnvelopeRequest, + proof: AttachmentProof, + ) -> radroots_transport::BoxFuture< + '_, + Result< + radroots_storage::inventory::StockDeliverySummary, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.stock_delivery_summary(source, proof)) + } + fn record_stock_delivery_observation<'a>( + &'a self, + binding: &'a WorkspaceBinding, + proof: &'a AttachmentProof, + observation: &'a radroots_storage::inventory::StockDeliveryObservation, + ) -> radroots_transport::BoxFuture< + 'a, + Result< + radroots_storage::inventory::StockDeliveryObservationOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(async move { + self.worker + .record_stock_delivery_observation( + binding.clone(), + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + observation.clone(), + false, + ) + .await + }) + } + fn reconcile_stock_delivery_observation<'a>( + &'a self, + binding: &'a WorkspaceBinding, + proof: &'a AttachmentProof, + observation: &'a radroots_storage::inventory::StockDeliveryObservation, + ) -> radroots_transport::BoxFuture< + 'a, + Result< + radroots_storage::inventory::StockDeliveryObservationOutcome, + radroots_storage::command::OperationError, + >, + > { + Box::pin(async move { + self.worker + .record_stock_delivery_observation( + binding.clone(), + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + observation.clone(), + true, + ) + .await + }) + } + fn stock_delivery_observations( + &self, + source: radroots_storage::inventory::StockEnvelopeRequest, + after: Option<Sequence>, + proof: AttachmentProof, + ) -> radroots_transport::BoxFuture< + '_, + Result< + radroots_storage::inventory::StockDeliveryObservationPage, + radroots_storage::command::OperationError, + >, + > { + Box::pin( + self.worker + .stock_delivery_observations(source, after, proof), + ) + } fn prepare_stock_acceptance( &self, request: StockAcceptanceRequest, diff --git a/crates/storage_sqlite/src/workspace/stock/consent.rs b/crates/storage_sqlite/src/workspace/stock/consent.rs @@ -260,6 +260,7 @@ struct Body<'a> { } pub(super) struct Retained { pub frame: ledger::Retained, + pub observed_at: UnixSeconds, pub command: CapturedOrderAcceptance, pub mode: StockConsentMode, pub resources: StockResources, @@ -386,6 +387,7 @@ pub(super) async fn read( let authorization = body.authorization; let subject_digest = body.subject_digest; Ok(Some(Retained { + observed_at: body.observed_at, frame, command, mode, @@ -422,7 +424,7 @@ pub(in crate::workspace) async fn issue( proof: AttachmentProof, ) -> Result<StockConsentOutcome, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=16) { + if !matches!(access.authority.catalog, 7..=17) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() @@ -683,7 +685,7 @@ pub(in crate::workspace) async fn query( proof: AttachmentProof, ) -> Result<Option<StockConsentReceipt>, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=16) { + if !matches!(access.authority.catalog, 7..=17) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() && access.current.input().grant_id() != subject { diff --git a/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs b/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs @@ -74,7 +74,7 @@ impl KeyWrapping for Provider { fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>> { Box::pin(async move { let result = self.inner.wrap(request).await; - if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v16" + if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v17" { self.gate.pause(); } diff --git a/crates/storage_sqlite/src/workspace/stock/delivery.rs b/crates/storage_sqlite/src/workspace/stock/delivery.rs @@ -0,0 +1,269 @@ +//! Stock-owned protected dispatch history. Transport stays outside transactions. +use super::*; +use inventory::{Turn, checkpoint}; +use radroots_domain::{ + ActorRef, CheckpointDigest, CommandDigest, EnvelopeEventId, OperationId, OrderId, PublicKey, + UnixSeconds, +}; +use radroots_storage::{ + command::{DeliveryIntent, DeliveryObservationKind, OperationError, SignedDmRelaySource}, + inventory::{ + InventoryCheckpointRef, StockDeliveryAttempt, StockDeliveryAttemptOutcome, + StockDeliveryObservation, StockDeliveryObservationOutcome, StockDeliveryObservationPage, + StockDeliveryObservationReceipt, StockDeliveryRequest, StockDeliverySummary, + StockDeliveryTargetProgress, StockEnvelopeRequest, + }, +}; +use radroots_transport::{ + TargetSet, + policy::SatisfactionPolicy, + sink::{DeliveryRequestId, DeliveryTargetReceipt}, + target::TargetFingerprint, +}; +use sha2::{Digest, Sha256}; +use sqlx::Row; +use std::{num::NonZeroU64, sync::Arc}; + +pub(in crate::workspace::stock) mod attempt; +mod graph; +pub(in crate::workspace::stock) mod observation; +mod observation_operations; +mod operations; +mod projection; +mod wire; +pub(in crate::workspace) use observation_operations::{capture_observation, page}; +pub(in crate::workspace) use operations::{prepare, query_attempt, summary}; +pub(in crate::workspace::stock) use projection::{Projection, raw_projection}; + +const ATTEMPT_MAX: usize = 65536; +const OBSERVATION_MAX: usize = 16384; +const ATTEMPT_COUNT_MAX: usize = 384; +const OBSERVATION_COUNT_MAX: usize = 2304; +const PAGE_MAX: usize = 16; + +pub(in crate::workspace::stock) async fn snapshot( + turn: &mut Turn<'_>, + request: StockEnvelopeRequest, + authority: &Authority, +) -> Result<[StockDeliverySummary; 2], OperationError> { + let graph = Box::pin(graph::Graph::read(turn, &request, authority, None, None)).await?; + let original = Box::pin(inventory::acceptance::codec::read( + turn.connection, + turn.selected, + turn.crypto, + request.operation_id(), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let checkpoint = authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let checkpoint = InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + checkpoint.revision, + checkpoint.head, + )? + .with_optional_authorization(authority.authorization); + let reports = original + .receipt + .rumor() + .recipients() + .each_ref() + .map(|recipient| { + let source = StockEnvelopeRequest::new( + request.binding().clone(), + request.minimum_checkpoint(), + request.operation_id(), + request.command_digest(), + *recipient, + None, + )?; + graph.summary(&source, checkpoint) + }); + let [first, second] = reports; + Ok([first?, second?]) +} + +fn request_key(request: &DeliveryRequestId) -> [u8; 32] { + Sha256::digest(request.as_str().as_bytes()).into() +} +fn target_key(target: &TargetFingerprint) -> [u8; 32] { + Sha256::digest(target.as_str().as_bytes()).into() +} +fn validate_request(request: &DeliveryRequestId) -> Result<(), OperationError> { + let raw = request.as_str(); + if raw.len() != 64 + || !raw + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return Err(OperationError::InvalidCommand); + } + Ok(()) +} +async fn confirm_record( + connection: &mut SqliteConnection, + frame: &ledger::Retained, + projection: Projection, +) -> Result<(), OperationError> { + if !matches!( + (frame.header.family, projection), + (ledger::Family::DeliveryAttempt, Projection::Attempt { .. }) + | ( + ledger::Family::DeliveryObservation, + Projection::Observation { .. } + ) + ) { + return Err(OperationError::RecoveryRequired); + } + ledger::confirm_header(connection, &frame.header, &frame.protected).await?; + ledger::confirm_parts( + connection, + frame.header.actor, + frame.header.operation, + frame.parts_witness, + frame.header.parts, + ) + .await?; + projection + .confirm( + connection, + frame.header.actor.participant(), + frame.header.operation, + ) + .await?; + let movements: i64 = + sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?") + .bind(frame.header.actor.participant().as_bytes().as_slice()) + .bind(frame.header.operation.as_bytes().as_slice()) + .fetch_one(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if movements != 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} +fn history(frame: ledger::Retained, projection: Projection) -> ledger::HistoryEntry { + ledger::HistoryEntry { + delivery: Some(projection), + envelope: None, + aborted: None, + preparation: None, + header: frame.header, + protected: frame.protected, + parts_witness: frame.parts_witness, + pools: vec![], + mapping: None, + movements: vec![], + signing: None, + installation: None, + local_record: None, + } +} +struct Append { + actor: ActorRef, + original: OperationId, + digest: CommandDigest, + order: OrderId, + family: ledger::Family, + projection: Projection, +} +struct Prepared { + frame: ledger::Prepared, + projection: Projection, + root: Vec<u8>, +} +impl Prepared { + async fn new( + turn: &Turn<'_>, + authority: &Authority, + append: Append, + body: &[u8], + ) -> Result<Self, OperationError> { + if authority.catalog != 17 { + return Err(OperationError::UnsupportedOperation); + } + let before = authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let revision = Sequence::new( + before + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let mut header = ledger::Header { + version: 5, + family: append.family, + namespace: SellerAuthoritySelection::from_attachment(turn.selected), + actor: append.actor, + operation: OperationId::from_bytes(super::super::random()?), + digest: append.digest, + transaction: TransactionId::from_bytes(super::super::random()?), + revision, + previous: before.head, + head: CheckpointDigest::from_bytes([0; 32]), + pool: None, + order: Some(append.order), + related_operation: Some(append.original), + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], + }; + header.head = wire::head(&header, body); + let frame = Box::pin(ledger::prepare(turn.crypto, turn.selected, header, body)).await?; + let mut next = authority.clone(); + next.inventory = Some(InventoryCheckpoint { + revision, + head: Some(frame.header.head), + ..before + }); + let root = Box::pin(turn.crypto.seal_stock_root( + turn.selected, + next.catalog, + &next.encode()?, + )) + .await?; + Ok(Self { + frame, + projection: append.projection, + root, + }) + } + fn checkpoint(&self, authority: &Authority) -> Result<InventoryCheckpointRef, OperationError> { + Ok(InventoryCheckpointRef::from_host_metadata( + authority.input.authority(), + self.frame.header.revision, + Some(self.frame.header.head), + )?) + } + async fn insert( + &self, + connection: &mut SqliteConnection, + original_root: &[u8], + ) -> Result<(), OperationError> { + self.frame.insert_record(connection).await?; + self.projection + .insert( + connection, + self.frame.header.actor.participant(), + self.frame.header.operation, + ) + .await?; + let result = + sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?") + .bind(&self.root) + .bind(original_root) + .execute(connection) + .await + .map_err(|_| OperationError::StorageFailure)?; + if result.rows_affected() != 1 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/attempt.rs b/crates/storage_sqlite/src/workspace/stock/delivery/attempt.rs @@ -0,0 +1,241 @@ +//! Original potential transport invocation, independently bound to stock sources. +use super::*; +use serde::{Deserialize, Serialize}; +use wire::Reference; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Wire { + version: u8, + envelope: Reference, + plan: Reference, + consent: Reference, + request: String, + event: EnvelopeEventId, + intent: [u8; 32], + #[serde(deserialize_with = "wire::targets")] + targets: TargetSet, + #[serde(deserialize_with = "wire::small_vec")] + selection: Vec<TargetFingerprint>, + #[serde(deserialize_with = "wire::policy")] + policy: SatisfactionPolicy, + deadline: u64, + at: UnixSeconds, + #[serde(deserialize_with = "wire::small_vec")] + ordinals: Vec<u8>, +} +impl Wire { + pub(super) fn new( + envelope: &envelope::Retained, + auth: &signing_plan::Authorized, + intent: &DeliveryIntent, + at: UnixSeconds, + ordinals: Vec<u8>, + ) -> Result<Self, OperationError> { + let plan = auth.plan.as_ref().ok_or(OperationError::MissingHistory)?; + validate_route( + plan.bound.plan(), + envelope.source.receipt().recipient(), + intent, + )?; + Ok(Self { + version: 1, + envelope: Reference::new(&envelope.frame.header), + plan: Reference::new(&plan.frame.header), + consent: Reference::new(&auth.consent.frame.header), + request: intent.request_id().as_str().into(), + event: intent.event_id(), + intent: *intent.digest(), + targets: intent.targets().clone(), + selection: intent.selection().to_vec(), + policy: intent.policy().clone(), + deadline: intent.deadline_unix_ms().get(), + at, + ordinals, + }) + } + fn intent(&self) -> Result<DeliveryIntent, OperationError> { + let selected = TargetSet::new( + self.targets + .targets() + .iter() + .filter(|target| self.selection.contains(target.fingerprint())) + .cloned() + .collect(), + ) + .map_err(|_| OperationError::RecoveryRequired)?; + let value = DeliveryIntent::new( + &self.request, + self.event, + &self.targets, + &self.policy, + NonZeroU64::new(self.deadline).ok_or(OperationError::RecoveryRequired)?, + ) + .and_then(|intent| intent.with_selection(&selected)) + .map_err(|_| OperationError::RecoveryRequired)?; + if value.selection() != self.selection || value.digest() != &self.intent { + return Err(OperationError::RecoveryRequired); + } + Ok(value) + } +} +pub(super) fn validate_route( + plan: &radroots_protocol::commerce::CommerceSigningPlan, + recipient: PublicKey, + intent: &DeliveryIntent, +) -> Result<(), OperationError> { + let route = plan + .routes() + .iter() + .find(|route| route.participant() == recipient) + .ok_or(OperationError::RecoveryRequired)?; + SignedDmRelaySource::verify(route.raw_json())?.validate_capture(route)?; + if intent.targets().targets().iter().any(|target| { + !route + .selected_relays() + .iter() + .any(|uri| target.matches_nostr_relay(uri).is_ok_and(|same| same)) + }) { + return Err(OperationError::UnverifiedApproval); + } + Ok(()) +} +pub(in crate::workspace::stock) struct Retained { + pub frame: ledger::Retained, + pub report: StockDeliveryAttempt, + pub projection: Projection, +} +impl Retained { + pub(super) async fn confirm( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + confirm_record(connection, &self.frame, self.projection).await + } + pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { + history(self.frame, self.projection) + } +} +pub(in crate::workspace::stock) async fn read_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + administrator: GrantId, + entry: OperationId, +) -> Result<Option<Retained>, OperationError> { + let Some(frame) = Box::pin(ledger::read(connection, input, crypto, entry)).await? else { + return Ok(None); + }; + if frame.header.family != ledger::Family::DeliveryAttempt { + return Err(OperationError::RecoveryRequired); + } + Ok(Some( + Box::pin(decode_entry( + connection, + input, + crypto, + binding, + administrator, + frame, + )) + .await?, + )) +} +async fn decode_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + administrator: GrantId, + frame: ledger::Retained, +) -> Result<Retained, OperationError> { + let value: Wire = wire::decode(&frame.body, ATTEMPT_MAX)?; + if value.version != 1 || wire::head(&frame.header, &frame.body) != frame.header.head { + return Err(OperationError::RecoveryRequired); + } + let outer = Box::pin(envelope::read_entry( + connection, + input, + crypto, + binding, + value.envelope.entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + value.envelope.confirm(&outer.frame.header)?; + let plan = Box::pin(signing_plan::read_entry( + connection, + input, + crypto, + value.plan.entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + value.plan.confirm(&plan.frame.header)?; + let consent = Box::pin(super::super::consent::read( + connection, + input, + crypto, + administrator, + value.consent.entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + value.consent.confirm(&consent.frame.header)?; + let installed = Box::pin(inventory::installation::read_entry( + connection, + input, + crypto, + outer.installation_entry(), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let source = outer.source.receipt(); + let original = source.attempt(); + let h = &frame.header; + let command = consent.command.context(); + if h.related_operation != Some(original.operation_id()) + || h.digest != original.command_digest() + || h.actor.participant() != outer.frame.header.actor.participant() + || h.actor.grant_id() != Some(consent.subject) + || h.order != outer.frame.header.order + || h.order != Some(installed.receipt.order_id()) + || h.revision <= outer.frame.header.revision + || h.revision <= plan.frame.header.revision + || h.revision <= consent.frame.header.revision + || plan.bound.attempt().operation_id() != original.operation_id() + || plan.bound.attempt().command_digest() != h.digest + || plan.frame.header.actor != outer.frame.header.actor + || command.operation_id() != original.operation_id() + || consent.command.digest() != h.digest + || value.at >= consent.expires + || value.at < consent.observed_at + || value.at < installed.receipt.installed_at() + { + return Err(OperationError::RecoveryRequired); + } + let intent = value.intent()?; + validate_route(plan.bound.plan(), source.recipient(), &intent) + .map_err(|_| OperationError::RecoveryRequired)?; + let projection = Projection::Attempt { + operation: original.operation_id(), + recipient: source.recipient(), + request: request_key(intent.request_id()), + }; + let report = StockDeliveryAttempt::from_store_report( + Arc::new(outer.source), + intent, + h.transaction, + value.at, + InventoryCheckpointRef::from_host_metadata(input.authority(), h.revision, Some(h.head))?, + value.ordinals, + )?; + let retained = Retained { + frame, + report, + projection, + }; + retained.confirm(connection).await?; + Ok(retained) +} diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/graph.rs b/crates/storage_sqlite/src/workspace/stock/delivery/graph.rs @@ -0,0 +1,314 @@ +//! Constant-memory reduction of bounded original per-recipient transport history. +use super::*; + +struct Endpoint { + fingerprint: TargetFingerprint, + attempts: u8, + accepted: bool, + last: Option<DeliveryObservationKind>, + observed: Option<NonZeroU64>, +} +struct Recipient { + participant: PublicKey, + source: Option<envelope::Retained>, + first: Option<DeliveryIntent>, + attempts: u16, + endpoints: Vec<Endpoint>, +} +impl Recipient { + fn observe_attempt(&mut self, value: &StockDeliveryAttempt) -> Result<(), OperationError> { + if self + .source + .as_ref() + .is_none_or(|source| source.source.receipt() != value.source().receipt()) + { + return Err(OperationError::RecoveryRequired); + } + if let Some(original) = &self.first { + if original.publication_policy_digest() != value.intent().publication_policy_digest() { + return Err(OperationError::RecoveryRequired); + } + } else { + self.first = Some(value.intent().clone()); + self.endpoints = value + .intent() + .targets() + .targets() + .iter() + .map(|target| Endpoint { + fingerprint: target.fingerprint().clone(), + attempts: 0, + accepted: false, + last: None, + observed: None, + }) + .collect(); + } + for (fingerprint, ordinal) in value + .intent() + .selection() + .iter() + .zip(value.target_ordinals()) + { + let endpoint = self + .endpoints + .iter_mut() + .find(|endpoint| &endpoint.fingerprint == fingerprint) + .ok_or(OperationError::RecoveryRequired)?; + if endpoint.attempts >= 12 || *ordinal != endpoint.attempts + 1 { + return Err(OperationError::RecoveryRequired); + } + endpoint.attempts = *ordinal; + } + self.attempts = self + .attempts + .checked_add(1) + .ok_or(OperationError::RecoveryRequired)?; + if self.attempts > 16 * 12 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } + fn observe(&mut self, value: &StockDeliveryObservation) -> Result<(), OperationError> { + let endpoint = self + .endpoints + .iter_mut() + .find(|endpoint| endpoint.fingerprint == *value.target_receipt().target().fingerprint()) + .ok_or(OperationError::RecoveryRequired)?; + if value.target_ordinal() == 0 || value.target_ordinal() > endpoint.attempts { + return Err(OperationError::RecoveryRequired); + } + endpoint.accepted |= value.kind() == DeliveryObservationKind::Accepted; + endpoint.last = Some(value.kind()); + endpoint.observed = value.observed_at_unix_ms(); + Ok(()) + } +} +pub(super) struct SelectObservation<'a> { + pub request: &'a DeliveryRequestId, + pub target: &'a TargetFingerprint, + pub kind: DeliveryObservationKind, +} +pub(super) struct Graph { + recipients: [Recipient; 2], + pub found_attempt: Option<attempt::Retained>, + pub found_observation: Option<observation::Retained>, + pub last_at: Option<UnixSeconds>, +} +impl Graph { + pub(super) async fn read( + turn: &mut Turn<'_>, + request: &StockEnvelopeRequest, + authority: &Authority, + wanted: Option<&DeliveryRequestId>, + observed: Option<SelectObservation<'_>>, + ) -> Result<Self, OperationError> { + let original = Box::pin(inventory::acceptance::codec::read( + turn.connection, + turn.selected, + turn.crypto, + request.operation_id(), + )) + .await? + .ok_or(OperationError::MissingHistory)?; + if original.receipt.attempt().command_digest() != request.command_digest() + || !original + .receipt + .rumor() + .recipients() + .contains(&request.recipient()) + { + return Err(OperationError::InvalidEvidence); + } + let mut recipients = Vec::with_capacity(2); + for participant in original.receipt.rumor().recipients() { + let selector = StockEnvelopeRequest::new( + request.binding().clone(), + request.minimum_checkpoint(), + request.operation_id(), + request.command_digest(), + *participant, + None, + )?; + let source = Box::pin(envelope::lookup(turn, &selector)).await?; + recipients.push(Recipient { + participant: *participant, + source, + first: None, + attempts: 0, + endpoints: vec![], + }); + } + let mut result = Self { + recipients: recipients + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + found_attempt: None, + found_observation: None, + last_at: None, + }; + let rows = sqlx::query("SELECT d.entry_id FROM stock_delivery_attempts d JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.entry_id WHERE d.actor=? AND d.operation_id=? ORDER BY o.revision LIMIT 385") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation_id().as_bytes().as_slice()) + .fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if rows.len() > ATTEMPT_COUNT_MAX { + return Err(OperationError::RecoveryRequired); + } + // Exact natural-key constraints and each body-derived projection prove + // uniqueness; retaining another history-sized identity set is unnecessary. + for row in rows { + let entry = entry(&row)?; + let value = Box::pin(attempt::read_entry( + turn.connection, + turn.selected, + turn.crypto, + request.binding(), + authority.input.grant_id(), + entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let source = value.report.source().receipt(); + if source.attempt().operation_id() != request.operation_id() + || source.attempt().command_digest() != request.command_digest() + || result + .last_at + .is_some_and(|at| value.report.retained_at() < at) + { + return Err(OperationError::RecoveryRequired); + } + result.last_at = Some(value.report.retained_at()); + result + .recipient_mut(source.recipient())? + .observe_attempt(&value.report)?; + if source.recipient() == request.recipient() + && wanted.is_some_and(|wanted| wanted == value.report.intent().request_id()) + { + result.found_attempt = Some(value); + } + } + let rows = sqlx::query("SELECT d.entry_id FROM stock_delivery_observations d JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.entry_id WHERE d.actor=? AND d.operation_id=? ORDER BY o.revision LIMIT 2305") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation_id().as_bytes().as_slice()) + .fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if rows.len() > OBSERVATION_COUNT_MAX { + return Err(OperationError::RecoveryRequired); + } + for row in rows { + let value = Box::pin(observation::read_entry( + turn.connection, + turn.selected, + turn.crypto, + request.binding(), + authority.input.grant_id(), + entry(&row)?, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let report = value.receipt.observation(); + let source = report.source(); + let target = report.target_receipt().target().fingerprint(); + if source.attempt().operation_id() != request.operation_id() + || source.attempt().command_digest() != request.command_digest() + { + return Err(OperationError::RecoveryRequired); + } + result.recipient_mut(source.recipient())?.observe(report)?; + if source.recipient() == request.recipient() + && observed.as_ref().is_some_and(|selected| { + selected.request == report.request_id() + && selected.target == target + && selected.kind == report.kind() + }) + { + result.found_observation = Some(value); + } + } + Ok(result) + } + fn recipient(&self, participant: PublicKey) -> Result<&Recipient, OperationError> { + self.recipients + .iter() + .find(|value| value.participant == participant) + .ok_or(OperationError::InvalidEvidence) + } + fn recipient_mut(&mut self, participant: PublicKey) -> Result<&mut Recipient, OperationError> { + self.recipients + .iter_mut() + .find(|value| value.participant == participant) + .ok_or(OperationError::RecoveryRequired) + } + pub(super) fn source( + &self, + recipient: PublicKey, + ) -> Result<&envelope::Retained, OperationError> { + self.recipient(recipient)? + .source + .as_ref() + .ok_or(OperationError::MissingHistory) + } + pub(super) fn ordinals( + &self, + recipient: PublicKey, + intent: &DeliveryIntent, + ) -> Result<Vec<u8>, OperationError> { + let original = self.recipient(recipient)?; + if original.first.as_ref().is_some_and(|first| { + first.publication_policy_digest() != intent.publication_policy_digest() + }) { + return Err(OperationError::IdempotencyConflict); + } + intent + .selection() + .iter() + .map(|fingerprint| { + let count = original + .endpoints + .iter() + .find(|value| &value.fingerprint == fingerprint) + .map_or(0, |value| value.attempts); + if count >= 12 { + Err(OperationError::DeliveryAttemptLimit) + } else { + Ok(count + 1) + } + }) + .collect() + } + pub(super) fn summary( + &self, + request: &StockEnvelopeRequest, + checkpoint: InventoryCheckpointRef, + ) -> Result<StockDeliverySummary, OperationError> { + let value = self.recipient(request.recipient())?; + let targets = value + .endpoints + .iter() + .map(|target| { + StockDeliveryTargetProgress::from_store_report( + target.fingerprint.clone(), + target.attempts, + target.accepted, + target.last, + target.observed, + ) + }) + .collect::<Result<Vec<_>, _>>()?; + StockDeliverySummary::from_store_report( + request, + value.source.as_ref().map(|source| source.source.receipt()), + value.first.clone(), + value.attempts, + targets, + checkpoint, + ) + } +} +fn entry(row: &sqlx::sqlite::SqliteRow) -> Result<OperationId, OperationError> { + let bytes: Vec<u8> = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + Ok(OperationId::from_bytes( + bytes + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) +} diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/observation.rs b/crates/storage_sqlite/src/workspace/stock/delivery/observation.rs @@ -0,0 +1,128 @@ +//! Original per-target classes, tied to one actual protected potential invocation. +use super::*; +use serde::{Deserialize, Serialize}; +use wire::Reference; + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Wire { + version: u8, + attempt: Reference, + target: DeliveryTargetReceipt, + kind: u8, + #[serde(deserialize_with = "super::super::required_nullable")] + observed: Option<NonZeroU64>, +} +impl Wire { + pub(super) fn new(attempt: &attempt::Retained, observation: &StockDeliveryObservation) -> Self { + Self { + version: 1, + attempt: Reference::new(&attempt.frame.header), + target: observation.target_receipt().clone(), + kind: observation.kind().code(), + observed: observation.observed_at_unix_ms(), + } + } +} +pub(in crate::workspace::stock) struct Retained { + pub frame: ledger::Retained, + pub receipt: StockDeliveryObservationReceipt, + pub projection: Projection, +} +impl Retained { + pub(super) async fn confirm( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + confirm_record(connection, &self.frame, self.projection).await + } + pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { + history(self.frame, self.projection) + } +} +pub(in crate::workspace::stock) async fn read_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + administrator: GrantId, + entry: OperationId, +) -> Result<Option<Retained>, OperationError> { + let Some(frame) = Box::pin(ledger::read(connection, input, crypto, entry)).await? else { + return Ok(None); + }; + if frame.header.family != ledger::Family::DeliveryObservation { + return Err(OperationError::RecoveryRequired); + } + Ok(Some( + Box::pin(decode_entry( + connection, + input, + crypto, + binding, + administrator, + frame, + )) + .await?, + )) +} +async fn decode_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + administrator: GrantId, + frame: ledger::Retained, +) -> Result<Retained, OperationError> { + let value: Wire = wire::decode(&frame.body, OBSERVATION_MAX)?; + if value.version != 1 || wire::head(&frame.header, &frame.body) != frame.header.head { + return Err(OperationError::RecoveryRequired); + } + let attempt = Box::pin(attempt::read_entry( + connection, + input, + crypto, + binding, + administrator, + value.attempt.entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + value.attempt.confirm(&attempt.frame.header)?; + let h = &frame.header; + let original = &attempt.frame.header; + if h.actor != original.actor + || h.digest != original.digest + || h.order != original.order + || h.related_operation != original.related_operation + || h.revision <= original.revision + { + return Err(OperationError::RecoveryRequired); + } + let observation = + StockDeliveryObservation::from_store_report(&attempt.report, &value.target, value.observed) + .map_err(|_| OperationError::RecoveryRequired)?; + if observation.kind().code() != value.kind { + return Err(OperationError::RecoveryRequired); + } + let source = observation.source(); + let projection = Projection::Observation { + operation: source.attempt().operation_id(), + recipient: source.recipient(), + request: request_key(observation.request_id()), + target: target_key(observation.target_receipt().target().fingerprint()), + kind: observation.kind().code(), + }; + let receipt = StockDeliveryObservationReceipt::from_store_report( + observation, + h.transaction, + InventoryCheckpointRef::from_host_metadata(input.authority(), h.revision, Some(h.head))?, + )?; + let retained = Retained { + frame, + receipt, + projection, + }; + retained.confirm(connection).await?; + Ok(retained) +} diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/observation_operations.rs b/crates/storage_sqlite/src/workspace/stock/delivery/observation_operations.rs @@ -0,0 +1,226 @@ +//! Capture obtained original outcomes, including after clock loss or revocation. +use super::*; +use graph::{Graph, SelectObservation}; + +pub(in crate::workspace) async fn capture_observation( + turn: &mut Turn<'_>, + binding: WorkspaceBinding, + proof: AttachmentProof, + supplied: StockDeliveryObservation, +) -> Result<StockDeliveryObservationOutcome, OperationError> { + if *turn.uncertain { + return Err(OperationError::RecoveryRequired); + } + turn.namespace.validate()?; + let input = binding.input(); + if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) { + return Err(OperationError::Unauthorized); + } + let (authority, credential, root, grant) = + super::super::read(turn.connection, input, turn.crypto).await?; + if authority.catalog != 17 { + return Err(OperationError::UnsupportedOperation); + } + credential.authenticate_retained_capture(input, &proof)?; + let original = supplied.source().attempt(); + let source = StockEnvelopeRequest::new( + binding.clone(), + InventoryCheckpointRef::from_host_metadata( + input.authority(), + Sequence::new(0).map_err(|_| OperationError::RecoveryRequired)?, + None, + )?, + original.operation_id(), + original.command_digest(), + supplied.source().recipient(), + None, + )?; + let witness = Box::pin(envelope::full_proof(turn, &source, &authority)).await?; + let mut graph = Box::pin(Graph::read( + turn, + &source, + &authority, + Some(supplied.request_id()), + Some(SelectObservation { + request: supplied.request_id(), + target: supplied.target_receipt().target().fingerprint(), + kind: supplied.kind(), + }), + )) + .await?; + let attempt = graph + .found_attempt + .as_ref() + .ok_or(OperationError::InvalidEvidence)?; + if attempt.frame.header.actor != binding.actor() + || attempt.frame.header.actor.grant_id() != Some(input.grant_id()) + { + return Err(OperationError::Unauthorized); + } + let checked = StockDeliveryObservation::from_store_report( + &attempt.report, + supplied.target_receipt(), + supplied.observed_at_unix_ms(), + )?; + if checked != supplied { + return Err(OperationError::InvalidEvidence); + } + let prepared = if graph.found_observation.is_none() { + let body = wire::encode(&observation::Wire::new(attempt, &supplied), OBSERVATION_MAX)?; + let projection = Projection::Observation { + operation: source.operation_id(), + recipient: source.recipient(), + request: request_key(supplied.request_id()), + target: target_key(supplied.target_receipt().target().fingerprint()), + kind: supplied.kind().code(), + }; + let prepared = Box::pin(Prepared::new( + turn, + &authority, + Append { + actor: attempt.frame.header.actor, + original: source.operation_id(), + digest: source.command_digest(), + order: attempt + .frame + .header + .order + .ok_or(OperationError::RecoveryRequired)?, + family: ledger::Family::DeliveryObservation, + projection, + }, + &body, + )) + .await?; + let receipt = StockDeliveryObservationReceipt::from_store_report( + supplied, + prepared.frame.header.transaction, + prepared.checkpoint(&authority)?, + )?; + Some((prepared, receipt)) + } else { + None + }; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let changed: Result<(), OperationError> = async { + turn.namespace.validate()?; + super::super::unchanged(&mut tx, input, authority.catalog, &root, &grant).await?; + credential.authenticate_retained_capture(input, &proof)?; + inventory::check_head( + &mut tx, + authority + .inventory + .ok_or(OperationError::RecoveryRequired)?, + ) + .await?; + witness.confirm(&mut tx).await?; + attempt.confirm(&mut tx).await?; + if let Some(old) = &graph.found_observation { + old.confirm(&mut tx).await?; + } + if let Some((prepared, _)) = &prepared { + prepared.insert(&mut tx, &root).await?; + } + turn.namespace.validate()?; + Ok(()) + } + .await; + let unknown = || { + StockDeliveryObservationOutcome::Unknown(radroots_storage::command::CommitAttempt::new( + input.workspace_id(), + source.operation_id(), + source.command_digest(), + prepared + .as_ref() + .map(|(prepared, _)| prepared.frame.header.transaction), + )) + }; + if let Err(error) = changed { + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Ok(unknown()); + } + return Err(error); + } + let completed = if prepared.is_some() { + tx.commit().await + } else { + tx.rollback().await + }; + if completed.is_err() { + *turn.uncertain = true; + return Ok(unknown()); + } + match prepared { + Some((_, receipt)) => Ok(StockDeliveryObservationOutcome::Committed(Box::new( + receipt, + ))), + None => Ok(StockDeliveryObservationOutcome::Committed(Box::new( + graph + .found_observation + .take() + .ok_or(OperationError::RecoveryRequired)? + .receipt, + ))), + } +} + +pub(in crate::workspace) async fn page( + turn: &mut Turn<'_>, + source: StockEnvelopeRequest, + after: Option<Sequence>, + proof: AttachmentProof, +) -> Result<StockDeliveryObservationPage, OperationError> { + let (auth, witness, _) = Box::pin(operations::read(turn, &source, &proof, None)).await?; + let current = auth + .access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + if after.is_some_and(|after| after > current.revision) { + return Err(WorkspaceError::StaleCheckpoint.into()); + } + let rows = sqlx::query("SELECT d.entry_id FROM stock_delivery_observations d JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.entry_id WHERE d.actor=? AND d.operation_id=? AND d.recipient=? AND o.revision>? ORDER BY o.revision LIMIT 17") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(source.operation_id().as_bytes().as_slice()) + .bind(source.recipient().as_bytes().as_slice()).bind(after.map_or(0, |value| value.get()) as i64) + .fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let more = rows.len() > PAGE_MAX; + let mut entries = Vec::with_capacity(rows.len().min(PAGE_MAX)); + for row in rows.into_iter().take(PAGE_MAX) { + let bytes: Vec<u8> = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + let entry = OperationId::from_bytes( + bytes + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let value = Box::pin(observation::read_entry( + turn.connection, + turn.selected, + turn.crypto, + source.binding(), + auth.access.authority.input.grant_id(), + entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + entries.push(value.receipt); + } + Box::pin(operations::confirm_read(turn, &auth, &witness, &proof)).await?; + StockDeliveryObservationPage::from_store_report( + &source, + entries, + more, + InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + current.revision, + current.head, + )? + .with_optional_authorization(auth.access.authority.authorization), + ) +} diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/operations.rs b/crates/storage_sqlite/src/workspace/stock/delivery/operations.rs @@ -0,0 +1,321 @@ +//! Concrete D admission and current-authorized reads on the stock connection. +use super::*; +use graph::Graph; + +async fn authorized( + turn: &mut Turn<'_>, + source: &StockEnvelopeRequest, + proof: &AttachmentProof, +) -> Result<signing_plan::Authorized, OperationError> { + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *turn.connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if catalog != 17 { + return Err(OperationError::UnsupportedOperation); + } + let loading = signing_plan::load( + turn, + source.binding(), + source.minimum_checkpoint(), + source.operation_id(), + source.command_digest(), + proof, + ); + let auth = Box::pin(loading).await?; + if auth.access.authority.catalog != 17 { + return Err(OperationError::UnsupportedOperation); + } + if !auth + .original + .receipt + .rumor() + .recipients() + .contains(&source.recipient()) + { + return Err(OperationError::InvalidEvidence); + } + Ok(auth) +} +pub(in crate::workspace) async fn prepare( + turn: &mut Turn<'_>, + request: StockDeliveryRequest, + proof: AttachmentProof, +) -> Result<StockDeliveryAttemptOutcome, OperationError> { + if *turn.uncertain { + return Err(OperationError::RecoveryRequired); + } + let source = request.source(); + validate_request(request.intent().request_id())?; + let auth = Box::pin(authorized(turn, source, &proof)).await?; + Box::pin(prepare_authorized(turn, request, proof, auth)).await +} +// Authorization has its own polling frame, as in the stock snapshot reader. +async fn prepare_authorized( + turn: &mut Turn<'_>, + request: StockDeliveryRequest, + proof: AttachmentProof, + auth: signing_plan::Authorized, +) -> Result<StockDeliveryAttemptOutcome, OperationError> { + let source = request.source(); + let witness = Box::pin(envelope::full_proof(turn, source, &auth.access.authority)).await?; + let mut graph = Box::pin(Graph::read( + turn, + source, + &auth.access.authority, + Some(request.intent().request_id()), + None, + )) + .await?; + + let envelope = graph.source(source.recipient())?; + if request.intent().event_id() != envelope.source.receipt().event_id() { + return Err(OperationError::InvalidEvidence); + } + if graph + .found_attempt + .as_ref() + .is_some_and(|old| old.report.intent().digest() != request.intent().digest()) + { + return Err(OperationError::IdempotencyConflict); + } + let fresh = graph.found_attempt.is_none(); + let now = auth.access.current.observed_at(); + let prepared = if fresh { + let installed = Box::pin(inventory::installation::read_entry( + turn.connection, + turn.selected, + turn.crypto, + envelope.installation_entry(), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if now < installed.receipt.installed_at() { + return Err(WorkspaceError::Unavailable.into()); + } + if graph.last_at.is_some_and(|at| now < at) || now < auth.consent.observed_at { + return Err(WorkspaceError::Unavailable.into()); + } + if now + .get() + .checked_mul(1000) + .is_none_or(|at| at >= request.intent().deadline_unix_ms().get()) + { + return Err(OperationError::DeadlineExceeded); + } + let ordinals = graph.ordinals(source.recipient(), request.intent())?; + let body = wire::encode( + &attempt::Wire::new(envelope, &auth, request.intent(), now, ordinals.clone())?, + ATTEMPT_MAX, + )?; + let projection = Projection::Attempt { + operation: source.operation_id(), + recipient: source.recipient(), + request: request_key(request.intent().request_id()), + }; + let prepared = Box::pin(Prepared::new( + turn, + &auth.access.authority, + Append { + actor: auth.access.current.actor(), + original: source.operation_id(), + digest: source.command_digest(), + order: auth.original.receipt.order_id(), + family: ledger::Family::DeliveryAttempt, + projection, + }, + &body, + )) + .await?; + + let copied = envelope.source.with_json(|raw| { + radroots_storage::inventory::StockEnvelopeSource::from_retained_wire( + envelope.source.receipt(), + raw, + ) + })?; + + let report = StockDeliveryAttempt::from_store_report( + Arc::new(copied), + request.intent().clone(), + prepared.frame.header.transaction, + now, + prepared.checkpoint(&auth.access.authority)?, + ordinals, + )?; + + Some((prepared, report)) + } else { + None + }; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let changed: Result<(), OperationError> = async { + let current = auth + .confirm(&mut tx, turn.namespace, turn.clock, &proof, false) + .await?; + inventory::check_head( + &mut tx, + auth.access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?, + ) + .await?; + witness.confirm(&mut tx).await?; + if let Some(old) = &graph.found_attempt { + old.confirm(&mut tx).await?; + } + if let Some((prepared, _)) = &prepared { + if current.observed_at() < now { + return Err(WorkspaceError::Unavailable.into()); + } + if current + .observed_at() + .get() + .checked_mul(1000) + .is_none_or(|at| at >= request.intent().deadline_unix_ms().get()) + { + return Err(OperationError::DeadlineExceeded); + } + prepared.insert(&mut tx, &auth.access.root).await?; + } + turn.namespace.validate()?; + Ok(()) + } + .await; + + let unknown = || StockDeliveryAttemptOutcome::Unknown { + operation: radroots_storage::command::CommitAttempt::new( + source.binding().input().workspace_id(), + source.operation_id(), + source.command_digest(), + prepared + .as_ref() + .map(|(prepared, _)| prepared.frame.header.transaction), + ), + request: request.intent().request_id().clone(), + }; + if let Err(error) = changed { + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Ok(unknown()); + } + return Err(error); + } + let completed = if fresh { + tx.commit().await + } else { + tx.rollback().await + }; + if completed.is_err() { + *turn.uncertain = true; + return Ok(unknown()); + } + match prepared { + Some((_, report)) => Ok(StockDeliveryAttemptOutcome::Claimed(Box::new(report))), + None => Ok(StockDeliveryAttemptOutcome::Retained(Box::new( + graph + .found_attempt + .take() + .ok_or(OperationError::RecoveryRequired)? + .report, + ))), + } +} +pub(in crate::workspace) async fn summary( + turn: &mut Turn<'_>, + source: StockEnvelopeRequest, + proof: AttachmentProof, +) -> Result<StockDeliverySummary, OperationError> { + let (auth, witness, graph) = Box::pin(read(turn, &source, &proof, None)).await?; + Box::pin(confirm_read(turn, &auth, &witness, &proof)).await?; + let current = auth + .access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + graph.summary( + &source, + InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + current.revision, + current.head, + )? + .with_optional_authorization(auth.access.authority.authorization), + ) +} +pub(in crate::workspace) async fn query_attempt( + turn: &mut Turn<'_>, + source: StockEnvelopeRequest, + request: DeliveryRequestId, + proof: AttachmentProof, +) -> Result<Option<StockDeliveryAttempt>, OperationError> { + validate_request(&request)?; + let (auth, witness, mut graph) = Box::pin(read(turn, &source, &proof, Some(&request))).await?; + Box::pin(confirm_read(turn, &auth, &witness, &proof)).await?; + Ok(graph.found_attempt.take().map(|value| value.report)) +} +pub(super) async fn read( + turn: &mut Turn<'_>, + source: &StockEnvelopeRequest, + proof: &AttachmentProof, + request: Option<&DeliveryRequestId>, +) -> Result<(signing_plan::Authorized, checkpoint::MinimumProof, Graph), OperationError> { + if *turn.uncertain { + return Err(OperationError::RecoveryRequired); + } + let auth = Box::pin(authorized(turn, source, proof)).await?; + let witness = Box::pin(envelope::full_proof(turn, source, &auth.access.authority)).await?; + let graph = Box::pin(Graph::read( + turn, + source, + &auth.access.authority, + request, + None, + )) + .await?; + Ok((auth, witness, graph)) +} +pub(super) async fn confirm_read( + turn: &mut Turn<'_>, + auth: &signing_plan::Authorized, + witness: &checkpoint::MinimumProof, + proof: &AttachmentProof, +) -> Result<(), OperationError> { + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + auth.confirm(&mut tx, turn.namespace, turn.clock, proof, false) + .await?; + inventory::check_head( + &mut tx, + auth.access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?, + ) + .await?; + witness.confirm(&mut tx).await?; + turn.namespace.validate()?; + Ok(()) + } + .await; + if let Err(error) = checked { + if tx.rollback().await.is_err() { + *turn.uncertain = true; + } + return Err(error); + } + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/projection.rs b/crates/storage_sqlite/src/workspace/stock/delivery/projection.rs @@ -0,0 +1,166 @@ +//! Exact body-derived indexes; projections cannot supply dispatch permission. +use super::*; + +#[derive(Clone, Copy)] +pub(in crate::workspace::stock) enum Projection { + Attempt { + operation: OperationId, + recipient: PublicKey, + request: [u8; 32], + }, + Observation { + operation: OperationId, + recipient: PublicKey, + request: [u8; 32], + target: [u8; 32], + kind: u8, + }, +} +impl Projection { + pub(in crate::workspace::stock) fn digest( + self, + actor: PublicKey, + entry: OperationId, + ) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.delivery_projection.v1\0"); + hash.update(actor.as_bytes()); + hash.update(entry.as_bytes()); + let (operation, recipient, request) = match self { + Self::Attempt { + operation, + recipient, + request, + } => { + hash.update([11]); + (operation, recipient, request) + } + Self::Observation { + operation, + recipient, + request, + target, + kind, + } => { + hash.update([12]); + hash.update(target); + hash.update([kind]); + (operation, recipient, request) + } + }; + hash.update(operation.as_bytes()); + hash.update(recipient.as_bytes()); + hash.update(request); + hash.finalize().into() + } + pub(super) async fn insert( + self, + connection: &mut SqliteConnection, + actor: PublicKey, + entry: OperationId, + ) -> Result<(), OperationError> { + match self { + Self::Attempt { + operation, + recipient, + request, + } => { + sqlx::query("INSERT INTO stock_delivery_attempts(actor,operation_id,recipient,request_key,entry_id) VALUES(?,?,?,?,?)") + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .bind(recipient.as_bytes().as_slice()).bind(request.as_slice()) + .bind(entry.as_bytes().as_slice()).execute(connection).await + .map_err(|_|OperationError::StorageFailure)?; + } + Self::Observation { + operation, + recipient, + request, + target, + kind, + } => { + sqlx::query("INSERT INTO stock_delivery_observations(actor,operation_id,recipient,request_key,target_key,kind,entry_id) VALUES(?,?,?,?,?,?,?)") + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .bind(recipient.as_bytes().as_slice()).bind(request.as_slice()).bind(target.as_slice()) + .bind(i64::from(kind)).bind(entry.as_bytes().as_slice()).execute(connection).await + .map_err(|_|OperationError::StorageFailure)?; + } + } + Ok(()) + } + pub(super) async fn confirm( + self, + connection: &mut SqliteConnection, + actor: PublicKey, + entry: OperationId, + ) -> Result<(), OperationError> { + let family = if matches!(self, Self::Attempt { .. }) { + 11 + } else { + 12 + }; + if raw_projection(connection, actor.as_bytes(), entry.as_bytes(), family).await? + != self.digest(actor, entry) + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} +pub(in crate::workspace::stock) async fn raw_projection( + connection: &mut SqliteConnection, + actor: &[u8; 32], + entry: &[u8; 32], + family: i64, +) -> Result<[u8; 32], OperationError> { + let sql = match family { + 11 => { + "SELECT operation_id,recipient,request_key,NULL,NULL FROM stock_delivery_attempts WHERE actor=? AND entry_id=?" + } + 12 => { + "SELECT operation_id,recipient,request_key,target_key,kind FROM stock_delivery_observations WHERE actor=? AND entry_id=?" + } + _ => return Err(OperationError::RecoveryRequired), + }; + let row = sqlx::query(sql) + .bind(actor.as_slice()) + .bind(entry.as_slice()) + .fetch_optional(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let field = |index| { + row.try_get::<Vec<u8>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let operation = OperationId::from_bytes(field(0)?); + let recipient = + PublicKey::from_bytes(field(1)?).map_err(|_| OperationError::RecoveryRequired)?; + let request = field(2)?; + let projection = if family == 11 { + Projection::Attempt { + operation, + recipient, + request, + } + } else { + let kind: i64 = row + .try_get(4) + .map_err(|_| OperationError::RecoveryRequired)?; + if !(1..=6).contains(&kind) { + return Err(OperationError::RecoveryRequired); + } + Projection::Observation { + operation, + recipient, + request, + target: field(3)?, + kind: kind as u8, + } + }; + Ok(projection.digest( + PublicKey::from_bytes(*actor).map_err(|_| OperationError::RecoveryRequired)?, + OperationId::from_bytes(*entry), + )) +} diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/wire.rs b/crates/storage_sqlite/src/workspace/stock/delivery/wire.rs @@ -0,0 +1,114 @@ +//! Closed bounded records and exact references on the stock protected chain. +use super::*; +use serde::{Deserialize, Serialize}; +use std::io::{Error, ErrorKind, Write}; +use zeroize::Zeroizing; + +pub(super) use super::super::super::delivery::json::{bounded, policy, small_vec, targets}; + +#[derive(Clone, Copy, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Reference { + pub entry: OperationId, + pub transaction: TransactionId, + pub head: CheckpointDigest, +} +impl Reference { + pub fn new(header: &ledger::Header) -> Self { + Self { + entry: header.operation, + transaction: header.transaction, + head: header.head, + } + } + pub fn confirm(self, header: &ledger::Header) -> Result<(), OperationError> { + if self.entry != header.operation + || self.transaction != header.transaction + || self.head != header.head + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} +struct Writer { + bytes: Zeroizing<Vec<u8>>, + limit: usize, +} +impl Write for Writer { + fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { + if self + .bytes + .len() + .checked_add(bytes.len()) + .is_none_or(|len| len > self.limit) + { + return Err(Error::new( + ErrorKind::InvalidInput, + "stock delivery record limit", + )); + } + self.bytes.extend_from_slice(bytes); + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} +pub(super) fn encode<T: Serialize>( + value: &T, + limit: usize, +) -> Result<Zeroizing<Vec<u8>>, OperationError> { + let mut writer = Writer { + bytes: Zeroizing::new(Vec::with_capacity(limit.min(4096))), + limit, + }; + serde_json::to_writer(&mut writer, value).map_err(|_| OperationError::InvalidEvidence)?; + Ok(writer.bytes) +} +pub(super) fn decode<T: for<'de> Deserialize<'de>>( + raw: &[u8], + limit: usize, +) -> Result<T, OperationError> { + if raw.len() > limit || !bounded(raw, 32) { + return Err(OperationError::RecoveryRequired); + } + serde_json::from_slice(raw).map_err(|_| OperationError::RecoveryRequired) +} +pub(super) fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.delivery_chain.v1\0"); + hash.update([header.family.code() as u8]); + hash.update(header.namespace.workspace_id().as_bytes()); + hash.update(header.namespace.authority().executor_id().as_bytes()); + hash.update( + header + .namespace + .authority() + .generation() + .get() + .to_be_bytes(), + ); + hash.update(header.namespace.route_digest().as_bytes()); + hash.update(header.actor.participant().as_bytes()); + hash.update( + header + .actor + .grant_id() + .map(|id| *id.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(header.operation.as_bytes()); + hash.update(header.digest.as_bytes()); + hash.update(header.transaction.as_bytes()); + hash.update(header.revision.get().to_be_bytes()); + hash.update([u8::from(header.previous.is_some())]); + hash.update( + header + .previous + .map(|value| *value.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(Sha256::digest(body)); + CheckpointDigest::from_bytes(hash.finalize().into()) +} diff --git a/crates/storage_sqlite/src/workspace/stock/envelope.rs b/crates/storage_sqlite/src/workspace/stock/envelope.rs @@ -14,8 +14,9 @@ use sqlx::Row; use zeroize::Zeroizing; mod codec; mod projection; +use codec::Original; +pub(in crate::workspace::stock) use codec::Retained; pub(super) use codec::read_entry; -use codec::{Original, Retained}; pub(super) use projection::{Projection, raw_projection}; async fn selected_entry( @@ -41,7 +42,7 @@ async fn selected_entry( }) .transpose() } -async fn lookup( +pub(in crate::workspace::stock) async fn lookup( turn: &mut Turn<'_>, request: &StockEnvelopeRequest, ) -> Result<Option<Retained>, OperationError> { @@ -73,7 +74,7 @@ async fn lookup( } Ok(Some(retained)) } -async fn full_proof( +pub(in crate::workspace::stock) async fn full_proof( turn: &mut Turn<'_>, request: &StockEnvelopeRequest, authority: &Authority, @@ -121,7 +122,7 @@ pub(in crate::workspace) async fn capture( return Err(OperationError::Unauthorized); } let (authority, record, root, grant) = super::read(turn.connection, input, turn.crypto).await?; - if authority.catalog != 16 { + if !matches!(authority.catalog, 16 | 17) { return Err(OperationError::UnsupportedOperation); } record.authenticate_retained_capture(input, &proof)?; @@ -300,7 +301,7 @@ pub(in crate::workspace) async fn read( .fetch_one(&mut *turn.connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - if catalog != 16 { + if !matches!(catalog, 16 | 17) { return Err(OperationError::UnsupportedOperation); } let auth = Box::pin(super::signing_plan::load( @@ -312,7 +313,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if auth.access.authority.catalog != 16 { + if !matches!(auth.access.authority.catalog, 16 | 17) { return Err(OperationError::UnsupportedOperation); } let witness = Box::pin(full_proof(turn, &request, &auth.access.authority)).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/envelope/codec.rs b/crates/storage_sqlite/src/workspace/stock/envelope/codec.rs @@ -151,12 +151,16 @@ pub(super) fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest { CheckpointDigest::from_bytes(hash.finalize().into()) } pub(in crate::workspace::stock) struct Retained { - frame: ledger::Retained, + pub(in crate::workspace::stock) frame: ledger::Retained, pub source: StockEnvelopeSource, projection: Projection, + installation: OperationId, } impl Retained { - pub(super) async fn confirm( + pub(in crate::workspace::stock) fn installation_entry(&self) -> OperationId { + self.installation + } + pub(in crate::workspace::stock) async fn confirm( &self, connection: &mut SqliteConnection, ) -> Result<(), OperationError> { @@ -191,6 +195,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: Some(self.projection), aborted: None, preparation: None, @@ -330,6 +335,7 @@ async fn decode_entry( let source = StockEnvelopeSource::from_retained_wire(receipt, raw) .map_err(|_| OperationError::RecoveryRequired)?; let retained = Retained { + installation: original.installation.frame.header.operation, projection: Projection { operation, recipient: receipt.recipient(), diff --git a/crates/storage_sqlite/src/workspace/stock/grants.rs b/crates/storage_sqlite/src/workspace/stock/grants.rs @@ -324,7 +324,7 @@ pub(in crate::workspace) async fn change( } let (mut authority, record, old_root, old_grant) = super::read(turn.connection, change.caller.input(), turn.crypto).await?; - if !(4..=16).contains(&authority.catalog) { + if !(4..=17).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } let catalog = authority.catalog; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -452,7 +452,7 @@ impl Turn<'_> { access.authority.authorization, mapping.as_ref().map(|value| value.effect), )?; - let framed = if matches!(catalog, 7..=16) { + let framed = if matches!(catalog, 7..=17) { Some( super::ledger::prepare( self.crypto, @@ -866,7 +866,7 @@ pub(super) async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let (frame, request, decoded) = if matches!(catalog, 7..=16) { + let (frame, request, decoded) = if matches!(catalog, 7..=17) { let retained = super::ledger::read(connection, input, crypto, operation) .await? .ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs @@ -160,7 +160,7 @@ async fn abort_authorized( proof: AttachmentProof, auth: signing_plan::Authorized, ) -> Result<StockAbortOutcome, OperationError> { - if !matches!(auth.access.authority.catalog, 13..=16) { + if !matches!(auth.access.authority.catalog, 13..=17) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; @@ -381,7 +381,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 13..=16) { + if !matches!(auth.access.authority.catalog, 13..=17) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort/codec.rs @@ -305,6 +305,7 @@ impl Retained { } pub fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: None, preparation: None, local_record: None, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort/proof.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort/proof.rs @@ -150,7 +150,7 @@ pub(super) async fn prepare( recipient: *recipient, }), Some(original) => { - if !matches!(auth.access.authority.catalog, 15..=16) { + if !matches!(auth.access.authority.catalog, 15..=17) { return Err(OperationError::RecoveryRequired); } if at < original.report.claimed_at() { @@ -180,7 +180,7 @@ pub(super) async fn prepare( } } } - let payload = if matches!(auth.access.authority.catalog, 15..=16) { + let payload = if matches!(auth.access.authority.catalog, 15..=17) { Payload::Current(Box::new( encoded .try_into() @@ -217,7 +217,7 @@ pub(super) async fn read( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - if !matches!(catalog, 15..=16) { + if !matches!(catalog, 15..=17) { return Err(OperationError::RecoveryRequired); } for (proof, expected) in proofs.iter().zip(recipients) { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs @@ -236,7 +236,7 @@ pub(in crate::workspace) async fn admit( let access = turn .access(request.binding(), request.minimum_checkpoint(), &proof) .await?; - if !matches!(access.authority.catalog, 9..=16) { + if !matches!(access.authority.catalog, 9..=17) { return Err(OperationError::UnsupportedOperation); } let command = request.command(); diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs @@ -104,6 +104,7 @@ impl Retained { ) }); ledger::HistoryEntry { + delivery: None, envelope: None, aborted: None, preparation, @@ -324,7 +325,7 @@ pub(in crate::workspace::stock) async fn read( .map_err(|_| OperationError::RecoveryRequired)?; let operation_keyed = match catalog { 1..=12 => false, - 13..=16 => true, + 13..=17 => true, _ => return Err(OperationError::RecoveryRequired), }; let actor = header.actor.participant(); diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -68,7 +68,9 @@ impl MinimumProof { let related: Option<Vec<u8>> = row .try_get(2) .map_err(|_| OperationError::RecoveryRequired)?; - if !(0..=if catalog >= 16 { + if !(0..=if catalog >= 17 { + 12 + } else if catalog >= 16 { 10 } else if catalog >= 15 { 9 @@ -92,6 +94,14 @@ impl MinimumProof { super::super::ledger::raw_parts_witness(connection, &actor, &operation).await?; hash.update([parts]); hash.update(witness); + if matches!(family, 11 | 12) { + hash.update( + super::super::delivery::raw_projection( + connection, &actor, &operation, family, + ) + .await?, + ); + } if family == 10 { hash.update( super::super::envelope::raw_projection(connection, &actor, &operation) @@ -159,7 +169,7 @@ pub(in crate::workspace::stock) async fn authenticate_order_state( authority: &Authority, order: radroots_domain::OrderId, ) -> Result<super::super::order_state::Checked, OperationError> { - if !matches!(authority.catalog, 13..=16) { + if !matches!(authority.catalog, 13..=17) { return Err(OperationError::UnsupportedOperation); } let current = authority @@ -228,7 +238,7 @@ pub(super) async fn authenticate_order_absence( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - if !matches!(authority.catalog, 9..=16) { + if !matches!(authority.catalog, 9..=17) { return Err(OperationError::UnsupportedOperation); } let upper = current.revision.get(); @@ -310,7 +320,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - let multipart = matches!(authority.catalog, 7..=16); + let multipart = matches!(authority.catalog, 7..=17); let upper = current.revision.get(); let mut previous = current.head; let mut hash = history_hash(multipart); @@ -487,7 +497,7 @@ pub(in crate::workspace::stock) async fn authenticate_minimum_with_local( minimum.revision().get().max(1) }; let upper = current.revision.get(); - let multipart = matches!(authority.catalog, 7..=16); + let multipart = matches!(authority.catalog, 7..=17); let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { @@ -751,7 +761,7 @@ async fn authenticate_projected( .ok_or(OperationError::UnsupportedOperation)?; let upper = current.revision.get(); let mut expected = current.head; - let multipart = matches!(authority.catalog, 7..=16); + let multipart = matches!(authority.catalog, 7..=17); let mut hash = history_hash(multipart); for revision in (1..=upper).rev() { let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32").bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs @@ -120,7 +120,7 @@ pub(super) fn encode_operation( String::from_utf8(clear.to_vec()).map_err(|_| OperationError::StorageFailure)?, ) .map_err(|_| OperationError::StorageFailure)?; - if matches!(catalog, 5..=16) { + if matches!(catalog, 5..=17) { return super::encode(&OperationV4 { version: 4, authorization: authorization.ok_or(OperationError::RecoveryRequired)?, @@ -158,7 +158,7 @@ fn decode_inner( catalog: i64, allow_mapping: bool, ) -> Result<(InventoryRequest, OperationData), OperationError> { - if matches!(catalog, 5..=16) { + if matches!(catalog, 5..=17) { let decoded: OperationV4<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 4 { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs @@ -222,7 +222,7 @@ pub(in crate::workspace) async fn install( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12..=16) { + if !matches!(auth.access.authority.catalog, 12..=17) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; @@ -481,7 +481,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12..=16) { + if !matches!(auth.access.authority.catalog, 12..=17) { return Err(OperationError::UnsupportedOperation); } let (retained, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs @@ -302,6 +302,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: None, aborted: None, preparation: None, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs b/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs @@ -58,7 +58,7 @@ impl MappingRead { } } pub(super) fn require(access: &Access, key: OptionMappingKey) -> Result<(), OperationError> { - if !(5..=16).contains(&access.authority.catalog) { + if !(5..=17).contains(&access.authority.catalog) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn record_version(catalog: i64) -> Result<u8, OperationError> { match catalog { 2 => Ok(1), - 3..=16 => Ok(2), + 3..=17 => Ok(2), _ => Err(OperationError::RecoveryRequired), } } diff --git a/crates/storage_sqlite/src/workspace/stock/issuance.rs b/crates/storage_sqlite/src/workspace/stock/issuance.rs @@ -46,6 +46,12 @@ pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<() return Err(WorkspaceError::RecoveryRequired); } } + if catalog >= 17 { + let (attempts, attempt_entries, observations, observation_entries): (i64,i64,i64,i64) = sqlx::query_as("SELECT (SELECT count(*) FROM stock_delivery_attempts),(SELECT count(*) FROM stock_operations WHERE family=11),(SELECT count(*) FROM stock_delivery_observations),(SELECT count(*) FROM stock_operations WHERE family=12)").fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + if attempts != attempt_entries || observations != observation_entries { + return Err(WorkspaceError::RecoveryRequired); + } + } if catalog >= 16 { let (rows, entries): (i64,i64) = sqlx::query_as("SELECT (SELECT count(*) FROM stock_envelopes),(SELECT count(*) FROM stock_operations WHERE family=10)").fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; if rows != entries { diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs @@ -147,6 +147,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: None, aborted: None, preparation: None, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs @@ -221,6 +221,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: None, aborted: None, preparation: None, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs b/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs @@ -81,7 +81,7 @@ pub(in crate::workspace) async fn authorize( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 13..=16) { + if !matches!(auth.access.authority.catalog, 13..=17) { return Err(OperationError::UnsupportedOperation); } let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/replay_admission.rs b/crates/storage_sqlite/src/workspace/stock/issuance/replay_admission.rs @@ -163,6 +163,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: None, aborted: None, preparation: None, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs b/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs @@ -224,6 +224,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: None, aborted: None, preparation: None, @@ -338,7 +339,7 @@ pub(in crate::workspace) async fn capture( } let (authority, record, root, grant) = super::super::read(turn.connection, input, turn.crypto).await?; - if !matches!(authority.catalog, 14..=16) { + if !matches!(authority.catalog, 14..=17) { return Err(OperationError::UnsupportedOperation); } record.authenticate_retained_capture(input, &proof)?; @@ -492,7 +493,7 @@ pub(in crate::workspace) async fn read( &proof, ) .await?; - if !matches!(auth.access.authority.catalog, 14..=16) { + if !matches!(auth.access.authority.catalog, 14..=17) { return Err(OperationError::UnsupportedOperation); } let witness = Box::pin(checkpoint::authenticate_minimum( diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -26,6 +26,8 @@ pub(super) enum Family { OriginalUnissued, ReplayAdmission, Envelope, + DeliveryAttempt, + DeliveryObservation, } #[derive(Serialize, Deserialize)] @@ -83,6 +85,8 @@ impl Header { | Family::OriginalUnissued | Family::ReplayAdmission | Family::Envelope + | Family::DeliveryAttempt + | Family::DeliveryObservation ) != self.related_operation.is_some() || (self.family == Family::Consent) != self.subject_grant.is_some() || self.bytes == 0 @@ -340,6 +344,8 @@ impl Family { Self::OriginalUnissued => 8, Self::ReplayAdmission => 9, Self::Envelope => 10, + Self::DeliveryAttempt => 11, + Self::DeliveryObservation => 12, } } } @@ -447,6 +453,7 @@ pub(super) struct MovementWitness { /// A completely decoded original effect. Only the owning family decoder /// supplies its pool effects and movement witnesses; SQL indexes do not. pub(super) struct HistoryEntry { + pub delivery: Option<super::delivery::Projection>, pub envelope: Option<super::envelope::Projection>, pub aborted: Option<super::inventory::abort::Projection>, pub preparation: Option<[u8; 32]>, @@ -476,150 +483,365 @@ pub(super) async fn history( .fetch_optional(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; + if matches!(family, Some(11 | 12)) && authority.catalog >= 17 { + return Box::pin(delivery_history( + connection, input, crypto, binding, authority, operation, family, + )) + .await; + } match family { None => Ok(None), Some(0) => { - let retained = Box::pin(super::inventory::read_operation( - connection, input, crypto, binding, operation, + Box::pin(history_family_0( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)?; - let (header, parts_witness) = retained.frame.ok_or(OperationError::RecoveryRequired)?; - let movements = match (retained.movement, retained.movement_protected) { - (Some(id), Some(protected)) => vec![MovementWitness { - id, - pool: retained.receipt.pool().id(), - grant: retained.original_grant, - protected, - }], - (None, None) => vec![], - _ => return Err(OperationError::RecoveryRequired), - }; - Ok(Some(HistoryEntry { - envelope: None, - aborted: None, - preparation: None, - local_record: None, - installation: None, - signing: None, - header, - protected: retained.protected, - parts_witness, - pools: vec![retained.receipt.pool()], - mapping: retained.receipt.mapping(), - movements, - })) + .await } Some(1) => { - let retained = Box::pin(super::consent::read( - connection, - input, - crypto, - authority.input.grant_id(), - operation, + Box::pin(history_family_1( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)?; - let count: i64 = sqlx::query_scalar( - "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?", - ) - .bind(input.participant().as_bytes().as_slice()) - .bind(operation.as_bytes().as_slice()) - .fetch_one(connection) .await - .map_err(|_| OperationError::RecoveryRequired)?; - if count != 0 { - return Err(OperationError::RecoveryRequired); - } - Ok(Some(HistoryEntry { - envelope: None, - aborted: None, - preparation: None, - local_record: None, - installation: None, - signing: None, - header: retained.frame.header, - protected: retained.frame.protected, - parts_witness: retained.frame.parts_witness, - pools: vec![], - mapping: None, - movements: vec![], - })) } - Some(2) if matches!(authority.catalog, 9..=16) => Ok(Some( - Box::pin(super::inventory::acceptance::codec::read( - connection, input, crypto, operation, + Some(2) if matches!(authority.catalog, 9..=17) => { + Box::pin(history_family_2( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)? - .into_history(), - )), + .await + } Some(2) => Err(OperationError::UnsupportedOperation), - Some(3) if matches!(authority.catalog, 10..=16) => { - let retained = Box::pin(super::signing_plan::read_entry( - connection, input, crypto, operation, + Some(3) if matches!(authority.catalog, 10..=17) => { + Box::pin(history_family_3( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)?; - Ok(Some(retained.into_history())) + .await } - Some(4) if authority.catalog >= 11 => Ok(Some( - Box::pin(super::issuance::read_entry( - connection, input, crypto, operation, + Some(4) if authority.catalog >= 11 => { + Box::pin(history_family_4( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)? - .into_history(), - )), - Some(5) if authority.catalog >= 11 => Ok(Some( - Box::pin(super::issuance::evidence::read_entry( - connection, input, crypto, operation, + .await + } + Some(5) if authority.catalog >= 11 => { + Box::pin(history_family_5( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)? - .into_history(), - )), - Some(6) if matches!(authority.catalog, 12..=16) => Ok(Some( - Box::pin(super::inventory::installation::read_entry( - connection, input, crypto, operation, + .await + } + Some(6) if matches!(authority.catalog, 12..=17) => { + Box::pin(history_family_6( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)? - .into_history(), - )), - Some(7) if authority.catalog >= 13 => Ok(Some( - Box::pin(super::inventory::abort::read_entry( - connection, input, crypto, operation, + .await + } + Some(7) if authority.catalog >= 13 => { + Box::pin(history_family_7( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)? - .into_history(), - )), - Some(8) if authority.catalog >= 14 => Ok(Some( - Box::pin(super::issuance::unissued::read_entry( - connection, input, crypto, operation, + .await + } + Some(8) if authority.catalog >= 14 => { + Box::pin(history_family_8( + connection, input, crypto, binding, authority, operation, )) - .await? - .ok_or(OperationError::RecoveryRequired)? - .into_history(), - )), - Some(9) if authority.catalog >= 15 => Ok(Some( - Box::pin(super::issuance::replay_admission::read_entry( - connection, input, crypto, operation, + .await + } + Some(9) if authority.catalog >= 15 => { + Box::pin(history_family_9( + connection, input, crypto, binding, authority, operation, + )) + .await + } + Some(10) if authority.catalog >= 16 => { + Box::pin(history_family_10( + connection, input, crypto, binding, authority, operation, + )) + .await + } + Some(_) => Err(OperationError::RecoveryRequired), + } +} +// Isolate each authenticated family decoder from the dispatch polling frame. +async fn history_family_0( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + { + let retained = Box::pin(super::inventory::read_operation( + connection, input, crypto, binding, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let (header, parts_witness) = retained.frame.ok_or(OperationError::RecoveryRequired)?; + let movements = match (retained.movement, retained.movement_protected) { + (Some(id), Some(protected)) => vec![MovementWitness { + id, + pool: retained.receipt.pool().id(), + grant: retained.original_grant, + protected, + }], + (None, None) => vec![], + _ => return Err(OperationError::RecoveryRequired), + }; + Ok(Some(HistoryEntry { + delivery: None, + envelope: None, + aborted: None, + preparation: None, + local_record: None, + installation: None, + signing: None, + header, + protected: retained.protected, + parts_witness, + pools: vec![retained.receipt.pool()], + mapping: retained.receipt.mapping(), + movements, + })) + } +} +async fn history_family_1( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + { + let retained = Box::pin(super::consent::read( + connection, + input, + crypto, + authority.input.grant_id(), + operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?", + ) + .bind(input.participant().as_bytes().as_slice()) + .bind(operation.as_bytes().as_slice()) + .fetch_one(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(Some(HistoryEntry { + delivery: None, + envelope: None, + aborted: None, + preparation: None, + local_record: None, + installation: None, + signing: None, + header: retained.frame.header, + protected: retained.frame.protected, + parts_witness: retained.frame.parts_witness, + pools: vec![], + mapping: None, + movements: vec![], + })) + } +} +async fn history_family_2( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::inventory::acceptance::codec::read( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} +async fn history_family_3( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + { + let retained = Box::pin(super::signing_plan::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + Ok(Some(retained.into_history())) + } +} +async fn history_family_4( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::issuance::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} +async fn history_family_5( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::issuance::evidence::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} +async fn history_family_6( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::inventory::installation::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} +async fn history_family_7( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::inventory::abort::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} +async fn history_family_8( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::issuance::unissued::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} +async fn history_family_9( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + _binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::issuance::replay_admission::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} +async fn history_family_10( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + _authority: &Authority, + operation: OperationId, +) -> Result<Option<HistoryEntry>, OperationError> { + Ok(Some( + Box::pin(super::envelope::read_entry( + connection, input, crypto, binding, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )) +} + +// Keep the new large delivery reports outside the legacy history polling frame. +async fn delivery_history( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + authority: &Authority, + operation: OperationId, + family: Option<i64>, +) -> Result<Option<HistoryEntry>, OperationError> { + match family { + Some(11) => Ok(Some( + Box::pin(super::delivery::attempt::read_entry( + connection, + input, + crypto, + binding, + authority.input.grant_id(), + operation, )) .await? .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(10) if authority.catalog >= 16 => Ok(Some( - Box::pin(super::envelope::read_entry( - connection, input, crypto, binding, operation, + Some(12) => Ok(Some( + Box::pin(super::delivery::observation::read_entry( + connection, + input, + crypto, + binding, + authority.input.grant_id(), + operation, )) .await? .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(_) => Err(OperationError::RecoveryRequired), + _ => Err(OperationError::RecoveryRequired), } } pub(super) fn hash_optional(hash: &mut Sha256, value: Option<&[u8]>) -> Result<(), OperationError> { @@ -723,6 +945,22 @@ impl HistoryEntry { } (_, None) => {} } + match (header.family, self.delivery) { + ( + Family::DeliveryAttempt, + Some(projection @ super::delivery::Projection::Attempt { .. }), + ) + | ( + Family::DeliveryObservation, + Some(projection @ super::delivery::Projection::Observation { .. }), + ) => { + hash.update(projection.digest(header.actor.participant(), header.operation)); + } + (Family::DeliveryAttempt | Family::DeliveryObservation, _) | (_, Some(_)) => { + return Err(OperationError::RecoveryRequired); + } + (_, None) => {} + } if (header.family == Family::SigningEvidence) != self.local_record.is_some() { return Err(OperationError::RecoveryRequired); } diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs @@ -122,7 +122,7 @@ async fn late_order_grant_pool_and_unrelated_preparation_changes_never_commit_a_ .unwrap(); provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .abort_proven_unissued(selected, r.enrollment.proof()), @@ -279,7 +279,7 @@ async fn losing_abort_observer_drains_original_admitted_work_before_reopen() { let selected = abort_request(&r, &receipt).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .abort_proven_unissued(selected, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs @@ -450,7 +450,7 @@ async fn lost_observer_retains_actual_two_pool_preparation_and_drain_precedes_re let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -504,7 +504,7 @@ async fn source_mapping_pool_order_and_grant_rows_are_rechecked_after_final_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -541,7 +541,7 @@ async fn final_clock_recheck_refuses_expiry_and_rollback_after_protection_withou let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs @@ -329,7 +329,7 @@ async fn lost_claim_observer_drains_and_reopens_as_existing_without_a_permit() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), @@ -406,7 +406,7 @@ async fn claim_rechecks_original_plan_projection_grant_root_and_clock_after_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/claimed_abort_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/claimed_abort_tests.rs @@ -400,7 +400,7 @@ async fn lost_claimed_cleanup_waiter_drains_before_reopen_and_keeps_original_pro let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin(r.store.abort_proven_unissued(request, r.enrollment.proof())); assert!(futures::poll!(pending.as_mut()).is_pending()); provider.gate.entered(); diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/delivery_boundaries_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/delivery_boundaries_tests.rs @@ -0,0 +1,140 @@ +//! Concrete endpoint limits, bounded pagination and late transaction witnesses. +use super::*; + +#[tokio::test] +async fn twelve_potential_invocations_are_retained_and_original_outcomes_page_at_sixteen() { + let (mut r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let mut expected = Vec::new(); + for ordinal in 1..=12 { + let attempt = claim(&r, &original, &outer, ordinal).await; + assert_eq!(attempt.target_ordinals(), &[ordinal]); + if ordinal <= 9 { + for outcome in [DeliveryOutcome::rejected(), DeliveryOutcome::unavailable()] { + expected.push(save(&r, &observed(&attempt, outcome, None)).await); + } + } + } + let before = inventory_minimum(&r).await; + assert!(matches!( + r.store + .prepare_stock_delivery_attempt(request(&r, &original, &outer, 13).await, proof(&r)) + .await, + Err(OperationError::DeliveryAttemptLimit) + )); + assert_eq!(inventory_minimum(&r).await, before); + reopen_plain(&mut r).await; + let summary = r + .store + .stock_delivery_summary( + envelope_request(&r, &original, outer.recipient(), None).await, + proof(&r), + ) + .await + .unwrap(); + assert_eq!(summary.attempt_count(), 12); + assert_eq!(summary.targets()[0].potential_attempts(), 12); + assert!(!summary.acceptance_satisfied().unwrap()); + let first = r + .store + .stock_delivery_observations( + envelope_request(&r, &original, outer.recipient(), None).await, + None, + proof(&r), + ) + .await + .unwrap(); + assert_eq!(first.entries(), &expected[..16]); + let second = r + .store + .stock_delivery_observations( + envelope_request(&r, &original, outer.recipient(), None).await, + first.next_after(), + proof(&r), + ) + .await + .unwrap(); + assert!(first.next_after().is_some()); + assert_eq!(second.entries(), &expected[16..]); + assert!(second.next_after().is_none()); + balances(&r, 80, 9, 0, 1, 3).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn late_extra_projection_cannot_cross_the_final_attempt_transaction() { + let (mut r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let selected = request(&r, &original, &outer, 21).await; + let provider = reopen(&mut r).await; + let mut db = database(&r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); + let mut pending = Box::pin(r.store.prepare_stock_delivery_attempt(selected, proof(&r))); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + sqlx::raw_sql("INSERT INTO stock_delivery_attempts(actor,operation_id,recipient,request_key,entry_id) SELECT e.actor,e.operation_id,e.recipient,randomblob(32),(SELECT operation_id FROM stock_operations WHERE family=0 LIMIT 1) FROM stock_envelopes e LIMIT 1").execute(&mut db).await.unwrap(); + provider.gate.release(); + assert_eq!(pending.await.unwrap_err().code(), "recovery_required"); + let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE family=11") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(rows, 0); + db.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn retained_sixteen_captures_original_outer_but_refuses_new_delivery_without_migration() { + let (r, original, _, outer) = setup(16).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + assert!(matches!( + r.store + .prepare_stock_delivery_attempt(request(&r, &original, &outer, 22).await, proof(&r)) + .await, + Err(OperationError::UnsupportedOperation) + )); + let mut db = database(&r).await; + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(catalog, 16); + db.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn current_operation_snapshot_retains_delivery_at_its_exact_authorized_checkpoint() { + let (r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let attempt = claim(&r, &original, &outer, 23).await; + save(&r, &observed(&attempt, DeliveryOutcome::accepted(), None)).await; + let snapshot = r + .store + .stock_operation_snapshot( + crate::workspace::StockSnapshotRequest::new( + r.binding.clone(), + inventory_minimum(&r).await, + original.attempt().operation_id(), + original.attempt().command_digest(), + ), + r.enrollment.proof(), + ) + .await + .unwrap(); + let delivery = snapshot.delivery().unwrap(); + for (value, recipient) in delivery.iter().zip(snapshot.recipients()) { + assert_eq!(value.checkpoint(), snapshot.checkpoint()); + if recipient.recipient() == outer.recipient() { + assert_eq!(value.attempt_count(), 1); + assert!(value.acceptance_satisfied().unwrap()); + } else { + assert!(value.source().is_none()); + assert_eq!(value.attempt_count(), 0); + } + } + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/delivery_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/delivery_tests.rs @@ -0,0 +1,477 @@ +//! Real stock D transactions and retained normalized reports, without network IO. +use super::*; +use radroots_storage::{ + command::{DeliveryIntent, DeliveryObservationKind}, + inventory::{ + StockDeliveryAttempt, StockDeliveryAttemptOutcome, StockDeliveryObservation, + StockDeliveryObservationOutcome, StockDeliveryObservationReceipt, StockDeliveryRequest, + }, +}; +use radroots_transport::{ + Target, TargetSet, + outcome::DeliveryOutcome, + policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}, + sink::DeliveryTargetReceipt, +}; +#[path = "delivery_boundaries_tests.rs"] +mod boundaries; + +fn intent(outer: &PrivateEnvelopeCandidate, request: u8) -> DeliveryIntent { + DeliveryIntent::new( + &format!("{request:064x}"), + outer.event_id(), + &TargetSet::new(vec![Target::nostr_relay("wss://relay.example").unwrap()]).unwrap(), + &SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), + NonZeroU64::new(180000).unwrap(), + ) + .unwrap() +} +async fn request( + r: &Rig, + original: &StockAcceptanceReceipt, + outer: &PrivateEnvelopeCandidate, + number: u8, +) -> StockDeliveryRequest { + StockDeliveryRequest::new( + r.binding.clone(), + inventory_minimum(r).await, + original.attempt().operation_id(), + original.attempt().command_digest(), + outer.recipient(), + intent(outer, number), + ) + .unwrap() +} +async fn claim( + r: &Rig, + original: &StockAcceptanceReceipt, + outer: &PrivateEnvelopeCandidate, + number: u8, +) -> Box<StockDeliveryAttempt> { + let outcome = r + .store + .prepare_stock_delivery_attempt(request(r, original, outer, number).await, proof(r)) + .await + .unwrap(); + let StockDeliveryAttemptOutcome::Claimed(value) = outcome else { + panic!("only a newly confirmed D can qualify one potential invocation") + }; + value +} +fn observed( + attempt: &StockDeliveryAttempt, + outcome: DeliveryOutcome, + at: Option<NonZeroU64>, +) -> StockDeliveryObservation { + StockDeliveryObservation::from_store_report( + attempt, + &DeliveryTargetReceipt::attempted(attempt.intent().targets().targets()[0].clone(), outcome), + at, + ) + .unwrap() +} +async fn save(r: &Rig, observation: &StockDeliveryObservation) -> StockDeliveryObservationReceipt { + let StockDeliveryObservationOutcome::Committed(receipt) = r + .store + .record_stock_delivery_observation(&r.binding, r.enrollment.proof(), observation) + .await + .unwrap() + else { + panic!("confirmed original observation required") + }; + *receipt +} + +#[tokio::test] +async fn fresh_attempt_existing_request_and_reopen_keep_original_outer_and_stock_effects() { + let (mut r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let first = claim(&r, &original, &outer, 1).await; + assert_eq!(first.target_ordinals(), &[1]); + first + .source() + .with_json(|raw| assert_eq!(raw, outer.raw_json())); + let before = inventory_minimum(&r).await; + let StockDeliveryAttemptOutcome::Retained(existing) = r + .store + .prepare_stock_delivery_attempt(request(&r, &original, &outer, 1).await, proof(&r)) + .await + .unwrap() + else { + panic!("existing request must never qualify another invocation") + }; + assert_eq!(existing.transaction_id(), first.transaction_id()); + assert_eq!(inventory_minimum(&r).await, before); + reopen_plain(&mut r).await; + let loaded = r + .store + .stock_delivery_attempt( + envelope_request(&r, &original, outer.recipient(), None).await, + first.intent().request_id().clone(), + proof(&r), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(loaded.transaction_id(), first.transaction_id()); + assert_eq!(loaded.checkpoint(), first.checkpoint()); + assert_eq!(loaded.intent(), first.intent()); + loaded + .source() + .with_json(|raw| assert_eq!(raw, outer.raw_json())); + let summary = r + .store + .stock_delivery_summary( + envelope_request(&r, &original, outer.recipient(), None).await, + proof(&r), + ) + .await + .unwrap(); + assert_eq!(summary.attempt_count(), 1); + assert_eq!(summary.targets()[0].potential_attempts(), 1); + assert!(!summary.acceptance_satisfied().unwrap()); + balances(&r, 80, 9, 0, 1, 3).await; + balances(&r, 81, 8, 0, 2, 3).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn first_null_observation_is_immutable_other_classes_append_and_acceptance_is_sticky() { + let (mut r, original, _, outer) = setup(17).await; + + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + + let attempt = claim(&r, &original, &outer, 2).await; + + let accepted = observed(&attempt, DeliveryOutcome::accepted(), None); + let first = save(&r, &accepted).await; + + let again = observed( + &attempt, + DeliveryOutcome::accepted(), + NonZeroU64::new(151000), + ); + assert_eq!(save(&r, &again).await, first); + let later = observed( + &attempt, + DeliveryOutcome::unavailable(), + NonZeroU64::new(152000), + ); + let second = save(&r, &later).await; + assert!(second.checkpoint().revision() > first.checkpoint().revision()); + reopen_plain(&mut r).await; + let page = r + .store + .stock_delivery_observations( + envelope_request(&r, &original, outer.recipient(), None).await, + None, + proof(&r), + ) + .await + .unwrap(); + assert_eq!(page.entries(), &[first, second]); + assert!(page.next_after().is_none()); + assert!( + page.entries()[0] + .observation() + .observed_at_unix_ms() + .is_none() + ); + let summary = r + .store + .stock_delivery_summary( + envelope_request(&r, &original, outer.recipient(), None).await, + proof(&r), + ) + .await + .unwrap(); + assert!(summary.acceptance_satisfied().unwrap()); + assert!(summary.targets()[0].accepted()); + assert_eq!( + summary.targets()[0].last_observation_kind(), + Some(DeliveryObservationKind::Unknown) + ); + balances(&r, 80, 9, 0, 1, 3).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn obtained_outcomes_survive_clock_loss_expiry_and_revocation_without_authorizing_reads() { + for mode in ["clock", "expired", "revoked"] { + let (r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let attempt = claim(&r, &original, &outer, 3).await; + let observation = observed(&attempt, DeliveryOutcome::accepted(), None); + let read = envelope_request(&r, &original, outer.recipient(), None).await; + match mode { + "clock" => r.clock.0.store(0, Ordering::SeqCst), + "expired" => r.clock.0.store(350, Ordering::SeqCst), + "revoked" => { + r.store + .revoke_stock_grant( + r.binding.clone(), + inventory_minimum(&r).await, + r.enrollment.proof(), + radroots_domain::TransactionId::from_bytes([99; 32]), + r.enrollment.input().grant_id(), + ) + .await + .unwrap(); + } + _ => unreachable!(), + } + let retained = save(&r, &observation).await; + assert!(retained.observation().observed_at_unix_ms().is_none()); + assert!( + r.store + .stock_delivery_summary(read, proof(&r)) + .await + .is_err() + ); + r.clock.0.store(150, Ordering::SeqCst); + if mode != "revoked" { + let page = r + .store + .stock_delivery_observations( + envelope_request(&r, &original, outer.recipient(), None).await, + None, + proof(&r), + ) + .await + .unwrap(); + assert_eq!(page.entries(), &[retained]); + } + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn wrong_route_event_request_and_target_cannot_create_delivery_or_outcome_records() { + use radroots_transport::{DeliveryReceipt, sink::DeliveryRequest}; + let (r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let before = inventory_minimum(&r).await; + let route = DeliveryIntent::new( + &format!("{:064x}", 4), + outer.event_id(), + &TargetSet::new(vec![Target::nostr_relay("wss://other.example").unwrap()]).unwrap(), + &SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()), + NonZeroU64::new(180000).unwrap(), + ) + .unwrap(); + let req = StockDeliveryRequest::new( + r.binding.clone(), + before, + original.attempt().operation_id(), + original.attempt().command_digest(), + outer.recipient(), + route, + ) + .unwrap(); + assert!(matches!( + r.store.prepare_stock_delivery_attempt(req, proof(&r)).await, + Err(OperationError::UnverifiedApproval) + )); + let wrong_event = DeliveryIntent::new( + &format!("{:064x}", 4), + radroots_domain::EnvelopeEventId::from_bytes([9; 32]), + intent(&outer, 4).targets(), + intent(&outer, 4).policy(), + NonZeroU64::new(180000).unwrap(), + ) + .unwrap(); + let req = StockDeliveryRequest::new( + r.binding.clone(), + before, + original.attempt().operation_id(), + original.attempt().command_digest(), + outer.recipient(), + wrong_event, + ) + .unwrap(); + assert!(matches!( + r.store.prepare_stock_delivery_attempt(req, proof(&r)).await, + Err(OperationError::InvalidEvidence) + )); + assert_eq!(inventory_minimum(&r).await, before); + let attempt = claim(&r, &original, &outer, 4).await; + let actual = attempt.transport_request().unwrap(); + let wrong_request = DeliveryRequest::new( + format!("{:064x}", 5), + actual.payload().clone(), + actual.target_set().clone(), + actual.satisfaction().clone(), + actual.deadline_unix_ms(), + ) + .unwrap(); + let receipt = DeliveryReceipt::for_request( + &wrong_request, + vec![DeliveryTargetReceipt::attempted( + actual.target_set().targets()[0].clone(), + DeliveryOutcome::accepted(), + )], + ) + .unwrap(); + assert!(matches!( + StockDeliveryObservation::from_receipt( + &attempt, + &receipt, + actual.target_set().targets()[0].fingerprint(), + None + ), + Err(OperationError::InvalidEvidence) + )); + let foreign = DeliveryTargetReceipt::attempted( + Target::nostr_relay("wss://other.example").unwrap(), + DeliveryOutcome::accepted(), + ); + assert!(matches!( + StockDeliveryObservation::from_store_report(&attempt, &foreign, None), + Err(OperationError::InvalidEvidence) + )); + let page = r + .store + .stock_delivery_observations( + envelope_request(&r, &original, outer.recipient(), None).await, + None, + proof(&r), + ) + .await + .unwrap(); + assert!(page.entries().is_empty()); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn failed_attempt_and_observation_writes_roll_back_before_same_request_can_be_confirmed() { + for (attempt_fault, observation_fault) in [ + ( + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations BEGIN SELECT RAISE(ABORT,'fixture'); END", + ), + ( + "CREATE TRIGGER fault BEFORE INSERT ON stock_operation_parts BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_operation_parts BEGIN SELECT RAISE(ABORT,'fixture'); END", + ), + ( + "CREATE TRIGGER fault BEFORE INSERT ON stock_delivery_attempts BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_delivery_observations BEGIN SELECT RAISE(ABORT,'fixture'); END", + ), + ( + "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fixture'); END", + ), + ] { + let (r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let before = inventory_minimum(&r).await; + let mut db = database(&r).await; + sqlx::raw_sql(attempt_fault).execute(&mut db).await.unwrap(); + assert_eq!( + r.store + .prepare_stock_delivery_attempt(request(&r, &original, &outer, 6).await, proof(&r)) + .await + .unwrap_err() + .code(), + "storage_failure" + ); + assert_eq!(inventory_minimum(&r).await, before); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut db) + .await + .unwrap(); + let attempt = claim(&r, &original, &outer, 6).await; + let observation = observed(&attempt, DeliveryOutcome::accepted(), None); + let before = inventory_minimum(&r).await; + sqlx::raw_sql(observation_fault) + .execute(&mut db) + .await + .unwrap(); + assert_eq!( + r.store + .record_stock_delivery_observation(&r.binding, r.enrollment.proof(), &observation) + .await + .unwrap_err() + .code(), + "storage_failure" + ); + assert_eq!(inventory_minimum(&r).await, before); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut db) + .await + .unwrap(); + save(&r, &observation).await; + balances(&r, 80, 9, 0, 1, 3).await; + db.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn unknown_observation_commit_keeps_original_owner_until_same_owner_reconciliation() { + let (r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let attempt = claim(&r, &original, &outer, 7).await; + let observation = observed(&attempt, DeliveryOutcome::accepted(), None); + let mut db = database(&r).await; + sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault AFTER INSERT ON stock_delivery_observations BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut db).await.unwrap(); + assert!(matches!( + r.store + .record_stock_delivery_observation(&r.binding, r.enrollment.proof(), &observation) + .await + .unwrap(), + StockDeliveryObservationOutcome::Unknown(_) + )); + let source = StockEnvelopeRequest::new( + r.binding.clone(), + attempt.checkpoint(), + original.attempt().operation_id(), + original.attempt().command_digest(), + outer.recipient(), + None, + ) + .unwrap(); + assert_eq!( + r.store + .stock_delivery_summary(source, proof(&r)) + .await + .unwrap_err() + .code(), + "recovery_required" + ); + assert!( + NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone() + ) + .await + .is_err() + ); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut db) + .await + .unwrap(); + let StockDeliveryObservationOutcome::Committed(retained) = r + .store + .reconcile_stock_delivery_observation(&r.binding, r.enrollment.proof(), &observation) + .await + .unwrap() + else { + panic!("same owner must reconcile obtained output") + }; + assert_eq!(retained.observation(), &observation); + let page = r + .store + .stock_delivery_observations( + envelope_request(&r, &original, outer.recipient(), None).await, + None, + proof(&r), + ) + .await + .unwrap(); + assert_eq!(page.entries(), &[*retained]); + db.close().await.unwrap(); + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/envelope_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/envelope_tests.rs @@ -7,6 +7,8 @@ use radroots_storage::{ inventory::{InventoryStore, StockEnvelopeOutcome, StockEnvelopeReceipt, StockEnvelopeRequest}, }; use std::num::NonZeroU64; +#[path = "delivery_tests.rs"] +mod delivery_tests; fn proof(r: &Rig) -> AttachmentProof { r.enrollment .proof() @@ -33,7 +35,7 @@ fn wrapped(raw: &str, recipient: PublicKey) -> PrivateEnvelopeCandidate { let pending = wrap_retained_seal( raw, recipient, - NonZeroU64::new(150000).unwrap(), + NonZeroU64::new(150).unwrap(), &OsNonceSource, ) .unwrap(); @@ -85,7 +87,7 @@ async fn capture( #[tokio::test] async fn original_peer_and_self_outers_retain_exact_bytes_once_and_reopen_without_new_stock_effects() { - let (mut r, original, installed, peer_outer) = setup(16).await; + let (mut r, original, installed, peer_outer) = setup(17).await; let before = inventory_minimum(&r).await; let first = committed_envelope(capture(&r, &original, &peer_outer, None).await.unwrap()); assert_eq!( @@ -142,7 +144,7 @@ async fn original_peer_and_self_outers_retain_exact_bytes_once_and_reopen_withou } #[tokio::test] async fn invalid_key_wrong_original_seal_and_rewrapping_cannot_replace_the_original_outer() { - let (r, original, _, outer) = setup(16).await; + let (r, original, _, outer) = setup(17).await; let before = inventory_minimum(&r).await; let wrong = PrivateEnvelopeCandidate::from_obtained(outer.recipient(), outer.raw_json(), &[9; 32]) @@ -232,7 +234,7 @@ async fn invalid_key_wrong_original_seal_and_rewrapping_cannot_replace_the_origi async fn original_credential_captures_after_clock_loss_expiry_or_revocation_but_never_grants_read_access() { for mode in ["clock_unavailable", "expired", "revoked"] { - let (r, original, _, outer) = setup(16).await; + let (r, original, _, outer) = setup(17).await; let selected = envelope_request(&r, &original, outer.recipient(), None).await; let read = envelope_request(&r, &original, outer.recipient(), None).await; match mode { @@ -284,13 +286,13 @@ async fn late_original_or_projection_damage_cannot_commit_a_partially_authentica "UPDATE stock_publication_work SET recipient=randomblob(32)", "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=3", ] { - let (mut r, original, _, outer) = setup(16).await; + let (mut r, original, _, outer) = setup(17).await; let selected = envelope_request(&r, &original, outer.recipient(), None).await; let provider = reopen(&mut r).await; let mut db = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin(r.store.capture_stock_envelope(selected, proof(&r), &outer)); assert!(futures::poll!(pending.as_mut()).is_pending()); provider.gate.entered(); @@ -353,7 +355,7 @@ async fn every_outer_write_failure_retains_caller_bytes_and_no_partial_row_or_st "CREATE TRIGGER fault BEFORE INSERT ON stock_envelopes BEGIN SELECT RAISE(ABORT,'fixture'); END", "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fixture'); END", ] { - let (r, original, _, outer) = setup(16).await; + let (r, original, _, outer) = setup(17).await; let before = inventory_minimum(&r).await; let raw = outer.raw_json().to_owned(); let mut db = database(&r).await; @@ -384,7 +386,7 @@ async fn every_outer_write_failure_retains_caller_bytes_and_no_partial_row_or_st } #[tokio::test] async fn uncertain_outer_commit_fences_owner_and_original_bytes_can_be_retained_after_reopen() { - let (mut r, original, _, outer) = setup(16).await; + let (mut r, original, _, outer) = setup(17).await; let before = inventory_minimum(&r).await; let mut db = database(&r).await; sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault AFTER INSERT ON stock_envelopes BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut db).await.unwrap(); @@ -423,12 +425,12 @@ async fn uncertain_outer_commit_fences_owner_and_original_bytes_can_be_retained_ } #[tokio::test] async fn lost_outer_observer_is_drained_and_one_exact_record_survives_reopen() { - let (mut r, original, _, outer) = setup(16).await; + let (mut r, original, _, outer) = setup(17).await; let selected = envelope_request(&r, &original, outer.recipient(), None).await; let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin(r.store.capture_stock_envelope(selected, proof(&r), &outer)); assert!(futures::poll!(pending.as_mut()).is_pending()); provider.gate.entered(); @@ -461,7 +463,7 @@ async fn protected_outer_or_cache_damage_is_recovery_evidence_not_missing_work() "DELETE FROM stock_publication_work", "UPDATE stock_signing_evidence SET evidence_digest=randomblob(32)", ] { - let (r, original, _, outer) = setup(16).await; + let (r, original, _, outer) = setup(17).await; committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); let selected = envelope_request(&r, &original, outer.recipient(), None).await; sqlx::raw_sql(statement) @@ -479,3 +481,28 @@ async fn protected_outer_or_cache_damage_is_recovery_evidence_not_missing_work() r.store.close().await.unwrap(); } } + +#[tokio::test] +async fn retained16_keeps_exact_outer_capture_and_query_without_a_catalog_upgrade() { + let (r, original, _, outer) = setup(16).await; + let receipt = committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let source = r + .store + .stock_envelope( + envelope_request(&r, &original, outer.recipient(), None).await, + proof(&r), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(source.receipt(), receipt); + source.with_json(|raw| assert_eq!(raw, outer.raw_json())); + let mut db = database(&r).await; + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(catalog, 16); + db.close().await.unwrap(); + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_reconciliation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_reconciliation_tests.rs @@ -128,13 +128,13 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho remove_fault(&mut database, true).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v17", 0); let mut recovery = Box::pin(reconcile(&r, &request)); assert!(futures::poll!(recovery.as_mut()).is_pending()); provider.gate.entered(); // The authorized old snapshot has already been read. Future schema then // refuses read-only preflight after close; no migration or repair occurs. - sqlx::raw_sql("PRAGMA user_version=17") + sqlx::raw_sql("PRAGMA user_version=18") .execute(&mut database) .await .unwrap(); @@ -146,7 +146,7 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho .fetch_one(&mut database) .await .unwrap(), - 17 + 18 ); let wrong = AttachmentProof::from_protected_input(&[99; 32]).unwrap(); assert!( @@ -155,7 +155,7 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho .is_err() ); request.with_json(|value| assert_eq!(value, raw)); - sqlx::raw_sql("PRAGMA user_version=16") + sqlx::raw_sql("PRAGMA user_version=17") .execute(&mut database) .await .unwrap(); @@ -184,7 +184,7 @@ async fn lost_reconciliation_observer_drains_the_actual_replacement_and_original remove_fault(&mut database, true).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v17", 0); let mut recovery = Box::pin(reconcile(&r, &request)); assert!(futures::poll!(recovery.as_mut()).is_pending()); provider.gate.entered(); diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs @@ -446,7 +446,7 @@ async fn lost_capture_observer_drains_owned_input_and_reopens_the_exact_original let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), @@ -534,7 +534,7 @@ async fn capture_rechecks_original_claim_plan_root_and_grant_after_provider_io() let mut rawdb = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs @@ -437,7 +437,7 @@ async fn replay_authorization_rechecks_actual_late_root_grant_plan_claim_backing let mut raw = database(&r).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .authorize_stock_exact_replay(request, r.enrollment.proof()), @@ -491,7 +491,7 @@ async fn observer_loss_drains_authorization_without_signing_or_a_new_claim_and_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .authorize_stock_exact_replay(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs @@ -414,7 +414,7 @@ async fn lost_t2_observer_drains_and_reopens_one_atomic_installation() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .install_stock_agreement(selected, r.enrollment.proof()), @@ -453,7 +453,7 @@ async fn late_t2_backing_or_grant_or_evidence_change_never_commits_partial_insta let mut db = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .install_stock_agreement(selected, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs @@ -166,7 +166,7 @@ async fn stock_process_child() { if control.before { provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); } let work = async { match control.edge { diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs @@ -354,7 +354,7 @@ async fn dropped_t1_observer_keeps_owned_work_and_close_drains_before_original_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), @@ -408,7 +408,7 @@ async fn t1_final_permission_order_root_and_clock_witnesses_refuse_changes_after let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs b/crates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs @@ -157,7 +157,7 @@ async fn public_source_close_drains_admitted_work_after_observer_loss() { let minimum = r.minimum().await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut future = Box::pin(r.store.retain_stock_listing( r.binding.clone(), minimum, @@ -213,7 +213,7 @@ async fn public_source_writes_recheck_expiry_and_head_rows_after_actual_protecti let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut future = Box::pin(r.store.retain_stock_listing( r.binding.clone(), minimum, diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs @@ -31,7 +31,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !matches!(authority.catalog, 8..=16) || authority.public_sources.is_none() { + if !matches!(authority.catalog, 8..=17) || authority.public_sources.is_none() { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/unissued_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/unissued_tests.rs @@ -364,7 +364,7 @@ async fn lost_original_negative_append_waiter_drains_and_reopens_the_same_fact() let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v16", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v17", 0); let mut pending = Box::pin(capture(&r, &value)); assert!(futures::poll!(pending.as_mut()).is_pending()); provider.gate.entered(); diff --git a/crates/storage_sqlite/src/workspace/stock/schema.rs b/crates/storage_sqlite/src/workspace/stock/schema.rs @@ -1,7 +1,7 @@ //! Exact stock catalogs. Enrollment-only version1 is retained without upgrade. use super::WorkspaceError; use sqlx::SqliteConnection; -pub(super) const CURRENT: i64 = 16; +pub(super) const CURRENT: i64 = 17; const AUTHORITY: &str = "CREATE TABLE stock_authority (singleton INTEGER PRIMARY KEY CHECK(singleton=1), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; const GRANTS: &str = "CREATE TABLE stock_grants (grant_id BLOB PRIMARY KEY CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; const POOLS: &str = "CREATE TABLE stock_pools (pool_id BLOB PRIMARY KEY CHECK(length(pool_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; @@ -20,6 +20,7 @@ const OPERATIONS_V13: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL const OPERATIONS_V14: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 8), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 8 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const OPERATIONS_V15: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 9), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 9 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const OPERATIONS_V16: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 10), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 10 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; +const OPERATIONS_V17: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 12), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 12 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const MOVEMENTS: &str = "CREATE TABLE stock_movements (movement_id BLOB PRIMARY KEY CHECK(length(movement_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), FOREIGN KEY(actor,grant_id,operation_id) REFERENCES stock_operations(actor,grant_id,operation_id)) STRICT, WITHOUT ROWID"; pub(super) fn objects( version: i64, @@ -30,13 +31,15 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=16 => objects.extend([ + 2..=17 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ( "table", "stock_operations", "stock_operations", - if version >= 16 { + if version >= 17 { + OPERATIONS_V17 + } else if version >= 16 { OPERATIONS_V16 } else if version >= 15 { OPERATIONS_V15 @@ -91,7 +94,7 @@ pub(super) fn objects( if version >= 5 { objects.push(("table","stock_mappings","stock_mappings","CREATE TABLE stock_mappings (listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), option_id BLOB NOT NULL CHECK(length(option_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(listing_author,listing_d,option_id)) STRICT, WITHOUT ROWID")); } - if (6..=16).contains(&version) { + if (6..=17).contains(&version) { objects.push(("table","stock_source_records","stock_source_records","CREATE TABLE stock_source_records (record_id BLOB PRIMARY KEY CHECK(length(record_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("table","stock_source_evidence","stock_source_evidence","CREATE TABLE stock_source_evidence (envelope_id BLOB PRIMARY KEY CHECK(length(envelope_id)=32), record_id BLOB REFERENCES stock_source_records(record_id), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_source_transaction_identity","stock_source_evidence","CREATE UNIQUE INDEX stock_source_transaction_identity ON stock_source_evidence(transaction_id)")); @@ -127,7 +130,7 @@ pub(super) fn objects( objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); } } - if matches!(version, 8..=16) { + if matches!(version, 8..=17) { objects.push(("table","stock_public_events","stock_public_events","CREATE TABLE stock_public_events (event_id BLOB PRIMARY KEY CHECK(length(event_id)=32), listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), created_at BLOB NOT NULL CHECK(length(created_at)=8), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_public_transaction_identity","stock_public_events","CREATE UNIQUE INDEX stock_public_transaction_identity ON stock_public_events(transaction_id)")); objects.push(( @@ -199,6 +202,12 @@ pub(super) fn objects( "CREATE UNIQUE INDEX stock_envelope_entry ON stock_envelopes(actor,entry_id)", )); } + if version >= 17 { + objects.push(("table","stock_delivery_attempts","stock_delivery_attempts","CREATE TABLE stock_delivery_attempts (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), recipient BLOB NOT NULL CHECK(length(recipient)=32), request_key BLOB NOT NULL CHECK(length(request_key)=32), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id,recipient,request_key), FOREIGN KEY(actor,operation_id,recipient) REFERENCES stock_envelopes(actor,operation_id,recipient), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(("index","stock_delivery_attempt_entry","stock_delivery_attempts","CREATE UNIQUE INDEX stock_delivery_attempt_entry ON stock_delivery_attempts(actor,entry_id)")); + objects.push(("table","stock_delivery_observations","stock_delivery_observations","CREATE TABLE stock_delivery_observations (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), recipient BLOB NOT NULL CHECK(length(recipient)=32), request_key BLOB NOT NULL CHECK(length(request_key)=32), target_key BLOB NOT NULL CHECK(length(target_key)=32), kind INTEGER NOT NULL CHECK(kind BETWEEN 1 AND 6), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id,recipient,request_key,target_key,kind), FOREIGN KEY(actor,operation_id,recipient,request_key) REFERENCES stock_delivery_attempts(actor,operation_id,recipient,request_key), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(("index","stock_delivery_observation_entry","stock_delivery_observations","CREATE UNIQUE INDEX stock_delivery_observation_entry ON stock_delivery_observations(actor,entry_id)")); + } Ok(objects) } pub(super) async fn admit(connection: &mut SqliteConnection) -> Result<i64, WorkspaceError> { diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan.rs @@ -148,7 +148,7 @@ pub(in crate::workspace::stock) async fn load( proof: &AttachmentProof, ) -> Result<Authorized, OperationError> { let access = Box::pin(turn.access(binding, minimum, proof)).await?; - if !matches!(access.authority.catalog, 10..=16) { + if !matches!(access.authority.catalog, 10..=17) { return Err(OperationError::UnsupportedOperation); } let original = Box::pin(acceptance::codec::read( diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs @@ -191,6 +191,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + delivery: None, envelope: None, aborted: None, preparation: None, diff --git a/crates/storage_sqlite/src/workspace/stock/snapshot.rs b/crates/storage_sqlite/src/workspace/stock/snapshot.rs @@ -124,8 +124,14 @@ pub struct StockOperationSnapshot { recipients: [StockRecipientSnapshot; 2], installation: Option<super::StockInstallationReceipt>, aborted: Option<super::StockAbortReceipt>, + delivery: Option<Box<[radroots_storage::inventory::StockDeliverySummary; 2]>>, } impl StockOperationSnapshot { + /// Coherent original per-recipient delivery progress; retained catalogs + /// without stock D expose no supported delivery view. + pub fn delivery(&self) -> Option<&[radroots_storage::inventory::StockDeliverySummary; 2]> { + self.delivery.as_deref() + } pub fn aborted(&self) -> Option<&super::StockAbortReceipt> { self.aborted.as_ref() } @@ -332,6 +338,25 @@ async fn read_authorized( .authority .inventory .ok_or(OperationError::RecoveryRequired)?; + let delivery = if auth.access.authority.catalog == 17 { + Some(Box::new( + Box::pin(super::delivery::snapshot( + turn, + radroots_storage::inventory::StockEnvelopeRequest::new( + request.binding.clone(), + request.minimum, + request.operation, + request.digest, + auth.original.receipt.rumor().recipients()[0], + None, + )?, + &auth.access.authority, + )) + .await?, + )) + } else { + None + }; let minimum = InventoryCheckpointRef::from_host_metadata( turn.selected.authority(), Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, @@ -414,6 +439,7 @@ async fn read_authorized( .ok_or(OperationError::RecoveryRequired)?, ); Ok(StockOperationSnapshot { + delivery, aborted: aborted.and_then(|(retained, _)| retained.map(|value| value.receipt)), installation: installation.and_then(|(retained, _)| retained.map(|value| value.receipt)), preparation: auth.original.receipt, diff --git a/crates/storage_sqlite/src/workspace/stock/source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/source/transaction.rs @@ -28,7 +28,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !(6..=16).contains(&authority.catalog) { + if !(6..=17).contains(&authority.catalog) { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; @@ -114,7 +114,7 @@ pub(in crate::workspace) async fn history( proof: AttachmentProof, ) -> Result<StockHistorySnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=16) { + if !matches!(access.authority.catalog, 8..=17) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::history::prepare( @@ -175,7 +175,7 @@ pub(in crate::workspace) async fn inspect_request( proof: AttachmentProof, ) -> Result<StockRequestSnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=16) { + if !matches!(access.authority.catalog, 8..=17) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::request::prepare( diff --git a/crates/storage_sqlite/src/workspace/stock/tests.rs b/crates/storage_sqlite/src/workspace/stock/tests.rs @@ -109,7 +109,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang ) .await .unwrap(); - assert_eq!(schema::admit(&mut connection).await, Ok(16)); + assert_eq!(schema::admit(&mut connection).await, Ok(17)); assert_eq!(schema::integrity(&mut connection).await, Ok(())); let root: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_authority") .fetch_one(&mut connection) @@ -117,18 +117,18 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang .unwrap(); let clear = fixture .crypto() - .open_stock_root(enrollment.input(), 16, &root) + .open_stock_root(enrollment.input(), 17, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 16)) + .expose_secret(|bytes| Authority::decode(bytes, 17)) .unwrap(); clear.expose_secret(|bytes| { let original:serde_json::Value=serde_json::from_slice(bytes).unwrap(); assert_eq!(original["inventory"]["mappings"],"0"); for bad in [serde_json::json!([]),serde_json::json!({"revision":"1","pools":"1","movements":"1","head":original["inventory"]["head"]})] { let mut value=original.clone();value["inventory"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),16).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),17).is_err()); } for bad in [ serde_json::json!([]), @@ -139,7 +139,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang serde_json::json!({"revision":"1","records":"2","parts":"3","head":"01".repeat(32)}), ] { let mut value=original.clone();value["sources"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),16).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),17).is_err()); } }); assert_eq!(authority.input, *enrollment.input()); @@ -189,7 +189,7 @@ async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_ca let caller = namespace.attachment(GrantId::from_bytes([9; 32])).unwrap(); let crypto = fixture.crypto(); let clear = b"synthetic context payload"; - for version in 4..=16 { + for version in 4..=17 { let current = crypto .seal_stock_root(&owner, version, clear) .await @@ -277,7 +277,7 @@ async fn retained_v10_preserves_prior_families_and_signing_plan_retention() { } #[tokio::test] async fn retained_v11_preserves_prior_families_and_adds_claims_and_obtained_evidence() { - assert_eq!(schema::CURRENT, 16); + assert_eq!(schema::CURRENT, 17); retained_inventory_catalog(11).await; } // Exact catalog fixtures exercise retained/successor codecs; they are not @@ -322,7 +322,7 @@ pub(in crate::workspace::stock) async fn literal_enrollment_catalog( catalog: i64, enrollment: &StockEnrollment, ) { - assert!(matches!(catalog, 13..=15)); + assert!(matches!(catalog, 13..=16)); let record = enrollment.record.lock().unwrap().take().unwrap(); literal_catalog_contents( fixture, @@ -381,7 +381,7 @@ async fn literal_catalog_contents( if catalog >= 7 { value["inventory"]["orders"] = serde_json::json!("0"); } - if matches!(catalog, 8..=15) { + if matches!(catalog, 8..=16) { value["public_sources"] = serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); } @@ -429,6 +429,7 @@ async fn literal_catalog_contents( 13 => "PRAGMA user_version=13", 14 => "PRAGMA user_version=14", 15 => "PRAGMA user_version=15", + 16 => "PRAGMA user_version=16", _ => unreachable!(), }) .execute(&mut *tx) @@ -453,7 +454,7 @@ async fn retained_inventory_catalog(catalog: i64) { assert_eq!(authority.source_checkpoint().is_some(), catalog >= 6); assert_eq!( authority.listing_checkpoint().is_some(), - matches!(catalog, 8..=15) + matches!(catalog, 8..=16) ); let minimum = authority.inventory_checkpoint().unwrap(); let context = CommandContextData::new( @@ -696,7 +697,7 @@ async fn retained_inventory_catalog(catalog: i64) { .fetch_one(&mut connection) .await .unwrap(); - let old = if matches!(catalog, 7..=15) { + let old = if matches!(catalog, 7..=16) { let retained = ledger::read( &mut connection, &input, @@ -749,7 +750,7 @@ async fn retained_inventory_catalog(catalog: i64) { // inside a real SQL transaction. Row counts and the protected header // stay unchanged while one referenced ciphertext changes. for part in [false, true] { - if part && !matches!(catalog, 7..=15) { + if part && !matches!(catalog, 7..=16) { continue; } let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) @@ -827,6 +828,7 @@ async fn retained_inventory_catalog(catalog: i64) { 13 => "PRAGMA user_version=12", 14 => "PRAGMA user_version=13", 15 => "PRAGMA user_version=14", + 16 => "PRAGMA user_version=15", _ => unreachable!(), }) .execute(&mut connection) @@ -956,24 +958,30 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() #[tokio::test] async fn retained_v12_preserves_initial_installation_catalog_without_upgrade() { - assert_eq!(schema::CURRENT, 16); + assert_eq!(schema::CURRENT, 17); retained_inventory_catalog(12).await; } #[tokio::test] async fn retained_v13_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 16); + assert_eq!(schema::CURRENT, 17); retained_inventory_catalog(13).await; } #[tokio::test] async fn retained_v14_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 16); + assert_eq!(schema::CURRENT, 17); retained_inventory_catalog(14).await; } #[tokio::test] async fn retained_v15_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 16); + assert_eq!(schema::CURRENT, 17); retained_inventory_catalog(15).await; } + +#[tokio::test] +async fn retained_v16_authenticates_literal_catalog_and_original_inventory_records() { + assert_eq!(schema::CURRENT, 17); + retained_inventory_catalog(16).await; +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -1,3 +1,4 @@ +mod dispatch; use super::{ AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceCrypto, WorkspaceError, @@ -89,6 +90,46 @@ enum Job { AttachmentProof, Reply<Option<stock::StockUnissuedReceipt>, OperationError>, ), + PrepareStockDelivery( + Box<radroots_storage::inventory::StockDeliveryRequest>, + AttachmentProof, + Reply<radroots_storage::inventory::StockDeliveryAttemptOutcome, OperationError>, + ), + StockDeliveryAttempt( + Box<radroots_storage::inventory::StockEnvelopeRequest>, + radroots_transport::sink::DeliveryRequestId, + AttachmentProof, + Reply<Option<radroots_storage::inventory::StockDeliveryAttempt>, OperationError>, + ), + StockDeliverySummary( + Box<radroots_storage::inventory::StockEnvelopeRequest>, + AttachmentProof, + Reply<radroots_storage::inventory::StockDeliverySummary, OperationError>, + ), + RecordStockDeliveryObservation( + Box<WorkspaceBinding>, + AttachmentProof, + Box<radroots_storage::inventory::StockDeliveryObservation>, + Reply<radroots_storage::inventory::StockDeliveryObservationOutcome, OperationError>, + ), + StockDeliveryObservations( + Box<radroots_storage::inventory::StockEnvelopeRequest>, + Option<radroots_domain::Sequence>, + AttachmentProof, + Reply<radroots_storage::inventory::StockDeliveryObservationPage, OperationError>, + ), + RecoverStockEnvelope( + Box<radroots_storage::inventory::StockEnvelopeRequest>, + AttachmentProof, + Box<radroots_storage::command::PrivateEnvelopeCandidate>, + Reply<radroots_storage::inventory::StockEnvelopeOutcome, OperationError>, + ), + RecoverStockObservation( + Box<WorkspaceBinding>, + AttachmentProof, + Box<radroots_storage::inventory::StockDeliveryObservation>, + Reply<radroots_storage::inventory::StockDeliveryObservationOutcome, OperationError>, + ), CaptureStockEnvelope( Box<radroots_storage::inventory::StockEnvelopeRequest>, AttachmentProof, @@ -369,6 +410,27 @@ impl Job { Self::CaptureStockEvidence(_, _, reply) | Self::RecoverStockEvidence(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } + Self::PrepareStockDelivery(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockDeliveryAttempt(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockDeliverySummary(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::RecordStockDeliveryObservation(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockDeliveryObservations(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::RecoverStockEnvelope(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::RecoverStockObservation(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::CaptureStockEnvelope(_, _, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -650,6 +712,13 @@ impl Handle { | Job::CaptureStockUnissued(..) | Job::RecoverStockUnissued(..) | Job::StockUnissued(..) + | Job::PrepareStockDelivery(..) + | Job::StockDeliveryAttempt(..) + | Job::StockDeliverySummary(..) + | Job::RecordStockDeliveryObservation(..) + | Job::StockDeliveryObservations(..) + | Job::RecoverStockEnvelope(..) + | Job::RecoverStockObservation(..) | Job::CaptureStockEnvelope(..) | Job::StockEnvelope(..) | Job::CaptureStockEvidence(..) @@ -669,7 +738,7 @@ impl Handle { continue; } let job = match job { - Job::RecoverStockUnissued(request, proof, reply) => { + Job::RecoverStockEnvelope(request, proof, candidate, reply) => { let result = Box::pin( super::recovery::RecoveryTurn { connection: &mut connection, @@ -681,13 +750,18 @@ impl Handle { uncertain: &mut uncertain, options: &options, } - .capture_unissued(*request, proof), + .capture_envelope(*request, proof, *candidate), ) .await; let _ = reply.send(result); continue; } - Job::RecoverStockEvidence(request, proof, reply) => { + Job::RecoverStockObservation( + binding, + proof, + observation, + reply, + ) => { let result = Box::pin( super::recovery::RecoveryTurn { connection: &mut connection, @@ -699,1013 +773,83 @@ impl Handle { uncertain: &mut uncertain, options: &options, } - .capture_stock(*request, proof), + .capture_observation(*binding, proof, *observation), ) .await; let _ = reply.send(result); continue; } - Job::RecoverCapture(selected, proof, evidence, reply) => { - let result = super::recovery::RecoveryTurn { - connection: &mut connection, - cached_grant: &mut cached_grant, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - options: &options, - } - .capture(*selected, proof, *evidence) - .await; - let _ = reply.send(result); - continue; - } - job => job, - }; - let Some(connection) = connection.as_mut() else { - job.reject_recovery(); - continue; - }; - match job { - Job::ChangeStockGrant(change, proof, reply) => { - let result = if kind == Kind::SellerStock && !uncertain { - stock::grants::change( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *change, - proof, - ) - .await - } else { - Err(WorkspaceError::RecoveryRequired) - }; - let _ = reply.send(result); - } - Job::ExecuteInventory(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .create(*request, proof) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::InventoryOperation( - binding, - minimum, - operation, - digest, - proof, - reply, - ) => { - let result = if kind == Kind::SellerStock { - stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .creation(*binding, minimum, operation, digest, proof) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::IssueStockConsent(binding, minimum, capture, proof, reply) => { - let result = if kind == Kind::SellerStock { - stock::consent::issue( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - minimum, - *capture, - proof, - ) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockConsent( - binding, - minimum, - operation, - subject, - proof, - reply, - ) => { - let result = if kind == Kind::SellerStock { - stock::consent::query( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - minimum, - operation, - subject, - proof, - ) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::RetainStockListing( - binding, - minimum, - capture, - proof, - reply, - ) => { - let result = if kind == Kind::SellerStock { - stock::public_source::retain( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - minimum, - *capture, - proof, - ) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockListing(binding, minimum, lookup, proof, reply) => { - let result = if kind == Kind::SellerStock { - stock::public_source::query( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - minimum, - lookup, - proof, - ) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::RetainStockSource(binding, minimum, capture, proof, reply) => { - let result = if kind == Kind::SellerStock { - stock::source::retain( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - minimum, - *capture, - proof, - ) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::InstallStockAgreement(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::inventory::installation::install( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockAgreementInstallation(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::inventory::installation::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::AbortStockPreparation(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::inventory::abort::abort( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockPreparationAbort(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::inventory::abort::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockSnapshot(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::snapshot::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockEvidencePage(request, after, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::evidence::page( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - after, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::CaptureStockUnissued(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::unissued::capture( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockUnissued(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::unissued::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::CaptureStockEnvelope(request, proof, candidate, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::envelope::capture( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - *candidate, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockEnvelope(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::envelope::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::CaptureStockEvidence(evidence, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::evidence::capture( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *evidence, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockEvidence(request, digest, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::evidence::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - digest, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::ClaimStockSigning(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::claim::claim( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::AuthorizeStockExactReplay(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::recovery::authorize( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockSigningAttempt(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::issuance::claim::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::BindStockSigningPlan(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::signing_plan::bind( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockSigningPlan( - binding, - minimum, - operation, - digest, - proof, - reply, - ) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::signing_plan::read( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - minimum, - operation, - digest, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::PrepareStockAcceptance(request, proof, reply) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::inventory::acceptance::admit( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *request, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockOrderRequest( - binding, - inventory_minimum, - minimum, - listings, - selected, - proof, - reply, - ) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::source::inspect_request( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - inventory_minimum, - minimum, - listings, - selected, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockOrderHistory( - binding, - inventory_minimum, - minimum, - listings, - scope, - proof, - reply, - ) => { - let result = if kind == Kind::SellerStock { - Box::pin(stock::source::query_history( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - inventory_minimum, - minimum, - listings, - scope, - proof, - )) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockSource(binding, minimum, envelope, proof, reply) => { - let result = if kind == Kind::SellerStock { - stock::source::query( - &mut stock::inventory::Turn { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - }, - *binding, - minimum, - envelope, - proof, - ) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::OptionMapping(binding, minimum, key, proof, reply) => { - let result = if kind == Kind::SellerStock { - stock::inventory::Turn { - connection, + Job::RecoverStockUnissued(request, proof, reply) => { + let result = Box::pin( + super::recovery::RecoveryTurn { + connection: &mut connection, + cached_grant: &mut cached_grant, namespace: &namespace, selected: &input, crypto: &crypto, clock: clock.as_ref(), uncertain: &mut uncertain, + options: &options, } - .option_mapping(*binding, minimum, key, proof) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; + .capture_unissued(*request, proof), + ) + .await; let _ = reply.send(result); + continue; } - Job::Pool(binding, minimum, id, proof, reply) => { - let result = if kind == Kind::SellerStock { - stock::inventory::Turn { - connection, + Job::RecoverStockEvidence(request, proof, reply) => { + let result = Box::pin( + super::recovery::RecoveryTurn { + connection: &mut connection, + cached_grant: &mut cached_grant, namespace: &namespace, selected: &input, crypto: &crypto, clock: clock.as_ref(), uncertain: &mut uncertain, + options: &options, } - .pool(*binding, minimum, id, proof) - .await - } else { - Err(OperationError::UnsupportedOperation) - }; - let _ = reply.send(result); - } - Job::StockAuthority(selected, proof, reply) => { - let result = if kind == Kind::SellerStock && !uncertain { - stock::authenticate( - connection, - &namespace, - &input, - &crypto, - clock.as_ref(), - &selected, - &proof, - ) - .await - .map(|(receipt, _)| receipt) - } else { - Err(WorkspaceError::RecoveryRequired) - }; - if result == Err(WorkspaceError::CommitUnknown) { - uncertain = true; - } - let _ = reply.send(result); - } - job @ (Job::RecoverCapture(..) - | Job::RecoverStockEvidence(..) - | Job::RecoverStockUnissued(..)) => job.reject_recovery(), - Job::CaptureDeliveryObservation( - binding, - proof, - observation, - reply, - ) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .capture_delivery_observation(*binding, proof, *observation) - .await; - let _ = reply.send(result); - } - Job::QueryDeliveryObservations( - binding, - operation, - digest, - recipient, - request, - proof, - reply, - ) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .query_delivery_observations( - *binding, operation, digest, recipient, request, proof, - ) - .await; - let _ = reply.send(result); - } - Job::PrepareDelivery(request, proof, candidate, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .prepare_delivery( - *request, - proof, - candidate.map(|value| *value), - ) - .await; - let _ = reply.send(result); - } - Job::QueryDelivery( - binding, - operation, - digest, - recipient, - request, - proof, - reply, - ) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .query_delivery( - *binding, operation, digest, recipient, request, proof, + .capture_stock(*request, proof), ) .await; let _ = reply.send(result); + continue; } - Job::Install(request, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .install_chat(*request, proof) - .await; - let _ = reply.send(result); - } - Job::Snapshot(binding, operation, digest, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .query_snapshot(*binding, operation, digest, proof) - .await; - let _ = reply.send(result); - } - Job::Claim(request, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .claim_issuance(*request, proof) - .await; - let _ = reply.send(result); - } - Job::Attempt(request, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .query_issuance(*request, proof) - .await; - let _ = reply.send(result); - } - Job::Capture(selected, proof, evidence, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .capture_issuance(*selected, proof, *evidence) - .await; - let _ = reply.send(result); - } - Job::Captured(request, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .query_captured(*request, proof) - .await; - let _ = reply.send(result); - } - Job::BindPlan(binding, plan, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .bind_plan(*binding, plan, proof) - .await; - let _ = reply.send(result); - } - Job::SigningPlan(binding, operation_id, digest, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .query_plan(*binding, operation_id, digest, proof) - .await; - let _ = reply.send(result); - } - Job::Authenticate(selected, proof, reply) => { - let result = if uncertain { - Err(WorkspaceError::RecoveryRequired) - } else if kind == Kind::SellerStock { - stock::authenticate( - connection, - &namespace, - &input, - &crypto, - clock.as_ref(), - &selected, - &proof, - ) - .await - .map(|(_, binding)| binding) - } else { - authenticate( - connection, - &namespace, - &input, - &crypto, - clock.as_ref(), - &selected, - &proof, - ) - .await - .map(|(_, binding)| binding) - }; - if result == Err(WorkspaceError::CommitUnknown) { - uncertain = true; - } - let _ = reply.send(result); - } - Job::Revoke(selected, proof, reply) => { - let result = if uncertain { - Err(WorkspaceError::RecoveryRequired) - } else if kind == Kind::SellerStock { - stock::revoke( - connection, - &namespace, - &input, - &crypto, - clock.as_ref(), - &selected, - &proof, - ) - .await - } else { - revoke( - connection, - &namespace, - &input, - &crypto, - clock.as_ref(), - &selected, - &proof, - ) - .await - }; - if result == Err(WorkspaceError::CommitUnknown) { - uncertain = true; - } - let _ = reply.send(result); - } - Job::Admit(request, proof, reply) => { - let result = Journal { - connection, - namespace: &namespace, - selected: &input, - crypto: &crypto, - clock: clock.as_ref(), - uncertain: &mut uncertain, - } - .admit(*request, proof) - .await; - let _ = reply.send(result); - } - Job::Operation(binding, operation_id, digest, proof, reply) => { - let result = Journal { - connection, + Job::RecoverCapture(selected, proof, evidence, reply) => { + let result = super::recovery::RecoveryTurn { + connection: &mut connection, + cached_grant: &mut cached_grant, namespace: &namespace, selected: &input, crypto: &crypto, clock: clock.as_ref(), uncertain: &mut uncertain, + options: &options, } - .query(*binding, operation_id, digest, proof) + .capture(*selected, proof, *evidence) .await; let _ = reply.send(result); + continue; } - } + job => job, + }; + let Some(connection) = connection.as_mut() else { + job.reject_recovery(); + continue; + }; + dispatch::run( + job, + kind, + stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + ) + .await; } } // The admission sender is gone. All admitted work has drained. @@ -2008,6 +1152,104 @@ impl Handle { self.send(Job::RecoverStockEvidence(Box::new(request), proof, reply))?; result.await.unwrap_or(Ok(unknown)) } + + pub(super) async fn reconcile_stock_envelope( + &self, + request: radroots_storage::inventory::StockEnvelopeRequest, + proof: AttachmentProof, + candidate: radroots_storage::command::PrivateEnvelopeCandidate, + ) -> Result<radroots_storage::inventory::StockEnvelopeOutcome, OperationError> { + let unknown = radroots_storage::inventory::StockEnvelopeOutcome::Unknown(request.attempt()); + let (reply, result) = oneshot::channel(); + self.send(Job::RecoverStockEnvelope( + Box::new(request), + proof, + Box::new(candidate), + reply, + ))?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn prepare_stock_delivery_attempt( + &self, + request: radroots_storage::inventory::StockDeliveryRequest, + proof: AttachmentProof, + ) -> Result<radroots_storage::inventory::StockDeliveryAttemptOutcome, OperationError> { + let unknown = radroots_storage::inventory::StockDeliveryAttemptOutcome::Unknown { + operation: request.attempt(), + request: request.intent().request_id().clone(), + }; + let (reply, result) = oneshot::channel(); + self.send(Job::PrepareStockDelivery(Box::new(request), proof, reply))?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn stock_delivery_attempt( + &self, + request: radroots_storage::inventory::StockEnvelopeRequest, + request_id: radroots_transport::sink::DeliveryRequestId, + proof: AttachmentProof, + ) -> Result<Option<radroots_storage::inventory::StockDeliveryAttempt>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockDeliveryAttempt( + Box::new(request), + request_id, + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } + pub(super) async fn stock_delivery_summary( + &self, + request: radroots_storage::inventory::StockEnvelopeRequest, + proof: AttachmentProof, + ) -> Result<radroots_storage::inventory::StockDeliverySummary, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockDeliverySummary(Box::new(request), proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } + pub(super) async fn record_stock_delivery_observation( + &self, + binding: WorkspaceBinding, + proof: AttachmentProof, + observation: radroots_storage::inventory::StockDeliveryObservation, + recovering: bool, + ) -> Result<radroots_storage::inventory::StockDeliveryObservationOutcome, OperationError> { + let source = observation.source().attempt(); + let unknown = radroots_storage::inventory::StockDeliveryObservationOutcome::Unknown( + radroots_storage::command::CommitAttempt::new( + source.workspace_id(), + source.operation_id(), + source.command_digest(), + None, + ), + ); + let (reply, result) = oneshot::channel(); + self.send(if recovering { + Job::RecoverStockObservation(Box::new(binding), proof, Box::new(observation), reply) + } else { + Job::RecordStockDeliveryObservation( + Box::new(binding), + proof, + Box::new(observation), + reply, + ) + })?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn stock_delivery_observations( + &self, + request: radroots_storage::inventory::StockEnvelopeRequest, + after: Option<radroots_domain::Sequence>, + proof: AttachmentProof, + ) -> Result<radroots_storage::inventory::StockDeliveryObservationPage, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockDeliveryObservations( + Box::new(request), + after, + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn capture_stock_envelope( &self, request: radroots_storage::inventory::StockEnvelopeRequest, @@ -2218,7 +1460,14 @@ impl Handle { | Job::RecoverStockUnissued(..) | Job::CaptureStockEvidence(..) | Job::RecoverStockEvidence(..) => 256 * 1024, - Job::CaptureStockEnvelope(..) + Job::PrepareStockDelivery(..) + | Job::StockDeliveryAttempt(..) + | Job::StockDeliverySummary(..) + | Job::RecordStockDeliveryObservation(..) + | Job::StockDeliveryObservations(..) + | Job::RecoverStockEnvelope(..) + | Job::RecoverStockObservation(..) + | Job::CaptureStockEnvelope(..) | Job::StockEnvelope(..) | Job::StockEvidence(..) | Job::StockUnissued(..) diff --git a/crates/storage_sqlite/src/workspace/worker/dispatch.rs b/crates/storage_sqlite/src/workspace/worker/dispatch.rs @@ -0,0 +1,1036 @@ +//! Each job has an isolated polling frame on the existing bounded worker. +use super::*; +use core::{future::Future, pin::Pin}; + +pub(super) fn run<'a>( + job: Job, + kind: Kind, + turn: stock::inventory::Turn<'a>, +) -> Pin<Box<dyn Future<Output = ()> + 'a>> { + let stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } = turn; + match job { + Job::ChangeStockGrant(change, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock && !*uncertain { + stock::grants::change( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *change, + proof, + ) + .await + } else { + Err(WorkspaceError::RecoveryRequired) + }; + let _ = reply.send(result); + }), + Job::ExecuteInventory(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .create(*request, proof) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::InventoryOperation(binding, minimum, operation, digest, proof, reply) => { + Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .creation(*binding, minimum, operation, digest, proof) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }) + } + Job::IssueStockConsent(binding, minimum, capture, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::consent::issue( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + minimum, + *capture, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockConsent(binding, minimum, operation, subject, proof, reply) => { + Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::consent::query( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + minimum, + operation, + subject, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }) + } + Job::RetainStockListing(binding, minimum, capture, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::public_source::retain( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + minimum, + *capture, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockListing(binding, minimum, lookup, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::public_source::query( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + minimum, + lookup, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::RetainStockSource(binding, minimum, capture, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::source::retain( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + minimum, + *capture, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::InstallStockAgreement(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::installation::install( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockAgreementInstallation(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::installation::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::AbortStockPreparation(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::abort::abort( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockPreparationAbort(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::abort::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockSnapshot(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::snapshot::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockEvidencePage(request, after, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::evidence::page( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + after, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::CaptureStockUnissued(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::unissued::capture( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockUnissued(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::unissued::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::PrepareStockDelivery(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::delivery::prepare( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockDeliveryAttempt(request, request_id, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::delivery::query_attempt( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + request_id, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockDeliverySummary(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::delivery::summary( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::RecordStockDeliveryObservation(binding, proof, observation, reply) => { + Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::delivery::capture_observation( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + proof, + *observation, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }) + } + Job::StockDeliveryObservations(request, after, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::delivery::page( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + after, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::CaptureStockEnvelope(request, proof, candidate, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::envelope::capture( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + *candidate, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockEnvelope(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::envelope::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::CaptureStockEvidence(evidence, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::evidence::capture( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *evidence, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockEvidence(request, digest, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::evidence::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + digest, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::ClaimStockSigning(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::claim::claim( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::AuthorizeStockExactReplay(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::recovery::authorize( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockSigningAttempt(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::claim::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::BindStockSigningPlan(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::signing_plan::bind( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockSigningPlan(binding, minimum, operation, digest, proof, reply) => { + Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::signing_plan::read( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + minimum, + operation, + digest, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }) + } + Job::PrepareStockAcceptance(request, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::acceptance::admit( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockOrderRequest( + binding, + inventory_minimum, + minimum, + listings, + selected, + proof, + reply, + ) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::source::inspect_request( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + inventory_minimum, + minimum, + listings, + selected, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockOrderHistory( + binding, + inventory_minimum, + minimum, + listings, + scope, + proof, + reply, + ) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + Box::pin(stock::source::query_history( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + inventory_minimum, + minimum, + listings, + scope, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockSource(binding, minimum, envelope, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::source::query( + &mut stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + }, + *binding, + minimum, + envelope, + proof, + ) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::OptionMapping(binding, minimum, key, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .option_mapping(*binding, minimum, key, proof) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::Pool(binding, minimum, id, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock { + stock::inventory::Turn { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .pool(*binding, minimum, id, proof) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + }), + Job::StockAuthority(selected, proof, reply) => Box::pin(async move { + let result = if kind == Kind::SellerStock && !*uncertain { + stock::authenticate( + connection, namespace, input, crypto, clock, &selected, &proof, + ) + .await + .map(|(receipt, _)| receipt) + } else { + Err(WorkspaceError::RecoveryRequired) + }; + if result == Err(WorkspaceError::CommitUnknown) { + *uncertain = true; + } + let _ = reply.send(result); + }), + job @ (Job::RecoverStockEnvelope(..) + | Job::RecoverStockObservation(..) + | Job::RecoverCapture(..) + | Job::RecoverStockEvidence(..) + | Job::RecoverStockUnissued(..)) => Box::pin(async move { job.reject_recovery() }), + Job::CaptureDeliveryObservation(binding, proof, observation, reply) => { + Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .capture_delivery_observation(*binding, proof, *observation) + .await; + let _ = reply.send(result); + }) + } + Job::QueryDeliveryObservations( + binding, + operation, + digest, + recipient, + request, + proof, + reply, + ) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .query_delivery_observations(*binding, operation, digest, recipient, request, proof) + .await; + let _ = reply.send(result); + }), + Job::PrepareDelivery(request, proof, candidate, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .prepare_delivery(*request, proof, candidate.map(|value| *value)) + .await; + let _ = reply.send(result); + }), + Job::QueryDelivery(binding, operation, digest, recipient, request, proof, reply) => { + Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .query_delivery(*binding, operation, digest, recipient, request, proof) + .await; + let _ = reply.send(result); + }) + } + Job::Install(request, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .install_chat(*request, proof) + .await; + let _ = reply.send(result); + }), + Job::Snapshot(binding, operation, digest, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .query_snapshot(*binding, operation, digest, proof) + .await; + let _ = reply.send(result); + }), + Job::Claim(request, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .claim_issuance(*request, proof) + .await; + let _ = reply.send(result); + }), + Job::Attempt(request, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .query_issuance(*request, proof) + .await; + let _ = reply.send(result); + }), + Job::Capture(selected, proof, evidence, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .capture_issuance(*selected, proof, *evidence) + .await; + let _ = reply.send(result); + }), + Job::Captured(request, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .query_captured(*request, proof) + .await; + let _ = reply.send(result); + }), + Job::BindPlan(binding, plan, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .bind_plan(*binding, plan, proof) + .await; + let _ = reply.send(result); + }), + Job::SigningPlan(binding, operation_id, digest, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .query_plan(*binding, operation_id, digest, proof) + .await; + let _ = reply.send(result); + }), + Job::Authenticate(selected, proof, reply) => Box::pin(async move { + let result = if *uncertain { + Err(WorkspaceError::RecoveryRequired) + } else if kind == Kind::SellerStock { + stock::authenticate( + connection, namespace, input, crypto, clock, &selected, &proof, + ) + .await + .map(|(_, binding)| binding) + } else { + authenticate( + connection, namespace, input, crypto, clock, &selected, &proof, + ) + .await + .map(|(_, binding)| binding) + }; + if result == Err(WorkspaceError::CommitUnknown) { + *uncertain = true; + } + let _ = reply.send(result); + }), + Job::Revoke(selected, proof, reply) => Box::pin(async move { + let result = if *uncertain { + Err(WorkspaceError::RecoveryRequired) + } else if kind == Kind::SellerStock { + stock::revoke( + connection, namespace, input, crypto, clock, &selected, &proof, + ) + .await + } else { + revoke( + connection, namespace, input, crypto, clock, &selected, &proof, + ) + .await + }; + if result == Err(WorkspaceError::CommitUnknown) { + *uncertain = true; + } + let _ = reply.send(result); + }), + Job::Admit(request, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .admit(*request, proof) + .await; + let _ = reply.send(result); + }), + Job::Operation(binding, operation_id, digest, proof, reply) => Box::pin(async move { + let result = Journal { + connection, + namespace, + selected: input, + crypto, + clock, + uncertain, + } + .query(*binding, operation_id, digest, proof) + .await; + let _ = reply.send(result); + }), + } +} diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -602,7 +602,7 @@ async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_c clock.release(); assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); store.close().await.unwrap(); - sqlx::query("PRAGMA user_version=16") + sqlx::query("PRAGMA user_version=17") .execute(&mut connection) .await .unwrap(); diff --git a/crates/storage_sqlite/tests/support/stock_envelope_port.rs b/crates/storage_sqlite/tests/support/stock_envelope_port.rs @@ -129,7 +129,7 @@ async fn envelope_ports_refuse_stock_without_original_work_and_ordinary_outbox_w .fetch_one(&mut connection) .await .unwrap(); - assert_eq!(catalog, 16); + assert_eq!(catalog, 17); assert_eq!(entries, 0); connection.close().await.unwrap(); assert!( diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -112,6 +112,7 @@ struct StockEnvelopeRetention { worker_charge_bytes: u32, capture_port: String, query_port: String, + recovery_port: String, original_preparation_plan_claim_seal_installation_required: bool, temporary_key_derivation_and_exact_decryption_required: bool, temporary_key_retained: bool, @@ -129,6 +130,7 @@ struct StockEnvelopeRetention { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct NativeSellerStockAuthority { + delivery: StockDelivery, envelope_retention: StockEnvelopeRetention, qualified_local_recovery: QualifiedLocalRecovery, source_payload_schemas: Vec<String>, @@ -224,6 +226,49 @@ struct NativeSellerStockAuthority { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct StockDelivery { + supported_catalogs: Vec<u16>, + retained_unsupported_catalogs: Vec<u16>, + attempt_journal_family: u16, + observation_journal_family: u16, + attempt_payload_version: u16, + observation_payload_version: u16, + attempt_body_max_bytes: u32, + observation_body_max_bytes: u32, + target_max: u16, + attempts_per_target: u16, + attempts_per_operation_max: u16, + observations_per_operation_max: u16, + observation_page_max: u16, + summary_target_max: u16, + worker_charge_bytes: u32, + storage_ports: Vec<String>, + original_stock_evidence_installation_outer_required: bool, + original_captured_route_and_current_write_policy_required: bool, + fresh_current_scoped_consent_grant_clock_required: bool, + installed_original_recovery_delivery_supported: bool, + fresh_claim_requires_confirmed_commit: bool, + existing_attempt_grants_dispatch: bool, + unknown_commit_grants_dispatch: bool, + query_grants_dispatch: bool, + first_complete_targets_and_criterion_immutable: bool, + ordinary_command_replays_existing_attempt: bool, + explicit_resume_claims_bounded_new_attempt: bool, + retries_use_original_outer_bytes: bool, + observation_nullable: bool, + original_credential_capture_requires_live_clock_or_grant: bool, + same_owner_obtained_material_reconciliation_required: bool, + first_observation_per_class_immutable: bool, + wrong_event_request_target_ack_rejected: bool, + protected_refs_indexes_complete_ancestry_required: bool, + final_transaction_witnesses_required: bool, + unbounded_attempt_or_observation_collections: bool, + physical_stock_effect: bool, + transport_inside_sql: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct AcceptancePreparation { shared_storage_port: String, shared_model_owner: String, @@ -640,13 +685,14 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { envelope.journal_family == 10 && envelope.payload_version == 1 && envelope.payload_prefix_bytes == 213 - && envelope.supported_catalogs == [16] + && envelope.supported_catalogs == [16, 17] && envelope.retained_unsupported_catalogs == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] && envelope.raw_max_bytes == 65536 && envelope.worker_charge_bytes == 1048576 && envelope.capture_port == "InventoryStore.capture_stock_envelope" && envelope.query_port == "InventoryStore.stock_envelope" + && envelope.recovery_port == "InventoryStore.reconcile_stock_envelope" && envelope.original_preparation_plan_claim_seal_installation_required && envelope.temporary_key_derivation_and_exact_decryption_required && !envelope.temporary_key_retained @@ -661,17 +707,68 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && !envelope.provider_io_inside_sql, "stock envelope retention drift", )?; + let delivery = &stock.delivery; + require( + delivery.supported_catalogs == [17] + && delivery.retained_unsupported_catalogs + == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + && delivery.attempt_journal_family == 11 + && delivery.observation_journal_family == 12 + && delivery.attempt_payload_version == 1 + && delivery.observation_payload_version == 1 + && delivery.attempt_body_max_bytes == 65536 + && delivery.observation_body_max_bytes == 16384 + && delivery.target_max == 16 + && delivery.attempts_per_target == 12 + && delivery.attempts_per_operation_max == 384 + && delivery.observations_per_operation_max == 2304 + && delivery.observation_page_max == 16 + && delivery.summary_target_max == 16 + && delivery.worker_charge_bytes == 1048576 + && delivery.storage_ports + == [ + "InventoryStore.prepare_stock_delivery_attempt", + "InventoryStore.stock_delivery_attempt", + "InventoryStore.stock_delivery_summary", + "InventoryStore.record_stock_delivery_observation", + "InventoryStore.reconcile_stock_delivery_observation", + "InventoryStore.stock_delivery_observations", + ] + && delivery.original_stock_evidence_installation_outer_required + && delivery.original_captured_route_and_current_write_policy_required + && delivery.fresh_current_scoped_consent_grant_clock_required + && delivery.installed_original_recovery_delivery_supported + && delivery.fresh_claim_requires_confirmed_commit + && !delivery.existing_attempt_grants_dispatch + && !delivery.unknown_commit_grants_dispatch + && !delivery.query_grants_dispatch + && delivery.first_complete_targets_and_criterion_immutable + && !delivery.ordinary_command_replays_existing_attempt + && delivery.explicit_resume_claims_bounded_new_attempt + && delivery.retries_use_original_outer_bytes + && delivery.observation_nullable + && !delivery.original_credential_capture_requires_live_clock_or_grant + && delivery.same_owner_obtained_material_reconciliation_required + && delivery.first_observation_per_class_immutable + && delivery.wrong_event_request_target_ack_rejected + && delivery.protected_refs_indexes_complete_ancestry_required + && delivery.final_transaction_witnesses_required + && !delivery.unbounded_attempt_or_observation_collections + && !delivery.physical_stock_effect + && !delivery.transport_inside_sql, + "stock delivery ownership or bounds drift", + )?; require( stock.capability_contract.id == "radroots.seller_stock.native_inventory" && stock.capability_contract.version == "1" && stock.scope == "seller_stock_owner" && stock.database == "stock_execution_v1.sqlite" && stock.lock == ".stock_execution_v1.lock" - && stock.schema_version == 16 + && stock.schema_version == 17 && stock.retained_enrollment_versions == [1] && stock.retained_inventory_versions - == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v16" + == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v17" && stock.public_source_payload_schemas == [ "radroots.seller_stock.public_source_event.v1", @@ -950,7 +1047,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.qualified_local_recovery.native_authorizer == "NativeWorkspace.authorize_stock_exact_replay" && stock.qualified_local_recovery.captured_replay == "local_replay_safe" - && stock.qualified_local_recovery.native_catalog == 16 + && stock.qualified_local_recovery.native_catalog == 17 && stock.qualified_local_recovery.worker_charge_bytes == 1048576 && stock .qualified_local_recovery @@ -1013,7 +1110,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.preparation_abort.unsupported_hosts_return == "capability_unavailable" && stock.preparation_abort.retained_payload_versions == [1] && stock.preparation_abort.retained_v1_requires_absent_claims - && stock.preparation_abort.claimed_cleanup_catalogs == [15, 16] + && stock.preparation_abort.claimed_cleanup_catalogs == [15, 16, 17] && stock.preparation_abort.untracked_claimed_catalogs == [13, 14] && stock.preparation_abort.per_recipient_proof_count == 2 && stock @@ -2381,6 +2478,64 @@ mod tests { } #[test] + fn stock_delivery_requires_fresh_confirmed_claims_and_bounded_original_outcomes() { + for (field, bad) in [ + ("supported_catalogs", json!([16, 17])), + ("attempt_journal_family", json!(10)), + ("observation_journal_family", json!(11)), + ("attempts_per_target", json!(13)), + ("observation_page_max", json!(1000)), + ("worker_charge_bytes", json!(65536)), + ( + "original_stock_evidence_installation_outer_required", + json!(false), + ), + ( + "original_captured_route_and_current_write_policy_required", + json!(false), + ), + ( + "fresh_current_scoped_consent_grant_clock_required", + json!(false), + ), + ("fresh_claim_requires_confirmed_commit", json!(false)), + ("existing_attempt_grants_dispatch", json!(true)), + ("unknown_commit_grants_dispatch", json!(true)), + ("query_grants_dispatch", json!(true)), + ( + "first_complete_targets_and_criterion_immutable", + json!(false), + ), + ("ordinary_command_replays_existing_attempt", json!(true)), + ("retries_use_original_outer_bytes", json!(false)), + ("observation_nullable", json!(false)), + ( + "original_credential_capture_requires_live_clock_or_grant", + json!(true), + ), + ( + "same_owner_obtained_material_reconciliation_required", + json!(false), + ), + ("first_observation_per_class_immutable", json!(false)), + ("wrong_event_request_target_ack_rejected", json!(false)), + ("final_transaction_witnesses_required", json!(false)), + ("unbounded_attempt_or_observation_collections", json!(true)), + ("physical_stock_effect", json!(true)), + ("transport_inside_sql", json!(true)), + ] { + assert!( + validate_bytes(&changed( + &format!("/native_seller_stock_authority/delivery/{field}"), + bad + )) + .is_err(), + "{field}" + ); + } + } + + #[test] fn initial_limits_and_exact_binding_economics_require_explicit_amendment() { for (pointer, bad) in [ ("/limits/public_event_bytes", json!(65537)),