commit 3dea9f6dde94f6b000308b34ac7b53cb3f381d1d parent 7b428cbd4431e4bf05db62ec4f1b07131f8e1442 Author: triesap <tyson@radroots.org> Date: Sun, 25 Oct 2026 15:27:28 +0000 storage: expose coherent original stock operation recovery - Authenticate preparation, plans and both recipient evidence summaries. - Confirm exact selectors, pages and absence facts after provider IO. - Preserve current consent, uncertainty fencing and observer ownership. - Verify native and Linux recovery with additive redacted APIs. Diffstat:
13 files changed, 1033 insertions(+), 61 deletions(-)
diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -399,6 +399,11 @@ pub radroots_storage_sqlite::workspace::StockListingOutcome::Unknown::transactio pub enum radroots_storage_sqlite::workspace::StockSigningPlanOutcome pub radroots_storage_sqlite::workspace::StockSigningPlanOutcome::Bound(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockBoundSigningPlan>) pub radroots_storage_sqlite::workspace::StockSigningPlanOutcome::Unknown(radroots_storage::command::CommitAttempt) +pub enum radroots_storage_sqlite::workspace::StockSigningProgress +pub radroots_storage_sqlite::workspace::StockSigningProgress::Bound +pub radroots_storage_sqlite::workspace::StockSigningProgress::Obtained +pub radroots_storage_sqlite::workspace::StockSigningProgress::Unbound +pub radroots_storage_sqlite::workspace::StockSigningProgress::Unknown pub enum radroots_storage_sqlite::workspace::StockSourceOutcome pub radroots_storage_sqlite::workspace::StockSourceOutcome::Committed(radroots_storage_sqlite::workspace::StockSourceReceipt) pub radroots_storage_sqlite::workspace::StockSourceOutcome::Unknown @@ -446,6 +451,8 @@ pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::retain_stock_s pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_order_history(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_domain::commerce::causal::CausalScope, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockHistorySnapshot, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_order_request(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_domain::identifier::RecordId, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockRequestSnapshot, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_source(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_domain::identifier::EnvelopeEventId, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockSourceSnapshot>, radroots_storage::command::OperationError> +impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_operation_snapshot(&self, radroots_storage_sqlite::workspace::StockSnapshotRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockOperationSnapshot, radroots_storage::command::OperationError> impl core::fmt::Debug for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl radroots_storage::command::OperationJournal for radroots_storage_sqlite::workspace::NativeWorkspace @@ -515,6 +522,12 @@ pub const fn radroots_storage_sqlite::workspace::StockCapturedEvidence::receipt( pub fn radroots_storage_sqlite::workspace::StockCapturedEvidence::with_json<T>(&self, impl core::ops::function::FnOnce(&str) -> T) -> T impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockCapturedEvidence pub fn radroots_storage_sqlite::workspace::StockCapturedEvidence::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockClaimReference +impl radroots_storage_sqlite::workspace::StockClaimReference +pub const fn radroots_storage_sqlite::workspace::StockClaimReference::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId +pub const fn radroots_storage_sqlite::workspace::StockClaimReference::binding(&self) -> radroots_protocol::intent::IntentBinding +pub const fn radroots_storage_sqlite::workspace::StockClaimReference::claimed_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage_sqlite::workspace::StockClaimReference::transaction_id(&self) -> radroots_domain::identifier::TransactionId pub struct radroots_storage_sqlite::workspace::StockClaimRequest impl radroots_storage_sqlite::workspace::StockClaimRequest pub const fn radroots_storage_sqlite::workspace::StockClaimRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey) -> Self @@ -623,6 +636,22 @@ pub const fn radroots_storage_sqlite::workspace::StockListingSnapshot::receipt(& pub const fn radroots_storage_sqlite::workspace::StockListingSnapshot::selection_checkpoint(&self) -> radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockListingSnapshot pub fn radroots_storage_sqlite::workspace::StockListingSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockOperationSnapshot +impl radroots_storage_sqlite::workspace::StockOperationSnapshot +pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::preparation(&self) -> &radroots_storage_sqlite::workspace::StockAcceptanceReceipt +pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::recipients(&self) -> &[radroots_storage_sqlite::workspace::StockRecipientSnapshot; 2] +pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::signing_plan(&self) -> core::option::Option<&radroots_storage_sqlite::workspace::StockBoundSigningPlan> +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockOperationSnapshot +pub fn radroots_storage_sqlite::workspace::StockOperationSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockRecipientSnapshot +impl radroots_storage_sqlite::workspace::StockRecipientSnapshot +pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::claim(&self) -> core::option::Option<radroots_storage_sqlite::workspace::StockClaimReference> +pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::evidence_count(&self) -> radroots_domain::context::Sequence +pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::expected_event_id(&self) -> core::option::Option<[u8; 32]> +pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::first_evidence(&self) -> core::option::Option<radroots_storage_sqlite::workspace::StockEvidenceReceipt> +pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::progress(&self) -> radroots_storage_sqlite::workspace::StockSigningProgress +pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::recipient(&self) -> radroots_identity::key::PublicKey pub struct radroots_storage_sqlite::workspace::StockRequestSnapshot impl radroots_storage_sqlite::workspace::StockRequestSnapshot pub const fn radroots_storage_sqlite::workspace::StockRequestSnapshot::checkpoint(&self) -> &radroots_domain::context::CheckpointRef @@ -653,6 +682,11 @@ impl radroots_storage_sqlite::workspace::StockSigningPlanRequest pub fn radroots_storage_sqlite::workspace::StockSigningPlanRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_nostr::commerce::signing_plan::VerifiedCommerceSigningPlan) -> core::result::Result<Self, radroots_storage::command::OperationError> impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockSigningPlanRequest pub fn radroots_storage_sqlite::workspace::StockSigningPlanRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockSnapshotRequest +impl radroots_storage_sqlite::workspace::StockSnapshotRequest +pub const fn radroots_storage_sqlite::workspace::StockSnapshotRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> Self +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockSnapshotRequest +pub fn radroots_storage_sqlite::workspace::StockSnapshotRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockSourceCapture impl radroots_storage_sqlite::workspace::StockSourceCapture pub const fn radroots_storage_sqlite::workspace::StockSourceCapture::envelope_id(&self) -> radroots_domain::identifier::EnvelopeEventId diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -221,6 +221,9 @@ "agreement_installed": false }, "signing_issuance": { + "coherent_operation_snapshot_required": true, + "final_evidence_selectors_and_page_rows_required": true, + "recovery_view_has_dispatch_or_installation_rights": false, "fresh_current_backing_projection_required": true, "evidence_page_max": 32, "claim_family": 4, diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -427,3 +427,11 @@ owner until drain/reopen and reconciliation; the caller retains its input. page by original operation and recipient, so recovery can retrieve exact bytes without retaining a caller-side digest or requesting another signature. Agreement installation, stock conversion and delivery remain pending. + +`stock_operation_snapshot` authenticates original T0/T1, both recipient claims, +and each recipient's evidence count and first exact artifact in one coherent +observation. A bound plan, unknown claim and obtained artifact remain distinct +from installation. Current RecoverOnly consent can inspect original progress +after the first-issue deadline. Evidence selectors, page row sets, counts and +absence facts are compared again after provider work inside the final read +transaction. A recovery view never returns a fresh dispatch permit. diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -25,13 +25,15 @@ mod stock; pub use stock::{ SellerStockConfig, StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest, StockAuthorityReceipt, StockBoundSigningPlan, StockCapturedEvidence, StockClaimOutcome, - StockClaimRequest, StockConsentCapture, StockConsentMode, StockConsentOutcome, - StockConsentReceipt, StockDispatchPermit, StockEnrollment, StockEvidenceCapture, - StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, StockGrantEnrollment, - StockGrantOutcome, StockGrantReceipt, StockHistorySnapshot, StockListingCapture, - StockListingOutcome, StockListingReceipt, StockListingSnapshot, StockRequestSnapshot, - StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, StockSourceCapture, - StockSourceOutcome, StockSourceProfile, StockSourceReceipt, StockSourceSnapshot, + StockClaimReference, StockClaimRequest, StockConsentCapture, StockConsentMode, + StockConsentOutcome, StockConsentReceipt, StockDispatchPermit, StockEnrollment, + StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, + StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt, StockHistorySnapshot, + StockListingCapture, StockListingOutcome, StockListingReceipt, StockListingSnapshot, + StockOperationSnapshot, StockRecipientSnapshot, StockRequestSnapshot, StockSigningAttempt, + StockSigningPlanOutcome, StockSigningPlanRequest, StockSigningProgress, StockSnapshotRequest, + StockSourceCapture, StockSourceOutcome, StockSourceProfile, StockSourceReceipt, + StockSourceSnapshot, }; mod worker; diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -24,7 +24,12 @@ pub use issuance::{ StockSigningAttempt, }; pub(in crate::workspace) mod signing_plan; +pub(in crate::workspace) mod snapshot; pub use signing_plan::{StockBoundSigningPlan, StockSigningPlanOutcome, StockSigningPlanRequest}; +pub use snapshot::{ + StockClaimReference, StockOperationSnapshot, StockRecipientSnapshot, StockSigningProgress, + StockSnapshotRequest, +}; pub(in crate::workspace) mod public_source; pub use public_source::{ StockListingCapture, StockListingOutcome, StockListingReceipt, StockListingSnapshot, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs @@ -174,7 +174,7 @@ struct Body { claimed_at: UnixSeconds, } -pub(super) async fn existing( +pub(in crate::workspace::stock) async fn existing( turn: &mut Turn<'_>, auth: &signing_plan::Authorized, operation: OperationId, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence.rs @@ -8,6 +8,7 @@ use radroots_signing::{ use std::num::NonZeroU64; use zeroize::Zeroizing; mod codec; +pub(in crate::workspace::stock) mod selection; pub(in crate::workspace::stock) use codec::read_entry; const MAX_RAW: usize = 64 * 1024; @@ -185,47 +186,29 @@ pub(in crate::workspace) async fn page( minimum, ) .await?; - let rows=sqlx::query("SELECT CASE WHEN length(e.evidence_digest)=32 THEN e.evidence_digest END,CASE WHEN length(e.entry_id)=32 THEN e.entry_id END,o.revision FROM stock_signing_evidence e JOIN stock_operations o ON o.actor=e.actor AND o.operation_id=e.entry_id WHERE e.actor=? AND e.operation_id=? AND e.recipient=? AND (? IS NULL OR o.revision>?) ORDER BY o.revision LIMIT 33") - .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation.as_bytes().as_slice()).bind(request.recipient.as_bytes().as_slice()).bind(after.map(|v|v.get() as i64)).bind(after.map(|v|v.get() as i64)).fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; - let more = rows.len() > 32; + let selected = selection::page( + turn.connection, + turn.selected.participant(), + request.operation, + request.recipient, + after, + ) + .await?; + let more = selected.len() > 32; let mut last = None; - let mut receipts = Vec::with_capacity(rows.len().min(32)); - for row in rows.into_iter().take(32) { - let digest: Vec<u8> = row - .try_get::<Option<Vec<u8>>, _>(0) - .map_err(|_| OperationError::RecoveryRequired)? - .ok_or(OperationError::RecoveryRequired)?; - let entry: Vec<u8> = row - .try_get::<Option<Vec<u8>>, _>(1) - .map_err(|_| OperationError::RecoveryRequired)? - .ok_or(OperationError::RecoveryRequired)?; - let retained = read_entry( + let mut receipts = Vec::with_capacity(selected.len().min(32)); + for value in selected.iter().take(32).copied() { + let retained = selection::open( turn.connection, turn.selected, turn.crypto, - OperationId::from_bytes( - entry - .try_into() - .map_err(|_| OperationError::RecoveryRequired)?, - ), + request.operation, + request.recipient, + value, ) - .await? - .ok_or(OperationError::RecoveryRequired)?; - let revision: i64 = row - .try_get(2) - .map_err(|_| OperationError::RecoveryRequired)?; - if revision <= 0 || retained.frame.header.revision.get() != revision as u64 { - return Err(OperationError::RecoveryRequired); - } - last = Some(retained.frame.header.revision); - let value = retained.value.receipt; - if value.digest.as_slice() != digest - || value.attempt.operation_id() != request.operation - || value.recipient != request.recipient - { - return Err(OperationError::RecoveryRequired); - } - receipts.push(value); + .await?; + last = Some(value.revision); + receipts.push(retained.value.receipt); } let mut tx = turn .connection @@ -234,6 +217,18 @@ pub(in crate::workspace) async fn page( .map_err(|_| OperationError::StorageFailure)?; let checked: Result<(), OperationError> = async { witness.confirm(&mut tx).await?; + if selection::page( + &mut tx, + turn.selected.participant(), + request.operation, + request.recipient, + after, + ) + .await? + != selected + { + return Err(OperationError::RecoveryRequired); + } auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) .await?; Ok(()) @@ -423,23 +418,27 @@ async fn lookup( recipient: PublicKey, digest: [u8; 32], ) -> Result<Option<codec::Retained>, OperationError> { - let id:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_signing_evidence WHERE actor=? AND operation_id=? AND recipient=? AND evidence_digest=?").bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).bind(digest.as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; - match id { - None => Ok(None), - Some(id) => Ok(Some( - read_entry( - connection, - input, - crypto, - OperationId::from_bytes( - id.try_into() - .map_err(|_| OperationError::RecoveryRequired)?, - ), - ) - .await? - .ok_or(OperationError::RecoveryRequired)?, - )), + let Some(entry) = selection::entry( + connection, + input.participant(), + operation, + recipient, + digest, + ) + .await? + else { + return Ok(None); + }; + let retained = read_entry(connection, input, crypto, entry) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.value.receipt.attempt().operation_id() != operation + || retained.value.receipt.recipient() != recipient + || retained.value.receipt.digest() != &digest + { + return Err(OperationError::RecoveryRequired); } + Ok(Some(retained)) } pub(in crate::workspace) async fn read( @@ -495,6 +494,18 @@ pub(in crate::workspace) async fn read( .map_err(|_| OperationError::StorageFailure)?; let checked: Result<(), OperationError> = async { witness.confirm(&mut tx).await?; + if selection::entry( + &mut tx, + turn.selected.participant(), + request.operation, + request.recipient, + digest, + ) + .await? + != retained.as_ref().map(|value| value.frame.header.operation) + { + return Err(OperationError::RecoveryRequired); + } claim.1.confirm(&mut tx).await?; auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) .await?; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence/selection.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence/selection.rs @@ -0,0 +1,120 @@ +//! Bind every returned selector and absence fact through final SQL observation. +use super::*; +#[derive(Clone, Copy, Eq, PartialEq)] +pub(in crate::workspace::stock) struct Selected { + pub digest: [u8; 32], + pub entry: OperationId, + pub revision: Sequence, +} +pub(in crate::workspace::stock) async fn page( + connection: &mut SqliteConnection, + actor: PublicKey, + operation: OperationId, + recipient: PublicKey, + after: Option<Sequence>, +) -> Result<Vec<Selected>, OperationError> { + let rows=sqlx::query("SELECT CASE WHEN length(e.evidence_digest)=32 THEN e.evidence_digest END,CASE WHEN length(e.entry_id)=32 THEN e.entry_id END,o.revision FROM stock_signing_evidence e JOIN stock_operations o ON o.actor=e.actor AND o.operation_id=e.entry_id WHERE e.actor=? AND e.operation_id=? AND e.recipient=? AND (? IS NULL OR o.revision>?) ORDER BY o.revision LIMIT 33") + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).bind(after.map(|v|v.get() as i64)).bind(after.map(|v|v.get() as i64)).fetch_all(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let mut selected = Vec::with_capacity(rows.len()); + let mut previous = after.map(Sequence::get).unwrap_or(0); + for row in rows { + let field = |index| { + row.try_get::<Option<Vec<u8>>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let revision: i64 = row + .try_get(2) + .map_err(|_| OperationError::RecoveryRequired)?; + if revision <= 0 || revision as u64 <= previous { + return Err(OperationError::RecoveryRequired); + } + let revision = + Sequence::new(revision as u64).map_err(|_| OperationError::RecoveryRequired)?; + previous = revision.get(); + selected.push(Selected { + digest: field(0)?, + entry: OperationId::from_bytes(field(1)?), + revision, + }); + } + Ok(selected) +} +pub(super) async fn entry( + connection: &mut SqliteConnection, + actor: PublicKey, + operation: OperationId, + recipient: PublicKey, + digest: [u8; 32], +) -> Result<Option<OperationId>, OperationError> { + let value:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_signing_evidence WHERE actor=? AND operation_id=? AND recipient=? AND evidence_digest=?").bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).bind(digest.as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + value + .map(|id| { + Ok(OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) + }) + .transpose() +} +pub(in crate::workspace::stock) async fn open( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + operation: OperationId, + recipient: PublicKey, + selected: Selected, +) -> Result<codec::Retained, OperationError> { + let retained = read_entry(connection, input, crypto, selected.entry) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.frame.header.revision != selected.revision + || retained.value.receipt.attempt().operation_id() != operation + || retained.value.receipt.recipient() != recipient + || retained.value.receipt.digest() != &selected.digest + { + return Err(OperationError::RecoveryRequired); + } + Ok(retained) +} +#[derive(Clone, Copy, Eq, PartialEq)] +pub(in crate::workspace::stock) struct Summary { + pub count: Sequence, + pub first: Option<Selected>, +} +impl Summary { + pub(in crate::workspace::stock) async fn read( + connection: &mut SqliteConnection, + actor: PublicKey, + operation: OperationId, + recipient: PublicKey, + ) -> Result<Self, OperationError> { + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_signing_evidence WHERE actor=? AND operation_id=? AND recipient=?").bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count < 0 { + return Err(OperationError::RecoveryRequired); + } + let count = Sequence::new(count as u64).map_err(|_| OperationError::RecoveryRequired)?; + let first = page(connection, actor, operation, recipient, None) + .await? + .first() + .copied(); + if (count.get() == 0) != first.is_none() { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { count, first }) + } + pub(in crate::workspace::stock) async fn confirm( + &self, + connection: &mut SqliteConnection, + actor: PublicKey, + operation: OperationId, + recipient: PublicKey, + ) -> Result<(), OperationError> { + if Self::read(connection, actor, operation, recipient).await? != *self { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} 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 @@ -1,5 +1,7 @@ //! Obtained-byte capture executes on the same real native stock owner. use super::*; +#[path = "snapshot_tests.rs"] +mod snapshots; use crate::workspace::{StockEvidenceCapture, StockEvidenceOutcome, StockEvidenceReceipt}; use sha2::{Digest, Sha256}; async fn obtained( diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/snapshot_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/snapshot_tests.rs @@ -0,0 +1,438 @@ +//! Coherent real native recovery; query results never become signing permits. +use super::*; +use crate::workspace::stock::issuance::evidence::selection; +use crate::workspace::{ + StockOperationSnapshot, StockSigningProgress as Progress, StockSnapshotRequest, +}; + +async fn request(r: &Rig, receipt: &StockAcceptanceReceipt) -> StockSnapshotRequest { + StockSnapshotRequest::new( + r.binding.clone(), + inventory_minimum(r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ) +} +async fn snapshot(r: &Rig, receipt: &StockAcceptanceReceipt) -> StockOperationSnapshot { + r.store + .stock_operation_snapshot(request(r, receipt).await, r.enrollment.proof()) + .await + .unwrap() +} +#[tokio::test] +async fn original_t0_t1_unknown_and_partial_obtained_states_form_one_coherent_reopened_view() { + let mut r = Rig::new().await; + let (_, receipt) = prepared(&r).await; + let initial = snapshot(&r, &receipt).await; + assert!(initial.signing_plan().is_none()); + assert!( + initial + .recipients() + .iter() + .all(|value| value.progress() == Progress::Unbound) + ); + bound(bind(&r, &receipt, 42).await.unwrap()); + let planned = snapshot(&r, &receipt).await; + assert!(planned.signing_plan().is_some()); + assert!( + planned + .recipients() + .iter() + .all(|value| value.progress() == Progress::Bound) + ); + let recipient = receipt.rumor().recipients()[0]; + let StockClaimOutcome::Fresh(permit) = claim(&r, &receipt, recipient).await.unwrap() else { + panic!("first claim"); + }; + let (intent, report) = permit + .into_signing_intent(CancellationSignal::new()) + .unwrap(); + let unknown = snapshot(&r, &receipt).await; + assert_eq!(unknown.recipients()[0].progress(), Progress::Unknown); + assert_eq!( + unknown.recipients()[0].claim().unwrap().attempt_id(), + report.attempt_id() + ); + let signer = LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { + Ok(150000) + }) + .unwrap(); + let (_, OutcomeKind::Obtained(signed)) = signer.sign_exact(intent).await.into_parts() else { + panic!("actual signing"); + }; + let raw = signed.with_json(str::to_owned); + let mut first = None; + for text in [raw.clone(), format!("\n{raw}\n")] { + let value = StockEvidenceCapture::verify(r.binding.clone(), &report, &text, None).unwrap(); + let receipt = committed( + r.store + .capture_stock_signing_evidence(&value, r.enrollment.proof()) + .await + .unwrap(), + ); + first.get_or_insert(receipt); + } + let partial = snapshot(&r, &receipt).await; + assert_eq!(partial.recipients()[0].progress(), Progress::Obtained); + assert_eq!(partial.recipients()[0].evidence_count().get(), 2); + assert_eq!(partial.recipients()[0].first_evidence(), first); + assert_eq!(partial.recipients()[1].progress(), Progress::Bound); + assert!(partial.recipients()[1].claim().is_none()); + assert_eq!(partial.preparation().attempt(), receipt.attempt()); + assert_eq!(partial.checkpoint(), inventory_minimum(&r).await); + assert_eq!(format!("{partial:?}"), "StockOperationSnapshot(<redacted>)"); + reopen_plain(&mut r).await; + r.clock.0.store(229, Ordering::SeqCst); + let recovered = snapshot(&r, &receipt).await; + assert_eq!(recovered.recipients(), partial.recipients()); + assert_eq!( + recovered.signing_plan().unwrap().plan().protected_wire(), + partial.signing_plan().unwrap().plan().protected_wire() + ); + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn valid_evidence_for_another_selector_is_refused_and_metadata_witnesses_detect_new_outputs() +{ + let r = Rig::new().await; + let receipt = ready(&r).await; + let recipients = *receipt.rumor().recipients(); + let mut originals = Vec::new(); + for recipient in recipients { + let (report, raw) = obtained(&r, &receipt, recipient).await; + let value = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + committed( + r.store + .capture_stock_signing_evidence(&value, r.enrollment.proof()) + .await + .unwrap(), + ); + originals.push((report, raw)); + } + let mut rawdb = database(&r).await; + let other = selection::page( + &mut rawdb, + r.enrollment.input().participant(), + receipt.attempt().operation_id(), + recipients[1], + None, + ) + .await + .unwrap()[0]; + assert!( + selection::open( + &mut rawdb, + r.enrollment.input(), + &r.fixture.crypto(), + receipt.attempt().operation_id(), + recipients[0], + other + ) + .await + .is_err() + ); + let summary = selection::Summary::read( + &mut rawdb, + r.enrollment.input().participant(), + receipt.attempt().operation_id(), + recipients[0], + ) + .await + .unwrap(); + let prior = selection::page( + &mut rawdb, + r.enrollment.input().participant(), + receipt.attempt().operation_id(), + recipients[0], + None, + ) + .await + .unwrap(); + let (report, raw) = &originals[0]; + let extra = + StockEvidenceCapture::verify(r.binding.clone(), report, &format!("\n{raw}\n"), None) + .unwrap(); + committed( + r.store + .capture_stock_signing_evidence(&extra, r.enrollment.proof()) + .await + .unwrap(), + ); + let mut tx = rawdb.begin_with("BEGIN IMMEDIATE").await.unwrap(); + assert_eq!( + summary + .confirm( + &mut tx, + r.enrollment.input().participant(), + receipt.attempt().operation_id(), + recipients[0] + ) + .await, + Err(OperationError::RecoveryRequired) + ); + assert_ne!( + selection::page( + &mut tx, + r.enrollment.input().participant(), + receipt.attempt().operation_id(), + recipients[0], + None + ) + .await + .unwrap() + .len(), + prior.len() + ); + tx.rollback().await.unwrap(); + let value = snapshot(&r, &receipt).await; + assert_eq!(value.recipients()[0].evidence_count().get(), 2); + assert_eq!(value.recipients()[1].evidence_count().get(), 1); + rawdb.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn snapshot_refuses_wrong_digest_missing_original_and_protected_graph_damage() { + for statement in [ + "UPDATE stock_signing_claims SET recipient=randomblob(32)", + "DELETE FROM stock_signing_evidence", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=3", + ] { + let r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let value = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + committed( + r.store + .capture_stock_signing_evidence(&value, r.enrollment.proof()) + .await + .unwrap(), + ); + let minimum = inventory_minimum(&r).await; + for (operation, digest, code) in [ + ( + OperationId::from_bytes([99; 32]), + receipt.attempt().command_digest(), + "stale_state", + ), + ( + receipt.attempt().operation_id(), + radroots_domain::CommandDigest::from_bytes([99; 32]), + "idempotency_conflict", + ), + ] { + assert_eq!( + r.store + .stock_operation_snapshot( + StockSnapshotRequest::new(r.binding.clone(), minimum, operation, digest), + r.enrollment.proof() + ) + .await + .unwrap_err() + .code(), + code + ); + } + let request = request(&r, &receipt).await; + let mut rawdb = database(&r).await; + sqlx::raw_sql(statement).execute(&mut rawdb).await.unwrap(); + assert!( + r.store + .stock_operation_snapshot(request, r.enrollment.proof()) + .await + .is_err(), + "{statement}" + ); + rawdb.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn dropped_snapshot_observation_drains_and_late_changes_never_return_a_mixed_view() { + for statement in [ + None, + Some("UPDATE stock_grants SET protected=randomblob(length(protected))"), + Some("DELETE FROM stock_signing_evidence"), + ] { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let value = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + committed( + r.store + .capture_stock_signing_evidence(&value, r.enrollment.proof()) + .await + .unwrap(), + ); + let request = request(&r, &receipt).await; + let provider = reopen(&mut r).await; + let mut rawdb = database(&r).await; + provider.gate.arm( + Direction::Unwrap, + "radroots.seller_stock.operation_part.v1", + 0, + ); + let mut pending = Box::pin( + r.store + .stock_operation_snapshot(request, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + if let Some(statement) = statement { + sqlx::raw_sql(statement).execute(&mut rawdb).await.unwrap(); + provider.gate.release(); + assert!(pending.await.is_err()); + } else { + drop(pending); + provider.gate.release(); + reopen_plain(&mut r).await; + assert_eq!( + snapshot(&r, &receipt).await.recipients()[0].progress(), + Progress::Obtained + ); + } + rawdb.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn replacement_recovery_only_reads_original_obtained_state_after_first_issue_expiry() { + let r = Rig::new().await; + let (command, receipt) = prepared(&r).await; + bound(bind(&r, &receipt, 42).await.unwrap()); + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let first = committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + ); + r.clock.0.store(250, Ordering::SeqCst); + let child = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(r.enrollment.input()), + "recovery operator".into(), + UnixSeconds::new(290).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + assert!(matches!( + r.store + .enroll_stock_grant( + r.binding.clone(), + inventory_minimum(&r).await, + r.enrollment.proof(), + &child + ) + .await + .unwrap(), + StockGrantOutcome::Committed(_) + )); + let binding = r + .store + .authenticate(child.input().clone(), child.proof()) + .await + .unwrap(); + let scope = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + child.input().grant_id(), + StockConsentMode::RecoverOnly, + StockResources::all_pools(), + UnixSeconds::new(280).unwrap(), + CapturedOrderAcceptance::parse(command.protected_wire()).unwrap(), + ) + .unwrap(); + assert!(matches!( + r.store + .issue_stock_consent( + r.binding.clone(), + inventory_minimum(&r).await, + &scope, + r.enrollment.proof() + ) + .await + .unwrap(), + StockConsentOutcome::Committed(_) + )); + let request = StockSnapshotRequest::new( + binding, + inventory_minimum(&r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ); + let recovered = r + .store + .stock_operation_snapshot(request, child.proof()) + .await + .unwrap(); + assert_eq!(recovered.preparation().attempt(), receipt.attempt()); + assert_eq!(recovered.recipients()[0].first_evidence(), Some(first)); + assert_eq!( + recovered.recipients()[0].claim().unwrap().attempt_id(), + report.attempt_id() + ); + assert_eq!(recovered.recipients()[1].progress(), Progress::Bound); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn uncertain_owner_never_returns_a_snapshot_until_original_reopen_reconciles() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let request = request(&r, &receipt).await; + let mut rawdb = 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_signing_evidence BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut rawdb).await.unwrap(); + assert!(matches!( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + StockEvidenceOutcome::Unknown(_) + )); + assert_eq!( + r.store + .stock_operation_snapshot(request, r.enrollment.proof()) + .await + .unwrap_err() + .code(), + "recovery_required" + ); + r.store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut rawdb) + .await + .unwrap(); + rawdb.close().await.unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + let recovered = snapshot(&r, &receipt).await; + assert_eq!(recovered.recipients()[0].progress(), Progress::Unknown); + assert_eq!(recovered.recipients()[0].evidence_count().get(), 0); + assert_eq!( + recovered.recipients()[0].claim().unwrap().attempt_id(), + report.attempt_id() + ); + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/snapshot.rs b/crates/storage_sqlite/src/workspace/stock/snapshot.rs @@ -0,0 +1,290 @@ +//! One authenticated observation of original preparation and per-recipient S. +use super::*; +use inventory::{Turn, checkpoint}; +use issuance::{claim, evidence::selection}; +use radroots_domain::{CommandDigest, OperationId, PublicKey, SigningAttemptId, UnixSeconds}; +use radroots_signing::issuance::IntentBinding; +use radroots_storage::{command::OperationError, inventory::InventoryCheckpointRef}; + +/// Original-operation selector data; it grants no read or execution permission. +pub struct StockSnapshotRequest { + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, +} +impl StockSnapshotRequest { + pub const fn new( + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + ) -> Self { + Self { + binding, + minimum, + operation, + digest, + } + } +} +impl std::fmt::Debug for StockSnapshotRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockSnapshotRequest(<redacted>)") + } +} + +/// Recorded signing facts, independent of installation or delivery success. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum StockSigningProgress { + Unbound, + Bound, + Unknown, + Obtained, +} +/// Immutable claim identity. This reference cannot construct a dispatch permit. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct StockClaimReference { + id: SigningAttemptId, + transaction: TransactionId, + at: UnixSeconds, + binding: IntentBinding, +} +impl StockClaimReference { + pub const fn attempt_id(&self) -> SigningAttemptId { + self.id + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + pub const fn claimed_at(&self) -> UnixSeconds { + self.at + } + pub const fn binding(&self) -> IntentBinding { + self.binding + } +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct StockRecipientSnapshot { + recipient: PublicKey, + expected: Option<[u8; 32]>, + claim: Option<StockClaimReference>, + count: Sequence, + first: Option<StockEvidenceReceipt>, +} +impl StockRecipientSnapshot { + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + pub const fn expected_event_id(&self) -> Option<[u8; 32]> { + self.expected + } + pub const fn claim(&self) -> Option<StockClaimReference> { + self.claim + } + /// Number of distinct retained original encodings, not new commitments. + pub const fn evidence_count(&self) -> Sequence { + self.count + } + pub const fn first_evidence(&self) -> Option<StockEvidenceReceipt> { + self.first + } + pub const fn progress(&self) -> StockSigningProgress { + if self.first.is_some() { + StockSigningProgress::Obtained + } else if self.claim.is_some() { + StockSigningProgress::Unknown + } else if self.expected.is_some() { + StockSigningProgress::Bound + } else { + StockSigningProgress::Unbound + } + } +} +/// Coherent original T0/T1/claim/obtained view. No installation, release, +/// reissuance, delivery or global history-completeness claim follows from it. +pub struct StockOperationSnapshot { + preparation: StockAcceptanceReceipt, + plan: Option<StockBoundSigningPlan>, + checkpoint: InventoryCheckpointRef, + recipients: [StockRecipientSnapshot; 2], +} +impl StockOperationSnapshot { + pub const fn preparation(&self) -> &StockAcceptanceReceipt { + &self.preparation + } + pub const fn signing_plan(&self) -> Option<&StockBoundSigningPlan> { + self.plan.as_ref() + } + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } + pub const fn recipients(&self) -> &[StockRecipientSnapshot; 2] { + &self.recipients + } +} +impl std::fmt::Debug for StockOperationSnapshot { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockOperationSnapshot(<redacted>)") + } +} + +pub(in crate::workspace) async fn read( + turn: &mut Turn<'_>, + request: StockSnapshotRequest, + proof: AttachmentProof, +) -> Result<StockOperationSnapshot, OperationError> { + let auth = signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + ) + .await?; + if auth.access.authority.catalog != 11 { + return Err(OperationError::UnsupportedOperation); + } + let mut reports = Vec::with_capacity(2); + let mut claims = Vec::with_capacity(2); + let mut summaries = Vec::with_capacity(2); + for recipient in auth.original.receipt.rumor().recipients() { + let (retained, claim_proof) = + claim::existing(turn, &auth, request.operation, *recipient).await?; + let reference = retained.as_ref().map(|value| StockClaimReference { + id: value.report.attempt_id(), + transaction: value.report.transaction_id(), + at: value.report.claimed_at(), + binding: value.report.binding(), + }); + let summary = selection::Summary::read( + turn.connection, + turn.selected.participant(), + request.operation, + *recipient, + ) + .await?; + let first = if let Some(selected) = summary.first { + Some( + selection::open( + turn.connection, + turn.selected, + turn.crypto, + request.operation, + *recipient, + selected, + ) + .await? + .value + .receipt(), + ) + } else { + None + }; + let expected = auth.plan.as_ref().and_then(|plan| { + plan.bound + .plan() + .seals() + .iter() + .find(|seal| seal.recipient() == *recipient) + .map(|seal| seal.event_id()) + }); + if reference.is_some() && expected.is_none() + || first.is_some_and(|value| { + reference.is_none_or(|claim| claim.id != value.signing_attempt_id()) + }) + { + return Err(OperationError::RecoveryRequired); + } + reports.push(StockRecipientSnapshot { + recipient: *recipient, + expected, + claim: reference, + count: summary.count, + first, + }); + claims.push(claim_proof); + summaries.push(summary); + } + let before = auth + .access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let minimum = InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, + None, + )?; + let witness = checkpoint::authenticate_minimum( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + minimum, + ) + .await?; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + witness.confirm(&mut tx).await?; + for (index, report) in reports.iter().enumerate() { + claims[index].confirm(&mut tx).await?; + summaries[index] + .confirm( + &mut tx, + turn.selected.participant(), + request.operation, + report.recipient, + ) + .await?; + } + auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) + .await?; + Ok(()) + } + .await; + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + let checkpoint = InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + before.revision, + before.head, + )? + .with_authorization( + auth.access + .authority + .authorization + .ok_or(OperationError::RecoveryRequired)?, + ); + Ok(StockOperationSnapshot { + preparation: auth.original.receipt, + plan: auth.plan.map(|value| value.bound), + checkpoint, + recipients: reports + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + }) +} +impl NativeWorkspace { + pub async fn stock_operation_snapshot( + &self, + request: StockSnapshotRequest, + proof: &AttachmentProof, + ) -> Result<StockOperationSnapshot, OperationError> { + self.worker + .stock_operation_snapshot( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -38,6 +38,11 @@ const QUEUE_MAX_BYTES: usize = 4 * 1024 * 1024; const QUEUE_CAPACITY: usize = 32; type Reply<T, E = WorkspaceError> = oneshot::Sender<Result<T, E>>; enum Job { + StockSnapshot( + Box<stock::StockSnapshotRequest>, + AttachmentProof, + Reply<stock::StockOperationSnapshot, OperationError>, + ), StockEvidencePage( Box<stock::StockClaimRequest>, Option<radroots_domain::Sequence>, @@ -279,6 +284,9 @@ enum Job { impl Job { fn reject_recovery(self) { match self { + Self::StockSnapshot(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::StockEvidencePage(_, _, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -556,6 +564,7 @@ impl Handle { | Job::CaptureStockEvidence(..) | Job::StockEvidence(..) | Job::StockEvidencePage(..) + | Job::StockSnapshot(..) | Job::Revoke(..) | Job::StockAuthority(..) ) @@ -772,6 +781,26 @@ impl Handle { }; 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( @@ -1560,6 +1589,15 @@ impl Handle { ))?; result.await.unwrap_or(Ok(anchor)) } + pub(super) async fn stock_operation_snapshot( + &self, + request: stock::StockSnapshotRequest, + proof: AttachmentProof, + ) -> Result<stock::StockOperationSnapshot, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockSnapshot(Box::new(request), proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn stock_signing_evidence_page( &self, request: stock::StockClaimRequest, @@ -1739,7 +1777,9 @@ impl Handle { fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { Job::RetainStockListing(..) | Job::CaptureStockEvidence(..) => 256 * 1024, - Job::StockEvidence(..) | Job::StockEvidencePage(..) => 1024 * 1024, + Job::StockEvidence(..) | Job::StockEvidencePage(..) | Job::StockSnapshot(..) => { + 1024 * 1024 + } Job::IssueStockConsent(..) | Job::PrepareStockAcceptance(..) => 512 * 1024, Job::BindStockSigningPlan(..) | Job::StockSigningPlan(..) diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -211,6 +211,9 @@ struct AcceptancePreparation { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct SigningIssuance { + coherent_operation_snapshot_required: bool, + final_evidence_selectors_and_page_rows_required: bool, + recovery_view_has_dispatch_or_installation_rights: bool, fresh_current_backing_projection_required: bool, evidence_page_max: u32, claim_family: u32, @@ -494,6 +497,13 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock .signing_issuance .fresh_current_backing_projection_required + && stock.signing_issuance.coherent_operation_snapshot_required + && stock + .signing_issuance + .final_evidence_selectors_and_page_rows_required + && !stock + .signing_issuance + .recovery_view_has_dispatch_or_installation_rights && stock.signing_issuance.evidence_page_max == 32 && stock.signing_issuance.claim_family == 4 && stock.signing_issuance.evidence_family == 5 @@ -1124,6 +1134,15 @@ mod tests { #[test] fn stock_claims_require_confirmed_dispatch_and_clock_independent_original_capture() { for (field, bad) in [ + ("coherent_operation_snapshot_required", json!(false)), + ( + "final_evidence_selectors_and_page_rows_required", + json!(false), + ), + ( + "recovery_view_has_dispatch_or_installation_rights", + json!(true), + ), ("fresh_current_backing_projection_required", json!(false)), ("evidence_page_max", json!(33)), ("claim_family", json!(3)),