lib

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

commit 26756c1823984a6c26210d46ee7dbd56b90e5e1e
parent 5517ffee7f45989c5645fc4537137b2708ed6196
Author: triesap <tyson@radroots.org>
Date:   Thu, 29 Oct 2026 02:18:18 +0000

execution: Deliver original stock acceptance through retained attempts

- Connect ordinary acceptance and signer-free resume to original envelope delivery.
- Retain obtained outers and complete transport results through failed drain and close.
- Refuse fresh delivery claims based on stale per-recipient attempt counts.
- Qualify native and Linux recovery, exact relay retries, contracts and generated APIs.

Diffstat:
Mcontracts/api_baselines/radroots_storage.txt | 2++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 4++++
Mcrates/execution/src/session/client_commerce.rs | 7++++---
Acrates/execution/src/session/commerce_delivery.rs | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/session/commerce_run.rs | 17+++++++++++++----
Acrates/execution/src/session/stock_delivery.rs | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/execution/src/session/stock_evidence.rs | 23+++++++++++++++++++++--
Mcrates/radroots/src/native_commerce_tests.rs | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcrates/radroots/src/native_refusal_tests.rs | 5++++-
Acrates/radroots/src/native_stock_delivery_tests.rs | 377+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/src/orders.rs | 8++++----
Mcrates/radroots/tests/fixtures/commerce_verification/README.md | 7+++++++
Mcrates/storage/src/inventory.rs | 2++
Mcrates/storage/src/inventory/delivery.rs | 16++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/delivery/graph.rs | 3+++
Mcrates/storage_sqlite/src/workspace/stock/delivery/operations.rs | 7+++++++
Mcrates/storage_sqlite/src/workspace/stock/public_source/delivery_boundaries_tests.rs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/architecture/decision_package.rs | 15+++++++++++++++
18 files changed, 1191 insertions(+), 40 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -1535,9 +1535,11 @@ pub fn radroots_storage::inventory::StockDeliveryObservationReceipt::fmt(&self, 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::expected_attempt_count(&self) -> core::option::Option<u16> 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 +pub fn radroots_storage::inventory::StockDeliveryRequest::with_expected_attempt_count(self, u16) -> core::result::Result<Self, radroots_storage::command::OperationError> 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 diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -507,6 +507,10 @@ "query_grants_dispatch": false, "first_complete_targets_and_criterion_immutable": true, "ordinary_command_replays_existing_attempt": false, + "ordinary_fresh_claim_binds_observed_attempt_count": true, + "ordinary_obtained_material_owner": "ClientSession.stock_captures", + "ordinary_peer_delivery_precedes_self_signing": true, + "installed_original_delivery_requires_signer": false, "explicit_resume_claims_bounded_new_attempt": true, "retries_use_original_outer_bytes": true, "observation_nullable": true, diff --git a/crates/execution/src/session/client_commerce.rs b/crates/execution/src/session/client_commerce.rs @@ -24,9 +24,10 @@ use radroots_storage::{ }; impl<H: SessionHost + 'static> ClientSession<H> { - /// Owns the original captured acceptance through T0/T1/S and initial T2. - /// The returned independent facts do not claim relay delivery or complete - /// self history. Missing IO leaves actual preparation pending without signing. + /// Owns original acceptance through T0/T1/S/T2 and bounded original delivery. + /// Inspect independent signing, installation and per-recipient relay facts; + /// relay acceptance never establishes buyer receipt or stock release. + /// Missing IO leaves actual preparation pending without signing. #[allow(clippy::too_many_arguments)] pub async fn accept_stock_order( &self, diff --git a/crates/execution/src/session/commerce_delivery.rs b/crates/execution/src/session/commerce_delivery.rs @@ -0,0 +1,203 @@ +//! Ordinary delivery uses the same protected original and fresh stock claims. +use super::*; +use crate::session::stock_evidence::DeliveryContext; +use radroots_storage::{ + command::DeliveryIntent, + inventory::{StockDeliveryAttemptOutcome, StockDeliveryRequest}, +}; +use radroots_transport::TargetSet; + +impl CommandRuntime { + #[allow(clippy::too_many_arguments)] + pub(super) async fn deliver_acceptance( + &self, + store: &Shared<dyn AcceptanceStore>, + inventory: &Shared<dyn InventoryStore>, + selection: &AcceptanceSelection, + proof: &AttachmentProof, + resources: &SigningResources, + recipient: radroots_domain::PublicKey, + mode: &RunMode, + ) -> crate::ExecutionResult<()> { + let fail = |e| { + crate::ExecutionFailure::from(Error::operation( + e, + OperationContext::retained(selection.operation), + )) + }; + // Shared by every acceptance task, including repeats and explicit resume. + // The store still owns cross-process writer exclusion and final witnesses. + let _creation = resources.stock_captures.delivery_serial.lock().await; + resources.stock_captures.ensure_ready().map_err(fail)?; + let current = store + .snapshot(selection.clone(), proof) + .await + .map_err(fail)?; + observe(selection, current.as_ref()).map_err(fail)?; + if current.aborted() || current.installation().is_none() { + return Ok(()); + } + let Some(evidence) = current + .recipients() + .iter() + .find(|v| v.recipient == recipient) + .and_then(|v| v.evidence) + else { + return Ok(()); + }; + let mut selection = selection.clone(); + selection.minimum = current.checkpoint(); + let index = current + .recipients() + .iter() + .position(|v| v.recipient == recipient) + .ok_or_else(|| fail(OperationError::RecoveryRequired))?; + // This fresh coherent snapshot already authenticates the delivery + // projection; do not repeat the entire protected-history read. + let state = current + .delivery() + .and_then(|values| values.get(index)) + .ok_or_else(|| fail(OperationError::UnsupportedOperation))?; + if state.acceptance_satisfied().map_err(fail)? + || (state.attempt_count() != 0 && matches!(mode, RunMode::Command)) + { + return Ok(()); + } + let route = current + .plan() + .and_then(|plan| plan.routes().iter().find(|v| v.participant() == recipient)) + .ok_or_else(|| fail(OperationError::RecoveryRequired))?; + let allowed = self.io.targets(route).map_err(fail)?; + let (targets, policy) = match state.original_intent() { + Some(original) => { + if original.targets().targets().iter().any(|target| { + !allowed + .targets() + .iter() + .any(|v| v.fingerprint() == target.fingerprint()) + }) { + return Err(fail(OperationError::UnverifiedApproval)); + } + (original.targets().clone(), original.policy().clone()) + } + None => (allowed, self.io.publication_policy()), + }; + let selected = targets + .targets() + .iter() + .filter(|target| { + !state.targets().iter().any(|v| { + v.target() == target.fingerprint() + && (v.accepted() || v.potential_attempts() >= 12) + }) + }) + .cloned() + .collect::<Vec<_>>(); + if selected.is_empty() { + return Ok(()); + } + let selected = + TargetSet::new(selected).map_err(|_| fail(OperationError::RecoveryRequired))?; + let context = || -> Result<DeliveryContext, OperationError> { + Ok(DeliveryContext { + selection: selection.clone(), + recipient, + store: inventory.clone(), + proof: copy(proof)?, + _lease: resources.lease.clone(), + }) + }; + let outer = match state.source() { + Some(source) => source, + None => { + let source = store + .signing_evidence(selection.clone(), evidence, proof) + .await + .map_err(fail)? + .ok_or_else(|| fail(OperationError::RecoveryRequired))?; + if source.receipt() != evidence { + return Err(fail(OperationError::RecoveryRequired)); + } + // Prepare credentials before wrapping, then register the obtained + // outer before another conversion or persistent write can fail. + let context = context().map_err(fail)?; + let candidate = source + .with_json(|raw| self.io.private_envelope(recipient, raw)) + .map_err(fail)?; + let observed = self + .io + .now() + .ok() + .and_then(|v| v.get().checked_mul(1000)) + .and_then(NonZeroU64::new); + let pending = resources + .stock_captures + .retain_envelope(context, candidate, observed); + resources.stock_captures.capture_envelope(&pending).await? + } + }; + let deadline = self + .io + .now() + .map_err(fail)? + .get() + .checked_add(30) + .and_then(|v| v.checked_mul(1000)) + .and_then(NonZeroU64::new) + .ok_or_else(|| fail(OperationError::RecoveryRequired))?; + let intent = DeliveryIntent::new( + &self.io.delivery_id().map_err(fail)?, + outer.event_id(), + &targets, + &policy, + deadline, + ) + .and_then(|v| v.with_selection(&selected)) + .map_err(fail)?; + let context = context().map_err(fail)?; + // The original outer's capture checkpoint is historical metadata. Use + // the authenticated current selection, including authorization state. + let request = StockDeliveryRequest::new( + selection.binding.clone(), + selection.minimum, + selection.operation, + selection.digest, + recipient, + intent.clone(), + ) + .and_then(|request| request.with_expected_attempt_count(state.attempt_count())) + .map_err(fail)?; + let attempt = match inventory + .prepare_stock_delivery_attempt(request, copy(proof).map_err(fail)?) + .await + .map_err(fail)? + { + StockDeliveryAttemptOutcome::Claimed(attempt) => attempt, + StockDeliveryAttemptOutcome::Retained(_) => return Ok(()), + StockDeliveryAttemptOutcome::Unknown { .. } => { + return Err(fail(OperationError::RecoveryRequired)); + } + }; + if attempt.intent() != &intent || attempt.source().receipt() != outer { + return Err(fail(OperationError::RecoveryRequired)); + } + let result = self + .io + .publish( + attempt.transport_request().map_err(fail)?, + attempt.intent().selected_target_set().map_err(fail)?, + ) + .await; + let observed = self + .io + .now() + .ok() + .and_then(|v| v.get().checked_mul(1000)) + .and_then(NonZeroU64::new); + let pending = resources + .stock_captures + .retain_delivery(context, attempt, result, observed); + resources.stock_captures.capture_delivery(&pending).await?; + Ok(()) + } +} diff --git a/crates/execution/src/session/commerce_run.rs b/crates/execution/src/session/commerce_run.rs @@ -1,4 +1,4 @@ -//! One shared T1/S/T2 algorithm; target hosts implement transactions only. +//! One shared T1/S/T2/D algorithm; target hosts implement transactions only. use super::*; use crate::{ Error, OperationContext, @@ -20,6 +20,8 @@ use radroots_signing::{ recovery::ReplayCapability, }; use radroots_storage::inventory::{InventoryStore, StockEvidenceOutcome}; +#[path = "commerce_delivery.rs"] +mod delivery; fn same(attempt: CommitAttempt, selection: &AcceptanceSelection) -> bool { attempt.workspace_id() == selection.binding.input().workspace_id() @@ -210,10 +212,10 @@ impl CommandRuntime { } self.drain().await?; resources.stock_captures.ensure_ready().map_err(fail)?; - let Some(signer) = resources.signer.as_ref() else { - return Ok(status); - }; if snapshot.plan().is_none() { + let Some(signer) = resources.signer.as_ref() else { + return Ok(status); + }; let plan = self .acceptance_plan(snapshot.preparation(), signer) .await @@ -255,6 +257,9 @@ impl CommandRuntime { .find(|v| v.recipient == recipient) .ok_or_else(|| fail(OperationError::RecoveryRequired))?; if facts.evidence.is_none() { + let Some(signer) = resources.signer.as_ref() else { + continue; + }; resources.stock_captures.ensure_ready().map_err(fail)?; let plan = current .plan() @@ -460,6 +465,10 @@ impl CommandRuntime { } } } + self.deliver_acceptance( + &store, &inventory, &selection, proof, &resources, recipient, &mode, + ) + .await?; } let final_view = store .snapshot(selection.clone(), proof) diff --git a/crates/execution/src/session/stock_delivery.rs b/crates/execution/src/session/stock_delivery.rs @@ -0,0 +1,273 @@ +//! Original obtained outers and complete transport results share stock ownership. +use super::*; +use crate::session::commerce::AcceptanceSelection; +use alloc::boxed::Box; +use core::num::NonZeroU64; +use radroots_domain::PublicKey; +use radroots_storage::{command::PrivateEnvelopeCandidate, inventory::*}; +use radroots_transport::{DeliveryReceipt, SinkFailure}; + +pub(in crate::session) struct DeliveryContext { + pub selection: AcceptanceSelection, + pub recipient: PublicKey, + pub store: Shared<dyn InventoryStore>, + pub proof: AttachmentProof, + pub _lease: Shared<dyn HostBound>, +} +impl DeliveryContext { + fn error(&self, reason: OperationError) -> Error { + Error::capture_pending(reason, OperationContext::retained(self.selection.operation)) + } + fn request( + &self, + observed: Option<NonZeroU64>, + ) -> Result<StockEnvelopeRequest, OperationError> { + StockEnvelopeRequest::new( + self.selection.binding.clone(), + self.selection.minimum, + self.selection.operation, + self.selection.digest, + self.recipient, + observed, + ) + } + fn proof(&self) -> Result<AttachmentProof, OperationError> { + self.proof + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .map_err(Into::into) + } +} +pub(in crate::session) struct RetainedEnvelope { + context: DeliveryContext, + candidate: PrivateEnvelopeCandidate, + observed: Option<NonZeroU64>, + receipt: Mutex<Option<StockEnvelopeReceipt>>, +} +pub(in crate::session) struct RetainedDelivery { + context: DeliveryContext, + attempt: Box<StockDeliveryAttempt>, + result: Result<DeliveryReceipt, SinkFailure>, + observed: Option<NonZeroU64>, + complete: Mutex<bool>, +} +impl Owner { + pub(in crate::session) fn retain_envelope( + &self, + context: DeliveryContext, + candidate: PrivateEnvelopeCandidate, + observed: Option<NonZeroU64>, + ) -> Shared<RetainedEnvelope> { + let entry = Shared::new(RetainedEnvelope { + context, + candidate, + observed, + receipt: Mutex::new(None), + }); + self.envelopes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(entry.clone()); + entry + } + pub(in crate::session) async fn capture_envelope( + &self, + entry: &Shared<RetainedEnvelope>, + ) -> crate::Result<StockEnvelopeReceipt> { + let _serial = self.serial.lock().await; + self.append_envelope(entry, false).await + } + async fn append_envelope( + &self, + entry: &Shared<RetainedEnvelope>, + reconciling: bool, + ) -> crate::Result<StockEnvelopeReceipt> { + let c = &entry.context; + if let Some(receipt) = *entry + .receipt + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + return Ok(receipt); + } + let request = c.request(entry.observed).map_err(|e| c.error(e))?; + let proof = c.proof().map_err(|e| c.error(e))?; + let outcome = if reconciling { + c.store + .reconcile_stock_envelope(request, proof, &entry.candidate) + .await + } else { + c.store + .capture_stock_envelope(request, proof, &entry.candidate) + .await + } + .map_err(|e| c.error(e))?; + let StockEnvelopeOutcome::Committed(receipt) = outcome else { + return Err(c.error(OperationError::RecoveryRequired)); + }; + let anchor = receipt.attempt(); + if anchor.workspace_id() != c.selection.binding.input().workspace_id() + || anchor.operation_id() != c.selection.operation + || anchor.command_digest() != c.selection.digest + || anchor.transaction_id().is_none() + || receipt.recipient() != c.recipient + || receipt.event_id() != entry.candidate.event_id() + || receipt.digest() != entry.candidate.digest() + || receipt.checkpoint().authority() != c.selection.minimum.authority() + { + return Err(c.error(OperationError::RecoveryRequired)); + } + *entry + .receipt + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(*receipt); + let removed = { + let mut entries = self + .envelopes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + entries + .iter() + .position(|v| Shared::ptr_eq(v, entry)) + .map(|i| entries.remove(i)) + }; + drop(removed); + Ok(*receipt) + } + pub(in crate::session) fn retain_delivery( + &self, + context: DeliveryContext, + attempt: Box<StockDeliveryAttempt>, + result: Result<DeliveryReceipt, SinkFailure>, + observed: Option<NonZeroU64>, + ) -> Shared<RetainedDelivery> { + // No descriptor conversion or storage call precedes registration. Even + // malformed adapter reports retain the original result and byte lease. + let entry = Shared::new(RetainedDelivery { + context, + attempt, + result, + observed, + complete: Mutex::new(false), + }); + self.deliveries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .push(entry.clone()); + entry + } + pub(in crate::session) async fn capture_delivery( + &self, + entry: &Shared<RetainedDelivery>, + ) -> crate::Result<()> { + let _serial = self.serial.lock().await; + self.append_delivery(entry, false).await + } + async fn append_delivery( + &self, + entry: &Shared<RetainedDelivery>, + reconciling: bool, + ) -> crate::Result<()> { + let c = &entry.context; + if *entry + .complete + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + { + return Ok(()); + } + let request = entry.attempt.transport_request().map_err(|e| c.error(e))?; + let reports = match &entry.result { + Ok(receipt) => { + receipt + .validate_for_request(&request) + .map_err(|_| c.error(OperationError::InvalidEvidence))?; + receipt.target_receipts() + } + Err(failure) => { + failure + .validate_for_request(&request) + .map_err(|_| c.error(OperationError::InvalidEvidence))?; + failure.partial_evidence() + } + }; + // Bound before allocating normalized copies and validate the entire + // original result before the first write. Empty partial evidence stays + // empty: a missing ACK never manufactures a target observation. + let intent = entry.attempt.intent(); + if reports.len() > intent.targets().len() + || reports.iter().any(|report| { + report.was_attempted() + && !intent.selection().contains(report.target().fingerprint()) + }) + { + return Err(c.error(OperationError::InvalidEvidence)); + } + let observations = reports + .iter() + .filter(|report| intent.selection().contains(report.target().fingerprint())) + .map(|report| { + StockDeliveryObservation::from_store_report(&entry.attempt, report, entry.observed) + }) + .collect::<Result<Vec<_>, _>>() + .map_err(|e| c.error(e))?; + for observation in &observations { + let result = if reconciling { + c.store + .reconcile_stock_delivery_observation( + &c.selection.binding, + &c.proof, + observation, + ) + .await + } else { + c.store + .record_stock_delivery_observation(&c.selection.binding, &c.proof, observation) + .await + } + .map_err(|e| c.error(e))?; + match result { + StockDeliveryObservationOutcome::Committed(receipt) + if receipt.observation() == observation => {} + _ => return Err(c.error(OperationError::RecoveryRequired)), + } + } + *entry + .complete + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = true; + let removed = { + let mut entries = self + .deliveries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + entries + .iter() + .position(|v| Shared::ptr_eq(v, entry)) + .map(|i| entries.remove(i)) + }; + drop(removed); + Ok(()) + } + pub(super) async fn drain_delivery(&self) -> crate::Result<()> { + loop { + let entry = self + .envelopes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .first() + .cloned(); + let Some(entry) = entry else { break }; + self.append_envelope(&entry, true).await?; + } + loop { + let entry = self + .deliveries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .first() + .cloned(); + let Some(entry) = entry else { return Ok(()) }; + self.append_delivery(&entry, true).await?; + } + } +} diff --git a/crates/execution/src/session/stock_evidence.rs b/crates/execution/src/session/stock_evidence.rs @@ -13,6 +13,9 @@ pub(super) use obtained::{ObtainedContext, RetainedObtained}; #[path = "stock_unissued.rs"] mod unissued; pub(super) use unissued::RetainedUnissued; +#[path = "stock_delivery.rs"] +mod delivery; +pub(super) use delivery::{DeliveryContext, RetainedDelivery, RetainedEnvelope}; pub(super) struct Pending { store: Shared<dyn InventoryStore>, @@ -26,6 +29,9 @@ pub(super) struct Owner { unmapped: Mutex<Vec<Shared<RetainedObtained>>>, pending: Mutex<Vec<Shared<Pending>>>, unissued: Mutex<Vec<Shared<RetainedUnissued>>>, + envelopes: Mutex<Vec<Shared<RetainedEnvelope>>>, + deliveries: Mutex<Vec<Shared<RetainedDelivery>>>, + pub(super) delivery_serial: futures::lock::Mutex<()>, serial: futures::lock::Mutex<()>, } impl Owner { @@ -44,7 +50,20 @@ impl Owner { .unissued .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if pending.is_empty() && unmapped.is_empty() && unissued.is_empty() { + let envelopes = self + .envelopes + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let deliveries = self + .deliveries + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if pending.is_empty() + && unmapped.is_empty() + && unissued.is_empty() + && envelopes.is_empty() + && deliveries.is_empty() + { Ok(()) } else { Err(OperationError::RecoveryRequired) @@ -192,7 +211,7 @@ impl Owner { .first() .cloned(); let Some(entry) = entry else { - return Ok(()); + return self.drain_delivery().await; }; if let StockEvidenceOutcome::Unknown(_) = self.append(&entry, true).await? { return Err(Error::operation( diff --git a/crates/radroots/src/native_commerce_tests.rs b/crates/radroots/src/native_commerce_tests.rs @@ -1,5 +1,6 @@ //! Real facade, SQLx and local crypto with explicitly controlled command IO. -//! This is no live Nostr transport or host-custody qualification. +//! Delivery cases additionally exercise explicit loopback Nostr transport. +//! Host custody and live route discovery remain outside these fixtures. use super::{Client, NativeConfig, StartMode}; use radroots_domain::{CommandContextData, OperationId, PoolId, PublicKey, UnixSeconds}; use radroots_execution::{ @@ -74,10 +75,23 @@ fn proof(value: &AttachmentProof) -> AttachmentProof { .with_secret(|b| AttachmentProof::from_protected_input(b)) .unwrap() } -struct Clock(AtomicU64); +struct Clock(AtomicU64, AtomicBool); +impl Clock { + fn enable_realtime(&self) { + self.1.store(true, Ordering::SeqCst); + } +} impl WorkspaceClock for Clock { fn now(&self) -> Result<UnixSeconds, WorkspaceError> { - UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable) + let seconds = if self.1.load(Ordering::SeqCst) { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| WorkspaceError::Unavailable)? + .as_secs() + } else { + self.0.load(Ordering::SeqCst) + }; + UnixSeconds::new(seconds).map_err(|_| WorkspaceError::Unavailable) } } struct Control { @@ -232,7 +246,44 @@ impl SignerCallbacks for Callbacks { Box::pin(async { Ok(()) }) } } -struct Io(Arc<Clock>); +struct Io { + clock: Arc<Clock>, + next: AtomicUsize, + wraps: AtomicUsize, + sent: std::sync::Mutex<Vec<String>>, + missing_ack: AtomicBool, + pause_delivery: AtomicBool, + entered: tokio::sync::Notify, + release: tokio::sync::Notify, + route_override: Option<Vec<String>>, + transport: std::sync::Mutex<Option<Arc<radroots_transport_nostr::NostrTransport>>>, +} +impl Io { + fn new(clock: Arc<Clock>) -> Self { + Self { + clock, + next: AtomicUsize::new(1), + wraps: AtomicUsize::new(0), + sent: std::sync::Mutex::new(Vec::new()), + missing_ack: AtomicBool::new(false), + pause_delivery: AtomicBool::new(false), + entered: tokio::sync::Notify::new(), + release: tokio::sync::Notify::new(), + route_override: None, + transport: std::sync::Mutex::new(None), + } + } + fn selected(&self) -> TargetSet { + self.route_override.as_ref().map_or_else(targets, |uris| { + TargetSet::new( + uris.iter() + .map(|uri| Target::nostr_relay(uri).unwrap()) + .collect(), + ) + .unwrap() + }) + } +} fn targets() -> TargetSet { TargetSet::new(vec![Target::nostr_relay("wss://relay.example").unwrap()]).unwrap() } @@ -241,7 +292,7 @@ impl CommandIo for Io { true } fn now(&self) -> Result<UnixSeconds, OperationError> { - self.0.now().map_err(Into::into) + self.clock.now().map_err(Into::into) } fn seal_time(&self, now: UnixSeconds) -> Result<UnixSeconds, OperationError> { Ok(now) @@ -252,6 +303,28 @@ impl CommandIo for Io { _: NonZeroU64, ) -> HostFuture<'_, Result<CapturedDmRoute, OperationError>> { Box::pin(async move { + if let Some(uris) = &self.route_override { + use nostr::JsonUtil; + let keys = [2, 3] + .into_iter() + .map(|scalar| { + nostr::Keys::new( + nostr::SecretKey::from_hex(&format!("{scalar:064x}")).unwrap(), + ) + }) + .find(|key| key.public_key().to_hex() == recipient.to_hex()) + .unwrap(); + let raw = nostr::EventBuilder::new(nostr::Kind::Custom(10050), "") + .tags( + uris.iter() + .map(|uri| nostr::Tag::parse(["relay", uri.as_str()]).unwrap()), + ) + .custom_created_at(nostr::Timestamp::from_secs(100)) + .sign_with_keys(&keys) + .unwrap() + .as_json(); + return capture_dm_route(recipient, [raw.as_str()], &self.selected()); + } let value = data(); let row = value["stock_routes"] .as_array() @@ -263,28 +336,70 @@ impl CommandIo for Io { }) } fn targets(&self, route: &CapturedDmRoute) -> Result<TargetSet, OperationError> { - selected_dm_targets(route, &targets()) + selected_dm_targets(route, &self.selected()) } fn publication_policy(&self) -> radroots_transport::policy::SatisfactionPolicy { - panic!("acceptance does not start D") + use radroots_transport::policy::{SatisfactionClass, SatisfactionPolicy, TargetPolicy}; + SatisfactionPolicy::new(SatisfactionClass::Accepted, TargetPolicy::all()) } fn private_envelope( &self, - _: PublicKey, - _: &str, + recipient: PublicKey, + raw: &str, ) -> Result<PrivateEnvelopeCandidate, OperationError> { - panic!("acceptance does not wrap") + self.wraps.fetch_add(1, Ordering::SeqCst); + let wrapped = radroots_nostr::signing::gift_wrap::wrap_retained_seal( + raw, + recipient, + NonZeroU64::new(self.now()?.get()).unwrap(), + &radroots_nostr::signing::OsNonceSource, + ) + .map_err(|_| OperationError::InvalidEvidence)?; + wrapped.with_wrapping_key(|key| { + PrivateEnvelopeCandidate::from_obtained(recipient, wrapped.signed_json(), key) + }) } fn delivery_id(&self) -> Result<String, OperationError> { - panic!("acceptance does not claim D") + Ok(format!("{:064x}", self.next.fetch_add(1, Ordering::SeqCst))) } fn publish( &self, - _: radroots_transport::sink::DeliveryRequest, - _: TargetSet, + request: radroots_transport::sink::DeliveryRequest, + selected: TargetSet, ) -> HostFuture<'_, Result<radroots_transport::DeliveryReceipt, radroots_transport::SinkFailure>> { - panic!("acceptance does not publish") + Box::pin(async move { + self.sent + .lock() + .unwrap() + .push(request.payload().event().raw_json().to_owned()); + if self.pause_delivery.swap(false, Ordering::SeqCst) { + self.entered.notify_one(); + self.release.notified().await; + } + let transport = self.transport.lock().unwrap().clone(); + if let Some(transport) = transport { + use radroots_transport::EventSink; + return transport.deliver_selected(request, selected).await; + } + use radroots_transport::{ + DeliveryReceipt, outcome::DeliveryOutcome, sink::DeliveryTargetReceipt, + }; + let outcome = if self.missing_ack.load(Ordering::SeqCst) { + DeliveryOutcome::unavailable() + } else { + DeliveryOutcome::accepted() + }; + Ok(DeliveryReceipt::for_request( + &request, + selected + .targets() + .iter() + .map(|target| DeliveryTargetReceipt::attempted(target.clone(), outcome.clone())) + .collect(), + ) + .unwrap()) + }) } } struct Rig { @@ -297,9 +412,13 @@ struct Rig { clock: Arc<Clock>, control: Arc<Control>, provider: Weak<Provider>, + io: Arc<Io>, } impl Rig { async fn new() -> Self { + Self::configured(None, 300).await + } + async fn configured(route: Option<Vec<String>>, expiry: u64) -> Self { let temp = tempfile::tempdir().unwrap(); let root = temp.path().canonicalize().unwrap(); let vault = Arc::new( @@ -329,7 +448,7 @@ impl Rig { AccessPolicy::standard(), ) .unwrap(); - let clock = Arc::new(Clock(AtomicU64::new(150))); + let clock = Arc::new(Clock(AtomicU64::new(150), AtomicBool::new(false))); let control = Arc::new(Control::new()); let provider = Arc::new(Provider { inner: LocalSigner::with_clock( @@ -347,7 +466,7 @@ impl Rig { key, key, "synthetic-ordinary-acceptance", - UnixSeconds::new(300).unwrap(), + UnixSeconds::new(expiry).unwrap(), ) .unwrap(), clock.as_ref(), @@ -374,10 +493,13 @@ impl Rig { .unwrap(); // Only IO is controlled. This preserves the actual client task host, // attached scopes, stock evidence owner and concrete native adapter. + let mut io = Io::new(clock.clone()); + io.route_override = route; + let io = Arc::new(io); client.session = client .session .clone() - .with_command_runtime(Arc::new(CommandRuntime::new(Arc::new(Io(clock.clone()))))); + .with_command_runtime(Arc::new(CommandRuntime::new(io.clone()))); let scope = client .attach(enrollment.input().clone(), proof(enrollment.proof())) .await @@ -398,6 +520,7 @@ impl Rig { clock, control, provider: weak, + io, }; rig.seed().await; rig @@ -605,6 +728,7 @@ async fn ordinary_acceptance_uses_real_t0_t1_s_t2_and_preserves_original_retry() assert!(status.installation().is_some()); assert!(status.recipients().iter().all(|v| v.evidence.is_some())); assert_eq!(r.control.signs.load(Ordering::SeqCst), 2); + assert_eq!(r.io.sent.lock().unwrap().len(), 2); let (_, _, minimum) = r.minima().await; let observed = r .client @@ -613,13 +737,13 @@ 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. + // Actual protected stock delivery uses controlled transport outcomes here. + // S remains independently readable through the same native owner. assert!(observed.delivery().unwrap().iter().all(|value| { value.checkpoint() == observed.checkpoint() - && value.source().is_none() - && value.attempt_count() == 0 + && value.source().is_some() + && value.attempt_count() == 1 + && value.acceptance_satisfied().unwrap() })); let evidence = observed.recipients()[0].evidence.unwrap(); let source = radroots_execution::session::commerce::AcceptanceStore::signing_evidence( @@ -793,6 +917,8 @@ async fn lost_observer_cannot_discard_actual_peer_artifact_and_close_installs_be reopened.close().await.unwrap(); } +#[path = "native_stock_delivery_tests.rs"] +mod delivery; #[path = "native_refusal_tests.rs"] mod original_refusals; @@ -813,6 +939,17 @@ async fn peer_installation_survives_self_refusal_and_resume_uses_original_exact_ 1 ); assert!(!status.aborted()); + assert_eq!(r.io.sent.lock().unwrap().len(), 1); + for (delivery, recipient) in status.delivery().unwrap().iter().zip(status.recipients()) { + assert_eq!( + delivery.attempt_count(), + u16::from(recipient.evidence.is_some()) + ); + assert_eq!( + delivery.acceptance_satisfied().unwrap(), + recipient.evidence.is_some() + ); + } let original_refusal = status .recipients() .iter() @@ -1091,6 +1228,17 @@ async fn rejected_self_callback_returns_bounded_tampering_without_losing_peer_in 1 ); assert!(!status.aborted()); + assert_eq!(r.io.sent.lock().unwrap().len(), 1); + for (delivery, recipient) in status.delivery().unwrap().iter().zip(status.recipients()) { + assert_eq!( + delivery.attempt_count(), + u16::from(recipient.evidence.is_some()) + ); + assert_eq!( + delivery.acceptance_satisfied().unwrap(), + recipient.evidence.is_some() + ); + } r.control.tamper_self.store(false, Ordering::SeqCst); let resumed = r .client @@ -1148,10 +1296,13 @@ async fn generic_inquiry_installs_actual_peer_and_returns_original_bounded_self_ let mut client = Client::open(NativeConfig::public_read(options).with_workspace(native)) .await .unwrap(); - client.session = client - .session - .clone() - .with_command_runtime(Arc::new(CommandRuntime::new(Arc::new(Io(r.clock.clone()))))); + client.session = + client + .session + .clone() + .with_command_runtime(Arc::new(CommandRuntime::new(Arc::new(Io::new( + r.clock.clone(), + ))))); let scope = client.attach(input, proof(&credential)).await.unwrap(); client .attach_signer(SignerHandle::new( diff --git a/crates/radroots/src/native_refusal_tests.rs b/crates/radroots/src/native_refusal_tests.rs @@ -208,8 +208,11 @@ async fn lost_refusal_waiter_and_failed_close_retain_owner_through_rollback_and_ .accept(context, minimum, private, public, input) .await }); + // Ordinary acceptance now retains and delivers the installed peer + // before reaching this self-signing barrier. Keep the same assertions + // while bounding observation of that larger debug-build prefix. tokio::time::timeout( - std::time::Duration::from_secs(20), + std::time::Duration::from_secs(120), r.control.entered.notified(), ) .await diff --git a/crates/radroots/src/native_stock_delivery_tests.rs b/crates/radroots/src/native_stock_delivery_tests.rs @@ -0,0 +1,377 @@ +//! Ordinary stock delivery and original-material recovery against real SQLx. +use super::*; + +#[tokio::test] +async fn obtained_outer_is_retained_through_failed_sql_capture_and_clockless_drain() { + use sqlx::Connection; + let r = Rig::new().await; + r.control.pause_peer.store(true, Ordering::SeqCst); + let (command, context) = r.captured().await; + let (private, public, minimum) = r.minima().await; + let input = AcceptOrderInput::new( + command.input().request(), + command.input().terms_digest(), + AllocationSelection::automatic(), + ); + let client = r.client.clone(); + let scope = r.scope.clone(); + let waiter = tokio::spawn(async move { + client + .orders(&scope) + .accept(context, minimum, private, public, input) + .await + }); + tokio::time::timeout( + std::time::Duration::from_secs(30), + r.control.entered.notified(), + ) + .await + .unwrap(); + let path = r._temp.path().join("stock/stock_execution_v1.sqlite"); + let mut fault = sqlx::SqliteConnection::connect(&format!("sqlite://{}", path.display())) + .await + .unwrap(); + sqlx::query("CREATE TRIGGER controlled_outer_failure BEFORE INSERT ON stock_envelopes BEGIN SELECT RAISE(ABORT, 'controlled_outer_failure'); END").execute(&mut fault).await.unwrap(); + r.control.release.notify_one(); + let error = waiter.await.unwrap().unwrap_err(); + assert_eq!(error.code(), crate::Code::StorageFailure); + assert_eq!(r.io.wraps.load(Ordering::SeqCst), 1); + assert!(r.io.sent.lock().unwrap().is_empty()); + sqlx::query("DROP TRIGGER controlled_outer_failure") + .execute(&mut fault) + .await + .unwrap(); + fault.close().await.unwrap(); + r.clock.0.store(0, Ordering::SeqCst); + r.client.stock(&r.scope).drain_evidence().await.unwrap(); + assert_eq!(r.io.wraps.load(Ordering::SeqCst), 1); + r.clock.0.store(150, Ordering::SeqCst); + let resumed = r + .client + .orders(&r.scope) + .resume_acceptance(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap(); + assert!( + resumed + .delivery() + .unwrap() + .iter() + .all(|v| v.acceptance_satisfied().unwrap()) + ); + assert_eq!(r.io.wraps.load(Ordering::SeqCst), 2); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 2); + r.client.close().await.unwrap(); +} + +#[tokio::test] +async fn recovery_delivers_original_stock_outers_through_actual_loopback_transport() { + use futures::{SinkExt, StreamExt}; + use radroots_transport_nostr::{ + Config, RelayAccess, RelayEndpoint, RelayProfile, RelayProfileKind, RelayUrlPolicy, + }; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + use tokio_tungstenite::{accept_async, tungstenite::Message}; + async fn relay(listener: tokio::net::TcpListener, originals: Vec<String>, misses: usize) { + let (tcp, _) = listener.accept().await.unwrap(); + let mut socket = accept_async(tcp).await.unwrap(); + for index in 0..(2 + misses) { + let raw = tokio::time::timeout(Duration::from_secs(300), async { + loop { + if let Message::Text(raw) = socket.next().await.unwrap().unwrap() { + break raw; + } + } + }) + .await + .unwrap(); + let original = &originals[index % 2]; + assert_eq!(raw.as_str(), format!("[\"EVENT\",{original}]")); + let event: serde_json::Value = serde_json::from_str(original).unwrap(); + socket + .send(Message::Text( + serde_json::json!(["OK", "ff".repeat(32), true, ""]) + .to_string() + .into(), + )) + .await + .unwrap(); + if index >= misses { + socket + .send(Message::Text( + serde_json::json!(["OK", event["id"], true, ""]) + .to_string() + .into(), + )) + .await + .unwrap(); + } + } + } + let first_relay = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let second_relay = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let uris = vec![ + format!("ws://{}", first_relay.local_addr().unwrap()), + format!("ws://{}", second_relay.local_addr().unwrap()), + ]; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let r = Rig::configured(Some(uris.clone()), now + 1800).await; + r.io.missing_ack.store(true, Ordering::SeqCst); + let (command, first) = r.accept().await; + let originals = r.io.sent.lock().unwrap().clone(); + assert_eq!(originals.len(), 2); + let accepted = tokio::spawn(relay(first_relay, originals.clone(), 0)); + let partial = tokio::spawn(relay(second_relay, originals.clone(), 2)); + let config = Config::from_profile( + RelayProfile::explicit( + RelayProfileKind::Simulator, + uris.iter().map(|uri| { + RelayEndpoint::new(uri, RelayUrlPolicy::Local, RelayAccess::ReadWrite).unwrap() + }), + ) + .unwrap(), + ) + .with_timeouts(1000, 1000, 500) + .unwrap(); + let transport = Arc::new(radroots_transport_nostr_native::create_transport(config)); + *r.io.transport.lock().unwrap() = Some(transport.clone()); + // Real transport uses advancing UTC; only this injected test clock follows + // it. Retained source events, S and original outers remain unchanged. + r.clock.enable_realtime(); + let (_, _, minimum) = r.minima().await; + let grant = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(r.enrollment.input()), + "loopback recovery".into(), + UnixSeconds::new(now + 1500).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + r.native + .enroll_stock_grant( + r.scope.binding().clone(), + minimum, + r.enrollment.proof(), + &grant, + ) + .await + .unwrap(); + let (_, _, minimum) = r.minima().await; + let capture = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + grant.input().grant_id(), + StockConsentMode::RecoverOnly, + StockResources::all_pools(), + UnixSeconds::new(now + 1200).unwrap(), + CapturedOrderAcceptance::parse(command.protected_wire()).unwrap(), + ) + .unwrap(); + r.native + .issue_stock_consent( + r.scope.binding().clone(), + minimum, + &capture, + r.enrollment.proof(), + ) + .await + .unwrap(); + let (_, _, minimum) = r.minima().await; + let recovery = r + .client + .attach(grant.input().clone(), proof(grant.proof())) + .await + .unwrap(); + let incomplete = r + .client + .orders(&recovery) + .resume_acceptance(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap(); + for state in incomplete.delivery().unwrap() { + assert_eq!(state.attempt_count(), 2); + assert!(!state.acceptance_satisfied().unwrap()); + assert_eq!( + state + .targets() + .iter() + .filter(|target| target.accepted()) + .count(), + 1 + ); + } + let resumed = r + .client + .orders(&recovery) + .resume_acceptance( + incomplete.checkpoint(), + command.context().operation_id(), + command.digest(), + ) + .await + .unwrap(); + assert_eq!(resumed.installation(), first.installation()); + for state in resumed.delivery().unwrap() { + assert_eq!(state.attempt_count(), 3); + assert!(state.acceptance_satisfied().unwrap()); + let mut counts: Vec<_> = state + .targets() + .iter() + .map(|v| v.potential_attempts()) + .collect(); + counts.sort(); + assert_eq!(counts, [2, 3]); + } + let sent = r.io.sent.lock().unwrap().clone(); + assert_eq!(&sent[2..4], originals.as_slice()); + assert_eq!(&sent[4..6], originals.as_slice()); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 2); + tokio::time::timeout(Duration::from_secs(10), accepted) + .await + .unwrap() + .unwrap(); + tokio::time::timeout(Duration::from_secs(10), partial) + .await + .unwrap() + .unwrap(); + transport.shutdown().await; + r.client.close().await.unwrap(); +} + +#[tokio::test] +async fn repeated_command_does_not_resend_and_signerless_resume_uses_exact_originals() { + let r = Rig::new().await; + r.io.missing_ack.store(true, Ordering::SeqCst); + let (command, first) = r.accept().await; + assert!( + first + .delivery() + .unwrap() + .iter() + .all(|v| v.attempt_count() == 1 && !v.acceptance_satisfied().unwrap()) + ); + let original = r.io.sent.lock().unwrap().clone(); + assert_eq!(original.len(), 2); + let (private, public, minimum) = r.minima().await; + let context = r + .scope + .command_context( + command.context().operation_id(), + command.context().expected().cloned(), + command.context().approval().cloned(), + command.context().not_after(), + ) + .unwrap(); + let repeated = r + .client + .orders(&r.scope) + .accept( + context, + minimum, + private, + public, + AcceptOrderInput::new( + command.input().request(), + command.input().terms_digest(), + AllocationSelection::automatic(), + ), + ) + .await + .unwrap(); + assert_eq!(repeated.installation(), first.installation()); + assert_eq!(r.io.sent.lock().unwrap().len(), 2); + + let path = r._temp.path().join("recovery_cache"); + std::fs::create_dir(&path).unwrap(); + let options = OpenOptions::new(Paths::from_directory(&path).unwrap(), OpenMode::Create) + .with_source_generation(SourceGeneration::new([99; 32]).unwrap(), 1) + .unwrap(); + let mut recovery = + Client::open(NativeConfig::public_read(options).with_workspace(r.native.clone())) + .await + .unwrap(); + recovery.session = recovery + .session + .clone() + .with_command_runtime(Arc::new(CommandRuntime::new(r.io.clone()))); + let scope = recovery + .attach(r.enrollment.input().clone(), proof(r.enrollment.proof())) + .await + .unwrap(); + recovery.start(StartMode::LocalOnly).await.unwrap(); + assert!(recovery.signer_session().is_none()); + r.io.missing_ack.store(false, Ordering::SeqCst); + let resumed = recovery + .orders(&scope) + .resume_acceptance(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap(); + assert_eq!(resumed.installation(), first.installation()); + assert!( + resumed + .delivery() + .unwrap() + .iter() + .all(|v| v.attempt_count() == 2 && v.acceptance_satisfied().unwrap()) + ); + assert_eq!(&r.io.sent.lock().unwrap()[2..], original.as_slice()); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 2); + recovery.close().await.unwrap(); + r.client.close().await.unwrap(); +} + +#[tokio::test] +async fn obtained_delivery_survives_failed_append_lost_waiter_and_clock_loss() { + use sqlx::Connection; + let r = Rig::new().await; + r.io.pause_delivery.store(true, Ordering::SeqCst); + let (command, context) = r.captured().await; + let (private, public, minimum) = r.minima().await; + let input = AcceptOrderInput::new( + command.input().request(), + command.input().terms_digest(), + AllocationSelection::automatic(), + ); + let client = r.client.clone(); + let scope = r.scope.clone(); + let waiter = tokio::spawn(async move { + client + .orders(&scope) + .accept(context, minimum, private, public, input) + .await + }); + tokio::time::timeout(std::time::Duration::from_secs(30), r.io.entered.notified()) + .await + .unwrap(); + assert_eq!(r.io.sent.lock().unwrap().len(), 1); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 1); + waiter.abort(); + assert!(waiter.await.unwrap_err().is_cancelled()); + let path = r._temp.path().join("stock/stock_execution_v1.sqlite"); + let mut fault = sqlx::SqliteConnection::connect(&format!("sqlite://{}", path.display())) + .await + .unwrap(); + sqlx::query("CREATE TRIGGER controlled_d_failure BEFORE INSERT ON stock_delivery_observations BEGIN SELECT RAISE(ABORT, 'controlled_d_failure'); END").execute(&mut fault).await.unwrap(); + r.clock.0.store(0, Ordering::SeqCst); + r.io.release.notify_one(); + // Close drains the admitted task and then its retained raw result, keeping + // the original credential and resource lease through the actual SQL fault. + let error = r.client.close().await.unwrap_err(); + assert_eq!(error.code(), crate::Code::StorageFailure); + assert!(r.provider.upgrade().is_some()); + sqlx::query("DROP TRIGGER controlled_d_failure") + .execute(&mut fault) + .await + .unwrap(); + r.client.close().await.unwrap(); + assert!(r.provider.upgrade().is_none()); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_delivery_observations") + .fetch_one(&mut fault) + .await + .unwrap(); + assert_eq!(count, 1); + assert_eq!(r.io.sent.lock().unwrap().len(), 1); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 1); + fault.close().await.unwrap(); +} diff --git a/crates/radroots/src/orders.rs b/crates/radroots/src/orders.rs @@ -19,10 +19,10 @@ impl<'a> Orders<'a> { pub(crate) const fn new(client: &'a Client, scope: WorkspaceSession) -> Self { Self { client, scope } } - /// Owns captured acceptance through actual native T0/T1/S and initial T2. - /// Inspect independent recipient/installation facts; this performs no gift - /// wrapping or relay publication. Available command IO determines whether - /// preparation can proceed to signing; a pending report is not acceptance. + /// Owns captured acceptance through native T0/T1/S/T2 and original delivery. + /// Inspect independent signing, installation and relay observations. An + /// installed peer can reach delivery even if later self signing fails. + /// Available command IO controls progress; pending preparation is not acceptance. pub async fn accept( &self, context: CommandContext, diff --git a/crates/radroots/tests/fixtures/commerce_verification/README.md b/crates/radroots/tests/fixtures/commerce_verification/README.md @@ -7,3 +7,10 @@ Source: `crates/nostr/tests/fixtures/commerce_signing.v1.json`, SHA-256 `1d0a2e8 - `command_wire.json`: SHA-256 `885ad89e2ece65a4bf670a7df6d5c25b9ca3018d0bff60634f5489b7610f058d`. - `record_wire.json`: SHA-256 `c6cae54b2d00d8675bd8694fa2eb46df8e9133220c08d1ebf71da91baaca2beb`. - `plan_wire.bin`: SHA-256 `458840ff907b5d478ce4be792b2a5e0cfb76e15a699b329624ed352894c66ee2`. + +The ordinary loopback delivery case derives kind 10050 advertisements for its +ephemeral loopback ports using the vector's public synthetic participant keys +(scalars 2 and 3). It signs and authenticates those routes through the ordinary +T1 path. The literal inputs above stay unchanged. Only that case switches its +injected clock to advancing UTC for actual transport and a separate scoped +recovery grant; it retains the original acceptance, seals and outer bytes. diff --git a/crates/storage/src/inventory.rs b/crates/storage/src/inventory.rs @@ -336,6 +336,8 @@ pub trait InventoryStore: WorkspaceStore { } /// Commits an actual potential invocation before transport. Existing or /// uncertain attempts never confer another dispatch right. + /// A fresh claim must enforce the requested expected-attempt-count + /// precondition against authenticated history in the same transaction. fn prepare_stock_delivery_attempt( &self, _request: StockDeliveryRequest, diff --git a/crates/storage/src/inventory/delivery.rs b/crates/storage/src/inventory/delivery.rs @@ -15,6 +15,7 @@ use std::sync::Arc; pub struct StockDeliveryRequest { source: StockEnvelopeRequest, intent: DeliveryIntent, + expected_attempts: Option<u16>, } impl StockDeliveryRequest { pub fn new( @@ -33,8 +34,23 @@ impl StockDeliveryRequest { binding, minimum, operation, digest, recipient, None, )?, intent, + expected_attempts: None, }) } + /// Requires a fresh claim to observe this exact per-recipient attempt count. + /// Ordinary execution supplies its authenticated snapshot count to prevent + /// concurrent clients from dispatching twice from the same observation. + /// An exact existing request remains a read without dispatch permission. + pub fn with_expected_attempt_count(mut self, count: u16) -> Result<Self, OperationError> { + if count > 16 * 12 { + return Err(OperationError::InvalidCommand); + } + self.expected_attempts = Some(count); + Ok(self) + } + pub const fn expected_attempt_count(&self) -> Option<u16> { + self.expected_attempts + } pub const fn source(&self) -> &StockEnvelopeRequest { &self.source } diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/graph.rs b/crates/storage_sqlite/src/workspace/stock/delivery/graph.rs @@ -273,6 +273,9 @@ impl Graph { }) .collect() } + pub(super) fn attempt_count(&self, recipient: PublicKey) -> Result<u16, OperationError> { + Ok(self.recipient(recipient)?.attempts) + } pub(super) fn summary( &self, request: &StockEnvelopeRequest, diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/operations.rs b/crates/storage_sqlite/src/workspace/stock/delivery/operations.rs @@ -80,6 +80,13 @@ async fn prepare_authorized( return Err(OperationError::IdempotencyConflict); } let fresh = graph.found_attempt.is_none(); + if fresh + && request + .expected_attempt_count() + .is_some_and(|expected| graph.attempt_count(source.recipient()) != Ok(expected)) + { + return Err(OperationError::StaleState); + } let now = auth.access.current.observed_at(); let prepared = if fresh { let installed = Box::pin(inventory::installation::read_entry( 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 @@ -2,6 +2,65 @@ use super::*; #[tokio::test] +async fn stale_observed_attempt_count_cannot_claim_another_invocation() { + let (r, original, _, outer) = setup(17).await; + committed_envelope(capture(&r, &original, &outer, None).await.unwrap()); + let first = request(&r, &original, &outer, 40) + .await + .with_expected_attempt_count(0) + .unwrap(); + let racing = request(&r, &original, &outer, 41) + .await + .with_expected_attempt_count(0) + .unwrap(); + assert!(matches!( + r.store + .prepare_stock_delivery_attempt(first, proof(&r)) + .await + .unwrap(), + StockDeliveryAttemptOutcome::Claimed(_) + )); + let before = inventory_minimum(&r).await; + assert!(matches!( + r.store + .prepare_stock_delivery_attempt(racing, proof(&r)) + .await, + Err(OperationError::StaleState) + )); + assert_eq!(inventory_minimum(&r).await, before); + let repeated = request(&r, &original, &outer, 40) + .await + .with_expected_attempt_count(0) + .unwrap(); + assert!(matches!( + r.store + .prepare_stock_delivery_attempt(repeated, proof(&r)) + .await + .unwrap(), + StockDeliveryAttemptOutcome::Retained(_) + )); + let next = request(&r, &original, &outer, 41) + .await + .with_expected_attempt_count(1) + .unwrap(); + assert!(matches!( + r.store + .prepare_stock_delivery_attempt(next, proof(&r)) + .await + .unwrap(), + StockDeliveryAttemptOutcome::Claimed(_) + )); + assert!( + request(&r, &original, &outer, 42) + .await + .with_expected_attempt_count(193) + .is_err() + ); + balances(&r, 80, 9, 0, 1, 3).await; + r.store.close().await.unwrap(); +} + +#[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()); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -253,6 +253,10 @@ struct StockDelivery { query_grants_dispatch: bool, first_complete_targets_and_criterion_immutable: bool, ordinary_command_replays_existing_attempt: bool, + ordinary_fresh_claim_binds_observed_attempt_count: bool, + ordinary_obtained_material_owner: String, + ordinary_peer_delivery_precedes_self_signing: bool, + installed_original_delivery_requires_signer: bool, explicit_resume_claims_bounded_new_attempt: bool, retries_use_original_outer_bytes: bool, observation_nullable: bool, @@ -744,6 +748,10 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && !delivery.query_grants_dispatch && delivery.first_complete_targets_and_criterion_immutable && !delivery.ordinary_command_replays_existing_attempt + && delivery.ordinary_fresh_claim_binds_observed_attempt_count + && delivery.ordinary_obtained_material_owner == "ClientSession.stock_captures" + && delivery.ordinary_peer_delivery_precedes_self_signing + && !delivery.installed_original_delivery_requires_signer && delivery.explicit_resume_claims_bounded_new_attempt && delivery.retries_use_original_outer_bytes && delivery.observation_nullable @@ -2507,6 +2515,13 @@ mod tests { json!(false), ), ("ordinary_command_replays_existing_attempt", json!(true)), + ( + "ordinary_fresh_claim_binds_observed_attempt_count", + json!(false), + ), + ("ordinary_obtained_material_owner", json!("application")), + ("ordinary_peer_delivery_precedes_self_signing", json!(false)), + ("installed_original_delivery_requires_signer", json!(true)), ("retries_use_original_outer_bytes", json!(false)), ("observation_nullable", json!(false)), (