lib

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

commit 25db2ec84e5e5e56586a0657b8dffa07936363c5
parent b97cc035d4c6ca3df350d3c3f2dee7329be8c174
Author: triesap <tyson@radroots.org>
Date:   Sun, 25 Oct 2026 22:13:31 +0000

storage: abort proven-unissued stock preparations atomically

- Release only authenticated original holds and retain immutable preparations.
- Authenticate order transitions and refuse issuance on aborted originals.
- Preserve exact catalog history and original replay after later preparation.
- Verify native and Linux transactions, recovery and six process-death edges.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 1+
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 22++++++++++++++++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 22+++++++++++++++++++---
Mcrates/domain/src/stock.rs | 13+++++++++++++
Mcrates/domain/tests/stock.rs | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/README.md | 43+++++++++++++++++++++++++++++++++++--------
Mcrates/storage_sqlite/src/workspace/crypto.rs | 20++++++++++++++------
Mcrates/storage_sqlite/src/workspace/mod.rs | 24++++++++++++------------
Mcrates/storage_sqlite/src/workspace/stock.rs | 10++++++----
Mcrates/storage_sqlite/src/workspace/stock/consent.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/consent/test_provider.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/grants.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory.rs | 5+++--
Acrates/storage_sqlite/src/workspace/stock/inventory/abort.rs | 491+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/inventory/abort/codec.rs | 307+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/inventory/abort/projection.rs | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs | 104++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcrates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs | 105++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/stock/inventory/codec.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/installation.rs | 27+++++++++++++++++++++++++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs | 2++
Mcrates/storage_sqlite/src/workspace/stock/inventory/mapping.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory/plan.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/issuance.rs | 9++++++++-
Mcrates/storage_sqlite/src/workspace/stock/issuance/claim.rs | 9+++++++++
Mcrates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs | 2++
Mcrates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs | 2++
Mcrates/storage_sqlite/src/workspace/stock/ledger.rs | 39++++++++++++++++++++++++++++++++++++---
Acrates/storage_sqlite/src/workspace/stock/order_state.rs | 259+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs | 307+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/public_source/abort_tests.rs | 282+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs | 11++++++-----
Mcrates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs | 7+++++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs | 134+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Mcrates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/transaction.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/schema.rs | 27+++++++++++++++++++++------
Mcrates/storage_sqlite/src/workspace/stock/signing_plan.rs | 11++++++++++-
Mcrates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs | 2++
Mcrates/storage_sqlite/src/workspace/stock/snapshot.rs | 78+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcrates/storage_sqlite/src/workspace/stock/source/transaction.rs | 6+++---
Mcrates/storage_sqlite/src/workspace/stock/tests.rs | 34+++++++++++++++++++++-------------
Mcrates/storage_sqlite/src/workspace/worker.rs | 85++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcrates/storage_sqlite/tests/support/stock_authority.rs | 2+-
Mtools/xtask/src/architecture/decision_package.rs | 76+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
49 files changed, 2674 insertions(+), 169 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -327,6 +327,7 @@ pub fn radroots_domain::stock::PoolBalances::install_preparatory(self, radroots_ pub const fn radroots_domain::stock::PoolBalances::introduced(self) -> radroots_domain::stock::StockTicks pub fn radroots_domain::stock::PoolBalances::new(radroots_domain::stock::StockTicks, radroots_domain::stock::PhysicalBalances) -> core::result::Result<Self, radroots_domain::stock::StockError> pub const fn radroots_domain::stock::PoolBalances::physical(self) -> radroots_domain::stock::PhysicalBalances +pub fn radroots_domain::stock::PoolBalances::release_preparatory(self, radroots_domain::stock::StockTicks) -> core::result::Result<Self, radroots_domain::stock::StockError> impl core::fmt::Debug for radroots_domain::stock::PoolBalances pub fn radroots_domain::stock::PoolBalances::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl serde_core::ser::Serialize for radroots_domain::stock::PoolBalances diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -368,7 +368,11 @@ pub use radroots_storage_sqlite::workspace::WorkspaceBinding pub use radroots_storage_sqlite::workspace::WorkspaceClock pub use radroots_storage_sqlite::workspace::WorkspaceError pub use radroots_storage_sqlite::workspace::WorkspaceScope +pub enum radroots_storage_sqlite::workspace::StockAbortOutcome +pub radroots_storage_sqlite::workspace::StockAbortOutcome::Aborted(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockAbortReceipt>) +pub radroots_storage_sqlite::workspace::StockAbortOutcome::Unknown(radroots_storage::command::CommitAttempt) pub enum radroots_storage_sqlite::workspace::StockAcceptanceOutcome +pub radroots_storage_sqlite::workspace::StockAcceptanceOutcome::Aborted(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockAbortReceipt>) pub radroots_storage_sqlite::workspace::StockAcceptanceOutcome::Prepared(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockAcceptanceReceipt>) pub radroots_storage_sqlite::workspace::StockAcceptanceOutcome::Unknown(radroots_storage::command::CommitAttempt) pub enum radroots_storage_sqlite::workspace::StockClaimOutcome @@ -418,6 +422,9 @@ pub radroots_storage_sqlite::workspace::StockSourceProfile::Rejected pub radroots_storage_sqlite::workspace::StockSourceProfile::Unsupported pub struct radroots_storage_sqlite::workspace::NativeWorkspace impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::abort_proven_unissued(&self, radroots_storage_sqlite::workspace::StockAbortRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockAbortOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_preparation_abort(&self, radroots_storage_sqlite::workspace::StockAbortRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockAbortReceipt>, radroots_storage::command::OperationError> +impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::close(&self) -> core::result::Result<(), radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::initialize_local_outbox(&std::path::Path, radroots_storage::workspace::local_outbox::LocalOutboxConfig, radroots_storage_sqlite::workspace::WorkspaceCrypto, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<(Self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof), radroots_storage::workspace::WorkspaceError> @@ -485,6 +492,20 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::pool(&self, radroots impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::close_workspace(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::workspace::WorkspaceError>> +pub struct radroots_storage_sqlite::workspace::StockAbortReceipt +impl radroots_storage_sqlite::workspace::StockAbortReceipt +pub const fn radroots_storage_sqlite::workspace::StockAbortReceipt::aborted_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage_sqlite::workspace::StockAbortReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage_sqlite::workspace::StockAbortReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub const fn radroots_storage_sqlite::workspace::StockAbortReceipt::order_id(&self) -> radroots_domain::identifier::OrderId +pub fn radroots_storage_sqlite::workspace::StockAbortReceipt::released_pools(&self) -> &[radroots_domain::stock::PoolSnapshot] +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockAbortReceipt +pub fn radroots_storage_sqlite::workspace::StockAbortReceipt::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockAbortRequest +impl radroots_storage_sqlite::workspace::StockAbortRequest +pub const fn radroots_storage_sqlite::workspace::StockAbortRequest::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::StockAbortRequest +pub fn radroots_storage_sqlite::workspace::StockAbortRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockAcceptanceReceipt impl radroots_storage_sqlite::workspace::StockAcceptanceReceipt pub const fn radroots_storage_sqlite::workspace::StockAcceptanceReceipt::allocation_count(&self) -> usize @@ -661,6 +682,7 @@ impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockListingSnapsh 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 fn radroots_storage_sqlite::workspace::StockOperationSnapshot::aborted(&self) -> core::option::Option<&radroots_storage_sqlite::workspace::StockAbortReceipt> pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef pub fn radroots_storage_sqlite::workspace::StockOperationSnapshot::installation(&self) -> core::option::Option<&radroots_storage_sqlite::workspace::StockInstallationReceipt> pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::preparation(&self) -> &radroots_storage_sqlite::workspace::StockAcceptanceReceipt diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -75,7 +75,7 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 12, + "schema_version": 13, "retained_enrollment_versions": [ 1 ], @@ -89,9 +89,10 @@ 8, 9, 10, - 11 + 11, + 12 ], - "authority_payload_schema": "radroots.seller_stock.authority.v12", + "authority_payload_schema": "radroots.seller_stock.authority.v13", "public_source_payload_schemas": [ "radroots.seller_stock.public_source_event.v1", "radroots.seller_stock.public_source_head.v1", @@ -261,6 +262,21 @@ "unknown_commit_fences_owner": true, "signer_or_transport_invoked": false, "relay_delivery_claimed": false + }, + "preparation_abort": { + "payload_version": 1, + "journal_family": 7, + "worker_charge_bytes": 1048576, + "all_recipient_claims_must_be_absent": true, + "caller_nonissuance_assertion_is_proof": false, + "current_exact_recovery_consent_required": true, + "atomic_exact_original_release_required": true, + "original_preparations_retained": true, + "current_order_projection_authenticated": true, + "later_initial_requires_original_abort": true, + "fresh_signing_after_abort": false, + "unknown_commit_fences_owner": true, + "signer_or_transport_invoked": false } }, "provenance": { diff --git a/crates/domain/src/stock.rs b/crates/domain/src/stock.rs @@ -284,6 +284,19 @@ impl PoolBalances { physical.committed_hold = physical.committed_hold.checked_add(quantity)?; Self::new(self.introduced, physical) } + /// Proposes release of this exact positive preparatory quantity back to + /// available backing. It creates no stock and changes no committed or + /// quarantined claim. The executor must prove the original operation is + /// unissued and atomically retain the abort, original quantities and release. + pub fn release_preparatory(self, quantity: StockTicks) -> Result<Self, StockError> { + if quantity == StockTicks::ZERO { + return Err(StockError::ZeroMovement); + } + let mut physical = self.physical; + physical.preparatory_hold = physical.preparatory_hold.checked_sub(quantity)?; + physical.available = physical.available.checked_add(quantity)?; + Self::new(self.introduced, physical) + } /// Proposes a nonzero, exact correction against available backing only. /// Held or quarantined stock is never silently substituted for available /// stock. Depleting it needs a separate obligation/deficit transition. diff --git a/crates/domain/tests/stock.rs b/crates/domain/tests/stock.rs @@ -8,6 +8,82 @@ fn ticks(value: u64) -> StockTicks { } #[test] +fn preparatory_release_preserves_other_claims_and_cumulative_physical_history() { + let physical = PhysicalBalances { + available: ticks(4), + preparatory_hold: ticks(3), + committed_hold: ticks(5), + physical_quarantine: ticks(7), + consumed: ticks(11), + waste: ticks(13), + removed: ticks(17), + }; + let original = PoolBalances::new(ticks(60), physical).unwrap(); + let partial = original.release_preparatory(ticks(2)).unwrap(); + assert_eq!(partial.introduced(), ticks(60)); + assert_eq!( + partial.physical(), + PhysicalBalances { + available: ticks(6), + preparatory_hold: ticks(1), + ..physical + } + ); + let complete = partial.release_preparatory(ticks(1)).unwrap(); + assert_eq!(complete.introduced(), ticks(60)); + assert_eq!( + complete.physical(), + PhysicalBalances { + available: ticks(7), + preparatory_hold: StockTicks::ZERO, + ..physical + } + ); + assert_eq!( + complete.release_preparatory(ticks(1)), + Err(StockError::Underflow) + ); + assert_eq!( + original.release_preparatory(ticks(4)), + Err(StockError::Underflow) + ); + assert_eq!( + original.release_preparatory(StockTicks::ZERO), + Err(StockError::ZeroMovement) + ); + assert_eq!(original.physical(), physical); +} + +#[test] +fn preparatory_release_at_introduced_maximum_does_not_mint_or_exhaust_capacity() { + let original = PoolBalances::new( + StockTicks::MAX, + PhysicalBalances { + preparatory_hold: StockTicks::MAX, + ..PhysicalBalances::ZERO + }, + ) + .unwrap(); + let released = original.release_preparatory(StockTicks::MAX).unwrap(); + assert_eq!(released.introduced(), StockTicks::MAX); + assert_eq!( + released.physical(), + PhysicalBalances { + available: StockTicks::MAX, + ..PhysicalBalances::ZERO + } + ); + assert_eq!( + released + .hold_available(StockTicks::MAX) + .unwrap() + .release_preparatory(StockTicks::MAX) + .unwrap(), + released + ); +} + +#[test] fn installation_moves_only_exact_preparatory_backing_and_preserves_all_other_categories() { let physical = PhysicalBalances { available: ticks(30), diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -316,7 +316,7 @@ protected credential and original creation transaction ID without touching the namespace. Retain those values through protected host handling before awaiting `NativeWorkspace::initialize_seller_stock`. This explicit factory uses `stock_execution_v1.sqlite` and `.stock_execution_v1.lock` in a new owner-only -directory. Its exact version-12 catalog has separate protected authority and +directory. Its exact version-13 catalog has separate protected authority and grant records. Grant scope, route, genesis, credential and AEAD context are separate from ordinary outboxes. The same bounded native worker owns the connection, admitted work, close completion and persistent writer lock. @@ -340,11 +340,11 @@ ordinary outbox journal jobs are refused on the stock namespace. ## Owner-private inventory transactions -The current stock factory creates exact catalog version12 and protected authority -payload version12. Retained enrollment-only version1 still authenticates and +The current stock factory creates exact catalog version13 and protected authority +payload version13. Retained enrollment-only version1 still authenticates and revokes with its original codec; its inventory ports refuse unsupported work. Retained inventory version2 keeps its original pool-creation records and refuses -new correction commands. Catalogs1–11 retain their exact original codecs and +new correction commands. Catalogs1–12 retain their exact original codecs and capabilities; current multipart operation framing uses version5. No namespace is automatically migrated. Ordinary outbox catalogs are separate. @@ -438,7 +438,8 @@ owner until drain/reopen and reconciliation; the caller retains its input. `stock_signing_evidence_page` discovers up to 32 authenticated references per 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. +Installation and stock conversion use the separate explicit transition below; +transport delivery remains pending. `stock_operation_snapshot` authenticates original T0/T1, both recipient claims, and each recipient's evidence count and first exact artifact in one coherent @@ -450,8 +451,9 @@ transaction. A recovery view never returns a fresh dispatch permit. Initial seller agreement installation uses `install_stock_agreement` on the same -bounded native owner. Exact catalog/root12 retains formats1–11 without upgrading -them. The original preparation fence remains immutable. Separate authenticated +bounded native owner. Catalog12 introduced this transition; current catalog13 +retains formats1–12 without upgrading them. The original preparation fence remains +immutable. Separate authenticated agreement and per-recipient work indexes bind original T0/T1 and retained S. Installation requires actual peer seal evidence; a missing self copy remains waiting work and cannot justify releasing the peer obligation. One transaction @@ -462,7 +464,32 @@ identity witnesses are confirmed after provider IO. No signer or transport runs under the transaction. Replaying or reopening returns the original installation; uncertain commit fences the owner until drain/reopen. `stock_operation_snapshot` reports installation separately from signing and delivery facts. This initial -primitive does not implement amendments, handovers, releases, deficits, browser +primitive does not implement amendments, handovers, fulfillment releases, deficits, browser stock or complete ordinary caller orchestration. Fresh installation also refuses an observed time before its original bound plan, before any write; recovery of an existing installation remains historical. + +`abort_proven_unissued` explicitly releases an original preparation only after +authenticating absence of both recipient claims through protected history. T1 +may be absent or bound. A claim, unknown dispatch, obtained artifact or installed +agreement refuses release; a caller assertion or missing response proves nothing. +Current exact recovery consent and scope are required, including replacement +RecoverOnly consent after first-issue expiry. Fresh cleanup time cannot precede +original T0 or T1. No signer or transport is invoked. + +One transaction returns only the original quantities from preparatory to +available, preserving other orders and current stock corrections, and appends +the abort, movements, current-order projection and protected root. Future promises +create no stock. Uncertain completion fences the owner; dropped observers leave +admitted work owned until drain. `stock_preparation_abort`, original preparation +replay and `stock_operation_snapshot().aborted()` retain the explicit outcome. +Original abort replay does not repeat release. + +Catalog13 retains preparation fences by actor/operation and authenticates its +derived current-order projection from complete history. A new initial preparation +for the same order requires an actual prior abort, new operation and consent, +and fresh source and causal checks. Installation prevents another initial +preparation. Fresh T1, claim and installation for an aborted original refuse; +original history remains readable. These primitives do not yet provide the +complete ordinary caller workflow, claimed-attempt reconciliation, amendments, +fulfillment, browser stock or platform resource qualification. diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -709,7 +709,7 @@ fn stock_root_context( input: &super::AttachmentInput, version: i64, ) -> Result<EnvelopeContext, WorkspaceError> { - if matches!(version, 4..=12) { + if matches!(version, 4..=13) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -738,8 +738,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v10\0".as_slice() } else if version == 11 { b"radroots.seller_stock.authority_context.v11\0".as_slice() - } else { + } else if version == 12 { b"radroots.seller_stock.authority_context.v12\0".as_slice() + } else { + b"radroots.seller_stock.authority_context.v13\0".as_slice() }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -764,8 +766,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v10" } else if version == 11 { "radroots.seller_stock.authority.v11" - } else { + } else if version == 12 { "radroots.seller_stock.authority.v12" + } else { + "radroots.seller_stock.authority.v13" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -818,6 +822,10 @@ fn stock_record_context( "radroots.seller_stock.order", "radroots.seller_stock.order.v1", ), + "abort_movement" => ( + "radroots.seller_stock.abort_movement", + "radroots.seller_stock.abort_movement.v1", + ), "installation_movement" => ( "radroots.seller_stock.installation_movement", "radroots.seller_stock.installation_movement.v1", @@ -879,12 +887,12 @@ fn stock_record_context_for_catalog( ) -> Result<EnvelopeContext, WorkspaceError> { let original = stock_record_context(input, kind, id)?; let schema = match (catalog, kind) { - (2, _) | (3..=12, "pool") => return Ok(original), + (2, _) | (3..=13, "pool") => return Ok(original), (3, "operation") => "radroots.seller_stock.operation.v2", (4, "operation") => "radroots.seller_stock.operation.v3", (5 | 6, "operation") => "radroots.seller_stock.operation.v4", - (7..=12, "operation") => "radroots.seller_stock.operation.v5", - (3..=12, "movement") => "radroots.seller_stock.movement.v2", + (7..=13, "operation") => "radroots.seller_stock.operation.v5", + (3..=13, "movement") => "radroots.seller_stock.movement.v2", _ => return Err(WorkspaceError::RecoveryRequired), }; Ok(EnvelopeContext::new( diff --git a/crates/storage_sqlite/src/workspace/mod.rs b/crates/storage_sqlite/src/workspace/mod.rs @@ -23,18 +23,18 @@ mod schema; mod snapshot; mod stock; pub use stock::{ - SellerStockConfig, StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest, - StockAuthorityReceipt, StockBoundSigningPlan, StockCapturedEvidence, StockClaimOutcome, - StockClaimReference, StockClaimRequest, StockConsentCapture, StockConsentMode, - StockConsentOutcome, StockConsentReceipt, StockDispatchPermit, StockEnrollment, - StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, - StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt, StockHistorySnapshot, - StockInstallationOutcome, StockInstallationReceipt, StockInstallationRequest, - StockListingCapture, StockListingOutcome, StockListingReceipt, StockListingSnapshot, - StockOperationSnapshot, StockPublicationWork, StockRecipientSnapshot, StockRequestSnapshot, - StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, StockSigningProgress, - StockSnapshotRequest, StockSourceCapture, StockSourceOutcome, StockSourceProfile, - StockSourceReceipt, StockSourceSnapshot, + SellerStockConfig, StockAbortOutcome, StockAbortReceipt, StockAbortRequest, + StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest, StockAuthorityReceipt, + StockBoundSigningPlan, StockCapturedEvidence, StockClaimOutcome, StockClaimReference, + StockClaimRequest, StockConsentCapture, StockConsentMode, StockConsentOutcome, + StockConsentReceipt, StockDispatchPermit, StockEnrollment, StockEvidenceCapture, + StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, StockGrantEnrollment, + StockGrantOutcome, StockGrantReceipt, StockHistorySnapshot, StockInstallationOutcome, + StockInstallationReceipt, StockInstallationRequest, StockListingCapture, StockListingOutcome, + StockListingReceipt, StockListingSnapshot, StockOperationSnapshot, StockPublicationWork, + 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 @@ -13,6 +13,7 @@ pub use consent::{ StockConsentCapture, StockConsentMode, StockConsentOutcome, StockConsentReceipt, }; pub(in crate::workspace) mod grants; +pub use inventory::abort::{StockAbortOutcome, StockAbortReceipt, StockAbortRequest}; pub use inventory::acceptance::{ StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest, }; @@ -22,6 +23,7 @@ pub use inventory::installation::{ }; pub(in crate::workspace) mod issuance; mod ledger; +mod order_state; pub use issuance::{ StockCapturedEvidence, StockClaimOutcome, StockClaimRequest, StockDispatchPermit, StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, @@ -438,10 +440,10 @@ struct AuthorityV8 { } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { - if !matches!(self.catalog, 8..=12) && self.public_sources.is_some() { + if !matches!(self.catalog, 8..=13) && self.public_sources.is_some() { return Err(WorkspaceError::RecoveryRequired); } - if matches!(self.catalog, 8..=12) { + if matches!(self.catalog, 8..=13) { let public_sources = self .public_sources .ok_or(WorkspaceError::RecoveryRequired)?; @@ -693,7 +695,7 @@ impl Authority { public_sources: None, } } - 8..=12 => { + 8..=13 => { let value: AuthorityV8 = closed_record(bytes)?; value.public_sources.validate()?; if i64::from(value.version) != catalog @@ -823,7 +825,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=12") + sqlx::query("PRAGMA user_version=13") .execute(&mut *tx) .await .map_err(|_| WorkspaceError::StorageFailure)?; diff --git a/crates/storage_sqlite/src/workspace/stock/consent.rs b/crates/storage_sqlite/src/workspace/stock/consent.rs @@ -422,7 +422,7 @@ pub(in crate::workspace) async fn issue( proof: AttachmentProof, ) -> Result<StockConsentOutcome, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=12) { + if !matches!(access.authority.catalog, 7..=13) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() @@ -683,7 +683,7 @@ pub(in crate::workspace) async fn query( proof: AttachmentProof, ) -> Result<Option<StockConsentReceipt>, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=12) { + if !matches!(access.authority.catalog, 7..=13) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() && access.current.input().grant_id() != subject { diff --git a/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs b/crates/storage_sqlite/src/workspace/stock/consent/test_provider.rs @@ -74,7 +74,7 @@ impl KeyWrapping for Provider { fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>> { Box::pin(async move { let result = self.inner.wrap(request).await; - if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v12" + if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v13" { self.gate.pause(); } diff --git a/crates/storage_sqlite/src/workspace/stock/grants.rs b/crates/storage_sqlite/src/workspace/stock/grants.rs @@ -324,7 +324,7 @@ pub(in crate::workspace) async fn change( } let (mut authority, record, old_root, old_grant) = super::read(turn.connection, change.caller.input(), turn.crypto).await?; - if !(4..=12).contains(&authority.catalog) { + if !(4..=13).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } let catalog = authority.catalog; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -1,4 +1,5 @@ //! Owner-private inventory effects on the existing connection owner. +pub(in crate::workspace) mod abort; pub(in crate::workspace) mod acceptance; pub(in crate::workspace::stock) mod backing; pub(super) mod checkpoint; @@ -451,7 +452,7 @@ impl Turn<'_> { access.authority.authorization, mapping.as_ref().map(|value| value.effect), )?; - let framed = if matches!(catalog, 7..=12) { + let framed = if matches!(catalog, 7..=13) { Some( super::ledger::prepare( self.crypto, @@ -865,7 +866,7 @@ pub(super) async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let (frame, request, decoded) = if matches!(catalog, 7..=12) { + let (frame, request, decoded) = if matches!(catalog, 7..=13) { let retained = super::ledger::read(connection, input, crypto, operation) .await? .ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs @@ -0,0 +1,491 @@ +//! Explicit release of original preparation only when every claim is absent. +use super::super::{issuance::claim, ledger, order_state, signing_plan}; +use super::*; +use checkpoint::{EntryIdentity, IdentityTarget}; +use radroots_domain::{OrderId, stock::StockTicks}; +mod codec; +mod projection; +pub(in crate::workspace::stock) use codec::read_entry; +pub(in crate::workspace::stock) use projection::{Projection, raw_projection}; + +/// Original-operation selectors; this value supplies no nonissuance proof. +pub struct StockAbortRequest { + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, +} +impl StockAbortRequest { + pub const fn new( + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + ) -> Self { + Self { + binding, + minimum, + operation, + digest, + } + } + pub(in crate::workspace) fn attempt(&self) -> CommitAttempt { + CommitAttempt::new( + self.binding.input().workspace_id(), + self.operation, + self.digest, + None, + ) + } +} +impl std::fmt::Debug for StockAbortRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockAbortRequest(<redacted>)") + } +} +/// Confirmed original cleanup, distinct from business cancellation or delivery. +pub struct StockAbortReceipt { + attempt: CommitAttempt, + order: OrderId, + at: UnixSeconds, + checkpoint: radroots_storage::inventory::InventoryCheckpointRef, + pools: Vec<PoolSnapshot>, +} +impl StockAbortReceipt { + pub const fn attempt(&self) -> CommitAttempt { + self.attempt + } + pub const fn order_id(&self) -> OrderId { + self.order + } + pub const fn aborted_at(&self) -> UnixSeconds { + self.at + } + pub const fn checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef { + self.checkpoint + } + pub fn released_pools(&self) -> &[PoolSnapshot] { + &self.pools + } +} +impl std::fmt::Debug for StockAbortReceipt { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockAbortReceipt(<redacted>)") + } +} +#[derive(Debug)] +pub enum StockAbortOutcome { + Aborted(Box<StockAbortReceipt>), + Unknown(CommitAttempt), +} + +#[derive(Clone, Copy, Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +struct Effect { + before: PoolSnapshot, + after: PoolSnapshot, + quantity: StockTicks, + movement: [u8; 32], +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Plan { + entry: OperationId, + head: CheckpointDigest, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Body { + version: u8, + operation: OperationId, + original_head: CheckpointDigest, + #[serde(deserialize_with = "super::super::required_nullable")] + plan: Option<Plan>, + aborted_at: UnixSeconds, + authorization: StockAuthorizationRef, + effects: Vec<Effect>, +} +fn after(before: PoolSnapshot, quantity: StockTicks) -> Result<PoolSnapshot, OperationError> { + let balances = before + .balances() + .release_preparatory(quantity) + .map_err(|_| OperationError::RecoveryRequired)?; + let version = Sequence::new( + before + .version() + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + Ok(PoolSnapshot::new( + before.id(), + before.unit(), + balances, + version, + )) +} +async fn no_claims( + connection: &mut SqliteConnection, + actor: radroots_domain::PublicKey, + operation: OperationId, +) -> Result<(), OperationError> { + let count:i64=sqlx::query_scalar("SELECT (SELECT count(*) FROM stock_signing_claims WHERE actor=? AND operation_id=?)+(SELECT count(*) FROM stock_signing_evidence WHERE actor=? AND operation_id=?)+(SELECT count(*) FROM stock_agreements WHERE actor=? AND operation_id=?)+(SELECT count(*) FROM stock_operations WHERE actor=? AND related_operation=? AND family BETWEEN 4 AND 6)") + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(connection).await + .map_err(|_|OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} +pub(in crate::workspace::stock) async fn existing( + turn: &mut Turn<'_>, + access: &Access, + operation: OperationId, +) -> Result<(Option<codec::Retained>, MinimumProof), OperationError> { + let id:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_aborts WHERE actor=? AND operation_id=?") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let retained = match id { + Some(id) => Some( + Box::pin(read_entry( + turn.connection, + turn.selected, + turn.crypto, + OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?, + ), + None => None, + }; + let proof = Box::pin(checkpoint::authenticate_identity( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + IdentityTarget::Abort { + operation, + expected: retained.as_ref().map(codec::Retained::identity), + }, + )) + .await?; + Ok((retained, proof)) +} +async fn confirm_read( + turn: &mut Turn<'_>, + auth: &signing_plan::Authorized, + identity: &MinimumProof, + retained: Option<&codec::Retained>, + proof: &AttachmentProof, +) -> Result<(), OperationError> { + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + Box::pin(identity.confirm(&mut tx)).await?; + if let Some(retained) = retained { + retained.confirm(&mut tx).await?; + } + Box::pin(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 +} +pub(in crate::workspace) async fn abort( + turn: &mut Turn<'_>, + request: StockAbortRequest, + proof: AttachmentProof, +) -> Result<StockAbortOutcome, OperationError> { + let auth = Box::pin(signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + )) + .await?; + if auth.access.authority.catalog != 13 { + return Err(OperationError::UnsupportedOperation); + } + let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation)).await?; + if let Some(old) = old { + Box::pin(confirm_read(turn, &auth, &identity, Some(&old), &proof)).await?; + return Ok(StockAbortOutcome::Aborted(Box::new(old.receipt))); + } + let at = auth.access.current.observed_at(); + let earliest = auth + .plan + .as_ref() + .map(|plan| plan.bound.bound_at()) + .unwrap_or(auth.original.receipt.prepared_at()); + if at < earliest { + return Err(WorkspaceError::Unavailable.into()); + } + let current = Box::pin(checkpoint::authenticate_order_state( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + auth.original.receipt.order_id(), + )) + .await?; + if current.witness.expected.is_none_or(|value| { + value.phase != order_state::Phase::Prepared || value.operation != request.operation + }) { + return Err(OperationError::StaleState); + } + let mut claims = Vec::with_capacity(2); + for recipient in auth.original.receipt.rumor().recipients() { + let (claim, witness) = + Box::pin(claim::existing(turn, &auth, request.operation, *recipient)).await?; + if claim.is_some() { + return Err(OperationError::RecoveryRequired); + } + claims.push(witness); + } + no_claims( + turn.connection, + turn.selected.participant(), + request.operation, + ) + .await?; + let backing = Box::pin(super::backing::read( + turn, + &auth.access, + auth.original.receipt.held_pools(), + )) + .await?; + let mut originals = Vec::new(); + let mut effects = Vec::new(); + for (pool, quantity) in auth.original.held_allocations()? { + let original = read_pool(turn.connection, turn.selected, turn.crypto, pool) + .await? + .ok_or(OperationError::RecoveryRequired)?; + effects.push(Effect { + before: original.pool, + after: after(original.pool, quantity)?, + quantity, + movement: super::super::super::random()?, + }); + originals.push(original); + } + let entry = OperationId::from_bytes(super::super::super::random()?); + let transaction = TransactionId::from_bytes(super::super::super::random()?); + let before = auth + .access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let revision = Sequence::new( + before + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let body = Body { + version: 1, + operation: request.operation, + original_head: auth.original.frame.header.head, + plan: auth.plan.as_ref().map(|plan| Plan { + entry: plan.frame.header.operation, + head: plan.frame.header.head, + }), + aborted_at: at, + authorization: auth + .access + .authority + .authorization + .ok_or(OperationError::RecoveryRequired)?, + effects, + }; + let clear = zeroize::Zeroizing::new( + serde_json::to_vec(&body).map_err(|_| OperationError::StorageFailure)?, + ); + if clear.len() > ledger::BODY_MAX_BYTES { + return Err(WorkspaceError::Capacity.into()); + } + let mut header = ledger::Header { + version: 5, + family: ledger::Family::AbortedPreparation, + namespace: SellerAuthoritySelection::from_attachment(turn.selected), + actor: auth.access.current.actor(), + operation: entry, + digest: request.digest, + transaction, + revision, + previous: before.head, + head: CheckpointDigest::from_bytes([0; 32]), + pool: None, + order: Some(auth.original.receipt.order_id()), + related_operation: Some(request.operation), + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], + }; + header.head = codec::head(&header, &clear); + let projection = Projection::new(&header, &body)?; + let framed = ledger::prepare(turn.crypto, turn.selected, header, &clear).await?; + let receipt = codec::receipt(turn.selected, &framed.header, &body)?; + let mut pool_bytes = Vec::new(); + let mut movement_bytes = Vec::new(); + for (effect, original) in body.effects.iter().zip(&originals) { + pool_bytes.push( + turn.crypto + .seal_stock_record( + turn.selected, + "pool", + effect.after.id().as_bytes(), + &encode(&PoolWire { + version: 1, + label: original.view.label(), + pool: effect.after, + })?, + ) + .await?, + ); + movement_bytes.push( + turn.crypto + .seal_stock_record( + turn.selected, + "abort_movement", + &effect.movement, + &encode(&codec::Movement { + version: 1, + operation: entry, + digest: request.digest, + original: request.operation, + effect: *effect, + })?, + ) + .await?, + ); + } + let mut next = auth.access.authority.clone(); + next.inventory = Some(InventoryCheckpoint { + revision, + head: Some(framed.header.head), + movements: Sequence::new( + before + .movements + .get() + .checked_add(body.effects.len() as u64) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?, + ..before + }); + let root = turn + .crypto + .seal_stock_root(turn.selected, next.catalog, &next.encode()?) + .await?; + let anchor = receipt.attempt; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let changed:Result<(),OperationError>=async { + Box::pin(identity.confirm(&mut tx)).await?; + for claim in &claims {Box::pin(claim.confirm(&mut tx)).await?;} + no_claims(&mut tx,turn.selected.participant(),request.operation).await?; + let checked=Box::pin(auth.confirm(&mut tx,turn.namespace,turn.clock,&proof,false)).await?; + if checked.observed_at()<at {return Err(WorkspaceError::Unavailable.into());} + for pool in &backing {Box::pin(pool.confirm(&mut tx)).await?;} + framed.insert_record(&mut tx).await?;projection.insert(&mut tx,turn.selected.participant(),entry).await?; + for (index,(effect,original)) in body.effects.iter().zip(&originals).enumerate() { + let changed=sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=? AND revision=? AND protected=?") + .bind(effect.after.version().get() as i64).bind(&pool_bytes[index]).bind(effect.before.id().as_bytes().as_slice()) + .bind(effect.before.version().get() as i64).bind(&original.protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if changed.rows_affected()!=1 {return Err(OperationError::StaleState);} + sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)") + .bind(effect.movement.as_slice()).bind(turn.selected.participant().as_bytes().as_slice()).bind(checked.input().grant_id().as_bytes().as_slice()) + .bind(entry.as_bytes().as_slice()).bind(effect.before.id().as_bytes().as_slice()).bind(&movement_bytes[index]) + .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + } + current.advance(&mut tx,order_state::Marker::from_header(&framed.header,order_state::Phase::Aborted)?).await?; + let changed=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?") + .bind(root).bind(&auth.access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if changed.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);} + turn.namespace.validate()?;Ok(()) + }.await; + if let Err(error) = changed { + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Ok(StockAbortOutcome::Unknown(anchor)); + } + return Err(error); + } + if tx.commit().await.is_err() { + *turn.uncertain = true; + return Ok(StockAbortOutcome::Unknown(anchor)); + } + Ok(StockAbortOutcome::Aborted(Box::new(receipt))) +} +pub(in crate::workspace) async fn read( + turn: &mut Turn<'_>, + request: StockAbortRequest, + proof: AttachmentProof, +) -> Result<Option<StockAbortReceipt>, OperationError> { + let auth = Box::pin(signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + )) + .await?; + if auth.access.authority.catalog != 13 { + return Err(OperationError::UnsupportedOperation); + } + let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation)).await?; + Box::pin(confirm_read(turn, &auth, &identity, old.as_ref(), &proof)).await?; + Ok(old.map(|value| value.receipt)) +} + +impl NativeWorkspace { + pub async fn abort_proven_unissued( + &self, + request: StockAbortRequest, + proof: &AttachmentProof, + ) -> Result<StockAbortOutcome, OperationError> { + self.worker + .abort_proven_unissued( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } + pub async fn stock_preparation_abort( + &self, + request: StockAbortRequest, + proof: &AttachmentProof, + ) -> Result<Option<StockAbortReceipt>, OperationError> { + self.worker + .stock_preparation_abort( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort/codec.rs @@ -0,0 +1,307 @@ +//! Decode original cleanup without recursively entering an authority/history read. +use super::*; +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub(super) struct Movement { + pub version: u8, + pub operation: OperationId, + pub digest: CommandDigest, + pub original: OperationId, + pub effect: Effect, +} +pub(in crate::workspace::stock) struct Retained { + pub frame: ledger::Retained, + pub receipt: StockAbortReceipt, + projection: Projection, + plan: Option<Plan>, + movements: Vec<ledger::MovementWitness>, +} +pub(super) fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.abort_chain.v1\0"); + hash.update(header.namespace.workspace_id().as_bytes()); + hash.update(header.namespace.authority().executor_id().as_bytes()); + hash.update( + header + .namespace + .authority() + .generation() + .get() + .to_be_bytes(), + ); + hash.update(header.namespace.route_digest().as_bytes()); + hash.update(header.actor.participant().as_bytes()); + hash.update( + header + .actor + .grant_id() + .map(|id| *id.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(header.operation.as_bytes()); + hash.update(header.digest.as_bytes()); + hash.update(header.transaction.as_bytes()); + hash.update(header.revision.get().to_be_bytes()); + hash.update([u8::from(header.previous.is_some())]); + hash.update(header.previous.map(|id| *id.as_bytes()).unwrap_or([0; 32])); + hash.update(Sha256::digest(body)); + CheckpointDigest::from_bytes(hash.finalize().into()) +} +pub(super) fn receipt( + input: &AttachmentInput, + header: &ledger::Header, + body: &Body, +) -> Result<StockAbortReceipt, OperationError> { + Ok(StockAbortReceipt { + attempt: CommitAttempt::new( + input.workspace_id(), + body.operation, + header.digest, + Some(header.transaction), + ), + order: header.order.ok_or(OperationError::RecoveryRequired)?, + at: body.aborted_at, + checkpoint: radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( + input.authority(), + header.revision, + Some(header.head), + )? + .with_authorization(body.authorization), + pools: body.effects.iter().map(|effect| effect.after).collect(), + }) +} +async fn plan_selector( + connection: &mut SqliteConnection, + actor: radroots_domain::PublicKey, + operation: OperationId, + plan: Option<&Plan>, +) -> Result<(), OperationError> { + let ids:Vec<(Vec<u8>,Vec<u8>)>=sqlx::query_as("SELECT operation_id,chain_head FROM stock_operations WHERE actor=? AND related_operation=? AND family=3 ORDER BY revision LIMIT 2") + .bind(actor.as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_all(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let matches = match (plan, ids.as_slice()) { + (None, []) => true, + (Some(plan), [(entry, head)]) => { + entry.as_slice() == plan.entry.as_bytes() && head.as_slice() == plan.head.as_bytes() + } + _ => false, + }; + if !matches { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} +pub(in crate::workspace::stock) async fn read_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + operation: OperationId, +) -> Result<Option<Retained>, OperationError> { + let Some(frame) = ledger::read(connection, input, crypto, operation).await? else { + return Ok(None); + }; + let header = &frame.header; + if header.family != ledger::Family::AbortedPreparation { + return Err(OperationError::RecoveryRequired); + } + let body: Body = super::super::super::closed_record(&frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + if body.version != 1 + || header.related_operation != Some(body.operation) + || head(header, &frame.body) != header.head + || body.effects.len() > 64 + { + return Err(OperationError::RecoveryRequired); + } + let original = Box::pin(acceptance::codec::read( + connection, + input, + crypto, + body.operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if original.frame.header.head != body.original_head + || original.frame.header.digest != header.digest + || original.frame.header.order != header.order + || original.frame.header.revision >= header.revision + || body.aborted_at < original.receipt.prepared_at() + { + return Err(OperationError::RecoveryRequired); + } + plan_selector( + connection, + input.participant(), + body.operation, + body.plan.as_ref(), + ) + .await?; + if let Some(plan) = &body.plan { + let retained = Box::pin(signing_plan::read_entry( + connection, input, crypto, plan.entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.frame.header.head != plan.head + || retained.frame.header.related_operation != Some(body.operation) + || retained.frame.header.revision >= header.revision + || body.aborted_at < retained.bound.bound_at() + { + return Err(OperationError::RecoveryRequired); + } + } + no_claims(connection, input.participant(), body.operation).await?; + let quantities = original.held_allocations()?; + if quantities.len() != body.effects.len() { + return Err(OperationError::RecoveryRequired); + } + let mut movements = Vec::with_capacity(body.effects.len()); + for ((pool, quantity), effect) in quantities.into_iter().zip(&body.effects) { + if pool != effect.before.id() + || quantity != effect.quantity + || effect.before.version().get() == 0 + || after(effect.before, quantity)? != effect.after + { + return Err(OperationError::RecoveryRequired); + } + let row=sqlx::query("SELECT actor,grant_id,operation_id,pool_id,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_movements WHERE movement_id=?") + .bind(effect.movement.as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let grant = header + .actor + .grant_id() + .ok_or(OperationError::RecoveryRequired)?; + for (index, wanted) in [ + *header.actor.participant().as_bytes(), + *grant.as_bytes(), + *header.operation.as_bytes(), + *pool.as_bytes(), + ] + .into_iter() + .enumerate() + { + let actual: Vec<u8> = row + .try_get(index) + .map_err(|_| OperationError::RecoveryRequired)?; + if actual != wanted { + return Err(OperationError::RecoveryRequired); + } + } + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(4) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let clear = crypto + .open_stock_record(input, "abort_movement", &effect.movement, &protected) + .await?; + let movement: Movement = clear + .expose_secret(|bytes| super::super::super::closed_record(bytes)) + .map_err(|_| OperationError::RecoveryRequired)?; + if movement + != (Movement { + version: 1, + operation: header.operation, + digest: header.digest, + original: body.operation, + effect: *effect, + }) + { + return Err(OperationError::RecoveryRequired); + } + movements.push(ledger::MovementWitness { + id: effect.movement, + pool, + grant, + protected, + }); + } + movements.sort_by_key(|value| value.id); + if movements.windows(2).any(|pair| pair[0].id >= pair[1].id) { + return Err(OperationError::RecoveryRequired); + } + let value = Retained { + receipt: receipt(input, header, &body)?, + projection: Projection::new(header, &body)?, + frame, + plan: body.plan, + movements, + }; + value.confirm(connection).await?; + Ok(Some(value)) +} +impl Retained { + pub fn identity(&self) -> EntryIdentity { + EntryIdentity { + operation: self.frame.header.operation, + revision: self.frame.header.revision, + head: self.frame.header.head, + protected_digest: Sha256::digest(&self.frame.protected).into(), + } + } + pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { + ledger::confirm_header(connection, &self.frame.header, &self.frame.protected).await?; + ledger::confirm_parts( + connection, + self.frame.header.actor, + self.frame.header.operation, + self.frame.parts_witness, + self.frame.header.parts, + ) + .await?; + self.projection + .confirm( + connection, + self.frame.header.actor.participant(), + self.frame.header.operation, + ) + .await?; + no_claims( + connection, + self.frame.header.actor.participant(), + self.projection.operation, + ) + .await?; + plan_selector( + connection, + self.frame.header.actor.participant(), + self.projection.operation, + self.plan.as_ref(), + ) + .await?; + let count: i64 = sqlx::query_scalar( + "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?", + ) + .bind(self.frame.header.actor.participant().as_bytes().as_slice()) + .bind(self.frame.header.operation.as_bytes().as_slice()) + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count != self.movements.len() as i64 { + return Err(OperationError::RecoveryRequired); + } + for movement in &self.movements { + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE movement_id=? AND actor=? AND grant_id=? AND operation_id=? AND pool_id=? AND protected=?") + .bind(movement.id.as_slice()).bind(self.frame.header.actor.participant().as_bytes().as_slice()) + .bind(movement.grant.as_bytes().as_slice()).bind(self.frame.header.operation.as_bytes().as_slice()) + .bind(movement.pool.as_bytes().as_slice()).bind(&movement.protected).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 1 { + return Err(OperationError::RecoveryRequired); + } + } + Ok(()) + } + pub fn into_history(self) -> ledger::HistoryEntry { + ledger::HistoryEntry { + preparation: None, + local_record: None, + installation: None, + signing: None, + aborted: Some(self.projection), + header: self.frame.header, + protected: self.frame.protected, + parts_witness: self.frame.parts_witness, + pools: self.receipt.pools, + mapping: None, + movements: self.movements, + } + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort/projection.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort/projection.rs @@ -0,0 +1,75 @@ +use super::*; +#[derive(Clone, Copy)] +pub(in crate::workspace::stock) struct Projection { + pub operation: OperationId, +} +impl Projection { + pub(super) fn new(header: &ledger::Header, body: &Body) -> Result<Self, OperationError> { + if header.related_operation != Some(body.operation) { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + operation: body.operation, + }) + } + pub(in crate::workspace::stock) fn digest( + self, + actor: radroots_domain::PublicKey, + entry: OperationId, + ) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.abort_projection.v1\0"); + hash.update(actor.as_bytes()); + hash.update(self.operation.as_bytes()); + hash.update(entry.as_bytes()); + hash.finalize().into() + } + pub(super) async fn insert( + self, + connection: &mut SqliteConnection, + actor: radroots_domain::PublicKey, + entry: OperationId, + ) -> Result<(), OperationError> { + sqlx::query("INSERT INTO stock_aborts(actor,operation_id,entry_id) VALUES(?,?,?)") + .bind(actor.as_bytes().as_slice()) + .bind(self.operation.as_bytes().as_slice()) + .bind(entry.as_bytes().as_slice()) + .execute(connection) + .await + .map_err(|_| OperationError::StorageFailure)?; + Ok(()) + } + pub(super) async fn confirm( + self, + connection: &mut SqliteConnection, + actor: radroots_domain::PublicKey, + entry: OperationId, + ) -> Result<(), OperationError> { + if raw_projection(connection, actor.as_bytes(), entry.as_bytes()).await? + != self.digest(actor, entry) + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} +pub(in crate::workspace::stock) async fn raw_projection( + connection: &mut SqliteConnection, + actor: &[u8; 32], + entry: &[u8; 32], +) -> Result<[u8; 32], OperationError> { + let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_aborts WHERE actor=? AND entry_id=? AND length(operation_id)=32") + .bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let value = Projection { + operation: OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + }; + Ok(value.digest( + radroots_domain::PublicKey::from_bytes(*actor) + .map_err(|_| OperationError::RecoveryRequired)?, + OperationId::from_bytes(*entry), + )) +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs @@ -109,6 +109,7 @@ impl std::fmt::Debug for StockAcceptanceReceipt { #[derive(Debug)] pub enum StockAcceptanceOutcome { Prepared(Box<StockAcceptanceReceipt>), + Aborted(Box<super::abort::StockAbortReceipt>), Unknown(CommitAttempt), } @@ -336,7 +337,7 @@ pub(in crate::workspace) async fn admit( let access = turn .access(&request.binding, request.minimum, &proof) .await?; - if !matches!(access.authority.catalog, 9..=12) { + if !matches!(access.authority.catalog, 9..=13) { return Err(OperationError::UnsupportedOperation); } let command = &request.command; @@ -371,6 +372,11 @@ pub(in crate::workspace) async fn admit( return Err(OperationError::Unauthorized); } } + let aborted = if access.authority.catalog == 13 { + Some(Box::pin(super::abort::existing(turn, &access, operation)).await?) + } else { + None + }; let mut tx = turn .connection .begin_with("BEGIN IMMEDIATE") @@ -380,6 +386,12 @@ pub(in crate::workspace) async fn admit( identity.confirm(&mut tx).await?; consent_proof.confirm(&mut tx).await?; original.confirm(&mut tx).await?; + if let Some((retained, witness)) = &aborted { + witness.confirm(&mut tx).await?; + if let Some(retained) = retained { + retained.confirm(&mut tx).await?; + } + } let current = access .confirm(&mut tx, turn.namespace, turn.clock, &proof) .await?; @@ -392,6 +404,9 @@ pub(in crate::workspace) async fn admit( return Err(OperationError::RecoveryRequired); } checked?; + if let Some((Some(aborted), _)) = aborted { + return Ok(StockAcceptanceOutcome::Aborted(Box::new(aborted.receipt))); + } return Ok(StockAcceptanceOutcome::Prepared(Box::new(original.receipt))); } // All fresh source/mapping/pool planning follows original identity recovery. @@ -447,15 +462,42 @@ pub(in crate::workspace) async fn admit( { return Err(OperationError::StaleState); } - let order_proof = checkpoint::authenticate_order_absence( - turn.connection, - turn.selected, - turn.crypto, - &access.current, - &access.authority, - expected.order_id(), - ) - .await?; + let current_order = if access.authority.catalog == 13 { + let checked = Box::pin(checkpoint::authenticate_order_state( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + expected.order_id(), + )) + .await?; + if checked + .witness + .expected + .is_some_and(|value| value.phase != super::super::order_state::Phase::Aborted) + { + return Err(OperationError::StaleState); + } + Some(checked) + } else { + None + }; + let order_proof = if current_order.is_none() { + Some( + checkpoint::authenticate_order_absence( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + expected.order_id(), + ) + .await?, + ) + } else { + None + }; let mut mappings = Vec::new(); let mut mapping_reads = Vec::new(); let mut pool_ids = BTreeSet::new(); @@ -741,7 +783,7 @@ pub(in crate::workspace) async fn admit( .map_err(|_| OperationError::StorageFailure)?; let changed: Result<(), OperationError> = async { identity.confirm(&mut tx).await?; consent_proof.confirm(&mut tx).await?; source_minimum.confirm(&mut tx).await?; - order_proof.confirm(&mut tx).await?; admitted.confirm(&mut tx).await?; + if let Some(order_proof) = &order_proof {order_proof.confirm(&mut tx).await?;} admitted.confirm(&mut tx).await?; super::super::check_source_counts(&mut tx, access.authority.sources.ok_or(OperationError::RecoveryRequired)?).await?; for mapping in &mapping_reads { mapping.confirm(&mut tx).await?; } for witness in &pool_proofs { witness.confirm(&mut tx).await?; } @@ -752,8 +794,10 @@ pub(in crate::workspace) async fn admit( let current = access.confirm(&mut tx, turn.namespace, turn.clock, &proof).await?; check_consent(&access, &consent, command, true, current.observed_at())?; admitted.validate_at(current.observed_at())?; if current.observed_at() >= body.issue_before { return Err(OperationError::DeadlineExceeded); } - let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_orders WHERE order_id=?").bind(fence.order.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; - if count != 0 { return Err(OperationError::StaleState); } + if current_order.is_none() { + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_orders WHERE order_id=?").bind(fence.order.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; + if count != 0 { return Err(OperationError::StaleState); } + } sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,NULL,?,?,?,2,?,NULL,NULL)") .bind(header.actor.participant().as_bytes().as_slice()).bind(access.current.input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(header.digest.as_bytes().as_slice()).bind(transaction.as_bytes().as_slice()).bind(revision.get() as i64).bind(header.head.as_bytes().as_slice()).bind(&framed.protected).bind(fence.order.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; framed.insert_parts(&mut tx, header.actor, operation).await?; @@ -763,7 +807,15 @@ pub(in crate::workspace) async fn admit( if updated.rows_affected() != 1 { return Err(OperationError::StaleState); } sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)").bind(body.movements[index].as_slice()).bind(header.actor.participant().as_bytes().as_slice()).bind(access.current.input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(effect.before().id().as_bytes().as_slice()).bind(&changed_movements[index]).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; } - sqlx::query("INSERT INTO stock_orders(order_id,revision,protected) VALUES(?,?,?)").bind(fence.order.as_bytes().as_slice()).bind(fence.revision.get() as i64).bind(order_cipher).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; + if let Some(current_order) = &current_order { + sqlx::query("INSERT INTO stock_orders(actor,operation_id,order_id,revision,protected) VALUES(?,?,?,?,?)") + .bind(header.actor.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()) + .bind(fence.order.as_bytes().as_slice()).bind(fence.revision.get() as i64).bind(order_cipher) + .execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; + current_order.advance(&mut tx, super::super::order_state::Marker::from_header(&framed.header, super::super::order_state::Phase::Prepared)?).await?; + } else { + sqlx::query("INSERT INTO stock_orders(order_id,revision,protected) VALUES(?,?,?)").bind(fence.order.as_bytes().as_slice()).bind(fence.revision.get() as i64).bind(order_cipher).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; + } let updated = sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&access.root).execute(&mut *tx).await.map_err(|_| OperationError::StorageFailure)?; if updated.rows_affected() != 1 { return Err(OperationError::RecoveryRequired); } turn.namespace.validate()?; Ok(()) diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs @@ -15,6 +15,7 @@ pub(in crate::workspace::stock) struct Retained { pub receipt: StockAcceptanceReceipt, pub movements: Vec<ledger::MovementWitness>, order_cipher: Vec<u8>, + operation_keyed: bool, } impl Retained { pub(in crate::workspace::stock) fn held_allocations( @@ -69,21 +70,41 @@ impl Retained { return Err(OperationError::RecoveryRequired); } } - let count: i64 = sqlx::query_scalar( - "SELECT count(*) FROM stock_orders WHERE order_id=? AND revision=1 AND protected=?", - ) - .bind(self.receipt.order.as_bytes().as_slice()) - .bind(&self.order_cipher) - .fetch_one(connection) - .await - .map_err(|_| OperationError::RecoveryRequired)?; + let actor = self.frame.header.actor.participant(); + let query = if self.operation_keyed { + sqlx::query_scalar("SELECT count(*) FROM stock_orders WHERE actor=? AND operation_id=? AND order_id=? AND revision=1 AND protected=?") + .bind(actor.as_bytes().as_slice()) + .bind(self.frame.header.operation.as_bytes().as_slice()) + .bind(self.receipt.order.as_bytes().as_slice()) + .bind(&self.order_cipher) + } else { + sqlx::query_scalar( + "SELECT count(*) FROM stock_orders WHERE order_id=? AND revision=1 AND protected=?", + ) + .bind(self.receipt.order.as_bytes().as_slice()) + .bind(&self.order_cipher) + }; + let count: i64 = query + .fetch_one(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; if count != 1 { return Err(OperationError::RecoveryRequired); } Ok(()) } pub fn into_history(self) -> ledger::HistoryEntry { + let preparation = self.operation_keyed.then(|| { + preparation_digest( + self.frame.header.actor.participant().as_bytes(), + self.frame.header.operation.as_bytes(), + self.receipt.order.as_bytes(), + &self.order_cipher, + ) + }); ledger::HistoryEntry { + aborted: None, + preparation, local_record: None, installation: None, signing: None, @@ -96,6 +117,47 @@ impl Retained { } } } +fn preparation_digest( + actor: &[u8; 32], + operation: &[u8; 32], + order: &[u8; 32], + protected: &[u8], +) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.preparation_projection.v1\0"); + hash.update(actor); + hash.update(operation); + hash.update(order); + hash.update(1_u64.to_be_bytes()); + hash.update((protected.len() as u64).to_be_bytes()); + hash.update(protected); + hash.finalize().into() +} +pub(in crate::workspace::stock) async fn raw_preparation( + connection: &mut SqliteConnection, + actor: &[u8; 32], + operation: &[u8; 32], +) -> Result<[u8; 32], OperationError> { + let row = sqlx::query("SELECT order_id,revision,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_orders WHERE actor=? AND operation_id=?") + .bind(actor.as_slice()).bind(operation.as_slice()).fetch_optional(connection).await + .map_err(|_| OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let order: [u8; 32] = row + .try_get::<Vec<u8>, _>(0) + .map_err(|_| OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?; + let revision: i64 = row + .try_get(1) + .map_err(|_| OperationError::RecoveryRequired)?; + if revision != 1 { + return Err(OperationError::RecoveryRequired); + } + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(2) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + Ok(preparation_digest(actor, operation, &order, &protected)) +} pub(super) fn receipt( input: &AttachmentInput, header: &ledger::Header, @@ -253,7 +315,30 @@ pub(in crate::workspace::stock) async fn read( return Err(OperationError::RecoveryRequired); } let expected_fence = fence(header, &command)?; - let row = sqlx::query("SELECT revision,protected FROM stock_orders WHERE order_id=? AND length(protected) BETWEEN 1 AND 262144").bind(expected_fence.order.as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + let operation_keyed = match catalog { + 1..=12 => false, + 13 => true, + _ => return Err(OperationError::RecoveryRequired), + }; + let actor = header.actor.participant(); + let query = if operation_keyed { + sqlx::query("SELECT revision,protected FROM stock_orders WHERE actor=? AND operation_id=? AND order_id=? AND length(protected) BETWEEN 1 AND 262144") + .bind(actor.as_bytes().as_slice()) + .bind(header.operation.as_bytes().as_slice()) + .bind(expected_fence.order.as_bytes().as_slice()) + } else { + sqlx::query("SELECT revision,protected FROM stock_orders WHERE order_id=? AND length(protected) BETWEEN 1 AND 262144") + .bind(expected_fence.order.as_bytes().as_slice()) + }; + let row = query + .fetch_optional(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; let revision: i64 = row .try_get(0) .map_err(|_| OperationError::RecoveryRequired)?; @@ -311,6 +396,7 @@ pub(in crate::workspace::stock) async fn read( frame, movements, order_cipher, + operation_keyed, }; retained.confirm(connection).await?; Ok(Some(retained)) diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -14,6 +14,10 @@ impl MinimumProof { &self, connection: &mut SqliteConnection, ) -> Result<(), OperationError> { + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; let mut hash = history_hash(self.multipart); for revision in (self.lower..=self.upper).rev() { let row=sqlx::query("SELECT actor,grant_id,operation_id,command_digest,transaction_id,pool_id,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_operations WHERE revision=?") @@ -64,7 +68,7 @@ impl MinimumProof { let related: Option<Vec<u8>> = row .try_get(2) .map_err(|_| OperationError::RecoveryRequired)?; - if !(0..=6).contains(&family) { + if !(0..=7).contains(&family) { return Err(OperationError::RecoveryRequired); } let subject: Option<Vec<u8>> = row @@ -78,6 +82,18 @@ impl MinimumProof { super::super::ledger::raw_parts_witness(connection, &actor, &operation).await?; hash.update([parts]); hash.update(witness); + if family == 7 { + hash.update( + super::abort::raw_projection(connection, &actor, &operation).await?, + ); + } + if catalog == 13 && family == 2 { + hash.update(b"P13"); + hash.update( + super::acceptance::codec::raw_preparation(connection, &actor, &operation) + .await?, + ); + } if matches!(family, 4 | 5) { hash.update( super::super::issuance::raw_projection( @@ -117,6 +133,72 @@ fn history_hash(multipart: bool) -> Sha256 { hash.update([u8::from(multipart)]); hash } +/// Authenticate current order cache data from the complete protected chain. +/// The caller must retain this proof through the final SQL transaction. +pub(in crate::workspace::stock) async fn authenticate_order_state( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + authority: &Authority, + order: radroots_domain::OrderId, +) -> Result<super::super::order_state::Checked, OperationError> { + if authority.catalog != 13 { + return Err(OperationError::UnsupportedOperation); + } + let current = authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let mut previous = current.head; + let mut hash = history_hash(true); + let mut chain = super::super::order_state::Chain::new(); + for revision in (1..=current.revision.get()).rev() { + let id: Vec<u8> = sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32") + .bind(revision as i64).fetch_optional(&mut *connection).await + .map_err(|_| OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let entry = Box::pin(super::super::ledger::history( + connection, + input, + crypto, + binding, + authority, + OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if entry.header.revision.get() != revision || Some(entry.header.head) != previous { + return Err(OperationError::RecoveryRequired); + } + if entry.header.order == Some(order) + && let Some(marker) = super::super::order_state::Marker::from_history(&entry)? + { + chain.observe(marker)?; + } + entry.hash(&mut hash)?; + previous = entry.header.previous; + } + if previous.is_some() { + return Err(OperationError::RecoveryRequired); + } + chain.complete()?; + let witness = super::super::order_state::Witness { + order, + expected: chain.latest, + }; + witness.confirm(connection).await?; + Ok(super::super::order_state::Checked { + witness, + ancestry: MinimumProof { + lower: 1, + upper: current.revision.get(), + digest: hash.finalize().into(), + multipart: true, + }, + }) +} /// Initial decisions must prove absence through authenticated effects, rather /// than trusting the mutable order index or its current row count alone. pub(super) async fn authenticate_order_absence( @@ -130,7 +212,7 @@ pub(super) async fn authenticate_order_absence( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - if !matches!(authority.catalog, 9..=12) { + if !matches!(authority.catalog, 9..=13) { return Err(OperationError::UnsupportedOperation); } let upper = current.revision.get(); @@ -177,6 +259,10 @@ pub(in crate::workspace::stock) struct EntryIdentity { pub protected_digest: [u8; 32], } pub(in crate::workspace::stock) enum IdentityTarget { + Abort { + operation: OperationId, + expected: Option<EntryIdentity>, + }, Operation(OperationId, Option<EntryIdentity>), Consent { operation: OperationId, @@ -208,7 +294,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - let multipart = matches!(authority.catalog, 7..=12); + let multipart = matches!(authority.catalog, 7..=13); let upper = current.revision.get(); let mut previous = current.head; let mut hash = history_hash(multipart); @@ -219,7 +305,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( id.try_into() .map_err(|_| OperationError::RecoveryRequired)?, ); - let (identity, predecessor, natural, signing_plan, signing_claim, installation) = + let (identity, predecessor, natural, signing_plan, signing_claim, installation, aborted) = if multipart { let entry = Box::pin(super::super::ledger::history( connection, input, crypto, binding, authority, operation, @@ -259,6 +345,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( None }, entry.installation.map(|value| value.operation), + entry.aborted.map(|value| value.operation), ) } else { let entry = read_operation(connection, input, crypto, binding, operation) @@ -281,9 +368,14 @@ pub(in crate::workspace::stock) async fn authenticate_identity( None, None, None, + None, ) }; let (matched, expected) = match &target { + IdentityTarget::Abort { + operation: wanted, + expected, + } => (aborted == Some(*wanted), *expected), IdentityTarget::Operation(wanted, expected) => (*wanted == operation, *expected), IdentityTarget::Consent { operation: wanted, @@ -322,6 +414,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( | IdentityTarget::Consent { expected, .. } | IdentityTarget::SigningPlan { expected, .. } | IdentityTarget::SigningClaim { expected, .. } + | IdentityTarget::Abort { expected, .. } | IdentityTarget::Installation { expected, .. } => expected, }; if previous.is_some() || expected.is_some() { @@ -378,7 +471,7 @@ pub(in crate::workspace::stock) async fn authenticate_minimum_with_local( minimum.revision().get().max(1) }; let upper = current.revision.get(); - let multipart = matches!(authority.catalog, 7..=12); + let multipart = matches!(authority.catalog, 7..=13); let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { @@ -642,7 +735,7 @@ async fn authenticate_projected( .ok_or(OperationError::UnsupportedOperation)?; let upper = current.revision.get(); let mut expected = current.head; - let multipart = matches!(authority.catalog, 7..=12); + let multipart = matches!(authority.catalog, 7..=13); let mut hash = history_hash(multipart); for revision in (1..=upper).rev() { let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32").bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs @@ -120,7 +120,7 @@ pub(super) fn encode_operation( String::from_utf8(clear.to_vec()).map_err(|_| OperationError::StorageFailure)?, ) .map_err(|_| OperationError::StorageFailure)?; - if matches!(catalog, 5..=12) { + if matches!(catalog, 5..=13) { return super::encode(&OperationV4 { version: 4, authorization: authorization.ok_or(OperationError::RecoveryRequired)?, @@ -158,7 +158,7 @@ fn decode_inner( catalog: i64, allow_mapping: bool, ) -> Result<(InventoryRequest, OperationData), OperationError> { - if matches!(catalog, 5..=12) { + if matches!(catalog, 5..=13) { let decoded: OperationV4<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 4 { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs @@ -222,7 +222,7 @@ pub(in crate::workspace) async fn install( &proof, )) .await?; - if auth.access.authority.catalog != 12 { + if !matches!(auth.access.authority.catalog, 12 | 13) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; @@ -234,6 +234,26 @@ pub(in crate::workspace) async fn install( if auth.access.current.observed_at() < plan.bound.bound_at() { return Err(WorkspaceError::Unavailable.into()); } + let current_order = if auth.access.authority.catalog == 13 { + let checked = Box::pin(super::checkpoint::authenticate_order_state( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + plan.bound.preparation().order_id(), + )) + .await?; + if checked.witness.expected.is_none_or(|value| { + value.phase != super::super::order_state::Phase::Prepared + || value.operation != request.operation + }) { + return Err(OperationError::StaleState); + } + Some(checked) + } else { + None + }; let recipients = *plan.bound.preparation().rumor().recipients(); let mut selections = Vec::with_capacity(2); let mut work = Vec::with_capacity(2); @@ -428,6 +448,9 @@ pub(in crate::workspace) async fn install( if changed.rows_affected()!=1 {return Err(OperationError::StaleState);} sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)").bind(effect.movement.as_slice()).bind(turn.selected.participant().as_bytes().as_slice()).bind(current.input().grant_id().as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(effect.before.id().as_bytes().as_slice()).bind(&movement_bytes[index]).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; } + if let Some(current_order) = &current_order { + current_order.advance(&mut tx, super::super::order_state::Marker::from_header(&framed.header, super::super::order_state::Phase::Installed)?).await?; + } let changed=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&auth.access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; if changed.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);}turn.namespace.validate()?;Ok(()) }.await; @@ -458,7 +481,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if auth.access.authority.catalog != 12 { + if !matches!(auth.access.authority.catalog, 12 | 13) { return Err(OperationError::UnsupportedOperation); } let (retained, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs @@ -292,6 +292,8 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + aborted: None, + preparation: None, local_record: None, header: self.frame.header, protected: self.frame.protected, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs b/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs @@ -58,7 +58,7 @@ impl MappingRead { } } pub(super) fn require(access: &Access, key: OptionMappingKey) -> Result<(), OperationError> { - if !(5..=12).contains(&access.authority.catalog) { + if !(5..=13).contains(&access.authority.catalog) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn record_version(catalog: i64) -> Result<u8, OperationError> { match catalog { 2 => Ok(1), - 3..=12 => Ok(2), + 3..=13 => Ok(2), _ => Err(OperationError::RecoveryRequired), } } diff --git a/crates/storage_sqlite/src/workspace/stock/issuance.rs b/crates/storage_sqlite/src/workspace/stock/issuance.rs @@ -32,12 +32,19 @@ pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<() return Err(WorkspaceError::RecoveryRequired); } if catalog >= 12 { - let (agreements, installs, work):(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM stock_agreements),(SELECT count(*) FROM stock_operations WHERE family=6),(SELECT count(*) FROM stock_publication_work)").fetch_one(connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + let (agreements, installs, work):(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM stock_agreements),(SELECT count(*) FROM stock_operations WHERE family=6),(SELECT count(*) FROM stock_publication_work)").fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; if agreements != installs || work != installs.checked_mul(2).ok_or(WorkspaceError::Capacity)? { return Err(WorkspaceError::RecoveryRequired); } } + if catalog == 13 { + let (aborts, entries, states, orders):(i64,i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM stock_aborts),(SELECT count(*) FROM stock_operations WHERE family=7),(SELECT count(*) FROM stock_order_states),(SELECT count(DISTINCT order_id) FROM stock_orders)") + .fetch_one(connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + if aborts != entries || states != orders { + return Err(WorkspaceError::RecoveryRequired); + } + } Ok(()) } diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs @@ -266,6 +266,14 @@ pub(in crate::workspace) async fn claim( confirm_read(turn, &auth, &witness, Some(&retained), &proof).await?; return Ok(StockClaimOutcome::Existing(retained.report)); } + let current_order = Box::pin(super::super::order_state::signing_state( + turn, + &auth.access, + auth.original.receipt.order_id(), + request.operation, + true, + )) + .await?; let at = auth.access.current.observed_at(); acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, at)?; if at < plan.bound.bound_at() || at >= plan.bound.preparation().first_issue_deadline() { @@ -367,6 +375,7 @@ pub(in crate::workspace) async fn claim( witness.confirm(&mut tx).await?; let current=auth.confirm(&mut tx,turn.namespace,turn.clock,&proof,true).await?; for pool in &backing { pool.confirm(&mut tx).await?; } + if let Some(current_order) = &current_order {current_order.confirm(&mut tx).await?;} if current.observed_at()<at {return Err(WorkspaceError::Unavailable.into());} framed.insert_record(&mut tx).await?; sqlx::query("INSERT INTO stock_signing_claims(actor,operation_id,recipient,entry_id) VALUES(?,?,?,?)").bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation.as_bytes().as_slice()).bind(request.recipient.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs @@ -142,6 +142,8 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + aborted: None, + preparation: None, local_record: None, installation: None, header: self.frame.header, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs @@ -211,6 +211,8 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + aborted: None, + preparation: None, installation: None, header: self.frame.header, protected: self.frame.protected, diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -22,6 +22,7 @@ pub(super) enum Family { SigningClaim, SigningEvidence, Installation, + AbortedPreparation, } #[derive(Serialize, Deserialize)] @@ -75,6 +76,7 @@ impl Header { | Family::SigningClaim | Family::SigningEvidence | Family::Installation + | Family::AbortedPreparation ) != self.related_operation.is_some() || (self.family == Family::Consent) != self.subject_grant.is_some() || self.bytes == 0 @@ -328,6 +330,7 @@ impl Family { Self::SigningClaim => 4, Self::SigningEvidence => 5, Self::Installation => 6, + Self::AbortedPreparation => 7, } } } @@ -435,6 +438,8 @@ pub(super) struct MovementWitness { /// A completely decoded original effect. Only the owning family decoder /// supplies its pool effects and movement witnesses; SQL indexes do not. pub(super) struct HistoryEntry { + pub aborted: Option<super::inventory::abort::Projection>, + pub preparation: Option<[u8; 32]>, pub header: Header, pub protected: Vec<u8>, pub parts_witness: [u8; 32], @@ -481,6 +486,8 @@ pub(super) async fn history( _ => return Err(OperationError::RecoveryRequired), }; Ok(Some(HistoryEntry { + aborted: None, + preparation: None, local_record: None, installation: None, signing: None, @@ -514,6 +521,8 @@ pub(super) async fn history( return Err(OperationError::RecoveryRequired); } Ok(Some(HistoryEntry { + aborted: None, + preparation: None, local_record: None, installation: None, signing: None, @@ -525,7 +534,7 @@ pub(super) async fn history( movements: vec![], })) } - Some(2) if matches!(authority.catalog, 9..=12) => Ok(Some( + Some(2) if matches!(authority.catalog, 9..=13) => Ok(Some( Box::pin(super::inventory::acceptance::codec::read( connection, input, crypto, operation, )) @@ -534,7 +543,7 @@ pub(super) async fn history( .into_history(), )), Some(2) => Err(OperationError::UnsupportedOperation), - Some(3) if matches!(authority.catalog, 10..=12) => { + Some(3) if matches!(authority.catalog, 10..=13) => { let retained = Box::pin(super::signing_plan::read_entry( connection, input, crypto, operation, )) @@ -558,7 +567,7 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(6) if authority.catalog == 12 => Ok(Some( + Some(6) if matches!(authority.catalog, 12 | 13) => Ok(Some( Box::pin(super::inventory::installation::read_entry( connection, input, crypto, operation, )) @@ -566,6 +575,14 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), + Some(7) if authority.catalog == 13 => Ok(Some( + Box::pin(super::inventory::abort::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )), Some(_) => Err(OperationError::RecoveryRequired), } } @@ -616,6 +633,22 @@ impl HistoryEntry { )?; hash.update([header.parts]); hash.update(self.parts_witness); + match (header.family, self.aborted) { + (Family::AbortedPreparation, Some(projection)) => { + hash.update(projection.digest(header.actor.participant(), header.operation)) + } + (Family::AbortedPreparation, None) | (_, Some(_)) => { + return Err(OperationError::RecoveryRequired); + } + (_, None) => {} + } + if let Some(preparation) = self.preparation { + if header.family != Family::Acceptance { + return Err(OperationError::RecoveryRequired); + } + hash.update(b"P13"); + hash.update(preparation); + } match (header.family, self.signing) { (Family::SigningClaim | Family::SigningEvidence, Some(projection)) => { hash.update(projection.digest(header.actor.participant(), header.operation)) diff --git a/crates/storage_sqlite/src/workspace/stock/order_state.rs b/crates/storage_sqlite/src/workspace/stock/order_state.rs @@ -0,0 +1,259 @@ +//! Current order selectors are derived cache data, never business authority. +use super::*; +use radroots_domain::{OperationId, OrderId, PublicKey}; +use radroots_storage::command::OperationError; +use sqlx::Row; + +#[derive(Clone, Copy, Eq, PartialEq)] +pub(super) enum Phase { + Prepared, + Installed, + Aborted, +} +impl Phase { + fn code(self) -> i64 { + match self { + Self::Prepared => 0, + Self::Installed => 1, + Self::Aborted => 2, + } + } +} +#[derive(Clone, Copy, Eq, PartialEq)] +pub(super) struct Marker { + pub order: OrderId, + pub actor: PublicKey, + pub operation: OperationId, + pub entry: OperationId, + pub revision: Sequence, + pub phase: Phase, +} +impl Marker { + /// Called only with a completely authenticated family-specific entry. + pub fn from_history(entry: &ledger::HistoryEntry) -> Result<Option<Self>, OperationError> { + let phase = match entry.header.family { + ledger::Family::Acceptance => Phase::Prepared, + ledger::Family::Installation => Phase::Installed, + ledger::Family::AbortedPreparation => Phase::Aborted, + _ => return Ok(None), + }; + Self::from_header(&entry.header, phase).map(Some) + } + pub fn from_header(header: &ledger::Header, phase: Phase) -> Result<Self, OperationError> { + let family = match phase { + Phase::Prepared => 2, + Phase::Installed => 6, + Phase::Aborted => 7, + }; + if header.family.code() != family { + return Err(OperationError::RecoveryRequired); + } + let operation = match phase { + Phase::Prepared => header.operation, + Phase::Installed | Phase::Aborted => header + .related_operation + .ok_or(OperationError::RecoveryRequired)?, + }; + Ok(Self { + order: header.order.ok_or(OperationError::RecoveryRequired)?, + actor: header.actor.participant(), + operation, + entry: header.operation, + revision: header.revision, + phase, + }) + } +} + +pub(super) struct Witness { + pub order: OrderId, + pub expected: Option<Marker>, +} +impl Witness { + /// Compare the complete selected raw cache row after all provider IO. + pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { + let row = sqlx::query("SELECT actor,operation_id,entry_id,revision,phase FROM stock_order_states WHERE order_id=?") + .bind(self.order.as_bytes().as_slice()).fetch_optional(connection).await + .map_err(|_| OperationError::RecoveryRequired)?; + let actual = if let Some(row) = row { + let bytes = |column| { + row.try_get::<Vec<u8>, _>(column) + .map_err(|_| OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let revision: i64 = row + .try_get(3) + .map_err(|_| OperationError::RecoveryRequired)?; + let phase: i64 = row + .try_get(4) + .map_err(|_| OperationError::RecoveryRequired)?; + if revision <= 0 { + return Err(OperationError::RecoveryRequired); + } + Some(Marker { + order: self.order, + actor: PublicKey::from_bytes(bytes(0)?) + .map_err(|_| OperationError::RecoveryRequired)?, + operation: OperationId::from_bytes(bytes(1)?), + entry: OperationId::from_bytes(bytes(2)?), + revision: Sequence::new(revision as u64) + .map_err(|_| OperationError::RecoveryRequired)?, + phase: match phase { + 0 => Phase::Prepared, + 1 => Phase::Installed, + 2 => Phase::Aborted, + _ => return Err(OperationError::RecoveryRequired), + }, + }) + } else { + None + }; + if actual != self.expected { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } + /// The owning BEGIN IMMEDIATE transaction must retain the bound history + /// and root witnesses as well. This row supplies no independent authority. + pub async fn advance( + &self, + connection: &mut SqliteConnection, + next: Marker, + ) -> Result<(), OperationError> { + if next.order != self.order + || self + .expected + .is_some_and(|old| next.revision <= old.revision) + { + return Err(OperationError::RecoveryRequired); + } + let legal = match self.expected { + None => next.phase == Phase::Prepared, + Some(old) if old.actor == next.actor => match (old.phase, next.phase) { + (Phase::Prepared, Phase::Installed | Phase::Aborted) => { + old.operation == next.operation + } + (Phase::Aborted, Phase::Prepared) => old.operation != next.operation, + _ => false, + }, + Some(_) => false, + }; + if !legal { + return Err(OperationError::RecoveryRequired); + } + self.confirm(connection).await?; + let result = if let Some(old) = self.expected { + sqlx::query("UPDATE stock_order_states SET actor=?,operation_id=?,entry_id=?,revision=?,phase=? WHERE order_id=? AND actor=? AND operation_id=? AND entry_id=? AND revision=? AND phase=?") + .bind(next.actor.as_bytes().as_slice()).bind(next.operation.as_bytes().as_slice()) + .bind(next.entry.as_bytes().as_slice()).bind(next.revision.get() as i64) + .bind(next.phase.code()).bind(self.order.as_bytes().as_slice()) + .bind(old.actor.as_bytes().as_slice()).bind(old.operation.as_bytes().as_slice()) + .bind(old.entry.as_bytes().as_slice()).bind(old.revision.get() as i64) + .bind(old.phase.code()).execute(connection).await + } else { + sqlx::query("INSERT INTO stock_order_states(order_id,actor,operation_id,entry_id,revision,phase) VALUES(?,?,?,?,?,?)") + .bind(next.order.as_bytes().as_slice()).bind(next.actor.as_bytes().as_slice()) + .bind(next.operation.as_bytes().as_slice()).bind(next.entry.as_bytes().as_slice()) + .bind(next.revision.get() as i64).bind(next.phase.code()).execute(connection).await + }.map_err(|_| OperationError::StorageFailure)?; + if result.rows_affected() != 1 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} + +/// Constant-memory backward validation of initial decision transitions. Each +/// original preparation remains independently recoverable after a later abort. +pub(super) struct Chain { + pub latest: Option<Marker>, + previous: Previous, +} +enum Previous { + Latest, + Preparation(OperationId), + AbortOrGenesis(OperationId), +} +impl Chain { + pub const fn new() -> Self { + Self { + latest: None, + previous: Previous::Latest, + } + } + pub fn observe(&mut self, marker: Marker) -> Result<(), OperationError> { + if self.latest.is_none() { + self.latest = Some(marker); + } + match self.previous { + Previous::Latest => {} + Previous::Preparation(operation) + if marker.phase == Phase::Prepared && marker.operation == operation => {} + Previous::AbortOrGenesis(operation) + if marker.phase == Phase::Aborted && marker.operation != operation => {} + _ => return Err(OperationError::RecoveryRequired), + } + self.previous = match marker.phase { + Phase::Prepared => Previous::AbortOrGenesis(marker.operation), + Phase::Installed | Phase::Aborted => Previous::Preparation(marker.operation), + }; + Ok(()) + } + pub fn complete(&self) -> Result<(), OperationError> { + match self.previous { + Previous::Latest | Previous::AbortOrGenesis(_) => Ok(()), + Previous::Preparation(_) => Err(OperationError::RecoveryRequired), + } + } +} + +pub(super) struct Checked { + pub witness: Witness, + pub ancestry: inventory::checkpoint::MinimumProof, +} +impl Checked { + pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { + Box::pin(self.ancestry.confirm(connection)).await?; + self.witness.confirm(connection).await + } + pub async fn advance( + &self, + connection: &mut SqliteConnection, + next: Marker, + ) -> Result<(), OperationError> { + self.confirm(connection).await?; + self.witness.advance(connection, next).await + } +} + +/// Order history eligibility only. The caller still confirms current consent, +/// exact intent, deadline, provider capability and this proof before dispatch. +pub(super) async fn signing_state( + turn: &mut inventory::Turn<'_>, + access: &inventory::Access, + order: OrderId, + operation: OperationId, + allow_installed_copy: bool, +) -> Result<Option<Checked>, OperationError> { + if access.authority.catalog < 13 { + return Ok(None); + } + let checked = Box::pin(inventory::checkpoint::authenticate_order_state( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + order, + )) + .await?; + if checked.witness.expected.is_none_or(|value| { + value.operation != operation + || !(value.phase == Phase::Prepared + || (allow_installed_copy && value.phase == Phase::Installed)) + }) { + return Err(OperationError::StaleState); + } + Ok(Some(checked)) +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs @@ -0,0 +1,307 @@ +use super::*; + +#[tokio::test] +async fn replacement_recover_only_consent_can_abort_after_first_issue_expiry() { + for has_plan in [false, true] { + let r = Rig::new().await; + let (command, receipt) = Box::pin(prepared(&r)).await; + if has_plan { + bound(bind(&r, &receipt, 42).await.unwrap()); + } + r.clock.0.store(250, Ordering::SeqCst); + assert_eq!( + abort(&r, &receipt).await.unwrap_err(), + OperationError::DeadlineExceeded + ); + 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 consent = 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, + &consent, + r.enrollment.proof() + ) + .await + .unwrap(), + StockConsentOutcome::Committed(_) + )); + let first = released( + r.store + .abort_proven_unissued( + StockAbortRequest::new( + binding.clone(), + inventory_minimum(&r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ), + child.proof(), + ) + .await + .unwrap(), + ); + assert_eq!(first.aborted_at().get(), 250); + balances(&r, 80, 10, 0, 0, 3).await; + balances(&r, 81, 10, 0, 0, 3).await; + let current = inventory_minimum(&r).await; + let replay = released( + r.store + .abort_proven_unissued( + StockAbortRequest::new( + binding, + current, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ), + child.proof(), + ) + .await + .unwrap(), + ); + assert_eq!(first.attempt(), replay.attempt()); + assert_eq!(inventory_minimum(&r).await, current); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn late_order_grant_pool_and_unrelated_preparation_changes_never_commit_a_release() { + for damage in 0..5 { + let mut r = Rig::new().await; + let (_, receipt) = Box::pin(prepared(&r)).await; + if damage == 4 { + retain_source(&r, "request_other_order").await; + let command = acceptance_command_snapshot( + &r, + 91, + false, + &inspect_named(&r, "request_other_order").await, + ); + acceptance_consent(&r, &command).await; + prepare(&r, &command).await.unwrap(); + } + let provider = reopen(&mut r).await; + let selected = abort_request(&r, &receipt).await; + let mut raw = database(&r).await; + let root: Vec<u8> = + sqlx::query_scalar("SELECT protected FROM stock_authority WHERE singleton=1") + .fetch_one(&mut raw) + .await + .unwrap(); + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + let mut pending = Box::pin( + r.store + .abort_proven_unissued(selected, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + match damage { + 0 => { + sqlx::raw_sql("UPDATE stock_order_states SET phase=1") + .execute(&mut raw) + .await + .unwrap(); + } + 1 => { + sqlx::raw_sql("UPDATE stock_grants SET protected=randomblob(length(protected))") + .execute(&mut raw) + .await + .unwrap(); + } + 2 => { + sqlx::raw_sql("UPDATE stock_pools SET protected=randomblob(length(protected))") + .execute(&mut raw) + .await + .unwrap(); + } + 3 => { + sqlx::raw_sql("UPDATE stock_orders SET protected=randomblob(length(protected))") + .execute(&mut raw) + .await + .unwrap(); + } + _ => { + sqlx::query("UPDATE stock_orders SET protected=randomblob(length(protected)) WHERE operation_id<>?") + .bind(receipt.attempt().operation_id().as_bytes().as_slice()).execute(&mut raw).await.unwrap(); + } + } + let pools: Vec<(Vec<u8>, i64, Vec<u8>)> = + sqlx::query_as("SELECT pool_id,revision,protected FROM stock_pools ORDER BY pool_id") + .fetch_all(&mut raw) + .await + .unwrap(); + provider.gate.release(); + assert!(pending.await.is_err(), "damage {damage}"); + let after: Vec<(Vec<u8>, i64, Vec<u8>)> = + sqlx::query_as("SELECT pool_id,revision,protected FROM stock_pools ORDER BY pool_id") + .fetch_all(&mut raw) + .await + .unwrap(); + assert_eq!(after, pools); + assert_eq!( + sqlx::query_scalar::<_, Vec<u8>>( + "SELECT protected FROM stock_authority WHERE singleton=1" + ) + .fetch_one(&mut raw) + .await + .unwrap(), + root + ); + assert_eq!(sqlx::query_scalar::<_,i64>("SELECT (SELECT count(*) FROM stock_aborts)+(SELECT count(*) FROM stock_operations WHERE family=7)").fetch_one(&mut raw).await.unwrap(),0); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn acknowledged_abort_refuses_restored_tail_without_erasing_original_history() { + let mut r = Rig::new().await; + let (_, receipt) = Box::pin(prepared(&r)).await; + r.store.close().await.unwrap(); + let backup = r.fixture.root().join("before-abort.sqlite"); + std::fs::copy(r.path.join("stock_execution_v1.sqlite"), &backup).unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + let acknowledged = released(abort(&r, &receipt).await.unwrap()).checkpoint(); + r.store.close().await.unwrap(); + std::fs::copy(&backup, r.path.join("stock_execution_v1.sqlite")).unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + let selected = StockAbortRequest::new( + r.binding.clone(), + acknowledged, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ); + assert_eq!( + r.store + .stock_preparation_abort(selected, r.enrollment.proof()) + .await + .unwrap_err() + .code(), + "stale_checkpoint" + ); + balances(&r, 80, 9, 1, 0, 2).await; + balances(&r, 81, 8, 2, 0, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn unknown_abort_commit_fences_owner_and_reopens_original_identity_without_signing() { + let mut r = Rig::new().await; + let (_, receipt) = Box::pin(prepared(&r)).await; + let selected = abort_request(&r, &receipt).await; + let mut raw = 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_aborts BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut raw).await.unwrap(); + let StockAbortOutcome::Unknown(anchor) = abort(&r, &receipt).await.unwrap() else { + panic!("unknown commit"); + }; + assert_eq!(anchor.operation_id(), receipt.attempt().operation_id()); + assert_eq!( + r.store + .abort_proven_unissued(selected, r.enrollment.proof()) + .await + .unwrap_err(), + OperationError::RecoveryRequired + ); + r.store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut raw) + .await + .unwrap(); + raw.close().await.unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + let outcome = released(abort(&r, &receipt).await.unwrap()); + assert_eq!(outcome.attempt().operation_id(), anchor.operation_id()); + balances(&r, 80, 10, 0, 0, 3).await; + balances(&r, 81, 10, 0, 0, 3).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn losing_abort_observer_drains_original_admitted_work_before_reopen() { + let mut r = Rig::new().await; + let (_, receipt) = Box::pin(prepared(&r)).await; + let provider = reopen(&mut r).await; + let selected = abort_request(&r, &receipt).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + let mut pending = Box::pin( + r.store + .abort_proven_unissued(selected, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + drop(pending); + provider.gate.release(); + reopen_plain(&mut r).await; + let original = r + .store + .stock_preparation_abort(abort_request(&r, &receipt).await, r.enrollment.proof()) + .await + .unwrap() + .unwrap(); + let before = inventory_minimum(&r).await; + assert_eq!( + released(abort(&r, &receipt).await.unwrap()).attempt(), + original.attempt() + ); + assert_eq!(inventory_minimum(&r).await, before); + balances(&r, 80, 10, 0, 0, 3).await; + balances(&r, 81, 10, 0, 0, 3).await; + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/abort_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/abort_tests.rs @@ -0,0 +1,282 @@ +//! Actual explicit release, retained originals and subsequent authorized work. +use super::super::super::super::super::super::retain as retain_source; +use super::super::super::super::super::{ + command as acceptance_command, command_snapshot as acceptance_command_snapshot, + consent as acceptance_consent, inspect_named, request as acceptance_request, +}; +use super::*; +use crate::workspace::{StockAbortOutcome, StockAbortReceipt, StockAbortRequest}; +#[path = "abort_failures_tests.rs"] +mod failures; + +async fn abort_request(r: &Rig, receipt: &StockAcceptanceReceipt) -> StockAbortRequest { + StockAbortRequest::new( + r.binding.clone(), + inventory_minimum(r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ) +} +pub(super) async fn abort( + r: &Rig, + receipt: &StockAcceptanceReceipt, +) -> Result<StockAbortOutcome, OperationError> { + r.store + .abort_proven_unissued(abort_request(r, receipt).await, r.enrollment.proof()) + .await +} +pub(super) fn released(value: StockAbortOutcome) -> StockAbortReceipt { + let StockAbortOutcome::Aborted(value) = value else { + panic!("abort must confirm"); + }; + *value +} +#[tokio::test] +async fn unclaimed_preparation_aborts_before_or_after_t1_and_originals_survive_new_order_attempt() { + for has_plan in [false, true] { + let mut r = Rig::new().await; + let (command, receipt) = Box::pin(prepared(&r)).await; + if has_plan { + bound(bind(&r, &receipt, 42).await.unwrap()); + } + let before = inventory_minimum(&r).await; + let first = released(abort(&r, &receipt).await.unwrap()); + assert_eq!( + first.attempt().operation_id(), + receipt.attempt().operation_id() + ); + assert_eq!( + first.checkpoint().revision().get(), + before.revision().get() + 1 + ); + balances(&r, 80, 10, 0, 0, 3).await; + balances(&r, 81, 10, 0, 0, 3).await; + assert!(history(&r).await.analysis().seller_head().is_none()); + let acknowledged = inventory_minimum(&r).await; + reopen_plain(&mut r).await; + let replay = released(abort(&r, &receipt).await.unwrap()); + assert_eq!(replay.attempt(), first.attempt()); + assert_eq!(inventory_minimum(&r).await, acknowledged); + assert!(matches!( + r.store + .prepare_stock_acceptance( + acceptance_request(&r, &command).await, + r.enrollment.proof() + ) + .await + .unwrap(), + StockAcceptanceOutcome::Aborted(_) + )); + if !has_plan { + assert!(bind(&r, &receipt, 42).await.is_err()); + } + for recipient in receipt.rumor().recipients() { + assert!(claim(&r, &receipt, *recipient).await.is_err()); + } + assert!(install(&r, &receipt).await.is_err()); + let next = acceptance_command(&r, 91, false).await; + acceptance_consent(&r, &next).await; + let next = prepare(&r, &next).await.unwrap(); + assert_eq!(next.order_id(), receipt.order_id()); + assert_ne!( + next.attempt().operation_id(), + receipt.attempt().operation_id() + ); + balances(&r, 80, 7, 3, 0, 4).await; + balances(&r, 81, 10, 0, 0, 3).await; + let current = inventory_minimum(&r).await; + let view = r + .store + .stock_operation_snapshot( + StockSnapshotRequest::new( + r.binding.clone(), + current, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ), + r.enrollment.proof(), + ) + .await + .unwrap(); + assert_eq!(view.aborted().unwrap().attempt(), first.attempt()); + assert!(view.installation().is_none()); + assert!( + view.recipients() + .iter() + .all(|value| value.claim().is_none() && value.first_evidence().is_none()) + ); + assert_eq!(inventory_minimum(&r).await, current); + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn claims_actual_output_and_installation_never_become_abortable_absence() { + for state in [0, 1, 2, 3] { + let r = Rig::new().await; + let receipt = Box::pin(ready(&r)).await; + if state < 2 { + let recipient = if state == 0 { + peer(&r, &receipt) + } else { + r.enrollment.input().participant() + }; + let StockClaimOutcome::Fresh(permit) = claim(&r, &receipt, recipient).await.unwrap() + else { + panic!("fresh claim"); + }; + drop(permit); + } else { + retain(&r, &receipt, peer(&r, &receipt)).await; + if state == 3 { + installed(install(&r, &receipt).await.unwrap()); + } + } + let before = inventory_minimum(&r).await; + assert!(abort(&r, &receipt).await.is_err()); + assert_eq!(inventory_minimum(&r).await, before); + if state == 3 { + balances(&r, 80, 9, 0, 1, 3).await; + balances(&r, 81, 8, 0, 2, 3).await; + } else { + balances(&r, 80, 9, 1, 0, 2).await; + balances(&r, 81, 8, 2, 0, 2).await; + } + assert!( + r.store + .stock_preparation_abort(abort_request(&r, &receipt).await, r.enrollment.proof()) + .await + .unwrap() + .is_none() + ); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn abort_releases_only_own_quantities_after_another_order_commits_and_stock_is_added() { + let r = Rig::new().await; + let (_, first) = Box::pin(prepared(&r)).await; + retain_source(&r, "request_other_order").await; + let command = acceptance_command_snapshot( + &r, + 91, + false, + &inspect_named(&r, "request_other_order").await, + ); + acceptance_consent(&r, &command).await; + let other = prepare(&r, &command).await.unwrap(); + bound(bind(&r, &other, 42).await.unwrap()); + retain(&r, &other, peer(&r, &other)).await; + installed(install(&r, &other).await.unwrap()); + balances(&r, 80, 6, 1, 3, 4).await; + physical(&r,serde_json::json!({"type":"stock.adjust","context":context(&r,95),"input":{"pool_id":pool(80),"expected_version":"4","direction":"add","amount":"5","reason":"available correction before explicit cleanup"}})).await; + released(abort(&r, &first).await.unwrap()); + balances(&r, 80, 12, 0, 3, 6).await; + balances(&r, 81, 10, 0, 0, 3).await; + assert!(abort(&r, &other).await.is_err()); + let before = inventory_minimum(&r).await; + let replay = released(abort(&r, &first).await.unwrap()); + assert_eq!(replay.released_pools()[0].balances().introduced().get(), 15); + assert_eq!(inventory_minimum(&r).await, before); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn explicit_future_promise_aborts_without_invented_pools_or_movements() { + let r = Rig::new().await; + r.retain(&r.capture("listing_fixed")).await; + retain_source(&r, "request_future_promise").await; + let command = acceptance_command_snapshot( + &r, + 90, + false, + &inspect_named(&r, "request_future_promise").await, + ); + acceptance_consent(&r, &command).await; + let receipt = prepare(&r, &command).await.unwrap(); + let outcome = released(abort(&r, &receipt).await.unwrap()); + assert!(outcome.released_pools().is_empty()); + let mut raw = database(&r).await; + for query in [ + "SELECT count(*) FROM stock_pools", + "SELECT count(*) FROM stock_movements", + ] { + assert_eq!( + sqlx::query_scalar::<_, i64>(query) + .fetch_one(&mut raw) + .await + .unwrap(), + 0 + ); + } + raw.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn each_abort_write_failure_rolls_back_all_release_index_and_order_effects() { + for statement in [ + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations WHEN NEW.family=7 BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_operation_parts WHEN (SELECT family FROM stock_operations WHERE operation_id=NEW.operation_id)=7 BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_aborts BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_pools WHEN OLD.pool_id=(SELECT min(pool_id) FROM stock_pools) BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_pools WHEN OLD.pool_id=(SELECT max(pool_id) FROM stock_pools) BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_movements WHEN (SELECT count(*) FROM stock_movements m JOIN stock_operations o ON o.actor=m.actor AND o.operation_id=m.operation_id WHERE o.family=7)=0 BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_movements WHEN (SELECT count(*) FROM stock_movements m JOIN stock_operations o ON o.actor=m.actor AND o.operation_id=m.operation_id WHERE o.family=7)=1 BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_order_states BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fault'); END", + ] { + let r = Rig::new().await; + let (_, receipt) = Box::pin(prepared(&r)).await; + let before = inventory_minimum(&r).await; + let mut raw = database(&r).await; + sqlx::raw_sql(statement).execute(&mut raw).await.unwrap(); + assert_eq!( + abort(&r, &receipt).await.unwrap_err().code(), + "storage_failure", + "{statement}" + ); + assert_eq!(inventory_minimum(&r).await, before); + balances(&r, 80, 9, 1, 0, 2).await; + balances(&r, 81, 8, 2, 0, 2).await; + assert_eq!(sqlx::query_scalar::<_,i64>("SELECT (SELECT count(*) FROM stock_aborts)+(SELECT count(*) FROM stock_operations WHERE family=7)+(SELECT count(*) FROM stock_order_states WHERE phase<>0)").fetch_one(&mut raw).await.unwrap(),0); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut raw) + .await + .unwrap(); + released(abort(&r, &receipt).await.unwrap()); + balances(&r, 80, 10, 0, 0, 3).await; + balances(&r, 81, 10, 0, 0, 3).await; + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn fresh_abort_refuses_time_before_original_preparation_and_preserves_historical_replay() { + for has_plan in [false, true] { + let r = Rig::new().await; + r.clock.0.store(155, Ordering::SeqCst); + let (_, receipt) = Box::pin(prepared(&r)).await; + if has_plan { + bound(bind(&r, &receipt, 42).await.unwrap()); + } + let before = inventory_minimum(&r).await; + r.clock.0.store(152, Ordering::SeqCst); + assert_eq!( + abort(&r, &receipt).await.unwrap_err().code(), + "workspace_unavailable" + ); + assert_eq!(inventory_minimum(&r).await, before); + r.clock.0.store(155, Ordering::SeqCst); + let original = released(abort(&r, &receipt).await.unwrap()); + let current = inventory_minimum(&r).await; + r.clock.0.store(152, Ordering::SeqCst); + assert_eq!( + released(abort(&r, &receipt).await.unwrap()).attempt(), + original.attempt() + ); + assert_eq!(inventory_minimum(&r).await, current); + r.store.close().await.unwrap(); + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs @@ -312,6 +312,7 @@ async fn each_actual_write_failure_rolls_back_all_pool_holds_and_order_fence() { "CREATE TRIGGER fault BEFORE UPDATE ON stock_pools WHEN hex(NEW.pool_id)=replace(hex(zeroblob(32)),'00','51') BEGIN SELECT RAISE(ABORT,'fixture'); END", "CREATE TRIGGER fault BEFORE INSERT ON stock_movements BEGIN SELECT RAISE(ABORT,'fixture'); END", "CREATE TRIGGER fault BEFORE INSERT ON stock_orders BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_order_states BEGIN SELECT RAISE(ABORT,'fixture'); END", "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fixture'); END", ] { let r = Rig::new().await; @@ -329,7 +330,7 @@ async fn each_actual_write_failure_rolls_back_all_pool_holds_and_order_fence() { assert_pool(&r, 80, 10, 0, 1).await; assert_pool(&r, 81, 10, 0, 1).await; assert_eq!( - sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_orders") + sqlx::query_scalar::<_, i64>("SELECT (SELECT count(*) FROM stock_orders)+(SELECT count(*) FROM stock_order_states)") .fetch_one(&mut raw) .await .unwrap(), @@ -415,7 +416,7 @@ async fn lost_observer_retains_actual_two_pool_preparation_and_drain_precedes_re let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -458,7 +459,7 @@ async fn source_mapping_pool_order_and_grant_rows_are_rechecked_after_final_prov "INSERT INTO stock_source_records(record_id,protected) VALUES(randomblob(32),x'01')", "UPDATE stock_public_heads SET protected=randomblob(length(protected))", "UPDATE stock_grants SET protected=randomblob(length(protected))", - "INSERT INTO stock_orders(order_id,revision,protected) VALUES(randomblob(32),1,x'01')", + "INSERT INTO stock_orders(actor,operation_id,order_id,revision,protected) SELECT actor,operation_id,randomblob(32),1,x'01' FROM stock_operations WHERE family=1 LIMIT 1", ] { let mut r = Rig::new().await; seed(&r, "10").await; @@ -469,7 +470,7 @@ async fn source_mapping_pool_order_and_grant_rows_are_rechecked_after_final_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -506,7 +507,7 @@ async fn final_clock_recheck_refuses_expiry_and_rollback_after_protection_withou let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs @@ -323,7 +323,7 @@ async fn lost_claim_observer_drains_and_reopens_as_existing_without_a_permit() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), @@ -400,7 +400,7 @@ async fn claim_rechecks_original_plan_projection_grant_root_and_clock_after_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs @@ -342,7 +342,7 @@ async fn lost_capture_observer_drains_owned_input_and_reopens_the_exact_original let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), @@ -430,7 +430,7 @@ async fn capture_rechecks_original_claim_plan_root_and_grant_after_provider_io() let mut rawdb = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs @@ -1,4 +1,6 @@ //! Real T2 transactions over original T0/T1 and authenticated peer evidence. +#[path = "abort_tests.rs"] +mod aborts; #[path = "local_history_tests.rs"] mod local_history; #[cfg(unix)] @@ -317,6 +319,7 @@ async fn every_t2_write_failure_rolls_back_all_pool_agreement_and_work_effects() "CREATE TRIGGER fault BEFORE INSERT ON stock_publication_work WHEN (SELECT count(*) FROM stock_publication_work)=1 BEGIN SELECT RAISE(ABORT,'fault'); END", "CREATE TRIGGER fault BEFORE UPDATE ON stock_pools WHEN OLD.pool_id=(SELECT max(pool_id) FROM stock_pools) BEGIN SELECT RAISE(ABORT,'fault'); END", "CREATE TRIGGER fault BEFORE INSERT ON stock_movements BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_order_states BEGIN SELECT RAISE(ABORT,'fault'); END", "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fault'); END", ] { let r = Rig::new().await; @@ -409,7 +412,7 @@ async fn lost_t2_observer_drains_and_reopens_one_atomic_installation() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .install_stock_agreement(selected, r.enrollment.proof()), @@ -448,7 +451,7 @@ async fn late_t2_backing_or_grant_or_evidence_change_never_commits_partial_insta let mut db = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .install_stock_agreement(selected, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs @@ -1,4 +1,4 @@ -//! Private process-death qualification of already implemented S and T2. +//! Private process-death qualification of S, T2 and proven-unissued abort. use super::*; use radroots_domain::{CommandDigest, OperationId}; use radroots_secrets::{ @@ -21,6 +21,7 @@ const CHILD: &str = "workspace::stock::public_source::tests::provider::history:: enum Edge { Capture, Install, + Abort, } #[derive(serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] @@ -141,33 +142,36 @@ async fn stock_process_child() { .unwrap() .inventory_checkpoint() .unwrap(); - let report = store - .stock_signing_attempt( - StockClaimRequest::new( - binding.clone(), - minimum, - control.operation, - control.digest, - control.recipient, - ), - &proof, - ) - .await - .unwrap() - .unwrap(); - let capture = - StockEvidenceCapture::verify(binding.clone(), &report, &control.raw, None).unwrap(); + let capture = if matches!(control.edge, Edge::Abort) { + None + } else { + let report = store + .stock_signing_attempt( + StockClaimRequest::new( + binding.clone(), + minimum, + control.operation, + control.digest, + control.recipient, + ), + &proof, + ) + .await + .unwrap() + .unwrap(); + Some(StockEvidenceCapture::verify(binding.clone(), &report, &control.raw, None).unwrap()) + }; if control.before { provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); } let work = async { match control.edge { Edge::Capture => { committed( store - .capture_stock_signing_evidence(&capture, &proof) + .capture_stock_signing_evidence(capture.as_ref().unwrap(), &proof) .await .unwrap(), ); @@ -188,6 +192,22 @@ async fn stock_process_child() { .unwrap(), ); } + Edge::Abort => { + aborts::released( + store + .abort_proven_unissued( + crate::workspace::StockAbortRequest::new( + binding, + minimum, + control.operation, + control.digest, + ), + &proof, + ) + .await + .unwrap(), + ); + } } }; let mut work = Box::pin(work); @@ -205,16 +225,31 @@ async fn stock_process_child() { } #[tokio::test] -async fn process_death_before_and_after_capture_or_install_preserves_original_stock_and_evidence() { - for edge in [Edge::Capture, Edge::Install] { +async fn process_death_before_and_after_capture_install_or_abort_preserves_original_stock_and_evidence() + { + for edge in [Edge::Capture, Edge::Install, Edge::Abort] { for before in [true, false] { let mut r = Rig::new().await; - let receipt = Box::pin(ready(&r)).await; + let receipt = if matches!(edge, Edge::Abort) { + Box::pin(prepared(&r)).await.1 + } else { + Box::pin(ready(&r)).await + }; let recipient = peer(&r, &receipt); - let (report, raw) = Box::pin(obtained(&r, &receipt, recipient)).await; + let (report, raw) = if matches!(edge, Edge::Abort) { + (None, String::new()) + } else { + let (report, raw) = Box::pin(obtained(&r, &receipt, recipient)).await; + (Some(report), raw) + }; if matches!(edge, Edge::Install) { - let capture = - StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let capture = StockEvidenceCapture::verify( + r.binding.clone(), + report.as_ref().unwrap(), + &raw, + None, + ) + .unwrap(); committed( r.store .capture_stock_signing_evidence(&capture, r.enrollment.proof()) @@ -250,10 +285,14 @@ async fn process_death_before_and_after_capture_or_install_preserves_original_st current.revision().get(), minimum.revision().get() + u64::from(!before) ); - assert!(matches!( - claim(&r, &receipt, recipient).await.unwrap(), - StockClaimOutcome::Existing(_) - )); + if matches!(edge, Edge::Abort) { + assert!(claim(&r, &receipt, recipient).await.is_err()); + } else { + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + } let snapshot = r .store .stock_operation_snapshot( @@ -272,15 +311,22 @@ async fn process_death_before_and_after_capture_or_install_preserves_original_st .iter() .find(|value| value.recipient() == recipient) .unwrap(); - let has_evidence = matches!(edge, Edge::Install) || !before; + let has_evidence = + matches!(edge, Edge::Install) || (matches!(edge, Edge::Capture) && !before); assert_eq!(peer.first_evidence().is_some(), has_evidence); let has_installation = matches!(edge, Edge::Install) && !before; assert_eq!(snapshot.installation().is_some(), has_installation); + let has_abort = matches!(edge, Edge::Abort) && !before; + assert_eq!(snapshot.aborted().is_some(), has_abort); + assert_eq!(peer.claim().is_some(), !matches!(edge, Edge::Abort)); assert_eq!( history(&r).await.analysis().seller_head(), has_evidence.then_some(receipt.rumor().record_id()) ); - if has_installation { + if has_abort { + balances(&r, 80, 10, 0, 0, 3).await; + balances(&r, 81, 10, 0, 0, 3).await; + } else if has_installation { balances(&r, 80, 9, 0, 1, 3).await; balances(&r, 81, 8, 0, 2, 3).await; let replay = installed(install(&r, &receipt).await.unwrap()); @@ -290,10 +336,30 @@ async fn process_death_before_and_after_capture_or_install_preserves_original_st balances(&r, 81, 8, 2, 0, 2).await; } assert_eq!(inventory_minimum(&r).await, current); + if matches!(edge, Edge::Abort) { + let first = aborts::released(aborts::abort(&r, &receipt).await.unwrap()); + if let Some(original) = snapshot.aborted() { + assert_eq!(first.attempt(), original.attempt()); + } + balances(&r, 80, 10, 0, 0, 3).await; + balances(&r, 81, 10, 0, 0, 3).await; + let complete = inventory_minimum(&r).await; + assert_eq!( + aborts::released(aborts::abort(&r, &receipt).await.unwrap()).attempt(), + first.attempt() + ); + assert_eq!(inventory_minimum(&r).await, complete); + r.store.close().await.unwrap(); + continue; + } if !has_evidence { - let capture = - StockEvidenceCapture::verify(r.binding.clone(), &report, &control.raw, None) - .unwrap(); + let capture = StockEvidenceCapture::verify( + r.binding.clone(), + report.as_ref().unwrap(), + &control.raw, + None, + ) + .unwrap(); committed( r.store .capture_stock_signing_evidence(&capture, r.enrollment.proof()) diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs @@ -346,7 +346,7 @@ async fn dropped_t1_observer_keeps_owned_work_and_close_drains_before_original_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), @@ -400,7 +400,7 @@ async fn t1_final_permission_order_root_and_clock_witnesses_refuse_changes_after let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs b/crates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs @@ -157,7 +157,7 @@ async fn public_source_close_drains_admitted_work_after_observer_loss() { let minimum = r.minimum().await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut future = Box::pin(r.store.retain_stock_listing( r.binding.clone(), minimum, @@ -213,7 +213,7 @@ async fn public_source_writes_recheck_expiry_and_head_rows_after_actual_protecti let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); let mut future = Box::pin(r.store.retain_stock_listing( r.binding.clone(), minimum, diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs @@ -31,7 +31,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !matches!(authority.catalog, 8..=12) || authority.public_sources.is_none() { + if !matches!(authority.catalog, 8..=13) || authority.public_sources.is_none() { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; diff --git a/crates/storage_sqlite/src/workspace/stock/schema.rs b/crates/storage_sqlite/src/workspace/stock/schema.rs @@ -1,7 +1,7 @@ //! Exact stock catalogs. Enrollment-only version1 is retained without upgrade. use super::WorkspaceError; use sqlx::SqliteConnection; -pub(super) const CURRENT: i64 = 12; +pub(super) const CURRENT: i64 = 13; const AUTHORITY: &str = "CREATE TABLE stock_authority (singleton INTEGER PRIMARY KEY CHECK(singleton=1), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT"; const GRANTS: &str = "CREATE TABLE stock_grants (grant_id BLOB PRIMARY KEY CHECK(length(grant_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; const POOLS: &str = "CREATE TABLE stock_pools (pool_id BLOB PRIMARY KEY CHECK(length(pool_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID"; @@ -16,6 +16,7 @@ const OPERATIONS_V7: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL const OPERATIONS_V10: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 3), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=3 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const OPERATIONS_V11: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 5), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 5 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const OPERATIONS_V12: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 6), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 6 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; +const OPERATIONS_V13: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 7), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 7 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const MOVEMENTS: &str = "CREATE TABLE stock_movements (movement_id BLOB PRIMARY KEY CHECK(length(movement_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), FOREIGN KEY(actor,grant_id,operation_id) REFERENCES stock_operations(actor,grant_id,operation_id)) STRICT, WITHOUT ROWID"; pub(super) fn objects( version: i64, @@ -26,13 +27,15 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=12 => objects.extend([ + 2..=13 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ( "table", "stock_operations", "stock_operations", - if version >= 12 { + if version >= 13 { + OPERATIONS_V13 + } else if version >= 12 { OPERATIONS_V12 } else if version >= 11 { OPERATIONS_V11 @@ -79,7 +82,7 @@ pub(super) fn objects( if version >= 5 { objects.push(("table","stock_mappings","stock_mappings","CREATE TABLE stock_mappings (listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), option_id BLOB NOT NULL CHECK(length(option_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(listing_author,listing_d,option_id)) STRICT, WITHOUT ROWID")); } - if (6..=12).contains(&version) { + if (6..=13).contains(&version) { objects.push(("table","stock_source_records","stock_source_records","CREATE TABLE stock_source_records (record_id BLOB PRIMARY KEY CHECK(length(record_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("table","stock_source_evidence","stock_source_evidence","CREATE TABLE stock_source_evidence (envelope_id BLOB PRIMARY KEY CHECK(length(envelope_id)=32), record_id BLOB REFERENCES stock_source_records(record_id), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_source_transaction_identity","stock_source_evidence","CREATE UNIQUE INDEX stock_source_transaction_identity ON stock_source_evidence(transaction_id)")); @@ -101,9 +104,21 @@ pub(super) fn objects( objects.push(("table","stock_operation_parts","stock_operation_parts","CREATE TABLE stock_operation_parts (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL CHECK(length(grant_id)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), part INTEGER NOT NULL CHECK(part BETWEEN 0 AND 15), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(actor,operation_id,part), FOREIGN KEY(actor,grant_id,operation_id) REFERENCES stock_operations(actor,grant_id,operation_id)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_consent_target_identity","stock_operations","CREATE UNIQUE INDEX stock_consent_target_identity ON stock_operations(actor,related_operation,subject_grant) WHERE family=1")); objects.push(("index","stock_order_operation_position","stock_operations","CREATE INDEX stock_order_operation_position ON stock_operations(order_id,revision) WHERE order_id IS NOT NULL")); - objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); + if version >= 13 { + objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), order_id BLOB NOT NULL CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision=1), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(actor,operation_id), FOREIGN KEY(actor,operation_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(("table","stock_order_states","stock_order_states","CREATE TABLE stock_order_states (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), revision INTEGER NOT NULL CHECK(revision>0), phase INTEGER NOT NULL CHECK(phase BETWEEN 0 AND 2), FOREIGN KEY(actor,operation_id) REFERENCES stock_orders(actor,operation_id), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(("table","stock_aborts","stock_aborts","CREATE TABLE stock_aborts (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id), FOREIGN KEY(actor,operation_id) REFERENCES stock_orders(actor,operation_id), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(( + "index", + "stock_abort_entry", + "stock_aborts", + "CREATE UNIQUE INDEX stock_abort_entry ON stock_aborts(actor,entry_id)", + )); + } else { + objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); + } } - if matches!(version, 8..=12) { + if matches!(version, 8..=13) { objects.push(("table","stock_public_events","stock_public_events","CREATE TABLE stock_public_events (event_id BLOB PRIMARY KEY CHECK(length(event_id)=32), listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), created_at BLOB NOT NULL CHECK(length(created_at)=8), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_public_transaction_identity","stock_public_events","CREATE UNIQUE INDEX stock_public_transaction_identity ON stock_public_events(transaction_id)")); objects.push(( diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan.rs @@ -148,7 +148,7 @@ pub(in crate::workspace::stock) async fn load( proof: &AttachmentProof, ) -> Result<Authorized, OperationError> { let access = turn.access(binding, minimum, proof).await?; - if !matches!(access.authority.catalog, 10..=12) { + if !matches!(access.authority.catalog, 10..=13) { return Err(OperationError::UnsupportedOperation); } let original = Box::pin(acceptance::codec::read( @@ -282,6 +282,14 @@ pub(in crate::workspace) async fn bind( auth.plan.ok_or(OperationError::RecoveryRequired)?.bound, ))); } + let current_order = Box::pin(super::order_state::signing_state( + turn, + &auth.access, + auth.original.receipt.order_id(), + plan.operation_id(), + false, + )) + .await?; let backing = Box::pin(inventory::backing::read( turn, &auth.access, @@ -361,6 +369,7 @@ pub(in crate::workspace) async fn bind( auth.original_proof.confirm(&mut tx).await?; auth.consent_proof.confirm(&mut tx).await?; auth.plan_proof.confirm(&mut tx).await?; auth.original.confirm(&mut tx).await?; let current = auth.access.confirm(&mut tx, turn.namespace, turn.clock, &proof).await?; for pool in &backing { pool.confirm(&mut tx).await?; } + if let Some(current_order) = &current_order {current_order.confirm(&mut tx).await?;} acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, current.observed_at())?; if current.observed_at() < bound_at || current.observed_at() >= auth.original.receipt.first_issue_deadline() { return Err(OperationError::DeadlineExceeded); } sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,NULL,?,?,?,3,?,?,NULL)") diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs @@ -191,6 +191,8 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + aborted: None, + preparation: None, local_record: None, installation: None, signing: None, diff --git a/crates/storage_sqlite/src/workspace/stock/snapshot.rs b/crates/storage_sqlite/src/workspace/stock/snapshot.rs @@ -109,8 +109,12 @@ pub struct StockOperationSnapshot { checkpoint: InventoryCheckpointRef, recipients: [StockRecipientSnapshot; 2], installation: Option<super::StockInstallationReceipt>, + aborted: Option<super::StockAbortReceipt>, } impl StockOperationSnapshot { + pub fn aborted(&self) -> Option<&super::StockAbortReceipt> { + self.aborted.as_ref() + } pub fn installation(&self) -> Option<&super::StockInstallationReceipt> { self.installation.as_ref() } @@ -211,7 +215,7 @@ pub(in crate::workspace) async fn read( claims.push(claim_proof); summaries.push(summary); } - let installation = if auth.access.authority.catalog == 12 { + let installation = if auth.access.authority.catalog >= 12 { Some( Box::pin(super::inventory::installation::existing( turn, @@ -223,6 +227,40 @@ pub(in crate::workspace) async fn read( } else { None }; + let aborted = if auth.access.authority.catalog == 13 { + Some( + Box::pin(super::inventory::abort::existing( + turn, + &auth.access, + request.operation, + )) + .await?, + ) + } else { + None + }; + if aborted.as_ref().is_some_and(|(value, _)| value.is_some()) + && installation + .as_ref() + .is_some_and(|(value, _)| value.is_some()) + { + return Err(OperationError::RecoveryRequired); + } + let current_order = if auth.access.authority.catalog == 13 { + Some( + Box::pin(super::inventory::checkpoint::authenticate_order_state( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + auth.original.receipt.order_id(), + )) + .await?, + ) + } else { + None + }; let before = auth .access .authority @@ -233,22 +271,39 @@ pub(in crate::workspace) async fn read( Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, None, )?; - let witness = Box::pin(checkpoint::authenticate_minimum( - turn.connection, - turn.selected, - turn.crypto, - &auth.access.current, - &auth.access.authority, - minimum, - )) - .await?; + let witness = if current_order.is_none() { + Some( + Box::pin(checkpoint::authenticate_minimum( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + minimum, + )) + .await?, + ) + } else { + None + }; let mut tx = turn .connection .begin_with("BEGIN IMMEDIATE") .await .map_err(|_| OperationError::StorageFailure)?; let checked: Result<(), OperationError> = async { - witness.confirm(&mut tx).await?; + if let Some(witness) = &witness { + witness.confirm(&mut tx).await?; + } + if let Some(current_order) = &current_order { + current_order.confirm(&mut tx).await?; + } + if let Some((retained, identity)) = &aborted { + identity.confirm(&mut tx).await?; + if let Some(retained) = retained { + retained.confirm(&mut tx).await?; + } + } if let Some((retained, identity)) = &installation { identity.confirm(&mut tx).await?; if let Some(retained) = retained { @@ -287,6 +342,7 @@ pub(in crate::workspace) async fn read( .ok_or(OperationError::RecoveryRequired)?, ); Ok(StockOperationSnapshot { + aborted: aborted.and_then(|(retained, _)| retained.map(|value| value.receipt)), installation: installation.and_then(|(retained, _)| retained.map(|value| value.receipt)), preparation: auth.original.receipt, plan: auth.plan.map(|value| value.bound), diff --git a/crates/storage_sqlite/src/workspace/stock/source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/source/transaction.rs @@ -28,7 +28,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !(6..=12).contains(&authority.catalog) { + if !(6..=13).contains(&authority.catalog) { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; @@ -114,7 +114,7 @@ pub(in crate::workspace) async fn history( proof: AttachmentProof, ) -> Result<StockHistorySnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=12) { + if !matches!(access.authority.catalog, 8..=13) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::history::prepare( @@ -175,7 +175,7 @@ pub(in crate::workspace) async fn inspect_request( proof: AttachmentProof, ) -> Result<StockRequestSnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=12) { + if !matches!(access.authority.catalog, 8..=13) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::request::prepare( diff --git a/crates/storage_sqlite/src/workspace/stock/tests.rs b/crates/storage_sqlite/src/workspace/stock/tests.rs @@ -109,7 +109,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang ) .await .unwrap(); - assert_eq!(schema::admit(&mut connection).await, Ok(12)); + assert_eq!(schema::admit(&mut connection).await, Ok(13)); assert_eq!(schema::integrity(&mut connection).await, Ok(())); let root: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_authority") .fetch_one(&mut connection) @@ -117,18 +117,18 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang .unwrap(); let clear = fixture .crypto() - .open_stock_root(enrollment.input(), 12, &root) + .open_stock_root(enrollment.input(), 13, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 12)) + .expose_secret(|bytes| Authority::decode(bytes, 13)) .unwrap(); clear.expose_secret(|bytes| { let original:serde_json::Value=serde_json::from_slice(bytes).unwrap(); assert_eq!(original["inventory"]["mappings"],"0"); for bad in [serde_json::json!([]),serde_json::json!({"revision":"1","pools":"1","movements":"1","head":original["inventory"]["head"]})] { let mut value=original.clone();value["inventory"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),12).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),13).is_err()); } for bad in [ serde_json::json!([]), @@ -139,7 +139,7 @@ async fn current_grant_set_reopens_with_original_namespace_after_one_grant_chang serde_json::json!({"revision":"1","records":"2","parts":"3","head":"01".repeat(32)}), ] { let mut value=original.clone();value["sources"]=bad; - assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),12).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),13).is_err()); } }); assert_eq!(authority.input, *enrollment.input()); @@ -189,7 +189,7 @@ async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_ca let caller = namespace.attachment(GrantId::from_bytes([9; 32])).unwrap(); let crypto = fixture.crypto(); let clear = b"synthetic context payload"; - for version in [4, 5, 6, 7, 8, 9, 10, 11, 12] { + for version in [4, 5, 6, 7, 8, 9, 10, 11, 12, 13] { let current = crypto .seal_stock_root(&owner, version, clear) .await @@ -277,7 +277,7 @@ async fn retained_v10_preserves_prior_families_and_signing_plan_retention() { } #[tokio::test] async fn retained_v11_preserves_prior_families_and_adds_claims_and_obtained_evidence() { - assert_eq!(schema::CURRENT, 12); + assert_eq!(schema::CURRENT, 13); retained_inventory_catalog(11).await; } // Exact catalog fixtures exercise retained/successor codecs; they are not @@ -340,7 +340,7 @@ pub(super) async fn literal_catalog( if catalog >= 7 { value["inventory"]["orders"] = serde_json::json!("0"); } - if matches!(catalog, 8..=12) { + if matches!(catalog, 8..=13) { value["public_sources"] = serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); } @@ -385,6 +385,7 @@ pub(super) async fn literal_catalog( 10 => "PRAGMA user_version=10", 11 => "PRAGMA user_version=11", 12 => "PRAGMA user_version=12", + 13 => "PRAGMA user_version=13", _ => unreachable!(), }) .execute(&mut *tx) @@ -410,7 +411,7 @@ async fn retained_inventory_catalog(catalog: i64) { assert_eq!(authority.source_checkpoint().is_some(), catalog >= 6); assert_eq!( authority.listing_checkpoint().is_some(), - matches!(catalog, 8..=12) + matches!(catalog, 8..=13) ); let minimum = authority.inventory_checkpoint().unwrap(); let context = CommandContextData::new( @@ -653,7 +654,7 @@ async fn retained_inventory_catalog(catalog: i64) { .fetch_one(&mut connection) .await .unwrap(); - let old = if matches!(catalog, 7..=12) { + let old = if matches!(catalog, 7..=13) { let retained = ledger::read( &mut connection, &input, @@ -706,7 +707,7 @@ async fn retained_inventory_catalog(catalog: i64) { // inside a real SQL transaction. Row counts and the protected header // stay unchanged while one referenced ciphertext changes. for part in [false, true] { - if part && !matches!(catalog, 7..=12) { + if part && !matches!(catalog, 7..=13) { continue; } let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) @@ -781,6 +782,7 @@ async fn retained_inventory_catalog(catalog: i64) { 10 => "PRAGMA user_version=9", 11 => "PRAGMA user_version=10", 12 => "PRAGMA user_version=11", + 13 => "PRAGMA user_version=12", _ => unreachable!(), }) .execute(&mut connection) @@ -909,7 +911,13 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() } #[tokio::test] -async fn current_v12_retains_v11_and_installs_separate_agreement_and_publication_indexes() { - assert_eq!(schema::CURRENT, 12); +async fn retained_v12_preserves_initial_installation_catalog_without_upgrade() { + assert_eq!(schema::CURRENT, 13); retained_inventory_catalog(12).await; } + +#[tokio::test] +async fn current_v13_authenticates_literal_catalog_and_original_inventory_records() { + assert_eq!(schema::CURRENT, 13); + retained_inventory_catalog(13).await; +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -48,6 +48,16 @@ enum Job { AttachmentProof, Reply<Option<stock::StockInstallationReceipt>, OperationError>, ), + AbortStockPreparation( + Box<stock::StockAbortRequest>, + AttachmentProof, + Reply<stock::StockAbortOutcome, OperationError>, + ), + StockPreparationAbort( + Box<stock::StockAbortRequest>, + AttachmentProof, + Reply<Option<stock::StockAbortReceipt>, OperationError>, + ), StockSnapshot( Box<stock::StockSnapshotRequest>, AttachmentProof, @@ -302,6 +312,12 @@ impl Job { Self::StockAgreementInstallation(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } + Self::AbortStockPreparation(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockPreparationAbort(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::StockSnapshot(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -585,6 +601,8 @@ impl Handle { | Job::StockSnapshot(..) | Job::InstallStockAgreement(..) | Job::StockAgreementInstallation(..) + | Job::AbortStockPreparation(..) + | Job::StockPreparationAbort(..) | Job::Revoke(..) | Job::StockAuthority(..) ) @@ -841,6 +859,46 @@ impl Handle { }; let _ = reply.send(result); } + Job::AbortStockPreparation(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::abort::abort( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } + Job::StockPreparationAbort(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::abort::read( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } Job::StockSnapshot(request, proof, reply) => { let result = if kind == Kind::SellerStock { Box::pin(stock::snapshot::read( @@ -1015,7 +1073,7 @@ impl Handle { } Job::PrepareStockAcceptance(request, proof, reply) => { let result = if kind == Kind::SellerStock { - stock::inventory::acceptance::admit( + Box::pin(stock::inventory::acceptance::admit( &mut stock::inventory::Turn { connection, namespace: &namespace, @@ -1026,7 +1084,7 @@ impl Handle { }, *request, proof, - ) + )) .await } else { Err(OperationError::UnsupportedOperation) @@ -1676,6 +1734,25 @@ impl Handle { ))?; result.await.map_err(|_| OperationError::RecoveryRequired)? } + pub(super) async fn abort_proven_unissued( + &self, + request: stock::StockAbortRequest, + proof: AttachmentProof, + ) -> Result<stock::StockAbortOutcome, OperationError> { + let unknown = stock::StockAbortOutcome::Unknown(request.attempt()); + let (reply, result) = oneshot::channel(); + self.send(Job::AbortStockPreparation(Box::new(request), proof, reply))?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn stock_preparation_abort( + &self, + request: stock::StockAbortRequest, + proof: AttachmentProof, + ) -> Result<Option<stock::StockAbortReceipt>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockPreparationAbort(Box::new(request), proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn stock_operation_snapshot( &self, request: stock::StockSnapshotRequest, @@ -1872,7 +1949,9 @@ impl Handle { | Job::StockEvidencePage(..) | Job::StockSnapshot(..) | Job::InstallStockAgreement(..) - | Job::StockAgreementInstallation(..) => 1024 * 1024, + | Job::StockAgreementInstallation(..) + | Job::AbortStockPreparation(..) + | Job::StockPreparationAbort(..) => 1024 * 1024, Job::IssueStockConsent(..) | Job::PrepareStockAcceptance(..) => 512 * 1024, Job::BindStockSigningPlan(..) | Job::StockSigningPlan(..) diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -602,7 +602,7 @@ async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_c clock.release(); assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); store.close().await.unwrap(); - sqlx::query("PRAGMA user_version=12") + sqlx::query("PRAGMA user_version=13") .execute(&mut connection) .await .unwrap(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -157,6 +157,7 @@ struct NativeSellerStockAuthority { signing_plan_binding: SigningPlanBinding, signing_issuance: SigningIssuance, initial_agreement_installation: InitialAgreementInstallation, + preparation_abort: PreparationAbort, business_consent_payload_version: u16, business_consent_action: String, business_consent_modes: Vec<String>, @@ -215,6 +216,24 @@ struct AcceptancePreparation { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct PreparationAbort { + payload_version: u32, + journal_family: u32, + worker_charge_bytes: u32, + all_recipient_claims_must_be_absent: bool, + caller_nonissuance_assertion_is_proof: bool, + current_exact_recovery_consent_required: bool, + atomic_exact_original_release_required: bool, + original_preparations_retained: bool, + current_order_projection_authenticated: bool, + later_initial_requires_original_abort: bool, + fresh_signing_after_abort: bool, + unknown_commit_fences_owner: bool, + signer_or_transport_invoked: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct InitialAgreementInstallation { payload_version: u32, journal_family: u32, @@ -448,10 +467,10 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.scope == "seller_stock_owner" && stock.database == "stock_execution_v1.sqlite" && stock.lock == ".stock_execution_v1.lock" - && stock.schema_version == 12 + && stock.schema_version == 13 && stock.retained_enrollment_versions == [1] - && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v12" + && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v13" && stock.public_source_payload_schemas == [ "radroots.seller_stock.public_source_event.v1", @@ -553,6 +572,29 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { .signing_issuance .capture_retains_distinct_valid_encodings && !stock.signing_issuance.agreement_installed + && stock.preparation_abort.payload_version == 1 + && stock.preparation_abort.journal_family == 7 + && stock.preparation_abort.worker_charge_bytes == 1048576 + && stock.preparation_abort.all_recipient_claims_must_be_absent + && !stock + .preparation_abort + .caller_nonissuance_assertion_is_proof + && stock + .preparation_abort + .current_exact_recovery_consent_required + && stock + .preparation_abort + .atomic_exact_original_release_required + && stock.preparation_abort.original_preparations_retained + && stock + .preparation_abort + .current_order_projection_authenticated + && stock + .preparation_abort + .later_initial_requires_original_abort + && !stock.preparation_abort.fresh_signing_after_abort + && stock.preparation_abort.unknown_commit_fences_owner + && !stock.preparation_abort.signer_or_transport_invoked && stock.initial_agreement_installation.payload_version == 1 && stock.initial_agreement_installation.journal_family == 6 && stock.initial_agreement_installation.worker_charge_bytes == 1048576 @@ -1267,6 +1309,34 @@ mod tests { } #[test] + fn abort_requires_protected_absence_exact_original_release_and_retained_preparations() { + for (field, bad) in [ + ("payload_version", json!(2)), + ("journal_family", json!(6)), + ("worker_charge_bytes", json!(1048577)), + ("all_recipient_claims_must_be_absent", json!(false)), + ("caller_nonissuance_assertion_is_proof", json!(true)), + ("current_exact_recovery_consent_required", json!(false)), + ("atomic_exact_original_release_required", json!(false)), + ("original_preparations_retained", json!(false)), + ("current_order_projection_authenticated", json!(false)), + ("later_initial_requires_original_abort", json!(false)), + ("fresh_signing_after_abort", json!(true)), + ("unknown_commit_fences_owner", json!(false)), + ("signer_or_transport_invoked", json!(true)), + ] { + assert!( + validate_bytes(&changed( + &format!("/native_seller_stock_authority/preparation_abort/{field}"), + bad + )) + .is_err(), + "{field}" + ); + } + } + + #[test] fn public_sources_require_original_signatures_bounded_parts_and_profile_independent_heads() { for (field, bad) in [ ("schema_version", json!(7)),