lib

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

commit 3821b72e5d90bd0c9ab57479ff1b06322833aa10
parent 8c0d337b98a9d3a54853495f8f212a67ffc3bce7
Author: triesap <tyson@radroots.org>
Date:   Mon, 26 Oct 2026 23:31:47 +0000

storage: retain owned original signing refusals

- Add catalog14 protected original-refusal records with exact claim ancestry.
- Preserve borrowed proof through write failure and same-owner reconciliation.
- Keep stock holds, original claims and later valid evidence independent.
- Verify actual faults, caller loss, retained catalogs and supported boundaries.

Diffstat:
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 14++++++++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 23++++++++++++++++++-----
Mcrates/storage_sqlite/README.md | 35++++++++++++++++++++++++-----------
Mcrates/storage_sqlite/src/workspace/crypto.rs | 16++++++++++------
Mcrates/storage_sqlite/src/workspace/mod.rs | 1+
Mcrates/storage_sqlite/src/workspace/recovery.rs | 39+++++++++++++++++++++++++++++++++++++++
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 | 4++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/abort.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs | 6+++---
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs | 16++++++++--------
Mcrates/storage_sqlite/src/workspace/stock/inventory/codec.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/installation.rs | 6+++---
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 | 13+++++++++++--
Mcrates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs | 13+++++++++----
Mcrates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/issuance/projection.rs | 48++++++++++++++++++++++++++++++++++++++++++------
Mcrates/storage_sqlite/src/workspace/stock/issuance/recovery.rs | 2+-
Acrates/storage_sqlite/src/workspace/stock/issuance/unissued.rs | 571+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/ledger.rs | 28++++++++++++++++++++--------
Mcrates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs | 6+++---
Mcrates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/dispatch_tests.rs | 2++
Mcrates/storage_sqlite/src/workspace/stock/public_source/evidence_reconciliation_tests.rs | 13+++++++------
Mcrates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs | 9++++++---
Mcrates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/process_death_tests.rs | 2+-
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+-
Acrates/storage_sqlite/src/workspace/stock/public_source/unissued_tests.rs | 385+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/schema.rs | 17++++++++++++-----
Mcrates/storage_sqlite/src/workspace/stock/signing_plan.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/snapshot.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/source/transaction.rs | 6+++---
Mcrates/storage_sqlite/src/workspace/stock/tests.rs | 36++++++++++++++++++++++--------------
Mcrates/storage_sqlite/src/workspace/worker.rs | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcrates/storage_sqlite/tests/support/stock_authority.rs | 2+-
Mtools/xtask/src/architecture/decision_package.rs | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
48 files changed, 1445 insertions(+), 139 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -421,6 +421,9 @@ pub enum radroots_storage_sqlite::workspace::StockSourceProfile pub radroots_storage_sqlite::workspace::StockSourceProfile::Known pub radroots_storage_sqlite::workspace::StockSourceProfile::Rejected pub radroots_storage_sqlite::workspace::StockSourceProfile::Unsupported +pub enum radroots_storage_sqlite::workspace::StockUnissuedOutcome +pub radroots_storage_sqlite::workspace::StockUnissuedOutcome::Committed(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockUnissuedReceipt>) +pub radroots_storage_sqlite::workspace::StockUnissuedOutcome::Unknown(radroots_storage::command::CommitAttempt) 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::inventory::abort::StockAbortRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::inventory::abort::StockAbortOutcome, radroots_storage::command::OperationError> @@ -437,6 +440,10 @@ impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::bind_stock_signing_intents(&self, radroots_storage_sqlite::workspace::StockSigningPlanRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockSigningPlanOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockBoundSigningPlan>, radroots_storage::command::OperationError> impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::capture_stock_original_unissued(&self, radroots_storage::workspace::WorkspaceBinding, &radroots_storage_sqlite::workspace::StockUnissuedInvocation, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockUnissuedOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::reconcile_stock_original_unissued(&self, radroots_storage::workspace::WorkspaceBinding, &radroots_storage_sqlite::workspace::StockUnissuedInvocation, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockUnissuedOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_original_unissued(&self, radroots_storage_sqlite::workspace::StockClaimRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockUnissuedReceipt>, radroots_storage::command::OperationError> +impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::capture_stock_signing_evidence(&self, &radroots_storage_sqlite::workspace::StockEvidenceCapture, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage::inventory::evidence::StockEvidenceOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_signing_evidence(&self, radroots_storage_sqlite::workspace::StockClaimRequest, [u8; 32], &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockCapturedEvidence>, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_signing_evidence_page(&self, radroots_storage_sqlite::workspace::StockClaimRequest, core::option::Option<radroots_domain::context::Sequence>, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockEvidencePage, radroots_storage::command::OperationError> @@ -750,6 +757,13 @@ pub const fn radroots_storage_sqlite::workspace::StockUnissuedInvocation::attemp pub const fn radroots_storage_sqlite::workspace::StockUnissuedInvocation::reason(&self) -> radroots_signing::provider::ProviderError impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockUnissuedInvocation pub fn radroots_storage_sqlite::workspace::StockUnissuedInvocation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockUnissuedReceipt +impl radroots_storage_sqlite::workspace::StockUnissuedReceipt +pub const fn radroots_storage_sqlite::workspace::StockUnissuedReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage_sqlite::workspace::StockUnissuedReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub const fn radroots_storage_sqlite::workspace::StockUnissuedReceipt::reason(&self) -> radroots_signing::provider::ProviderError +pub const fn radroots_storage_sqlite::workspace::StockUnissuedReceipt::recipient(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage_sqlite::workspace::StockUnissuedReceipt::signing_attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId pub struct radroots_storage_sqlite::workspace::WorkspaceCrypto impl radroots_storage_sqlite::workspace::WorkspaceCrypto pub fn radroots_storage_sqlite::workspace::WorkspaceCrypto::new(alloc::sync::Arc<dyn radroots_secrets::provider::SecretProvider>, radroots_secrets::id::SecretRef, radroots_secrets::wrapping::SecretMaterial, radroots_secrets::provider::AccessPolicy) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -82,7 +82,7 @@ "adapter": "radroots_nostr.signing.LocalSigner", "native_authorizer": "NativeWorkspace.authorize_stock_exact_replay", "captured_replay": "local_replay_safe", - "native_catalog": 13, + "native_catalog": 14, "worker_charge_bytes": 1048576, "existing_protected_claim_required": true, "current_execute_consent_required": true, @@ -98,7 +98,7 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 13, + "schema_version": 14, "retained_enrollment_versions": [ 1 ], @@ -113,9 +113,10 @@ 9, 10, 11, - 12 + 12, + 13 ], - "authority_payload_schema": "radroots.seller_stock.authority.v13", + "authority_payload_schema": "radroots.seller_stock.authority.v14", "public_source_payload_schemas": [ "radroots.seller_stock.public_source_event.v1", "radroots.seller_stock.public_source_head.v1", @@ -288,7 +289,19 @@ "current_issued_consent_required": true, "final_permission_and_clock_witnesses_required": true, "signer_invoked": false, - "agreement_installed": false + "agreement_installed": false, + "original_unissued_capture_owner": "NativeWorkspace.capture_stock_original_unissued", + "original_unissued_payload_version": 1, + "original_unissued_journal_family": 8, + "original_unissued_capture_requires_owned_observation": true, + "original_unissued_capture_borrows_observation": true, + "original_unissued_capture_rechecks_original_claim": true, + "original_unissued_capture_requires_fresh_permission": false, + "original_unissued_capture_requires_fresh_clock": false, + "original_unissued_capture_releases_stock": false, + "original_unissued_reconciliation_same_owner": true, + "original_unissued_late_evidence_retained": true, + "original_unissued_worker_charge_bytes": 262144 }, "signing_issuance": { "shared_capture_port": "InventoryStore.capture_stock_evidence", 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-13 catalog has separate protected authority and +directory. Its exact version-14 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 version13 and protected authority -payload version13. Retained enrollment-only version1 still authenticates and +The current stock factory creates exact catalog version14 and protected authority +payload version14. 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–12 retain their exact original codecs and +new correction commands. Catalogs1–13 retain their exact original codecs and capabilities; current multipart operation framing uses version5. No namespace is automatically migrated. Ordinary outbox catalogs are separate. @@ -451,8 +451,8 @@ transaction. A recovery view never returns a fresh dispatch permit. Initial seller agreement installation uses `install_stock_agreement` on the same -bounded native owner. Catalog12 introduced this transition; current catalog13 -retains formats1–12 without upgrading them. The original preparation fence remains +bounded native owner. Catalog12 introduced this transition; current catalog14 +retains formats1–13 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 @@ -499,7 +499,7 @@ complete ordinary caller workflow, claimed-attempt reconciliation, amendments, fulfillment, browser stock or platform resource qualification. `authorize_stock_exact_replay` returns a non-cloneable `StockExactReplayPermit` -only for an existing protected catalog13 claim whose retained T1 permits local +only for an existing protected catalog13/14 claim whose retained T1 permits local exact replay. A short read transaction rechecks current ExecuteAndRecover consent, original actor/resources, acknowledged minimum, original window and non-regressing time, order eligibility, backing and raw/root/grant/claim witnesses. @@ -556,7 +556,20 @@ implementation supplies no execution evidence or guarantee about unrelated root-key use. The predecessor intent-extraction method consumes the same permit and supplies no unissued observation while its composing callers await cutover. -This live observation is not persisted and cannot authorize abort or release. -Catalog13, protected formats and the absent-claims-only abort rule are unchanged. -Retained/durable original negative capture and the composing caller cutover -remain required before claimed-attempt reconciliation can release stock. +The live observation alone is not durable evidence and cannot authorize release. +Catalog14 adds a separate protected original-refusal journal family. Its105-byte +body binds the actual original claim entry, transaction, head and fixed reason; +its SQL projection is independently authenticated in the protected ancestry. +`capture_stock_original_unissued` borrows the owned observation and retained +credential; failed writes leave that observation available. It requires no +fresh clock, grant or issuance window. `reconcile_stock_original_unissued` +resolves uncertainty through the same retained namespace owner, and +`stock_original_unissued` reads authenticated original facts. Reports distinguish +confirmed append from transaction uncertainty; duplicates preserve the original +receipt. Old catalogs/root contexts1–13 are retained without automatic upgrade. + +The original refusal does not prove operation-wide nonissuance or prevent later +valid S from being retained. It has no stock effect. The absent-claims-only abort +rule remains conservative. Shared caller retention/cutover, predecessor removal +and safe claimed-abort/late-S reconciliation remain required before releasing +claimed preparatory stock. 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..=13) { + if matches!(version, 4..=14) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -740,8 +740,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v11\0".as_slice() } else if version == 12 { b"radroots.seller_stock.authority_context.v12\0".as_slice() - } else { + } else if version == 13 { b"radroots.seller_stock.authority_context.v13\0".as_slice() + } else { + b"radroots.seller_stock.authority_context.v14\0".as_slice() }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -768,8 +770,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v11" } else if version == 12 { "radroots.seller_stock.authority.v12" - } else { + } else if version == 13 { "radroots.seller_stock.authority.v13" + } else { + "radroots.seller_stock.authority.v14" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -887,12 +891,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..=13, "pool") => return Ok(original), + (2, _) | (3..=14, "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..=13, "operation") => "radroots.seller_stock.operation.v5", - (3..=13, "movement") => "radroots.seller_stock.movement.v2", + (7..=14, "operation") => "radroots.seller_stock.operation.v5", + (3..=14, "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 @@ -34,6 +34,7 @@ pub use stock::{ StockRequestSnapshot, StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, StockSigningProgress, StockSnapshotRequest, StockSourceCapture, StockSourceOutcome, StockSourceProfile, StockSourceReceipt, StockSourceSnapshot, StockUnissuedInvocation, + StockUnissuedOutcome, StockUnissuedReceipt, }; mod worker; diff --git a/crates/storage_sqlite/src/workspace/recovery.rs b/crates/storage_sqlite/src/workspace/recovery.rs @@ -38,18 +38,21 @@ pub(super) struct RecoveryAuthorization { enum Material { Outbox(Box<(AttachmentInput, ArtifactEvidence)>), Stock(Box<StockEvidenceRequest>), + Unissued(Box<stock::issuance::unissued::Request>), } impl Material { fn input(&self) -> &AttachmentInput { match self { Self::Outbox(value) => &value.0, Self::Stock(value) => value.binding().input(), + Self::Unissued(value) => value.binding.input(), } } } enum Captured { Outbox(EvidenceCaptureOutcome), Stock(StockEvidenceOutcome), + Unissued(stock::StockUnissuedOutcome), } impl Captured { fn committed(&self) -> bool { @@ -57,6 +60,7 @@ impl Captured { self, Self::Outbox(EvidenceCaptureOutcome::Committed(_)) | Self::Stock(StockEvidenceOutcome::Committed(_)) + | Self::Unissued(stock::StockUnissuedOutcome::Committed(_)) ) } } @@ -112,6 +116,27 @@ impl RecoveryTurn<'_> { _ => Err(OperationError::RecoveryRequired), } } + pub(super) async fn capture_unissued( + &mut self, + request: stock::issuance::unissued::Request, + proof: AttachmentProof, + ) -> Result<stock::StockUnissuedOutcome, OperationError> { + if self.namespace.kind() != Kind::SellerStock { + return Err(OperationError::UnsupportedOperation); + } + if !SellerAuthoritySelection::from_attachment(self.selected) + .matches_attachment(request.binding.input()) + { + return Err(OperationError::Unauthorized); + } + match self + .recover(Material::Unissued(Box::new(request)), proof) + .await? + { + Captured::Unissued(value) => Ok(value), + _ => Err(OperationError::RecoveryRequired), + } + } async fn recover( &mut self, material: Material, @@ -146,6 +171,20 @@ impl RecoveryTurn<'_> { .await .map(Captured::Outbox) } + Material::Unissued(request) => Box::pin(stock::issuance::unissued::capture( + &mut stock::inventory::Turn { + connection, + namespace: self.namespace, + selected: self.selected, + crypto: self.crypto, + clock: self.clock, + uncertain: uncertainty, + }, + *request, + proof, + )) + .await + .map(Captured::Unissued), Material::Stock(request) => Box::pin(stock::issuance::evidence::capture( &mut stock::inventory::Turn { connection, diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -30,7 +30,7 @@ mod order_state; pub use issuance::{ StockCapturedEvidence, StockClaimOutcome, StockClaimRequest, StockDispatchOutcome, StockDispatchPermit, StockEvidenceCapture, StockEvidencePage, StockExactReplayPermit, - StockSigningAttempt, StockUnissuedInvocation, + StockSigningAttempt, StockUnissuedInvocation, StockUnissuedOutcome, StockUnissuedReceipt, }; pub(in crate::workspace) mod signing_plan; pub(in crate::workspace) mod snapshot; @@ -443,10 +443,10 @@ struct AuthorityV8 { } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { - if !matches!(self.catalog, 8..=13) && self.public_sources.is_some() { + if !matches!(self.catalog, 8..=14) && self.public_sources.is_some() { return Err(WorkspaceError::RecoveryRequired); } - if matches!(self.catalog, 8..=13) { + if matches!(self.catalog, 8..=14) { let public_sources = self .public_sources .ok_or(WorkspaceError::RecoveryRequired)?; @@ -698,7 +698,7 @@ impl Authority { public_sources: None, } } - 8..=13 => { + 8..=14 => { let value: AuthorityV8 = closed_record(bytes)?; value.public_sources.validate()?; if i64::from(value.version) != catalog @@ -828,7 +828,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=13") + sqlx::query("PRAGMA user_version=14") .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..=13) { + if !matches!(access.authority.catalog, 7..=14) { 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..=13) { + if !matches!(access.authority.catalog, 7..=14) { 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.v13" + if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v14" { 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..=13).contains(&authority.catalog) { + if !(4..=14).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } let catalog = authority.catalog; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -452,7 +452,7 @@ impl Turn<'_> { access.authority.authorization, mapping.as_ref().map(|value| value.effect), )?; - let framed = if matches!(catalog, 7..=13) { + let framed = if matches!(catalog, 7..=14) { Some( super::ledger::prepare( self.crypto, @@ -866,7 +866,7 @@ pub(super) async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let (frame, request, decoded) = if matches!(catalog, 7..=13) { + let (frame, request, decoded) = if matches!(catalog, 7..=14) { 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 @@ -149,7 +149,7 @@ pub(in crate::workspace) async fn abort( &proof, )) .await?; - if auth.access.authority.catalog != 13 { + if !matches!(auth.access.authority.catalog, 13..=14) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; @@ -389,7 +389,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if auth.access.authority.catalog != 13 { + if !matches!(auth.access.authority.catalog, 13..=14) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs @@ -236,7 +236,7 @@ pub(in crate::workspace) async fn admit( let access = turn .access(request.binding(), request.minimum_checkpoint(), &proof) .await?; - if !matches!(access.authority.catalog, 9..=13) { + if !matches!(access.authority.catalog, 9..=14) { return Err(OperationError::UnsupportedOperation); } let command = request.command(); @@ -271,7 +271,7 @@ pub(in crate::workspace) async fn admit( return Err(OperationError::Unauthorized); } } - let aborted = if access.authority.catalog == 13 { + let aborted = if access.authority.catalog >= 13 { Some(Box::pin(super::abort::existing(turn, &access, operation)).await?) } else { None @@ -361,7 +361,7 @@ pub(in crate::workspace) async fn admit( { return Err(OperationError::StaleState); } - let current_order = if access.authority.catalog == 13 { + let current_order = if access.authority.catalog >= 13 { let checked = Box::pin(checkpoint::authenticate_order_state( turn.connection, turn.selected, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs @@ -323,7 +323,7 @@ pub(in crate::workspace::stock) async fn read( .map_err(|_| OperationError::RecoveryRequired)?; let operation_keyed = match catalog { 1..=12 => false, - 13 => true, + 13 | 14 => true, _ => return Err(OperationError::RecoveryRequired), }; let actor = header.actor.participant(); diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -68,7 +68,7 @@ impl MinimumProof { let related: Option<Vec<u8>> = row .try_get(2) .map_err(|_| OperationError::RecoveryRequired)?; - if !(0..=7).contains(&family) { + if !(0..=if catalog >= 14 { 8 } else { 7 }).contains(&family) { return Err(OperationError::RecoveryRequired); } let subject: Option<Vec<u8>> = row @@ -87,14 +87,14 @@ impl MinimumProof { super::abort::raw_projection(connection, &actor, &operation).await?, ); } - if catalog == 13 && family == 2 { + 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) { + if matches!(family, 4 | 5 | 8) { hash.update( super::super::issuance::raw_projection( connection, &actor, &operation, family, @@ -143,7 +143,7 @@ pub(in crate::workspace::stock) async fn authenticate_order_state( authority: &Authority, order: radroots_domain::OrderId, ) -> Result<super::super::order_state::Checked, OperationError> { - if authority.catalog != 13 { + if !matches!(authority.catalog, 13..=14) { return Err(OperationError::UnsupportedOperation); } let current = authority @@ -212,7 +212,7 @@ pub(super) async fn authenticate_order_absence( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - if !matches!(authority.catalog, 9..=13) { + if !matches!(authority.catalog, 9..=14) { return Err(OperationError::UnsupportedOperation); } let upper = current.revision.get(); @@ -294,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..=13); + let multipart = matches!(authority.catalog, 7..=14); let upper = current.revision.get(); let mut previous = current.head; let mut hash = history_hash(multipart); @@ -471,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..=13); + let multipart = matches!(authority.catalog, 7..=14); let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { @@ -735,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..=13); + let multipart = matches!(authority.catalog, 7..=14); 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..=13) { + if matches!(catalog, 5..=14) { 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..=13) { + if matches!(catalog, 5..=14) { let decoded: OperationV4<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 4 { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs @@ -222,7 +222,7 @@ pub(in crate::workspace) async fn install( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12 | 13) { + if !matches!(auth.access.authority.catalog, 12..=14) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; @@ -234,7 +234,7 @@ 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 current_order = if auth.access.authority.catalog >= 13 { let checked = Box::pin(super::checkpoint::authenticate_order_state( turn.connection, turn.selected, @@ -481,7 +481,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12 | 13) { + if !matches!(auth.access.authority.catalog, 12..=14) { 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/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..=13).contains(&access.authority.catalog) { + if !(5..=14).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..=13 => Ok(2), + 3..=14 => 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 @@ -13,14 +13,16 @@ pub(in crate::workspace) mod claim; pub(in crate::workspace) mod evidence; mod projection; pub(in crate::workspace) mod recovery; +pub(in crate::workspace) mod unissued; pub(super) use claim::read_entry; pub use claim::{ StockClaimOutcome, StockClaimRequest, StockDispatchOutcome, StockDispatchPermit, StockSigningAttempt, StockUnissuedInvocation, }; pub use evidence::{StockCapturedEvidence, StockEvidenceCapture, StockEvidencePage}; -pub(super) use projection::{Projection, raw_projection}; +pub(super) use projection::{Projection, ProjectionKind, raw_projection}; pub use recovery::StockExactReplayPermit; +pub use unissued::{StockUnissuedOutcome, StockUnissuedReceipt}; pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<(), WorkspaceError> { let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") @@ -35,6 +37,13 @@ pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<() if claims != entries || evidence != captures { return Err(WorkspaceError::RecoveryRequired); } + if catalog >= 14 { + let (facts,entries):(i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM stock_original_unissued),(SELECT count(*) FROM stock_operations WHERE family=8)") + .fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + if facts != entries { + 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(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; if agreements != installs @@ -43,7 +52,7 @@ pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<() return Err(WorkspaceError::RecoveryRequired); } } - if catalog == 13 { + 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 { diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs @@ -54,9 +54,14 @@ pub(in crate::workspace::stock) async fn read_entry( } let body: Body = super::super::super::closed_record(&frame.body) .map_err(|_| OperationError::RecoveryRequired)?; - let plan = signing_plan::read_entry(connection, input, crypto, body.plan_entry) - .await? - .ok_or(OperationError::RecoveryRequired)?; + let plan = Box::pin(signing_plan::read_entry( + connection, + input, + crypto, + body.plan_entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; let selected = intent(&plan.bound, body.recipient, CancellationSignal::new())?; let header = &frame.header; if body.version != 1 @@ -80,7 +85,7 @@ pub(in crate::workspace::stock) async fn read_entry( let projection = Projection { operation: body.operation, recipient: body.recipient, - evidence: None, + kind: ProjectionKind::Claim, }; let report = StockSigningAttempt { bound: Arc::new(plan.bound), diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs @@ -108,7 +108,7 @@ pub(in crate::workspace::stock) async fn read_entry( return Err(OperationError::RecoveryRequired); } let raw = std::str::from_utf8(&body[PREFIX..]).map_err(|_| OperationError::RecoveryRequired)?; - let original = claim::read_entry(connection, input, crypto, claim) + let original = Box::pin(claim::read_entry(connection, input, crypto, claim)) .await? .ok_or(OperationError::RecoveryRequired)?; let header = &frame.header; @@ -148,7 +148,7 @@ pub(in crate::workspace::stock) async fn read_entry( let projection = Projection { operation: original.report.bound_plan().plan().operation_id(), recipient: original.report.recipient(), - evidence: Some(digest), + kind: ProjectionKind::Obtained(digest), }; let receipt = StockEvidenceReceipt::from_committed_store( CommitAttempt::new( diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/projection.rs b/crates/storage_sqlite/src/workspace/stock/issuance/projection.rs @@ -4,7 +4,22 @@ use super::*; pub(in crate::workspace::stock) struct Projection { pub operation: OperationId, pub recipient: PublicKey, - pub evidence: Option<[u8; 32]>, + pub kind: ProjectionKind, +} +#[derive(Clone, Copy)] +pub(in crate::workspace::stock) enum ProjectionKind { + Claim, + Obtained([u8; 32]), + OriginalUnissued(u8), +} +impl ProjectionKind { + fn family(self) -> i64 { + match self { + Self::Claim => 4, + Self::Obtained(_) => 5, + Self::OriginalUnissued(_) => 8, + } + } } impl Projection { pub fn digest(self, actor: PublicKey, entry: OperationId) -> [u8; 32] { @@ -14,9 +29,16 @@ impl Projection { hash.update(entry.as_bytes()); hash.update(self.operation.as_bytes()); hash.update(self.recipient.as_bytes()); - hash.update([u8::from(self.evidence.is_some())]); - if let Some(value) = self.evidence { - hash.update(value); + match self.kind { + ProjectionKind::Claim => hash.update([0]), + ProjectionKind::Obtained(value) => { + hash.update([1]); + hash.update(value); + } + ProjectionKind::OriginalUnissued(reason) => { + hash.update([2]); + hash.update([reason]); + } } hash.finalize().into() } @@ -30,7 +52,7 @@ impl Projection { connection, actor.as_bytes(), entry.as_bytes(), - if self.evidence.is_some() { 5 } else { 4 }, + self.kind.family(), ) .await?; if actual != self.digest(actor, entry) { @@ -48,6 +70,7 @@ pub(in crate::workspace::stock) async fn raw_projection( let row = match family { 4 => sqlx::query("SELECT CASE WHEN length(operation_id)=32 THEN operation_id END,CASE WHEN length(recipient)=32 THEN recipient END,NULL FROM stock_signing_claims WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await, 5 => sqlx::query("SELECT CASE WHEN length(operation_id)=32 THEN operation_id END,CASE WHEN length(recipient)=32 THEN recipient END,CASE WHEN length(evidence_digest)=32 THEN evidence_digest END FROM stock_signing_evidence WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await, + 8 => sqlx::query("SELECT CASE WHEN length(operation_id)=32 THEN operation_id END,CASE WHEN length(recipient)=32 THEN recipient END,reason FROM stock_original_unissued WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(connection).await, _ => return Err(OperationError::RecoveryRequired), }.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; let field = |index| { @@ -61,7 +84,20 @@ pub(in crate::workspace::stock) async fn raw_projection( operation: OperationId::from_bytes(field(0)?), recipient: PublicKey::from_bytes(field(1)?) .map_err(|_| OperationError::RecoveryRequired)?, - evidence: if family == 5 { Some(field(2)?) } else { None }, + kind: match family { + 4 => ProjectionKind::Claim, + 5 => ProjectionKind::Obtained(field(2)?), + 8 => { + let reason: u8 = row + .try_get::<i64, _>(2) + .ok() + .and_then(|v| v.try_into().ok()) + .filter(|v| (1..=9).contains(v)) + .ok_or(OperationError::RecoveryRequired)?; + ProjectionKind::OriginalUnissued(reason) + } + _ => return Err(OperationError::RecoveryRequired), + }, }; Ok(projection.digest( PublicKey::from_bytes(*actor).map_err(|_| OperationError::RecoveryRequired)?, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs b/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs @@ -70,7 +70,7 @@ pub(in crate::workspace) async fn authorize( &proof, )) .await?; - if auth.access.authority.catalog != 13 { + if !matches!(auth.access.authority.catalog, 13..=14) { return Err(OperationError::UnsupportedOperation); } let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs b/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs @@ -0,0 +1,571 @@ +//! Retain an owned original invocation's refusal; this never releases stock. +use super::super::inventory::{Turn, checkpoint}; +use super::*; +use radroots_domain::CheckpointDigest; +use radroots_signing::provider::ProviderError; +use zeroize::Zeroizing; + +const MAGIC: &[u8; 8] = b"RDSTKN1\0"; +const BYTES: usize = 105; + +/// An authenticated retained fact about one original invocation, not a permit. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct StockUnissuedReceipt { + attempt: CommitAttempt, + claim: SigningAttemptId, + recipient: PublicKey, + reason: ProviderError, + checkpoint: InventoryCheckpointRef, +} +impl StockUnissuedReceipt { + pub const fn attempt(&self) -> CommitAttempt { + self.attempt + } + pub const fn signing_attempt_id(&self) -> SigningAttemptId { + self.claim + } + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + pub const fn reason(&self) -> ProviderError { + self.reason + } + pub const fn checkpoint(&self) -> InventoryCheckpointRef { + self.checkpoint + } +} +/// Confirmed append versus actual transaction uncertainty, never business success. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum StockUnissuedOutcome { + Committed(Box<StockUnissuedReceipt>), + Unknown(CommitAttempt), +} + +/// Private worker transport, constructed only from the owned original proof. +pub(in crate::workspace) struct Request { + pub(in crate::workspace) binding: WorkspaceBinding, + claim: SigningAttemptId, + operation: OperationId, + digest: CommandDigest, + recipient: PublicKey, + intent: [u8; 32], + reason: u8, +} +impl Request { + fn from_observation( + binding: WorkspaceBinding, + value: &StockUnissuedInvocation, + ) -> Result<Self, OperationError> { + let original = value.attempt(); + if binding.input().workspace_id() != original.attempt().workspace_id() + || binding.actor().participant() != original.bound_plan().preparation().rumor().author() + { + return Err(OperationError::InvalidEvidence); + } + Ok(Self { + binding, + claim: original.attempt_id(), + operation: original.attempt().operation_id(), + digest: original.attempt().command_digest(), + recipient: original.recipient(), + intent: *original.binding().digest(), + reason: encode_reason(value.reason())?, + }) + } + pub(in crate::workspace) fn attempt(&self) -> CommitAttempt { + CommitAttempt::new( + self.binding.input().workspace_id(), + self.operation, + self.digest, + None, + ) + } +} +fn encode_reason(reason: ProviderError) -> Result<u8, OperationError> { + Ok(match reason.as_str() { + "invalid_input" => 1, + "limit_exceeded" => 2, + "unsupported_version" => 3, + "capability_unavailable" => 4, + "identity_changed" => 5, + "authentication_failed" => 6, + "cancelled" => 7, + "deadline_exceeded" => 8, + "provider_failure" => 9, + _ => return Err(OperationError::UnsupportedOperation), + }) +} +fn decode_reason(reason: u8) -> Result<ProviderError, OperationError> { + Ok(match reason { + 1 => ProviderError::InvalidInput, + 2 => ProviderError::LimitExceeded, + 3 => ProviderError::UnsupportedVersion, + 4 => ProviderError::CapabilityUnavailable, + 5 => ProviderError::IdentityChanged, + 6 => ProviderError::AuthenticationFailed, + 7 => ProviderError::Cancelled, + 8 => ProviderError::DeadlineExceeded, + 9 => ProviderError::ProviderFailure, + _ => return Err(OperationError::RecoveryRequired), + }) +} +fn body(original: &claim::codec::Retained, reason: u8) -> Zeroizing<Vec<u8>> { + let mut bytes = Zeroizing::new(Vec::with_capacity(BYTES)); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(original.frame.header.operation.as_bytes()); + bytes.extend_from_slice(original.frame.header.transaction.as_bytes()); + bytes.extend_from_slice(original.frame.header.head.as_bytes()); + bytes.push(reason); + bytes +} +fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.original_unissued_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(|v| *v.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(|v| *v.as_bytes()).unwrap_or([0; 32])); + hash.update(Sha256::digest(body)); + CheckpointDigest::from_bytes(hash.finalize().into()) +} +fn receipt( + input: &AttachmentInput, + header: &ledger::Header, + original: &claim::codec::Retained, + reason: u8, +) -> Result<StockUnissuedReceipt, OperationError> { + Ok(StockUnissuedReceipt { + attempt: CommitAttempt::new( + input.workspace_id(), + original.report.attempt().operation_id(), + header.digest, + Some(header.transaction), + ), + claim: original.report.attempt_id(), + recipient: original.report.recipient(), + reason: decode_reason(reason)?, + checkpoint: InventoryCheckpointRef::from_host_metadata( + input.authority(), + header.revision, + Some(header.head), + )?, + }) +} +pub(in crate::workspace::stock) struct Retained { + frame: ledger::Retained, + value: Box<StockUnissuedReceipt>, + projection: Projection, +} +impl Retained { + 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?; + 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(connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } + 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, + parts_witness: self.frame.parts_witness, + pools: vec![], + mapping: None, + movements: vec![], + signing: Some(self.projection), + local_record: None, + } + } +} +pub(in crate::workspace::stock) async fn read_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + entry: OperationId, +) -> Result<Option<Retained>, OperationError> { + let Some(frame) = ledger::read(connection, input, crypto, entry).await? else { + return Ok(None); + }; + let raw = frame.body.as_slice(); + if frame.header.family != ledger::Family::OriginalUnissued + || raw.len() != BYTES + || &raw[..8] != MAGIC + { + return Err(OperationError::RecoveryRequired); + } + let array = |start, end| { + raw[start..end] + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let original = Box::pin(claim::read_entry( + connection, + input, + crypto, + OperationId::from_bytes(array(8, 40)?), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if original.frame.header.transaction != TransactionId::from_bytes(array(40, 72)?) + || original.frame.header.head != CheckpointDigest::from_bytes(array(72, 104)?) + || frame.header.actor != original.frame.header.actor + || frame.header.related_operation != original.frame.header.related_operation + || frame.header.order != original.frame.header.order + || frame.header.digest != original.frame.header.digest + || frame.header.revision <= original.frame.header.revision + || head(&frame.header, raw) != frame.header.head + { + return Err(OperationError::RecoveryRequired); + } + let reason = raw[104]; + decode_reason(reason)?; + let projection = Projection { + operation: original.report.attempt().operation_id(), + recipient: original.report.recipient(), + kind: ProjectionKind::OriginalUnissued(reason), + }; + let value = receipt(input, &frame.header, &original, reason)?; + let retained = Retained { + frame, + value: Box::new(value), + projection, + }; + retained.confirm(connection).await?; + Ok(Some(retained)) +} +async fn lookup( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + operation: OperationId, + recipient: PublicKey, +) -> Result<Option<Retained>, OperationError> { + let entry:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_original_unissued WHERE actor=? AND operation_id=? AND recipient=?") + .bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()) + .fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(entry) = entry else { return Ok(None) }; + let retained = Box::pin(read_entry( + connection, + input, + crypto, + OperationId::from_bytes( + entry + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if retained.value.attempt.operation_id() != operation || retained.value.recipient != recipient { + return Err(OperationError::RecoveryRequired); + } + Ok(Some(retained)) +} +pub(in crate::workspace) async fn capture( + turn: &mut Turn<'_>, + request: Request, + proof: AttachmentProof, +) -> Result<StockUnissuedOutcome, OperationError> { + if *turn.uncertain { + return Err(OperationError::RecoveryRequired); + } + turn.namespace.validate()?; + let input = request.binding.input(); + if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) { + return Err(OperationError::Unauthorized); + } + let (authority, record, root, grant) = + super::super::read(turn.connection, input, turn.crypto).await?; + if authority.catalog != 14 { + return Err(OperationError::UnsupportedOperation); + } + record.authenticate_retained_capture(input, &proof)?; + let original = Box::pin(claim::read_entry( + turn.connection, + input, + turn.crypto, + OperationId::from_bytes(*request.claim.as_bytes()), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if original.frame.header.actor != request.binding.actor() + || original.report.attempt().operation_id() != request.operation + || original.report.attempt().command_digest() != request.digest + || original.report.recipient() != request.recipient + || original.report.binding().digest() != &request.intent + { + return Err(OperationError::InvalidEvidence); + } + decode_reason(request.reason)?; + let before = authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let witness = Box::pin(checkpoint::authenticate_minimum( + turn.connection, + turn.selected, + turn.crypto, + &request.binding, + &authority, + InventoryCheckpointRef::from_host_metadata( + input.authority(), + Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, + None, + )?, + )) + .await?; + let existing = Box::pin(lookup( + turn.connection, + input, + turn.crypto, + request.operation, + request.recipient, + )) + .await?; + let (frame, updated_root, value) = if let Some(retained) = &existing { + if retained.value.claim != request.claim + || retained.value.reason != decode_reason(request.reason)? + { + return Err(OperationError::RecoveryRequired); + } + (None, None, *retained.value) + } else { + let entry = OperationId::from_bytes(super::super::super::random()?); + let transaction = TransactionId::from_bytes(super::super::super::random()?); + let revision = Sequence::new( + before + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let body = body(&original, request.reason); + let mut header = ledger::Header { + version: 5, + family: ledger::Family::OriginalUnissued, + namespace: SellerAuthoritySelection::from_attachment(turn.selected), + actor: original.frame.header.actor, + operation: entry, + digest: original.frame.header.digest, + transaction, + revision, + previous: before.head, + head: CheckpointDigest::from_bytes([0; 32]), + pool: None, + order: original.frame.header.order, + related_operation: original.frame.header.related_operation, + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], + }; + header.head = head(&header, &body); + let value = receipt(input, &header, &original, request.reason)?; + let mut next = authority.clone(); + next.inventory = Some(InventoryCheckpoint { + revision, + head: Some(header.head), + ..before + }); + let frame = ledger::prepare(turn.crypto, input, header, &body).await?; + let updated = turn + .crypto + .seal_stock_root(input, next.catalog, &next.encode()?) + .await?; + (Some(frame), Some(updated), value) + }; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let changed:Result<(),OperationError>=async { + turn.namespace.validate()?; + super::super::unchanged(&mut tx,input,authority.catalog,&root,&grant).await?; + record.authenticate_retained_capture(input,&proof)?; + witness.confirm(&mut tx).await?;original.confirm(&mut tx).await?; + if let Some(retained)=&existing {retained.confirm(&mut tx).await?;} + if let Some(frame)=&frame { + frame.insert_record(&mut tx).await?; + sqlx::query("INSERT INTO stock_original_unissued(actor,operation_id,recipient,reason,entry_id) VALUES(?,?,?,?,?)") + .bind(input.participant().as_bytes().as_slice()).bind(request.operation.as_bytes().as_slice()) + .bind(request.recipient.as_bytes().as_slice()).bind(i64::from(request.reason)) + .bind(frame.header.operation.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + let updated=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?") + .bind(updated_root.as_ref().ok_or(OperationError::RecoveryRequired)?).bind(&root) + .execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if updated.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(StockUnissuedOutcome::Unknown(value.attempt)); + } + return Err(error); + } + let done = if frame.is_some() { + tx.commit().await + } else { + tx.rollback().await + }; + if done.is_err() { + *turn.uncertain = true; + return Ok(StockUnissuedOutcome::Unknown(value.attempt)); + } + Ok(StockUnissuedOutcome::Committed(Box::new(value))) +} +pub(in crate::workspace) async fn read( + turn: &mut Turn<'_>, + request: StockClaimRequest, + proof: AttachmentProof, +) -> Result<Option<StockUnissuedReceipt>, OperationError> { + let auth = super::super::signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + ) + .await?; + if auth.access.authority.catalog != 14 { + return Err(OperationError::UnsupportedOperation); + } + let witness = Box::pin(checkpoint::authenticate_minimum( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, + None, + )?, + )) + .await?; + let retained = Box::pin(lookup( + turn.connection, + turn.selected, + turn.crypto, + request.operation, + request.recipient, + )) + .await?; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + witness.confirm(&mut tx).await?; + if let Some(value) = &retained { + value.confirm(&mut tx).await?; + } + auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) + .await?; + Ok(()) + } + .await; + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + Ok(retained.map(|v| *v.value)) +} +impl super::super::NativeWorkspace { + /// Borrows the actual owned original observation. Failed/uncertain writes + /// leave that observation available; no new issuance or stock effect occurs. + pub async fn capture_stock_original_unissued( + &self, + binding: WorkspaceBinding, + observation: &StockUnissuedInvocation, + proof: &AttachmentProof, + ) -> Result<StockUnissuedOutcome, OperationError> { + self.worker + .capture_stock_original_unissued( + Request::from_observation(binding, observation)?, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + false, + ) + .await + } + /// Reconciles only original material on this namespace's retained owner. + pub async fn reconcile_stock_original_unissued( + &self, + binding: WorkspaceBinding, + observation: &StockUnissuedInvocation, + proof: &AttachmentProof, + ) -> Result<StockUnissuedOutcome, OperationError> { + self.worker + .capture_stock_original_unissued( + Request::from_observation(binding, observation)?, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + true, + ) + .await + } + /// Reads the authenticated original invocation fact; never a release permit. + pub async fn stock_original_unissued( + &self, + request: StockClaimRequest, + proof: &AttachmentProof, + ) -> Result<Option<StockUnissuedReceipt>, OperationError> { + self.worker + .stock_original_unissued( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -23,6 +23,7 @@ pub(super) enum Family { SigningEvidence, Installation, AbortedPreparation, + OriginalUnissued, } #[derive(Serialize, Deserialize)] @@ -77,6 +78,7 @@ impl Header { | Family::SigningEvidence | Family::Installation | Family::AbortedPreparation + | Family::OriginalUnissued ) != self.related_operation.is_some() || (self.family == Family::Consent) != self.subject_grant.is_some() || self.bytes == 0 @@ -331,6 +333,7 @@ impl Family { Self::SigningEvidence => 5, Self::Installation => 6, Self::AbortedPreparation => 7, + Self::OriginalUnissued => 8, } } } @@ -534,7 +537,7 @@ pub(super) async fn history( movements: vec![], })) } - Some(2) if matches!(authority.catalog, 9..=13) => Ok(Some( + Some(2) if matches!(authority.catalog, 9..=14) => Ok(Some( Box::pin(super::inventory::acceptance::codec::read( connection, input, crypto, operation, )) @@ -543,7 +546,7 @@ pub(super) async fn history( .into_history(), )), Some(2) => Err(OperationError::UnsupportedOperation), - Some(3) if matches!(authority.catalog, 10..=13) => { + Some(3) if matches!(authority.catalog, 10..=14) => { let retained = Box::pin(super::signing_plan::read_entry( connection, input, crypto, operation, )) @@ -567,7 +570,7 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(6) if matches!(authority.catalog, 12 | 13) => Ok(Some( + Some(6) if matches!(authority.catalog, 12..=14) => Ok(Some( Box::pin(super::inventory::installation::read_entry( connection, input, crypto, operation, )) @@ -575,7 +578,7 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(7) if authority.catalog == 13 => Ok(Some( + Some(7) if authority.catalog >= 13 => Ok(Some( Box::pin(super::inventory::abort::read_entry( connection, input, crypto, operation, )) @@ -583,6 +586,14 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), + Some(8) if authority.catalog == 14 => Ok(Some( + Box::pin(super::issuance::unissued::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )), Some(_) => Err(OperationError::RecoveryRequired), } } @@ -650,10 +661,11 @@ impl HistoryEntry { hash.update(preparation); } match (header.family, self.signing) { - (Family::SigningClaim | Family::SigningEvidence, Some(projection)) => { - hash.update(projection.digest(header.actor.participant(), header.operation)) - } - (Family::SigningClaim | Family::SigningEvidence, None) => { + ( + Family::SigningClaim | Family::SigningEvidence | Family::OriginalUnissued, + Some(projection), + ) => hash.update(projection.digest(header.actor.participant(), header.operation)), + (Family::SigningClaim | Family::SigningEvidence | Family::OriginalUnissued, None) => { return Err(OperationError::RecoveryRequired); } (_, Some(_)) => return Err(OperationError::RecoveryRequired), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/abort_failures_tests.rs @@ -122,7 +122,7 @@ async fn late_order_grant_pool_and_unrelated_preparation_changes_never_commit_a_ .unwrap(); provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .abort_proven_unissued(selected, r.enrollment.proof()), @@ -279,7 +279,7 @@ async fn losing_abort_observer_drains_original_admitted_work_before_reopen() { let selected = abort_request(&r, &receipt).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .abort_proven_unissued(selected, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs @@ -450,7 +450,7 @@ async fn lost_observer_retains_actual_two_pool_preparation_and_drain_precedes_re let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -504,7 +504,7 @@ async fn source_mapping_pool_order_and_grant_rows_are_rechecked_after_final_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -541,7 +541,7 @@ async fn final_clock_recheck_refuses_expiry_and_rollback_after_protection_withou let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs @@ -329,7 +329,7 @@ async fn lost_claim_observer_drains_and_reopens_as_existing_without_a_permit() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), @@ -406,7 +406,7 @@ async fn claim_rechecks_original_plan_projection_grant_root_and_clock_after_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 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/dispatch_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/dispatch_tests.rs @@ -9,6 +9,8 @@ use radroots_signing::{ use std::sync::atomic::{AtomicUsize, Ordering}; static CLOCK_MODE: AtomicUsize = AtomicUsize::new(0); static CLOCK_CALLS: AtomicUsize = AtomicUsize::new(0); +#[path = "unissued_tests.rs"] +mod retained; fn clock() -> Result<u64, radroots_signing::Error> { CLOCK_CALLS.fetch_add(1, Ordering::SeqCst); match CLOCK_MODE.load(Ordering::SeqCst) { diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_reconciliation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_reconciliation_tests.rs @@ -78,7 +78,8 @@ async fn same_owner_capture_reconciliation_resolves_real_rollback_and_unknown_co writer_remains_owned(&r).await; remove_fault(&mut database, unknown).await; let original_clock = r.clock.0.load(Ordering::SeqCst); - r.clock.0.store(0, Ordering::SeqCst); + r.clock.0.store(u64::MAX, Ordering::SeqCst); + assert!(r.clock.now().is_err()); let retained = committed(reconcile(&r, &request).await.unwrap()); assert_eq!(retained.signing_attempt_id(), report.attempt_id()); assert_eq!(retained.observed_at_unix_ms(), None); @@ -127,13 +128,13 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho remove_fault(&mut database, true).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); let mut recovery = Box::pin(reconcile(&r, &request)); assert!(futures::poll!(recovery.as_mut()).is_pending()); provider.gate.entered(); // The authorized old snapshot has already been read. Future schema then // refuses read-only preflight after close; no migration or repair occurs. - sqlx::raw_sql("PRAGMA user_version=14") + sqlx::raw_sql("PRAGMA user_version=15") .execute(&mut database) .await .unwrap(); @@ -145,7 +146,7 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho .fetch_one(&mut database) .await .unwrap(), - 14 + 15 ); let wrong = AttachmentProof::from_protected_input(&[99; 32]).unwrap(); assert!( @@ -154,7 +155,7 @@ async fn refused_stock_recovery_preflight_keeps_writer_and_cached_original_autho .is_err() ); request.with_json(|value| assert_eq!(value, raw)); - sqlx::raw_sql("PRAGMA user_version=13") + sqlx::raw_sql("PRAGMA user_version=14") .execute(&mut database) .await .unwrap(); @@ -183,7 +184,7 @@ async fn lost_reconciliation_observer_drains_the_actual_replacement_and_original remove_fault(&mut database, true).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); let mut recovery = Box::pin(reconcile(&r, &request)); assert!(futures::poll!(recovery.as_mut()).is_pending()); provider.gate.entered(); diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs @@ -211,7 +211,10 @@ async fn already_obtained_bytes_survive_expiry_revocation_cancellation_and_missi rawdb.close().await.unwrap(); } "expired" => r.clock.0.store(350, Ordering::SeqCst), - "clock_unavailable" => r.clock.0.store(0, Ordering::SeqCst), + "clock_unavailable" => { + r.clock.0.store(u64::MAX, Ordering::SeqCst); + assert!(r.clock.now().is_err()); + } "revoked" => { r.store .revoke_stock_grant( @@ -439,7 +442,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.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), @@ -527,7 +530,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.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/exact_recovery_tests.rs @@ -429,7 +429,7 @@ async fn replay_authorization_rechecks_actual_late_root_grant_plan_claim_backing let mut raw = database(&r).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .authorize_stock_exact_replay(request, r.enrollment.proof()), @@ -483,7 +483,7 @@ async fn observer_loss_drains_authorization_without_signing_or_a_new_claim_and_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Unwrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Unwrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .authorize_stock_exact_replay(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs @@ -412,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.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .install_stock_agreement(selected, r.enrollment.proof()), @@ -451,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.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 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 @@ -164,7 +164,7 @@ async fn stock_process_child() { if control.before { provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); } let work = async { match control.edge { diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs @@ -354,7 +354,7 @@ async fn dropped_t1_observer_keeps_owned_work_and_close_drains_before_original_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), @@ -408,7 +408,7 @@ async fn t1_final_permission_order_root_and_clock_witnesses_refuse_changes_after let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 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.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 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.v13", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 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..=13) || authority.public_sources.is_none() { + if !matches!(authority.catalog, 8..=14) || authority.public_sources.is_none() { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/unissued_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/unissued_tests.rs @@ -0,0 +1,385 @@ +//! Actual catalog14 original-negative transactions; no release authority. +use super::*; +use crate::workspace::{StockUnissuedInvocation, StockUnissuedOutcome, StockUnissuedReceipt}; + +fn committed(value: StockUnissuedOutcome) -> StockUnissuedReceipt { + let StockUnissuedOutcome::Committed(value) = value else { + panic!("confirmed original-negative append") + }; + *value +} +async fn observation( + r: &Rig, + receipt: &StockAcceptanceReceipt, + mode: usize, +) -> StockUnissuedInvocation { + let recipient = receipt.rumor().recipients()[0]; + let StockClaimOutcome::Fresh(permit) = claim(r, receipt, recipient).await.unwrap() else { + panic!("fresh original claim") + }; + CLOCK_MODE.store(mode, Ordering::SeqCst); + CLOCK_CALLS.store(0, Ordering::SeqCst); + let signer = + LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), clock).unwrap(); + let cancel = CancellationSignal::new(); + if mode == 3 { + cancel.cancel(); + } + let StockDispatchOutcome::Unissued(value) = permit.dispatch(&signer, cancel).await.unwrap() + else { + panic!("actual original local refusal") + }; + assert_eq!(CLOCK_CALLS.load(Ordering::SeqCst), 1); + value +} +async fn capture( + r: &Rig, + value: &StockUnissuedInvocation, +) -> Result<StockUnissuedOutcome, OperationError> { + r.store + .capture_stock_original_unissued(r.binding.clone(), value, r.enrollment.proof()) + .await +} +async fn read_fact( + r: &Rig, + receipt: &StockAcceptanceReceipt, +) -> Result<Option<StockUnissuedReceipt>, OperationError> { + r.store + .stock_original_unissued( + selector(r, receipt, receipt.rumor().recipients()[0]).await, + r.enrollment.proof(), + ) + .await +} +#[tokio::test] +async fn qualified_original_refusals_are_durable_idempotent_and_keep_holds_without_clock() { + for mode in 0..4 { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + assert!(read_fact(&r, &receipt).await.unwrap().is_none()); + let value = observation(&r, &receipt, mode).await; + let before = inventory_minimum(&r).await; + r.clock.0.store(u64::MAX, Ordering::SeqCst); + assert!(r.clock.now().is_err()); + let captured = committed(capture(&r, &value).await.unwrap()); + assert_eq!(captured.signing_attempt_id(), value.attempt().attempt_id()); + assert_eq!(captured.reason(), value.reason()); + assert_eq!(captured.recipient(), value.attempt().recipient()); + assert_eq!( + captured.attempt().operation_id(), + receipt.attempt().operation_id() + ); + assert_eq!( + captured.checkpoint().revision().get(), + before.revision().get() + 1 + ); + assert!(captured.attempt().transaction_id().is_some()); + assert_eq!(committed(capture(&r, &value).await.unwrap()), captured); + assert_eq!(CLOCK_CALLS.load(Ordering::SeqCst), 1); + r.clock.0.store(150, Ordering::SeqCst); + assert_eq!(read_fact(&r, &receipt).await.unwrap(), Some(captured)); + let minimum = inventory_minimum(&r).await; + assert_eq!(minimum.revision(), captured.checkpoint().revision()); + let abort = radroots_storage::inventory::StockAbortRequest::new( + r.binding.clone(), + minimum, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ); + assert!(matches!( + radroots_storage::inventory::InventoryStore::abort_proven_unissued( + &r.store, + abort, + r.enrollment + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap() + ) + .await, + Err(OperationError::RecoveryRequired) + )); + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + drop(value); + reopen_plain(&mut r).await; + assert_eq!(read_fact(&r, &receipt).await.unwrap(), Some(captured)); + assert!(matches!( + claim(&r, &receipt, captured.recipient()).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn every_original_negative_write_failure_preserves_owned_proof_and_all_holds() { + for statement in [ + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations WHEN NEW.family=8 BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_operation_parts BEGIN SELECT RAISE(ABORT,'fixture'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_original_unissued 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; + let receipt = ready(&r).await; + let value = observation(&r, &receipt, 1).await; + let original = value.attempt().attempt_id(); + let before = inventory_minimum(&r).await; + let mut raw = database(&r).await; + sqlx::raw_sql(statement).execute(&mut raw).await.unwrap(); + assert_eq!( + capture(&r, &value).await.unwrap_err().code(), + "storage_failure" + ); + assert_eq!(value.attempt().attempt_id(), original); + assert_eq!(inventory_minimum(&r).await, before); + assert!(read_fact(&r, &receipt).await.unwrap().is_none()); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut raw) + .await + .unwrap(); + raw.close().await.unwrap(); + assert_eq!( + committed(capture(&r, &value).await.unwrap()).signing_attempt_id(), + original + ); + assert_eq!(CLOCK_CALLS.load(Ordering::SeqCst), 1); + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn unknown_original_negative_commit_reconciles_same_owner_without_clock_or_reissue() { + let r = Rig::new().await; + let receipt = ready(&r).await; + let value = observation(&r, &receipt, 1).await; + let original = value.attempt().attempt_id(); + 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_original_unissued BEGIN INSERT INTO deferred_fault VALUES(2); END") + .execute(&mut raw).await.unwrap(); + let StockUnissuedOutcome::Unknown(attempt) = capture(&r, &value).await.unwrap() else { + panic!("real deferred COMMIT failure") + }; + assert!(attempt.transaction_id().is_some()); + assert!(matches!( + capture(&r, &value).await, + Err(OperationError::RecoveryRequired) + )); + assert_eq!(value.attempt().attempt_id(), original); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut raw) + .await + .unwrap(); + raw.close().await.unwrap(); + r.clock.0.store(u64::MAX, Ordering::SeqCst); + assert!(r.clock.now().is_err()); + let captured = committed( + r.store + .reconcile_stock_original_unissued(r.binding.clone(), &value, r.enrollment.proof()) + .await + .unwrap(), + ); + assert_eq!(captured.signing_attempt_id(), original); + r.clock.0.store(150, Ordering::SeqCst); + assert_eq!(read_fact(&r, &receipt).await.unwrap(), Some(captured)); + assert_eq!(CLOCK_CALLS.load(Ordering::SeqCst), 1); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn original_negative_projections_and_protected_bodies_are_authenticated_after_reopen() { + for statement in [ + "UPDATE stock_original_unissued SET reason=CASE WHEN reason=8 THEN 7 ELSE 8 END", + "DELETE FROM stock_original_unissued", + "UPDATE stock_operation_parts SET protected=randomblob(length(protected)) WHERE operation_id IN (SELECT entry_id FROM stock_original_unissued)", + ] { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let value = observation(&r, &receipt, 1).await; + committed(capture(&r, &value).await.unwrap()); + r.store.close().await.unwrap(); + let mut raw = database(&r).await; + sqlx::raw_sql(statement).execute(&mut raw).await.unwrap(); + raw.close().await.unwrap(); + match NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + { + Ok(store) => { + r.store = store; + assert!( + read_fact(&r, &receipt).await.is_err(), + "tampered original-negative ancestry must refuse" + ); + r.store.close().await.unwrap(); + } + Err(error) => assert!(matches!(error, WorkspaceError::RecoveryRequired)), + } + } +} +#[tokio::test] +async fn later_valid_evidence_does_not_erase_original_refusal_or_release_backing() { + let r = Rig::new().await; + let receipt = ready(&r).await; + let value = observation(&r, &receipt, 1).await; + let negative = committed(capture(&r, &value).await.unwrap()); + // Controlled independent late positive input; not a second dispatch permit + // or qualification of an external key owner or recovery adapter. + fn late_clock() -> Result<u64, radroots_signing::Error> { + Ok(150000) + } + let report = value.attempt(); + let seal = report + .bound_plan() + .plan() + .seals() + .iter() + .find(|v| v.recipient() == report.recipient()) + .unwrap(); + let intent = radroots_signing::issuance::SigningIntent::from_commerce_seal( + seal, + radroots_signing::provider::ProviderCall::new( + seal.fields().author, + core::num::NonZeroU64::new( + report + .bound_plan() + .preparation() + .first_issue_deadline() + .get() + * 1000, + ) + .unwrap(), + CancellationSignal::new(), + ), + ) + .unwrap(); + let signer = LocalSigner::with_clock( + SecretKey::parse(&format!("{:064x}", 3)).unwrap(), + late_clock, + ) + .unwrap(); + let (_, OutcomeKind::Obtained(artifact)) = + radroots_signing::provider::ParticipantProvider::sign_exact(&signer, intent) + .await + .into_parts() + else { + panic!("independent valid original signature") + }; + let evidence = artifact + .with_json(|raw| { + crate::workspace::StockEvidenceCapture::verify( + r.binding.clone(), + report, + raw, + artifact.observed_at_unix_ms(), + ) + }) + .unwrap(); + let radroots_storage::inventory::StockEvidenceOutcome::Committed(positive) = r + .store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap() + else { + panic!("late evidence retained") + }; + assert_eq!(positive.signing_attempt_id(), negative.signing_attempt_id()); + assert_eq!(read_fact(&r, &receipt).await.unwrap(), Some(negative)); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn retained_original_refusal_survives_expired_and_revoked_permission_without_pool_effects() { + for expired in [false, true] { + let r = Rig::new().await; + let receipt = ready(&r).await; + let value = observation(&r, &receipt, 1).await; + let read_request = selector(&r, &receipt, value.attempt().recipient()).await; + let mut raw = database(&r).await; + let before: 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(); + let movements: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_movements") + .fetch_one(&mut raw) + .await + .unwrap(); + if expired { + r.clock.0.store(350, Ordering::SeqCst); + } else { + r.store + .revoke_stock_grant( + r.binding.clone(), + inventory_minimum(&r).await, + r.enrollment.proof(), + radroots_domain::TransactionId::from_bytes([94; 32]), + r.enrollment.input().grant_id(), + ) + .await + .unwrap(); + } + assert!( + r.store + .stock_original_unissued(read_request, r.enrollment.proof()) + .await + .is_err(), + "fresh read permission really refuses" + ); + let retained = committed(capture(&r, &value).await.unwrap()); + assert_eq!(committed(capture(&r, &value).await.unwrap()), retained); + assert_eq!(retained.signing_attempt_id(), value.attempt().attempt_id()); + 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, before, + "all protected pool bytes and versions unchanged" + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_movements") + .fetch_one(&mut raw) + .await + .unwrap(), + movements + ); + assert_eq!(CLOCK_CALLS.load(Ordering::SeqCst), 1); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn lost_original_negative_append_waiter_drains_and_reopens_the_same_fact() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let value = observation(&r, &receipt, 1).await; + let original = value.attempt().attempt_id(); + let reason = value.reason(); + let provider = reopen(&mut r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v14", 0); + let mut pending = Box::pin(capture(&r, &value)); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + drop(pending); + drop(value); + provider.gate.release(); + reopen_plain(&mut r).await; + let retained = read_fact(&r, &receipt).await.unwrap().unwrap(); + assert_eq!(retained.signing_attempt_id(), original); + assert_eq!(retained.reason(), reason); + assert_eq!(CLOCK_CALLS.load(Ordering::SeqCst), 1); + assert!(matches!( + claim(&r, &receipt, retained.recipient()).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} 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 = 13; +pub(super) const CURRENT: i64 = 14; 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"; @@ -17,6 +17,7 @@ const OPERATIONS_V10: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL 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 OPERATIONS_V14: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 8), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 8 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const 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, @@ -27,13 +28,15 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=13 => objects.extend([ + 2..=14 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ( "table", "stock_operations", "stock_operations", - if version >= 13 { + if version >= 14 { + OPERATIONS_V14 + } else if version >= 13 { OPERATIONS_V13 } else if version >= 12 { OPERATIONS_V12 @@ -82,7 +85,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..=13).contains(&version) { + if (6..=14).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)")); @@ -118,7 +121,7 @@ pub(super) fn objects( objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); } } - if matches!(version, 8..=13) { + if matches!(version, 8..=14) { 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(( @@ -172,6 +175,10 @@ pub(super) fn objects( )); objects.push(("table","stock_publication_work","stock_publication_work","CREATE TABLE stock_publication_work (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), recipient BLOB NOT NULL CHECK(length(recipient)=32), installation_entry BLOB NOT NULL CHECK(length(installation_entry)=32), PRIMARY KEY(actor,operation_id,recipient), FOREIGN KEY(actor,installation_entry) REFERENCES stock_operations(actor,operation_id), FOREIGN KEY(actor,operation_id) REFERENCES stock_agreements(actor,operation_id)) STRICT, WITHOUT ROWID")); } + if version >= 14 { + objects.push(("table","stock_original_unissued","stock_original_unissued","CREATE TABLE stock_original_unissued (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), recipient BLOB NOT NULL CHECK(length(recipient)=32), reason INTEGER NOT NULL CHECK(reason BETWEEN 1 AND 9), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id,recipient), FOREIGN KEY(actor,operation_id,recipient) REFERENCES stock_signing_claims(actor,operation_id,recipient), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(("index","stock_original_unissued_entry","stock_original_unissued","CREATE UNIQUE INDEX stock_original_unissued_entry ON stock_original_unissued(actor,entry_id)")); + } Ok(objects) } pub(super) async fn admit(connection: &mut SqliteConnection) -> Result<i64, WorkspaceError> { diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan.rs @@ -148,7 +148,7 @@ pub(in crate::workspace::stock) async fn load( proof: &AttachmentProof, ) -> Result<Authorized, OperationError> { let access = turn.access(binding, minimum, proof).await?; - if !matches!(access.authority.catalog, 10..=13) { + if !matches!(access.authority.catalog, 10..=14) { return Err(OperationError::UnsupportedOperation); } let original = Box::pin(acceptance::codec::read( diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs @@ -103,7 +103,7 @@ pub(in crate::workspace::stock) async fn read_entry( take(&frame.body, &mut offset)?, take(&frame.body, &mut offset)?, ]; - let original = acceptance::codec::read(connection, input, crypto, related) + let original = Box::pin(acceptance::codec::read(connection, input, crypto, related)) .await? .ok_or(OperationError::RecoveryRequired)?; if header.related_operation != Some(related) diff --git a/crates/storage_sqlite/src/workspace/stock/snapshot.rs b/crates/storage_sqlite/src/workspace/stock/snapshot.rs @@ -227,7 +227,7 @@ pub(in crate::workspace) async fn read( } else { None }; - let aborted = if auth.access.authority.catalog == 13 { + let aborted = if auth.access.authority.catalog >= 13 { Some( Box::pin(super::inventory::abort::existing( turn, @@ -246,7 +246,7 @@ pub(in crate::workspace) async fn read( { return Err(OperationError::RecoveryRequired); } - let current_order = if auth.access.authority.catalog == 13 { + let current_order = if auth.access.authority.catalog >= 13 { Some( Box::pin(super::inventory::checkpoint::authenticate_order_state( turn.connection, 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..=13).contains(&authority.catalog) { + if !(6..=14).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..=13) { + if !matches!(access.authority.catalog, 8..=14) { 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..=13) { + if !matches!(access.authority.catalog, 8..=14) { 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(13)); + assert_eq!(schema::admit(&mut connection).await, Ok(14)); 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(), 13, &root) + .open_stock_root(enrollment.input(), 14, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 13)) + .expose_secret(|bytes| Authority::decode(bytes, 14)) .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(),13).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),14).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(),13).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),14).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, 13] { + for version in [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] { 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, 13); + assert_eq!(schema::CURRENT, 14); 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..=13) { + if matches!(catalog, 8..=14) { value["public_sources"] = serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); } @@ -386,6 +386,7 @@ pub(super) async fn literal_catalog( 11 => "PRAGMA user_version=11", 12 => "PRAGMA user_version=12", 13 => "PRAGMA user_version=13", + 14 => "PRAGMA user_version=14", _ => unreachable!(), }) .execute(&mut *tx) @@ -411,7 +412,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..=13) + matches!(catalog, 8..=14) ); let minimum = authority.inventory_checkpoint().unwrap(); let context = CommandContextData::new( @@ -654,7 +655,7 @@ async fn retained_inventory_catalog(catalog: i64) { .fetch_one(&mut connection) .await .unwrap(); - let old = if matches!(catalog, 7..=13) { + let old = if matches!(catalog, 7..=14) { let retained = ledger::read( &mut connection, &input, @@ -707,7 +708,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..=13) { + if part && !matches!(catalog, 7..=14) { continue; } let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) @@ -783,6 +784,7 @@ async fn retained_inventory_catalog(catalog: i64) { 11 => "PRAGMA user_version=10", 12 => "PRAGMA user_version=11", 13 => "PRAGMA user_version=12", + 14 => "PRAGMA user_version=13", _ => unreachable!(), }) .execute(&mut connection) @@ -912,12 +914,18 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() #[tokio::test] async fn retained_v12_preserves_initial_installation_catalog_without_upgrade() { - assert_eq!(schema::CURRENT, 13); + assert_eq!(schema::CURRENT, 14); retained_inventory_catalog(12).await; } #[tokio::test] -async fn current_v13_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 13); +async fn retained_v13_authenticates_literal_catalog_and_original_inventory_records() { + assert_eq!(schema::CURRENT, 14); retained_inventory_catalog(13).await; } + +#[tokio::test] +async fn current_v14_authenticates_literal_catalog_and_original_inventory_records() { + assert_eq!(schema::CURRENT, 14); + retained_inventory_catalog(14).await; +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -74,6 +74,21 @@ enum Job { AttachmentProof, Reply<stock::StockEvidenceOutcome, OperationError>, ), + CaptureStockUnissued( + Box<stock::issuance::unissued::Request>, + AttachmentProof, + Reply<stock::StockUnissuedOutcome, OperationError>, + ), + RecoverStockUnissued( + Box<stock::issuance::unissued::Request>, + AttachmentProof, + Reply<stock::StockUnissuedOutcome, OperationError>, + ), + StockUnissued( + Box<stock::StockClaimRequest>, + AttachmentProof, + Reply<Option<stock::StockUnissuedReceipt>, OperationError>, + ), CaptureStockEvidence( Box<radroots_storage::inventory::StockEvidenceRequest>, AttachmentProof, @@ -334,6 +349,12 @@ impl Job { Self::StockEvidencePage(_, _, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } + Self::CaptureStockUnissued(_, _, reply) | Self::RecoverStockUnissued(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockUnissued(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::CaptureStockEvidence(_, _, reply) | Self::RecoverStockEvidence(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -537,7 +558,7 @@ impl Handle { return; } }; - let result = runtime.block_on(async { + let result = runtime.block_on(Box::pin(async { if !creating { let preflight = preflight_existing(&namespace, &input, &crypto).await; if let Err(error) = preflight { @@ -609,6 +630,9 @@ impl Handle { | Job::ClaimStockSigning(..) | Job::StockSigningAttempt(..) | Job::AuthorizeStockExactReplay(..) + | Job::CaptureStockUnissued(..) + | Job::RecoverStockUnissued(..) + | Job::StockUnissued(..) | Job::CaptureStockEvidence(..) | Job::RecoverStockEvidence(..) | Job::StockEvidence(..) @@ -626,6 +650,24 @@ impl Handle { continue; } let job = match job { + Job::RecoverStockUnissued(request, proof, reply) => { + let result = Box::pin( + super::recovery::RecoveryTurn { + connection: &mut connection, + cached_grant: &mut cached_grant, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + options: &options, + } + .capture_unissued(*request, proof), + ) + .await; + let _ = reply.send(result); + continue; + } Job::RecoverStockEvidence(request, proof, reply) => { let result = Box::pin( super::recovery::RecoveryTurn { @@ -973,6 +1015,46 @@ impl Handle { }; let _ = reply.send(result); } + Job::CaptureStockUnissued(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::unissued::capture( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } + Job::StockUnissued(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::unissued::read( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } Job::CaptureStockEvidence(evidence, proof, reply) => { let result = if kind == Kind::SellerStock { Box::pin(stock::issuance::evidence::capture( @@ -1285,9 +1367,9 @@ impl Handle { } let _ = reply.send(result); } - job @ (Job::RecoverCapture(..) | Job::RecoverStockEvidence(..)) => { - job.reject_recovery() - } + job @ (Job::RecoverCapture(..) + | Job::RecoverStockEvidence(..) + | Job::RecoverStockUnissued(..)) => job.reject_recovery(), Job::CaptureDeliveryObservation( binding, proof, @@ -1582,7 +1664,7 @@ impl Handle { .await .map_err(|_| WorkspaceError::StorageFailure); checked.and(closed).and_then(|()| namespace.validate()) - }); + })); drop(namespace); let _ = completion.send(Some(result)); }) @@ -1832,6 +1914,30 @@ impl Handle { ))?; result.await.map_err(|_| OperationError::RecoveryRequired)? } + pub(super) async fn capture_stock_original_unissued( + &self, + request: stock::issuance::unissued::Request, + proof: AttachmentProof, + reconcile: bool, + ) -> Result<stock::StockUnissuedOutcome, OperationError> { + let unknown = stock::StockUnissuedOutcome::Unknown(request.attempt()); + let (reply, result) = oneshot::channel(); + self.send(if reconcile { + Job::RecoverStockUnissued(Box::new(request), proof, reply) + } else { + Job::CaptureStockUnissued(Box::new(request), proof, reply) + })?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn stock_original_unissued( + &self, + request: stock::StockClaimRequest, + proof: AttachmentProof, + ) -> Result<Option<stock::StockUnissuedReceipt>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockUnissued(Box::new(request), proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn reconcile_stock_evidence( &self, request: radroots_storage::inventory::StockEvidenceRequest, @@ -2023,9 +2129,12 @@ impl Handle { fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { Job::RetainStockListing(..) + | Job::CaptureStockUnissued(..) + | Job::RecoverStockUnissued(..) | Job::CaptureStockEvidence(..) | Job::RecoverStockEvidence(..) => 256 * 1024, Job::StockEvidence(..) + | Job::StockUnissued(..) | Job::StockEvidencePage(..) | Job::StockSnapshot(..) | Job::InstallStockAgreement(..) 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=13") + sqlx::query("PRAGMA user_version=14") .execute(&mut connection) .await .unwrap(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -349,6 +349,18 @@ struct SigningPlanBinding { browser_failure_boundary: String, browser_failure_preserves_signer_rejection: bool, browser_failure_max_bytes: u16, + original_unissued_capture_owner: String, + original_unissued_payload_version: u32, + original_unissued_journal_family: u32, + original_unissued_capture_requires_owned_observation: bool, + original_unissued_capture_borrows_observation: bool, + original_unissued_capture_rechecks_original_claim: bool, + original_unissued_capture_requires_fresh_permission: bool, + original_unissued_capture_requires_fresh_clock: bool, + original_unissued_capture_releases_stock: bool, + original_unissued_reconciliation_same_owner: bool, + original_unissued_late_evidence_retained: bool, + original_unissued_worker_charge_bytes: u32, original_unissued_live_observation_owner: String, original_unissued_observation_is_durable: bool, original_unissued_observation_releases_stock: bool, @@ -575,10 +587,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 == 13 + && stock.schema_version == 14 && stock.retained_enrollment_versions == [1] - && 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.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v14" && stock.public_source_payload_schemas == [ "radroots.seller_stock.public_source_event.v1", @@ -697,6 +709,38 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && !stock .signing_plan_binding .recovery_refusal_creates_original_unissued_observation + && stock.signing_plan_binding.original_unissued_capture_owner + == "NativeWorkspace.capture_stock_original_unissued" + && stock.signing_plan_binding.original_unissued_payload_version == 1 + && stock.signing_plan_binding.original_unissued_journal_family == 8 + && stock + .signing_plan_binding + .original_unissued_capture_requires_owned_observation + && stock + .signing_plan_binding + .original_unissued_capture_borrows_observation + && stock + .signing_plan_binding + .original_unissued_capture_rechecks_original_claim + && !stock + .signing_plan_binding + .original_unissued_capture_requires_fresh_permission + && !stock + .signing_plan_binding + .original_unissued_capture_requires_fresh_clock + && !stock + .signing_plan_binding + .original_unissued_capture_releases_stock + && stock + .signing_plan_binding + .original_unissued_reconciliation_same_owner + && stock + .signing_plan_binding + .original_unissued_late_evidence_retained + && stock + .signing_plan_binding + .original_unissued_worker_charge_bytes + == 262144 && !stock .signing_plan_binding .ordinary_existing_claim_grants_first_dispatch @@ -809,7 +853,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.qualified_local_recovery.native_authorizer == "NativeWorkspace.authorize_stock_exact_replay" && stock.qualified_local_recovery.captured_replay == "local_replay_safe" - && stock.qualified_local_recovery.native_catalog == 13 + && stock.qualified_local_recovery.native_catalog == 14 && stock.qualified_local_recovery.worker_charge_bytes == 1048576 && stock .qualified_local_recovery @@ -1831,6 +1875,36 @@ mod tests { "original_unissued_live_observation_owner", json!("caller_assertion"), ), + ( + "original_unissued_capture_owner", + json!("caller_certificate"), + ), + ("original_unissued_payload_version", json!(2)), + ("original_unissued_journal_family", json!(5)), + ( + "original_unissued_capture_requires_owned_observation", + json!(false), + ), + ( + "original_unissued_capture_borrows_observation", + json!(false), + ), + ( + "original_unissued_capture_rechecks_original_claim", + json!(false), + ), + ( + "original_unissued_capture_requires_fresh_permission", + json!(true), + ), + ( + "original_unissued_capture_requires_fresh_clock", + json!(true), + ), + ("original_unissued_capture_releases_stock", json!(true)), + ("original_unissued_reconciliation_same_owner", json!(false)), + ("original_unissued_late_evidence_retained", json!(false)), + ("original_unissued_worker_charge_bytes", json!(1)), ("original_unissued_observation_is_durable", json!(true)), ("original_unissued_observation_releases_stock", json!(true)), (