lib

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

commit 7b428cbd4431e4bf05db62ec4f1b07131f8e1442
parent afd18fe38f6d1942d5faeb667e31e44df3512921
Author: triesap <tyson@radroots.org>
Date:   Sun, 25 Oct 2026 14:27:05 +0000

storage: retain stock signing claims and obtained evidence

- Commit per-recipient first-dispatch claims over authenticated backing.
- Preserve exact obtained signatures through late and uncertain capture.
- Recover protected original outputs with bounded authenticated pages.
- Verify native and Linux faults, recovery, schemas and additive APIs.

Diffstat:
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 25++++++++++++++++++++++---
Mcrates/storage_sqlite/README.md | 29+++++++++++++++++++++++------
Mcrates/storage_sqlite/src/workspace/crypto.rs | 16++++++++++------
Mcrates/storage_sqlite/src/workspace/mod.rs | 10++++++----
Mcrates/storage_sqlite/src/workspace/stock.rs | 14++++++++++----
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 | 6++++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs | 1+
Acrates/storage_sqlite/src/workspace/stock/inventory/backing.rs | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs | 43+++++++++++++++++++++++++++++++++++--------
Mcrates/storage_sqlite/src/workspace/stock/inventory/codec.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/mapping.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory/plan.rs | 2+-
Acrates/storage_sqlite/src/workspace/stock/issuance.rs | 35+++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/issuance/claim.rs | 452+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs | 154+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/issuance/evidence.rs | 555+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/issuance/projection.rs | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/ledger.rs | 62+++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs | 6+++---
Acrates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs | 521+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs | 574+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs | 24++++++++++++++++++++++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/transaction.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/schema.rs | 24+++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/stock/signing_plan.rs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcrates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs | 5+++--
Mcrates/storage_sqlite/src/workspace/stock/source/transaction.rs | 6+++---
Mcrates/storage_sqlite/src/workspace/stock/tests.rs | 32+++++++++++++++++++-------------
Mcrates/storage_sqlite/src/workspace/worker.rs | 219++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcrates/storage_sqlite/tests/support/stock_authority.rs | 2+-
Mtools/xtask/src/architecture/decision_package.rs | 93++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
38 files changed, 3304 insertions(+), 100 deletions(-)

diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -371,6 +371,10 @@ pub use radroots_storage_sqlite::workspace::WorkspaceScope pub enum radroots_storage_sqlite::workspace::StockAcceptanceOutcome pub radroots_storage_sqlite::workspace::StockAcceptanceOutcome::Prepared(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockAcceptanceReceipt>) pub radroots_storage_sqlite::workspace::StockAcceptanceOutcome::Unknown(radroots_storage::command::CommitAttempt) +pub enum radroots_storage_sqlite::workspace::StockClaimOutcome +pub radroots_storage_sqlite::workspace::StockClaimOutcome::Existing(radroots_storage_sqlite::workspace::StockSigningAttempt) +pub radroots_storage_sqlite::workspace::StockClaimOutcome::Fresh(radroots_storage_sqlite::workspace::StockDispatchPermit) +pub radroots_storage_sqlite::workspace::StockClaimOutcome::Unknown(radroots_storage::command::CommitAttempt) pub enum radroots_storage_sqlite::workspace::StockConsentMode pub radroots_storage_sqlite::workspace::StockConsentMode::ExecuteAndRecover pub radroots_storage_sqlite::workspace::StockConsentMode::RecoverOnly @@ -381,6 +385,9 @@ pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::command_op pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::control_operation: radroots_domain::identifier::OperationId pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::subject: radroots_domain::identifier::GrantId pub radroots_storage_sqlite::workspace::StockConsentOutcome::Unknown::transaction: radroots_domain::identifier::TransactionId +pub enum radroots_storage_sqlite::workspace::StockEvidenceOutcome +pub radroots_storage_sqlite::workspace::StockEvidenceOutcome::Committed(radroots_storage_sqlite::workspace::StockEvidenceReceipt) +pub radroots_storage_sqlite::workspace::StockEvidenceOutcome::Unknown(radroots_storage::command::CommitAttempt) pub enum radroots_storage_sqlite::workspace::StockGrantOutcome pub radroots_storage_sqlite::workspace::StockGrantOutcome::Committed(radroots_storage_sqlite::workspace::StockGrantReceipt) pub radroots_storage_sqlite::workspace::StockGrantOutcome::Unknown(radroots_domain::identifier::TransactionId) @@ -412,6 +419,13 @@ 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_signing_evidence(&self, &radroots_storage_sqlite::workspace::StockEvidenceCapture, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::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> +impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::claim_stock_signing_attempt(&self, radroots_storage_sqlite::workspace::StockClaimRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockClaimOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_signing_attempt(&self, radroots_storage_sqlite::workspace::StockClaimRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockSigningAttempt>, radroots_storage::command::OperationError> +impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::enroll_stock_grant(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, &radroots_storage::workspace::AttachmentProof, &radroots_storage_sqlite::workspace::StockGrantEnrollment) -> core::result::Result<radroots_storage_sqlite::workspace::StockGrantOutcome, radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::revoke_stock_grant(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, &radroots_storage::workspace::AttachmentProof, radroots_domain::identifier::TransactionId, radroots_domain::identifier::GrantId) -> core::result::Result<radroots_storage_sqlite::workspace::StockGrantOutcome, radroots_storage::workspace::WorkspaceError> impl radroots_storage_sqlite::workspace::NativeWorkspace @@ -495,6 +509,17 @@ pub const fn radroots_storage_sqlite::workspace::StockBoundSigningPlan::plan(&se pub const fn radroots_storage_sqlite::workspace::StockBoundSigningPlan::preparation(&self) -> &radroots_storage_sqlite::workspace::StockAcceptanceReceipt impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockBoundSigningPlan pub fn radroots_storage_sqlite::workspace::StockBoundSigningPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockCapturedEvidence +impl radroots_storage_sqlite::workspace::StockCapturedEvidence +pub const fn radroots_storage_sqlite::workspace::StockCapturedEvidence::receipt(&self) -> radroots_storage_sqlite::workspace::StockEvidenceReceipt +pub fn radroots_storage_sqlite::workspace::StockCapturedEvidence::with_json<T>(&self, impl core::ops::function::FnOnce(&str) -> T) -> T +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockCapturedEvidence +pub fn radroots_storage_sqlite::workspace::StockCapturedEvidence::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockClaimRequest +impl radroots_storage_sqlite::workspace::StockClaimRequest +pub const fn radroots_storage_sqlite::workspace::StockClaimRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey) -> Self +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockClaimRequest +pub fn radroots_storage_sqlite::workspace::StockClaimRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockConsentCapture impl radroots_storage_sqlite::workspace::StockConsentCapture pub fn radroots_storage_sqlite::workspace::StockConsentCapture::command(&self) -> &radroots_protocol::command::order_acceptance::CapturedOrderAcceptance @@ -519,6 +544,12 @@ pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::order_id(& pub fn radroots_storage_sqlite::workspace::StockConsentReceipt::resources(&self) -> &radroots_storage::workspace::seller_stock::permissions::StockResources pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::subject_grant(&self) -> radroots_domain::identifier::GrantId pub const fn radroots_storage_sqlite::workspace::StockConsentReceipt::transaction_id(&self) -> radroots_domain::identifier::TransactionId +pub struct radroots_storage_sqlite::workspace::StockDispatchPermit +impl radroots_storage_sqlite::workspace::StockDispatchPermit +pub fn radroots_storage_sqlite::workspace::StockDispatchPermit::into_signing_intent(self, radroots_signing::request::CancellationSignal) -> core::result::Result<(radroots_signing::issuance::SigningIntent, radroots_storage_sqlite::workspace::StockSigningAttempt), radroots_storage::command::OperationError> +pub const fn radroots_storage_sqlite::workspace::StockDispatchPermit::report(&self) -> &radroots_storage_sqlite::workspace::StockSigningAttempt +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockDispatchPermit +pub fn radroots_storage_sqlite::workspace::StockDispatchPermit::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockEnrollment impl radroots_storage_sqlite::workspace::StockEnrollment pub fn radroots_storage_sqlite::workspace::StockEnrollment::input(&self) -> &radroots_storage::workspace::AttachmentInput @@ -527,6 +558,24 @@ pub fn radroots_storage_sqlite::workspace::StockEnrollment::proof(&self) -> &rad pub const fn radroots_storage_sqlite::workspace::StockEnrollment::transaction_id(&self) -> radroots_domain::identifier::TransactionId impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockEnrollment pub fn radroots_storage_sqlite::workspace::StockEnrollment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockEvidenceCapture +impl radroots_storage_sqlite::workspace::StockEvidenceCapture +pub const fn radroots_storage_sqlite::workspace::StockEvidenceCapture::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub fn radroots_storage_sqlite::workspace::StockEvidenceCapture::verify(radroots_storage::workspace::WorkspaceBinding, &radroots_storage_sqlite::workspace::StockSigningAttempt, &str, core::option::Option<core::num::nonzero::NonZeroU64>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage_sqlite::workspace::StockEvidenceCapture::with_json<T>(&self, impl core::ops::function::FnOnce(&str) -> T) -> T +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockEvidenceCapture +pub fn radroots_storage_sqlite::workspace::StockEvidenceCapture::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockEvidencePage +impl radroots_storage_sqlite::workspace::StockEvidencePage +pub const fn radroots_storage_sqlite::workspace::StockEvidencePage::next(&self) -> core::option::Option<radroots_domain::context::Sequence> +pub fn radroots_storage_sqlite::workspace::StockEvidencePage::receipts(&self) -> &[radroots_storage_sqlite::workspace::StockEvidenceReceipt] +pub struct radroots_storage_sqlite::workspace::StockEvidenceReceipt +impl radroots_storage_sqlite::workspace::StockEvidenceReceipt +pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::digest(&self) -> &[u8; 32] +pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::observed_at_unix_ms(&self) -> core::option::Option<core::num::nonzero::NonZeroU64> +pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::recipient(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage_sqlite::workspace::StockEvidenceReceipt::signing_attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId pub struct radroots_storage_sqlite::workspace::StockGrantEnrollment impl radroots_storage_sqlite::workspace::StockGrantEnrollment pub fn radroots_storage_sqlite::workspace::StockGrantEnrollment::input(&self) -> &radroots_storage::workspace::AttachmentInput @@ -588,6 +637,17 @@ pub fn radroots_storage_sqlite::workspace::StockRequestSnapshot::terms(&self) -> pub const fn radroots_storage_sqlite::workspace::StockRequestSnapshot::terms_digest(&self) -> radroots_domain::identifier::TermsDigest impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockRequestSnapshot pub fn radroots_storage_sqlite::workspace::StockRequestSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockSigningAttempt +impl radroots_storage_sqlite::workspace::StockSigningAttempt +pub fn radroots_storage_sqlite::workspace::StockSigningAttempt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub fn radroots_storage_sqlite::workspace::StockSigningAttempt::attempt_id(&self) -> radroots_domain::identifier::SigningAttemptId +pub const fn radroots_storage_sqlite::workspace::StockSigningAttempt::binding(&self) -> radroots_protocol::intent::IntentBinding +pub fn radroots_storage_sqlite::workspace::StockSigningAttempt::bound_plan(&self) -> &radroots_storage_sqlite::workspace::StockBoundSigningPlan +pub const fn radroots_storage_sqlite::workspace::StockSigningAttempt::claimed_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_storage_sqlite::workspace::StockSigningAttempt::recipient(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage_sqlite::workspace::StockSigningAttempt::transaction_id(&self) -> radroots_domain::identifier::TransactionId +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockSigningAttempt +pub fn radroots_storage_sqlite::workspace::StockSigningAttempt::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockSigningPlanRequest impl radroots_storage_sqlite::workspace::StockSigningPlanRequest pub fn radroots_storage_sqlite::workspace::StockSigningPlanRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_nostr::commerce::signing_plan::VerifiedCommerceSigningPlan) -> core::result::Result<Self, radroots_storage::command::OperationError> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -75,7 +75,7 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 10, + "schema_version": 11, "retained_enrollment_versions": [ 1 ], @@ -87,9 +87,10 @@ 6, 7, 8, - 9 + 9, + 10 ], - "authority_payload_schema": "radroots.seller_stock.authority.v10", + "authority_payload_schema": "radroots.seller_stock.authority.v11", "public_source_payload_schemas": [ "radroots.seller_stock.public_source_event.v1", "radroots.seller_stock.public_source_head.v1", @@ -218,6 +219,24 @@ "final_permission_and_clock_witnesses_required": true, "signer_invoked": false, "agreement_installed": false + }, + "signing_issuance": { + "fresh_current_backing_projection_required": true, + "evidence_page_max": 32, + "claim_family": 4, + "evidence_family": 5, + "claim_worker_charge_bytes": 1048576, + "capture_worker_charge_bytes": 262144, + "capture_raw_max_bytes": 65536, + "first_dispatch_requires_confirmed_commit": true, + "existing_claim_returns_dispatch_permit": false, + "protected_identity_presence_and_absence_required": true, + "capture_requires_original_claim_and_credential": true, + "capture_requires_current_consent": false, + "capture_requires_observation_clock": false, + "capture_preserves_first_optional_time": true, + "capture_retains_distinct_valid_encodings": true, + "agreement_installed": false } }, "provenance": { 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-10 catalog has separate protected authority and +directory. Its exact version-11 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 version10 and protected authority -payload version10. Retained enrollment-only version1 still authenticates and +The current stock factory creates exact catalog version11 and protected authority +payload version11. 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–9 retain their exact original codecs and +new correction commands. Catalogs1–10 retain their exact original codecs and capabilities; current multipart operation framing uses version5. No namespace is automatically migrated. Ordinary outbox catalogs are separate. @@ -408,5 +408,22 @@ intent digests and all original plan bytes in one protected journal advance, with final permission, deadline and row-witness checks. Stock does not move again. `stock_signing_plan` reads the original plan through current consent; replacement RecoverOnly access cannot create missing intents. Uncertain commit -requires drain/reopen and original-identity reconciliation. Durable stock -signing claims, S capture, agreement installation and delivery remain pending. +requires drain/reopen and original-identity reconciliation. + +`claim_stock_signing_attempt` commits one protected claim per original recipient +before returning a single-use dispatch permit. Existing/recovered claims return +reports without a new permit. Exact obtained signatures are independently +verified again against the backend claim and appended through the borrowed +`capture_stock_signing_evidence` input. Fresh T1 and dispatch claims also check +current backing against protected history and compare each pool again at commit; +legitimate changes to available stock do not reconstruct the original allocation. +Capture requires the original scoped +credential, preserves the first optional observation time and every distinct +valid original encoding, and survives expiry, revocation and unavailable clocks. +It grants no new read, signing, installation or delivery permission. Current +consent governs `stock_signing_evidence` reads. Uncertain commits fence the +owner until drain/reopen and reconciliation; the caller retains its input. +`stock_signing_evidence_page` discovers up to 32 authenticated references per +page by original operation and recipient, so recovery can retrieve exact bytes +without retaining a caller-side digest or requesting another signature. +Agreement installation, stock conversion and delivery remain pending. 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..=10) { + if matches!(version, 4..=11) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -734,8 +734,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v8\0" } else if version == 9 { b"radroots.seller_stock.authority_context.v9\0" - } else { + } else if version == 10 { b"radroots.seller_stock.authority_context.v10\0".as_slice() + } else { + b"radroots.seller_stock.authority_context.v11\0".as_slice() }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -756,8 +758,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v8" } else if version == 9 { "radroots.seller_stock.authority.v9" - } else { + } else if version == 10 { "radroots.seller_stock.authority.v10" + } else { + "radroots.seller_stock.authority.v11" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -867,12 +871,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..=10, "pool") => return Ok(original), + (2, _) | (3..=11, "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..=10, "operation") => "radroots.seller_stock.operation.v5", - (3..=10, "movement") => "radroots.seller_stock.movement.v2", + (7..=11, "operation") => "radroots.seller_stock.operation.v5", + (3..=11, "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 @@ -24,12 +24,14 @@ mod snapshot; mod stock; pub use stock::{ SellerStockConfig, StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest, - StockAuthorityReceipt, StockBoundSigningPlan, StockConsentCapture, StockConsentMode, - StockConsentOutcome, StockConsentReceipt, StockEnrollment, StockGrantEnrollment, + StockAuthorityReceipt, StockBoundSigningPlan, StockCapturedEvidence, StockClaimOutcome, + StockClaimRequest, StockConsentCapture, StockConsentMode, StockConsentOutcome, + StockConsentReceipt, StockDispatchPermit, StockEnrollment, StockEvidenceCapture, + StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt, StockHistorySnapshot, StockListingCapture, StockListingOutcome, StockListingReceipt, StockListingSnapshot, StockRequestSnapshot, - StockSigningPlanOutcome, StockSigningPlanRequest, StockSourceCapture, StockSourceOutcome, - StockSourceProfile, StockSourceReceipt, StockSourceSnapshot, + StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, StockSourceCapture, + StockSourceOutcome, StockSourceProfile, StockSourceReceipt, StockSourceSnapshot, }; mod worker; diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -16,7 +16,13 @@ pub(in crate::workspace) mod grants; pub use inventory::acceptance::{ StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest, }; +pub(in crate::workspace) mod issuance; mod ledger; +pub use issuance::{ + StockCapturedEvidence, StockClaimOutcome, StockClaimRequest, StockDispatchPermit, + StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, + StockSigningAttempt, +}; pub(in crate::workspace) mod signing_plan; pub use signing_plan::{StockBoundSigningPlan, StockSigningPlanOutcome, StockSigningPlanRequest}; pub(in crate::workspace) mod public_source; @@ -423,10 +429,10 @@ struct AuthorityV8 { } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { - if !matches!(self.catalog, 8..=10) && self.public_sources.is_some() { + if !matches!(self.catalog, 8..=11) && self.public_sources.is_some() { return Err(WorkspaceError::RecoveryRequired); } - if matches!(self.catalog, 8..=10) { + if matches!(self.catalog, 8..=11) { let public_sources = self .public_sources .ok_or(WorkspaceError::RecoveryRequired)?; @@ -678,7 +684,7 @@ impl Authority { public_sources: None, } } - 8..=10 => { + 8..=11 => { let value: AuthorityV8 = closed_record(bytes)?; value.public_sources.validate()?; if i64::from(value.version) != catalog @@ -808,7 +814,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=10") + sqlx::query("PRAGMA user_version=11") .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..=10) { + if !matches!(access.authority.catalog, 7..=11) { 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..=10) { + if !matches!(access.authority.catalog, 7..=11) { 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.v10" + if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v11" { 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..=10).contains(&authority.catalog) { + if !(4..=11).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } let catalog = authority.catalog; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -1,5 +1,6 @@ //! Owner-private inventory effects on the existing connection owner. pub(in crate::workspace) mod acceptance; +pub(in crate::workspace::stock) mod backing; pub(super) mod checkpoint; mod codec; mod mapping; @@ -36,6 +37,7 @@ pub(super) async fn check_head( connection: &mut SqliteConnection, checkpoint: InventoryCheckpoint, ) -> Result<(), WorkspaceError> { + super::issuance::check_counts(connection).await?; if let Some(expected) = checkpoint.orders { let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_orders") .fetch_one(&mut *connection) @@ -448,7 +450,7 @@ impl Turn<'_> { access.authority.authorization, mapping.as_ref().map(|value| value.effect), )?; - let framed = if matches!(catalog, 7..=10) { + let framed = if matches!(catalog, 7..=11) { Some( super::ledger::prepare( self.crypto, @@ -862,7 +864,7 @@ pub(super) async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let (frame, request, decoded) = if matches!(catalog, 7..=10) { + let (frame, request, decoded) = if matches!(catalog, 7..=11) { let retained = super::ledger::read(connection, input, crypto, operation) .await? .ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs @@ -336,7 +336,7 @@ pub(in crate::workspace) async fn admit( let access = turn .access(&request.binding, request.minimum, &proof) .await?; - if !matches!(access.authority.catalog, 9 | 10) { + if !matches!(access.authority.catalog, 9..=11) { return Err(OperationError::UnsupportedOperation); } let command = &request.command; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs @@ -73,6 +73,7 @@ impl Retained { } pub fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + signing: None, header: self.frame.header, protected: self.frame.protected, parts_witness: self.frame.parts_witness, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/backing.rs b/crates/storage_sqlite/src/workspace/stock/inventory/backing.rs @@ -0,0 +1,63 @@ +//! Fresh issuance checks current backing without freezing unrelated pool changes. +use super::*; +pub(in crate::workspace::stock) struct BackingProof { + id: PoolId, + version: Sequence, + protected_digest: [u8; 32], + ancestry: MinimumProof, +} +pub(in crate::workspace::stock) async fn read( + turn: &mut Turn<'_>, + access: &Access, + pools: &[PoolSnapshot], +) -> Result<Vec<BackingProof>, OperationError> { + if pools.len() > 96 { + return Err(WorkspaceError::Capacity.into()); + } + let mut proofs = Vec::with_capacity(pools.len()); + for held in pools { + let current = read_pool(turn.connection, turn.selected, turn.crypto, held.id()) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let ancestry = authenticate_projection( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + &access.authority, + held.id(), + Some(current.pool), + ) + .await?; + proofs.push(BackingProof { + id: held.id(), + version: current.pool.version(), + protected_digest: Sha256::digest(&current.protected).into(), + ancestry, + }); + } + Ok(proofs) +} +impl BackingProof { + pub(in crate::workspace::stock) async fn confirm( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + self.ancestry.confirm(connection).await?; + let row=sqlx::query("SELECT revision,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_pools WHERE pool_id=?").bind(self.id.as_bytes().as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let version: i64 = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(1) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + if version <= 0 + || version as u64 != self.version.get() + || <[u8; 32]>::from(Sha256::digest(protected)) != self.protected_digest + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -64,7 +64,7 @@ impl MinimumProof { let related: Option<Vec<u8>> = row .try_get(2) .map_err(|_| OperationError::RecoveryRequired)?; - if !(0..=3).contains(&family) { + if !(0..=5).contains(&family) { return Err(OperationError::RecoveryRequired); } let subject: Option<Vec<u8>> = row @@ -78,6 +78,14 @@ impl MinimumProof { super::super::ledger::raw_parts_witness(connection, &actor, &operation).await?; hash.update([parts]); hash.update(witness); + if matches!(family, 4 | 5) { + hash.update( + super::super::issuance::raw_projection( + connection, &actor, &operation, family, + ) + .await?, + ); + } } hash_current_movements(&mut hash, connection, &actor, &operation).await?; } @@ -107,7 +115,7 @@ pub(super) async fn authenticate_order_absence( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - if !matches!(authority.catalog, 9 | 10) { + if !matches!(authority.catalog, 9..=11) { return Err(OperationError::UnsupportedOperation); } let upper = current.revision.get(); @@ -163,6 +171,11 @@ pub(in crate::workspace::stock) enum IdentityTarget { operation: OperationId, expected: Option<EntryIdentity>, }, + SigningClaim { + operation: OperationId, + recipient: radroots_domain::PublicKey, + expected: Option<EntryIdentity>, + }, } pub(in crate::workspace::stock) async fn authenticate_identity( connection: &mut SqliteConnection, @@ -175,7 +188,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - let multipart = matches!(authority.catalog, 7..=10); + let multipart = matches!(authority.catalog, 7..=11); let upper = current.revision.get(); let mut previous = current.head; let mut hash = history_hash(multipart); @@ -186,7 +199,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( id.try_into() .map_err(|_| OperationError::RecoveryRequired)?, ); - let (identity, predecessor, natural, signing_plan) = if multipart { + let (identity, predecessor, natural, signing_plan, signing_claim) = if multipart { let entry = super::super::ledger::history( connection, input, crypto, binding, authority, operation, ) @@ -217,6 +230,13 @@ pub(in crate::workspace::stock) async fn authenticate_identity( } else { None }, + if entry.header.family == super::super::ledger::Family::SigningClaim { + entry + .signing + .map(|value| (value.operation, value.recipient)) + } else { + None + }, ) } else { let entry = read_operation(connection, input, crypto, binding, operation) @@ -237,6 +257,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( entry.previous_head, None, None, + None, ) }; let (matched, expected) = match &target { @@ -250,6 +271,11 @@ pub(in crate::workspace::stock) async fn authenticate_identity( operation: wanted, expected, } => (signing_plan == Some(*wanted), *expected), + IdentityTarget::SigningClaim { + operation: wanted, + recipient, + expected, + } => (signing_claim == Some((*wanted, *recipient)), *expected), }; if matched { if expected != Some(identity) { @@ -267,7 +293,8 @@ pub(in crate::workspace::stock) async fn authenticate_identity( let expected = match target { IdentityTarget::Operation(_, expected) | IdentityTarget::Consent { expected, .. } - | IdentityTarget::SigningPlan { expected, .. } => expected, + | IdentityTarget::SigningPlan { expected, .. } + | IdentityTarget::SigningClaim { expected, .. } => expected, }; if previous.is_some() || expected.is_some() { return Err(OperationError::RecoveryRequired); @@ -279,7 +306,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( multipart, }) } -pub(super) async fn authenticate_minimum( +pub(in crate::workspace::stock) async fn authenticate_minimum( connection: &mut SqliteConnection, input: &AttachmentInput, crypto: &WorkspaceCrypto, @@ -298,7 +325,7 @@ pub(super) async fn authenticate_minimum( } let lower = minimum.revision().get().max(1); let upper = current.revision.get(); - let multipart = matches!(authority.catalog, 7..=10); + let multipart = matches!(authority.catalog, 7..=11); let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { @@ -546,7 +573,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..=10); + let multipart = matches!(authority.catalog, 7..=11); 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..=10) { + if matches!(catalog, 5..=11) { 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..=10) { + if matches!(catalog, 5..=11) { 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/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..=10).contains(&access.authority.catalog) { + if !(5..=11).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..=10 => Ok(2), + 3..=11 => 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 @@ -0,0 +1,35 @@ +//! Durable per-recipient claims and original evidence on the stock journal. +use super::*; +use radroots_domain::{CommandDigest, OperationId, PublicKey, SigningAttemptId, UnixSeconds}; +use radroots_storage::{ + command::{CommitAttempt, OperationError}, + inventory::InventoryCheckpointRef, +}; +use sha2::{Digest, Sha256}; +use sqlx::Row; +pub(in crate::workspace) mod claim; +pub(in crate::workspace) mod evidence; +mod projection; +pub(super) use claim::read_entry; +pub use claim::{StockClaimOutcome, StockClaimRequest, StockDispatchPermit, StockSigningAttempt}; +pub use evidence::{ + StockCapturedEvidence, StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, + StockEvidenceReceipt, +}; +pub(super) use projection::{Projection, raw_projection}; + +pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<(), WorkspaceError> { + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if catalog < 11 { + return Ok(()); + } + let (claims, entries): (i64,i64) = sqlx::query_as("SELECT (SELECT count(*) FROM stock_signing_claims),(SELECT count(*) FROM stock_operations WHERE family=4)").fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + let (evidence, captures): (i64,i64) = sqlx::query_as("SELECT (SELECT count(*) FROM stock_signing_evidence),(SELECT count(*) FROM stock_operations WHERE family=5)").fetch_one(connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + if claims != entries || evidence != captures { + return Err(WorkspaceError::RecoveryRequired); + } + Ok(()) +} diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs @@ -0,0 +1,452 @@ +//! First-dispatch linearization. Existing claims never create a new permit. +use super::super::{ + inventory::{ + Turn, acceptance, + checkpoint::{self, EntryIdentity, IdentityTarget}, + }, + signing_plan, +}; +use super::*; +use radroots_signing::{ + issuance::{IntentBinding, SigningIntent}, + provider::ProviderCall, + request::CancellationSignal, +}; +use std::{num::NonZeroU64, sync::Arc}; +pub(in crate::workspace::stock) mod codec; +pub(in crate::workspace::stock) use codec::read_entry; + +/// Captured selector data, without permission or provider capability evidence. +pub struct StockClaimRequest { + pub(super) binding: WorkspaceBinding, + pub(super) minimum: InventoryCheckpointRef, + pub(super) operation: OperationId, + pub(super) digest: CommandDigest, + pub(super) recipient: PublicKey, +} +impl StockClaimRequest { + pub const fn new( + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + recipient: PublicKey, + ) -> Self { + Self { + binding, + minimum, + operation, + digest, + recipient, + } + } + pub(in crate::workspace) fn attempt(&self) -> CommitAttempt { + CommitAttempt::new( + self.binding.input().workspace_id(), + self.operation, + self.digest, + None, + ) + } +} +impl std::fmt::Debug for StockClaimRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockClaimRequest(<redacted>)") + } +} + +/// An original durable claim. This report provides no fresh dispatch permit. +#[derive(Clone)] +pub struct StockSigningAttempt { + bound: Arc<StockBoundSigningPlan>, + recipient: PublicKey, + entry: EntryIdentity, + transaction: TransactionId, + claimed_at: UnixSeconds, + binding: IntentBinding, +} +impl StockSigningAttempt { + pub fn attempt_id(&self) -> SigningAttemptId { + SigningAttemptId::from_bytes(*self.entry.operation.as_bytes()) + } + pub const fn transaction_id(&self) -> TransactionId { + self.transaction + } + pub const fn claimed_at(&self) -> UnixSeconds { + self.claimed_at + } + pub const fn recipient(&self) -> PublicKey { + self.recipient + } + pub const fn binding(&self) -> IntentBinding { + self.binding + } + pub fn bound_plan(&self) -> &StockBoundSigningPlan { + &self.bound + } + pub fn attempt(&self) -> CommitAttempt { + CommitAttempt::new( + self.bound.attempt().workspace_id(), + self.bound.plan().operation_id(), + self.bound.plan().command_digest(), + Some(self.transaction), + ) + } +} +impl std::fmt::Debug for StockSigningAttempt { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockSigningAttempt(<redacted>)") + } +} + +/// Single-use confirmed first-dispatch boundary, distinct from actual provider +/// capability and destination policy. Those remain caller obligations before +/// invoking the signer. An original/recovered claim cannot construct this type. +pub struct StockDispatchPermit { + report: StockSigningAttempt, +} +impl StockDispatchPermit { + pub const fn report(&self) -> &StockSigningAttempt { + &self.report + } + /// Consumes this first-dispatch permit to expose the unchanged exact intent. + /// The returned report anchors later capture; it cannot reissue a permit. + pub fn into_signing_intent( + self, + cancellation: CancellationSignal, + ) -> Result<(SigningIntent, StockSigningAttempt), OperationError> { + let intent = intent(&self.report.bound, self.report.recipient, cancellation)?; + if intent.binding() != self.report.binding { + return Err(OperationError::RecoveryRequired); + } + Ok((intent, self.report)) + } +} +impl std::fmt::Debug for StockDispatchPermit { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockDispatchPermit(<redacted>)") + } +} +#[derive(Debug)] +pub enum StockClaimOutcome { + Fresh(StockDispatchPermit), + Existing(StockSigningAttempt), + Unknown(CommitAttempt), +} +pub(in crate::workspace::stock) fn intent( + bound: &StockBoundSigningPlan, + recipient: PublicKey, + cancellation: CancellationSignal, +) -> Result<SigningIntent, OperationError> { + let seal = bound + .plan() + .seals() + .iter() + .find(|seal| seal.recipient() == recipient) + .ok_or(OperationError::InvalidCommand)?; + let deadline = NonZeroU64::new( + bound + .preparation() + .first_issue_deadline() + .get() + .checked_mul(1000) + .ok_or(OperationError::RecoveryRequired)?, + ) + .ok_or(OperationError::RecoveryRequired)?; + SigningIntent::from_commerce_seal( + seal, + ProviderCall::new(seal.fields().author, deadline, cancellation), + ) + .map_err(|_| OperationError::InvalidEvidence) +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Body { + version: u8, + operation: OperationId, + plan_entry: OperationId, + plan_transaction: TransactionId, + plan_head: radroots_domain::CheckpointDigest, + plan_digest: [u8; 32], + recipient: PublicKey, + intent: [u8; 32], + deadline: UnixSeconds, + claimed_at: UnixSeconds, +} + +pub(super) async fn existing( + turn: &mut Turn<'_>, + auth: &signing_plan::Authorized, + operation: OperationId, + recipient: PublicKey, +) -> Result<(Option<codec::Retained>, checkpoint::MinimumProof), OperationError> { + let id:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_signing_claims WHERE actor=? AND operation_id=? AND recipient=?") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let retained = if let Some(id) = id { + Some( + read_entry( + turn.connection, + turn.selected, + turn.crypto, + OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + ) + .await? + .ok_or(OperationError::RecoveryRequired)?, + ) + } else { + None + }; + let witness = checkpoint::authenticate_identity( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + IdentityTarget::SigningClaim { + operation, + recipient, + expected: retained.as_ref().map(codec::Retained::identity), + }, + ) + .await?; + Ok((retained, witness)) +} +async fn confirm_read( + turn: &mut Turn<'_>, + auth: &signing_plan::Authorized, + witness: &checkpoint::MinimumProof, + retained: Option<&codec::Retained>, + proof: &AttachmentProof, +) -> Result<(), OperationError> { + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + 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 +} +pub(in crate::workspace) async fn claim( + turn: &mut Turn<'_>, + request: StockClaimRequest, + proof: AttachmentProof, +) -> Result<StockClaimOutcome, OperationError> { + let mut auth = signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + ) + .await?; + if auth.access.authority.catalog != 11 { + return Err(OperationError::UnsupportedOperation); + } + let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; + let selected = intent(&plan.bound, request.recipient, CancellationSignal::new())?; + let (retained, witness) = existing(turn, &auth, request.operation, request.recipient).await?; + if let Some(retained) = retained { + confirm_read(turn, &auth, &witness, Some(&retained), &proof).await?; + return Ok(StockClaimOutcome::Existing(retained.report)); + } + let at = auth.access.current.observed_at(); + acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, at)?; + if at < plan.bound.bound_at() || at >= plan.bound.preparation().first_issue_deadline() { + return Err(OperationError::DeadlineExceeded); + } + let backing = Box::pin(super::super::inventory::backing::read( + turn, + &auth.access, + auth.original.receipt.held_pools(), + )) + .await?; + let entry = OperationId::from_bytes(super::super::super::random()?); + let transaction = TransactionId::from_bytes(super::super::super::random()?); + let before = auth + .access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let revision = Sequence::new( + before + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let body = Body { + version: 1, + operation: request.operation, + plan_entry: plan.frame.header.operation, + plan_transaction: plan + .bound + .attempt() + .transaction_id() + .ok_or(OperationError::RecoveryRequired)?, + plan_head: plan.frame.header.head, + plan_digest: *plan.bound.plan().digest(), + recipient: request.recipient, + intent: *selected.binding().digest(), + deadline: plan.bound.preparation().first_issue_deadline(), + claimed_at: at, + }; + let clear = zeroize::Zeroizing::new( + serde_json::to_vec(&body).map_err(|_| OperationError::StorageFailure)?, + ); + if clear.len() > 16 * 1024 { + return Err(WorkspaceError::Capacity.into()); + } + let mut header = ledger::Header { + version: 5, + family: ledger::Family::SigningClaim, + namespace: SellerAuthoritySelection::from_attachment(turn.selected), + actor: auth.access.current.actor(), + operation: entry, + digest: request.digest, + transaction, + revision, + previous: before.head, + head: radroots_domain::CheckpointDigest::from_bytes([0; 32]), + pool: None, + order: Some(plan.bound.preparation().order_id()), + related_operation: Some(request.operation), + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], + }; + header.head = codec::head(&header, &clear); + let head = header.head; + let framed = ledger::prepare(turn.crypto, turn.selected, header, &clear).await?; + let entry_identity = EntryIdentity { + operation: entry, + revision, + head, + protected_digest: Sha256::digest(&framed.protected).into(), + }; + let mut next = auth.access.authority.clone(); + next.inventory = Some(InventoryCheckpoint { + revision, + head: Some(head), + ..before + }); + let root = turn + .crypto + .seal_stock_root(turn.selected, next.catalog, &next.encode()?) + .await?; + let anchor = CommitAttempt::new( + turn.selected.workspace_id(), + request.operation, + request.digest, + Some(transaction), + ); + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let changed:Result<(),OperationError>=async { + witness.confirm(&mut tx).await?; + let current=auth.confirm(&mut tx,turn.namespace,turn.clock,&proof,true).await?; + for pool in &backing { pool.confirm(&mut tx).await?; } + if current.observed_at()<at {return Err(WorkspaceError::Unavailable.into());} + framed.insert_record(&mut tx).await?; + sqlx::query("INSERT INTO stock_signing_claims(actor,operation_id,recipient,entry_id) VALUES(?,?,?,?)").bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation.as_bytes().as_slice()).bind(request.recipient.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + let updated=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&auth.access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if 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(StockClaimOutcome::Unknown(anchor)); + } + return Err(error); + } + if tx.commit().await.is_err() { + *turn.uncertain = true; + return Ok(StockClaimOutcome::Unknown(anchor)); + } + let bound = Arc::new( + auth.plan + .take() + .ok_or(OperationError::RecoveryRequired)? + .bound, + ); + Ok(StockClaimOutcome::Fresh(StockDispatchPermit { + report: StockSigningAttempt { + bound, + recipient: request.recipient, + entry: entry_identity, + transaction, + claimed_at: at, + binding: selected.binding(), + }, + })) +} +pub(in crate::workspace) async fn read( + turn: &mut Turn<'_>, + request: StockClaimRequest, + proof: AttachmentProof, +) -> Result<Option<StockSigningAttempt>, OperationError> { + let auth = signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + ) + .await?; + if auth.access.authority.catalog != 11 { + return Err(OperationError::UnsupportedOperation); + } + let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; + intent(&plan.bound, request.recipient, CancellationSignal::new())?; + let (retained, witness) = existing(turn, &auth, request.operation, request.recipient).await?; + confirm_read(turn, &auth, &witness, retained.as_ref(), &proof).await?; + Ok(retained.map(|value| value.report)) +} +impl NativeWorkspace { + pub async fn claim_stock_signing_attempt( + &self, + request: StockClaimRequest, + proof: &AttachmentProof, + ) -> Result<StockClaimOutcome, OperationError> { + self.worker + .claim_stock_signing_attempt( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } + pub async fn stock_signing_attempt( + &self, + request: StockClaimRequest, + proof: &AttachmentProof, + ) -> Result<Option<StockSigningAttempt>, OperationError> { + self.worker + .stock_signing_attempt( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs @@ -0,0 +1,154 @@ +use super::*; +pub(in crate::workspace::stock) struct Retained { + pub frame: ledger::Retained, + pub report: StockSigningAttempt, + projection: Projection, +} +pub(super) fn head(header: &ledger::Header, body: &[u8]) -> radroots_domain::CheckpointDigest { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.signing_claim_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(|value| *value.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(header.operation.as_bytes()); + hash.update(header.digest.as_bytes()); + hash.update(header.transaction.as_bytes()); + hash.update(header.revision.get().to_be_bytes()); + hash.update([u8::from(header.previous.is_some())]); + hash.update( + header + .previous + .map(|value| *value.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(Sha256::digest(body)); + radroots_domain::CheckpointDigest::from_bytes(hash.finalize().into()) +} +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); + }; + if frame.header.family != ledger::Family::SigningClaim || frame.body.len() > 16 * 1024 { + return Err(OperationError::RecoveryRequired); + } + 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 selected = intent(&plan.bound, body.recipient, CancellationSignal::new())?; + let header = &frame.header; + if body.version != 1 + || header.related_operation != Some(body.operation) + || header.digest != plan.bound.plan().command_digest() + || body.operation != plan.bound.plan().operation_id() + || header.actor != plan.frame.header.actor + || header.order != plan.frame.header.order + || header.revision <= plan.frame.header.revision + || body.plan_transaction != plan.frame.header.transaction + || body.plan_head != plan.frame.header.head + || body.plan_digest != *plan.bound.plan().digest() + || body.intent != *selected.binding().digest() + || body.deadline != plan.bound.preparation().first_issue_deadline() + || body.claimed_at < plan.bound.bound_at() + || body.claimed_at >= body.deadline + || head(header, &frame.body) != header.head + { + return Err(OperationError::RecoveryRequired); + } + let projection = Projection { + operation: body.operation, + recipient: body.recipient, + evidence: None, + }; + let report = StockSigningAttempt { + bound: Arc::new(plan.bound), + recipient: body.recipient, + entry: EntryIdentity { + operation: header.operation, + revision: header.revision, + head: header.head, + protected_digest: Sha256::digest(&frame.protected).into(), + }, + transaction: header.transaction, + claimed_at: body.claimed_at, + binding: selected.binding(), + }; + let retained = Retained { + frame, + report, + projection, + }; + retained.confirm(connection).await?; + Ok(Some(retained)) +} +impl Retained { + pub(in crate::workspace::stock) fn identity(&self) -> EntryIdentity { + self.report.entry + } + pub(in crate::workspace::stock) 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 { + header: self.frame.header, + protected: self.frame.protected, + parts_witness: self.frame.parts_witness, + pools: vec![], + mapping: None, + movements: vec![], + signing: Some(self.projection), + } + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence.rs @@ -0,0 +1,555 @@ +//! Append-only obtained bytes. Capture never obtains fresh business permission. +use super::super::inventory::{Turn, checkpoint}; +use super::*; +use radroots_signing::{ + issuance::{OutcomeKind, SigningOutcome}, + request::CancellationSignal, +}; +use std::num::NonZeroU64; +use zeroize::Zeroizing; +mod codec; +pub(in crate::workspace::stock) use codec::read_entry; +const MAX_RAW: usize = 64 * 1024; + +/// Independently checked obtained bytes. A store error leaves the caller's +/// original borrowed value intact. This supplies no installation or retry right. +pub struct StockEvidenceCapture { + anchor: CommitAttempt, + binding: WorkspaceBinding, + claim: OperationId, + intent: [u8; 32], + raw: Zeroizing<String>, + observed: Option<NonZeroU64>, +} +impl StockEvidenceCapture { + pub fn verify( + binding: WorkspaceBinding, + attempt: &StockSigningAttempt, + raw: &str, + observed: Option<NonZeroU64>, + ) -> Result<Self, OperationError> { + if raw.len() > MAX_RAW { + return Err(WorkspaceError::Capacity.into()); + } + if binding.input().workspace_id() != attempt.attempt().workspace_id() + || binding.actor().participant() != attempt.bound_plan().preparation().rumor().author() + { + return Err(OperationError::InvalidEvidence); + } + let selected = claim::intent( + attempt.bound_plan(), + attempt.recipient(), + CancellationSignal::new(), + )?; + if selected.binding() != attempt.binding() { + return Err(OperationError::InvalidEvidence); + } + let (_, kind) = SigningOutcome::capture(&selected, raw.into(), observed).into_parts(); + let OutcomeKind::Obtained(signed) = kind else { + return Err(OperationError::InvalidEvidence); + }; + Ok(Self { + anchor: CommitAttempt::new( + attempt.attempt().workspace_id(), + attempt.attempt().operation_id(), + attempt.attempt().command_digest(), + None, + ), + binding, + claim: OperationId::from_bytes(*attempt.attempt_id().as_bytes()), + intent: *attempt.binding().digest(), + raw: Zeroizing::new(raw.into()), + observed: signed.observed_at_unix_ms(), + }) + } + pub fn with_json<T>(&self, use_json: impl FnOnce(&str) -> T) -> T { + use_json(&self.raw) + } + pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { + self.observed + } + pub(in crate::workspace) const fn attempt(&self) -> CommitAttempt { + self.anchor + } + pub(in crate::workspace) fn retained_copy(&self) -> Self { + Self { + anchor: self.anchor, + binding: self.binding.clone(), + claim: self.claim, + intent: self.intent, + raw: Zeroizing::new(self.raw.to_string()), + observed: self.observed, + } + } +} +impl std::fmt::Debug for StockEvidenceCapture { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockEvidenceCapture(<redacted>)") + } +} + +/// Confirmed append identity, independent of command installation or delivery. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct StockEvidenceReceipt { + attempt: CommitAttempt, + claim: SigningAttemptId, + recipient: PublicKey, + digest: [u8; 32], + observed: Option<NonZeroU64>, +} +impl StockEvidenceReceipt { + 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 digest(&self) -> &[u8; 32] { + &self.digest + } + pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { + self.observed + } +} +pub struct StockCapturedEvidence { + receipt: StockEvidenceReceipt, + raw: Zeroizing<String>, +} +impl StockCapturedEvidence { + pub const fn receipt(&self) -> StockEvidenceReceipt { + self.receipt + } + pub fn with_json<T>(&self, use_json: impl FnOnce(&str) -> T) -> T { + use_json(&self.raw) + } +} +impl std::fmt::Debug for StockCapturedEvidence { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockCapturedEvidence(<redacted>)") + } +} +#[derive(Debug)] +pub enum StockEvidenceOutcome { + Committed(StockEvidenceReceipt), + Unknown(CommitAttempt), +} + +/// At most 32 authenticated references in append order. The cursor discovers +/// retained bytes after process loss without reconstructing a signer output. +#[derive(Debug)] +pub struct StockEvidencePage { + receipts: Vec<StockEvidenceReceipt>, + next: Option<Sequence>, +} +impl StockEvidencePage { + pub fn receipts(&self) -> &[StockEvidenceReceipt] { + &self.receipts + } + pub const fn next(&self) -> Option<Sequence> { + self.next + } +} + +pub(in crate::workspace) async fn page( + turn: &mut Turn<'_>, + request: StockClaimRequest, + after: Option<Sequence>, + proof: AttachmentProof, +) -> Result<StockEvidencePage, OperationError> { + let auth = super::super::signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + ) + .await?; + if auth.access.authority.catalog != 11 { + return Err(OperationError::UnsupportedOperation); + } + let minimum = InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, + None, + )?; + let witness = checkpoint::authenticate_minimum( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + minimum, + ) + .await?; + let rows=sqlx::query("SELECT CASE WHEN length(e.evidence_digest)=32 THEN e.evidence_digest END,CASE WHEN length(e.entry_id)=32 THEN e.entry_id END,o.revision FROM stock_signing_evidence e JOIN stock_operations o ON o.actor=e.actor AND o.operation_id=e.entry_id WHERE e.actor=? AND e.operation_id=? AND e.recipient=? AND (? IS NULL OR o.revision>?) ORDER BY o.revision LIMIT 33") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation.as_bytes().as_slice()).bind(request.recipient.as_bytes().as_slice()).bind(after.map(|v|v.get() as i64)).bind(after.map(|v|v.get() as i64)).fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let more = rows.len() > 32; + let mut last = None; + let mut receipts = Vec::with_capacity(rows.len().min(32)); + for row in rows.into_iter().take(32) { + let digest: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(0) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let entry: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(1) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let retained = read_entry( + turn.connection, + turn.selected, + turn.crypto, + OperationId::from_bytes( + entry + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + ) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let revision: i64 = row + .try_get(2) + .map_err(|_| OperationError::RecoveryRequired)?; + if revision <= 0 || retained.frame.header.revision.get() != revision as u64 { + return Err(OperationError::RecoveryRequired); + } + last = Some(retained.frame.header.revision); + let value = retained.value.receipt; + if value.digest.as_slice() != digest + || value.attempt.operation_id() != request.operation + || value.recipient != request.recipient + { + return Err(OperationError::RecoveryRequired); + } + receipts.push(value); + } + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + witness.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?; + let next = if more { + Some(last.ok_or(OperationError::RecoveryRequired)?) + } else { + None + }; + Ok(StockEvidencePage { receipts, next }) +} + +pub(in crate::workspace) async fn capture( + turn: &mut Turn<'_>, + supplied: StockEvidenceCapture, + proof: AttachmentProof, +) -> Result<StockEvidenceOutcome, OperationError> { + if *turn.uncertain { + return Err(OperationError::RecoveryRequired); + } + turn.namespace.validate()?; + let input = supplied.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 != 11 { + return Err(OperationError::UnsupportedOperation); + } + record.authenticate_retained_capture(input, &proof)?; + let original = claim::read_entry(turn.connection, turn.selected, turn.crypto, supplied.claim) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if original.frame.header.actor != supplied.binding.actor() + || original.report.binding().digest() != &supplied.intent + { + return Err(OperationError::InvalidEvidence); + } + // Verify again against the actual protected claim, never a caller descriptor. + let checked = StockEvidenceCapture::verify( + supplied.binding.clone(), + &original.report, + &supplied.raw, + supplied.observed, + )?; + let digest: [u8; 32] = Sha256::digest(checked.raw.as_bytes()).into(); + let before = authority + .inventory + .ok_or(OperationError::RecoveryRequired)?; + let minimum = InventoryCheckpointRef::from_host_metadata( + input.authority(), + Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, + None, + )?; + let witness = checkpoint::authenticate_minimum( + turn.connection, + turn.selected, + turn.crypto, + &supplied.binding, + &authority, + minimum, + ) + .await?; + let existing = lookup( + turn.connection, + turn.selected, + turn.crypto, + original.report.bound_plan().plan().operation_id(), + original.report.recipient(), + digest, + ) + .await?; + let (frame, updated_root, receipt) = if let Some(retained) = &existing { + if retained.value.raw.as_str() != checked.raw.as_str() + || retained.value.receipt.claim != original.report.attempt_id() + { + return Err(OperationError::RecoveryRequired); + } + (None, None, retained.value.receipt) + } 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 = Zeroizing::new(codec::encode(&original, &checked)); + let mut header = ledger::Header { + version: 5, + family: ledger::Family::SigningEvidence, + namespace: SellerAuthoritySelection::from_attachment(turn.selected), + actor: original.frame.header.actor, + operation: entry, + digest: original.frame.header.digest, + transaction, + revision, + previous: before.head, + head: radroots_domain::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 = codec::head(&header, &body); + let mut next = authority.clone(); + next.inventory = Some(InventoryCheckpoint { + revision, + head: Some(header.head), + ..before + }); + let frame = ledger::prepare(turn.crypto, turn.selected, header, &body).await?; + let updated = turn + .crypto + .seal_stock_root(turn.selected, next.catalog, &next.encode()?) + .await?; + let receipt = StockEvidenceReceipt { + attempt: CommitAttempt::new( + input.workspace_id(), + original.report.bound_plan().plan().operation_id(), + original.frame.header.digest, + Some(transaction), + ), + claim: original.report.attempt_id(), + recipient: original.report.recipient(), + digest, + observed: checked.observed, + }; + (Some(frame), Some(updated), receipt) + }; + 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(existing)=&existing {existing.confirm(&mut tx).await?;} + if let Some(frame)=&frame { + frame.insert_record(&mut tx).await?; + sqlx::query("INSERT INTO stock_signing_evidence(actor,operation_id,recipient,evidence_digest,entry_id) VALUES(?,?,?,?,?)").bind(input.participant().as_bytes().as_slice()).bind(receipt.attempt.operation_id().as_bytes().as_slice()).bind(receipt.recipient.as_bytes().as_slice()).bind(digest.as_slice()).bind(frame.header.operation.as_bytes().as_slice()).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + let result=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 result.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(StockEvidenceOutcome::Unknown(receipt.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(StockEvidenceOutcome::Unknown(receipt.attempt)); + } + Ok(StockEvidenceOutcome::Committed(receipt)) +} + +async fn lookup( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + operation: OperationId, + recipient: PublicKey, + digest: [u8; 32], +) -> Result<Option<codec::Retained>, OperationError> { + let id:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_signing_evidence WHERE actor=? AND operation_id=? AND recipient=? AND evidence_digest=?").bind(input.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).bind(digest.as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + match id { + None => Ok(None), + Some(id) => Ok(Some( + read_entry( + connection, + input, + crypto, + OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + ) + .await? + .ok_or(OperationError::RecoveryRequired)?, + )), + } +} + +pub(in crate::workspace) async fn read( + turn: &mut Turn<'_>, + request: StockClaimRequest, + digest: [u8; 32], + proof: AttachmentProof, +) -> Result<Option<StockCapturedEvidence>, OperationError> { + let auth = super::super::signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + ) + .await?; + if auth.access.authority.catalog != 11 { + return Err(OperationError::UnsupportedOperation); + } + let claim = claim::existing(turn, &auth, request.operation, request.recipient).await?; + let retained = lookup( + turn.connection, + turn.selected, + turn.crypto, + request.operation, + request.recipient, + digest, + ) + .await?; + if retained.is_some() && claim.0.is_none() { + return Err(OperationError::RecoveryRequired); + } + // Full protected ancestry proves natural evidence presence/absence. + let minimum = InventoryCheckpointRef::from_host_metadata( + turn.selected.authority(), + Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, + None, + )?; + let witness = checkpoint::authenticate_minimum( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + minimum, + ) + .await?; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let checked: Result<(), OperationError> = async { + witness.confirm(&mut tx).await?; + claim.1.confirm(&mut tx).await?; + auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) + .await?; + if let Some(value) = &retained { + value.confirm(&mut tx).await?; + } + Ok(()) + } + .await; + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Err(OperationError::RecoveryRequired); + } + checked?; + Ok(retained.map(|value| value.value)) +} +impl NativeWorkspace { + pub async fn stock_signing_evidence_page( + &self, + request: StockClaimRequest, + after: Option<Sequence>, + proof: &AttachmentProof, + ) -> Result<StockEvidencePage, OperationError> { + self.worker + .stock_signing_evidence_page( + request, + after, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } + pub async fn capture_stock_signing_evidence( + &self, + evidence: &StockEvidenceCapture, + proof: &AttachmentProof, + ) -> Result<StockEvidenceOutcome, OperationError> { + self.worker + .capture_stock_signing_evidence( + evidence.retained_copy(), + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } + pub async fn stock_signing_evidence( + &self, + request: StockClaimRequest, + digest: [u8; 32], + proof: &AttachmentProof, + ) -> Result<Option<StockCapturedEvidence>, OperationError> { + self.worker + .stock_signing_evidence( + request, + digest, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs @@ -0,0 +1,212 @@ +//! Fixed prefix followed by original exact JSON, without escape inflation. +use super::*; +const PREFIX: usize = 117; +const MAGIC: &[u8; 8] = b"RDSTKS1\0"; +pub(super) fn encode( + original: &claim::codec::Retained, + supplied: &StockEvidenceCapture, +) -> Vec<u8> { + let mut out = Vec::with_capacity(PREFIX + supplied.raw.len()); + out.extend_from_slice(MAGIC); + out.extend_from_slice(original.frame.header.operation.as_bytes()); + out.extend_from_slice(original.frame.header.transaction.as_bytes()); + out.extend_from_slice(original.frame.header.head.as_bytes()); + out.push(u8::from(supplied.observed.is_some())); + out.extend_from_slice( + &supplied + .observed + .map(NonZeroU64::get) + .unwrap_or(0) + .to_be_bytes(), + ); + out.extend_from_slice(&(supplied.raw.len() as u32).to_be_bytes()); + out.extend_from_slice(supplied.raw.as_bytes()); + out +} +pub(super) fn head(header: &ledger::Header, body: &[u8]) -> radroots_domain::CheckpointDigest { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.signing_evidence_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(|value| *value.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(header.operation.as_bytes()); + hash.update(header.digest.as_bytes()); + hash.update(header.transaction.as_bytes()); + hash.update(header.revision.get().to_be_bytes()); + hash.update([u8::from(header.previous.is_some())]); + hash.update( + header + .previous + .map(|value| *value.as_bytes()) + .unwrap_or([0; 32]), + ); + hash.update(Sha256::digest(body)); + radroots_domain::CheckpointDigest::from_bytes(hash.finalize().into()) +} +pub(in crate::workspace::stock) struct Retained { + pub frame: ledger::Retained, + pub value: StockCapturedEvidence, + projection: Projection, +} +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 body = frame.body.as_slice(); + if frame.header.family != ledger::Family::SigningEvidence + || !(PREFIX..=PREFIX + MAX_RAW).contains(&body.len()) + || &body[..8] != MAGIC + { + return Err(OperationError::RecoveryRequired); + } + let array = |start, end| { + body[start..end] + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let claim = OperationId::from_bytes(array(8, 40)?); + let transaction = TransactionId::from_bytes(array(40, 72)?); + let original_head = radroots_domain::CheckpointDigest::from_bytes(array(72, 104)?); + let at = u64::from_be_bytes( + body[105..113] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let observed = match (body[104], at) { + (0, 0) => None, + (1, n) if n > 0 => NonZeroU64::new(n), + _ => return Err(OperationError::RecoveryRequired), + }; + let length = u32::from_be_bytes( + body[113..PREFIX] + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ) as usize; + if length != body.len() - PREFIX { + 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) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let header = &frame.header; + if original.frame.header.transaction != transaction + || original.frame.header.head != original_head + || header.actor != original.frame.header.actor + || header.related_operation != original.frame.header.related_operation + || header.order != original.frame.header.order + || header.digest != original.frame.header.digest + || header.revision <= original.frame.header.revision + || head(header, body) != header.head + { + return Err(OperationError::RecoveryRequired); + } + let selected = claim::intent( + original.report.bound_plan(), + original.report.recipient(), + CancellationSignal::new(), + )?; + let (_, kind) = SigningOutcome::capture(&selected, raw.into(), observed).into_parts(); + let OutcomeKind::Obtained(signed) = kind else { + return Err(OperationError::RecoveryRequired); + }; + if signed.observed_at_unix_ms() != observed { + return Err(OperationError::RecoveryRequired); + } + let digest = Sha256::digest(raw.as_bytes()).into(); + let projection = Projection { + operation: original.report.bound_plan().plan().operation_id(), + recipient: original.report.recipient(), + evidence: Some(digest), + }; + let receipt = StockEvidenceReceipt { + attempt: CommitAttempt::new( + input.workspace_id(), + projection.operation, + header.digest, + Some(header.transaction), + ), + claim: original.report.attempt_id(), + recipient: projection.recipient, + digest, + observed, + }; + let value = StockCapturedEvidence { + receipt, + raw: Zeroizing::new(raw.into()), + }; + let retained = Retained { + frame, + value, + projection, + }; + retained.confirm(connection).await?; + Ok(Some(retained)) +} +impl Retained { + pub(in crate::workspace::stock) 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 { + header: self.frame.header, + protected: self.frame.protected, + parts_witness: self.frame.parts_witness, + pools: vec![], + mapping: None, + movements: vec![], + signing: Some(self.projection), + } + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/projection.rs b/crates/storage_sqlite/src/workspace/stock/issuance/projection.rs @@ -0,0 +1,70 @@ +use super::*; +/// Immutable body-derived selector, independently compared with its SQL index. +#[derive(Clone, Copy)] +pub(in crate::workspace::stock) struct Projection { + pub operation: OperationId, + pub recipient: PublicKey, + pub evidence: Option<[u8; 32]>, +} +impl Projection { + pub fn digest(self, actor: PublicKey, entry: OperationId) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.issuance_projection.v1\0"); + hash.update(actor.as_bytes()); + 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); + } + hash.finalize().into() + } + pub async fn confirm( + self, + connection: &mut SqliteConnection, + actor: PublicKey, + entry: OperationId, + ) -> Result<(), OperationError> { + let actual = raw_projection( + connection, + actor.as_bytes(), + entry.as_bytes(), + if self.evidence.is_some() { 5 } else { 4 }, + ) + .await?; + if actual != self.digest(actor, entry) { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} +pub(in crate::workspace::stock) async fn raw_projection( + connection: &mut SqliteConnection, + actor: &[u8; 32], + entry: &[u8; 32], + family: i64, +) -> Result<[u8; 32], OperationError> { + let 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, + _ => return Err(OperationError::RecoveryRequired), + }.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let field = |index| { + row.try_get::<Option<Vec<u8>>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let projection = 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 }, + }; + Ok(projection.digest( + PublicKey::from_bytes(*actor).map_err(|_| OperationError::RecoveryRequired)?, + OperationId::from_bytes(*entry), + )) +} diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -19,6 +19,8 @@ pub(super) enum Family { Consent, Acceptance, SigningPlan, + SigningClaim, + SigningEvidence, } #[derive(Serialize, Deserialize)] @@ -65,8 +67,13 @@ impl Header { || (self.revision.get() == 1) != self.previous.is_none() || (self.family == Family::Inventory) != self.pool.is_some() || (self.family == Family::Inventory) != self.order.is_none() - || matches!(self.family, Family::Consent | Family::SigningPlan) - != self.related_operation.is_some() + || matches!( + self.family, + Family::Consent + | Family::SigningPlan + | Family::SigningClaim + | Family::SigningEvidence + ) != self.related_operation.is_some() || (self.family == Family::Consent) != self.subject_grant.is_some() || self.bytes == 0 || self.bytes as usize > BODY_MAX_BYTES @@ -81,6 +88,7 @@ impl Header { pub(super) struct Prepared { pub protected: Vec<u8>, parts: Vec<Vec<u8>>, + pub(super) header: Header, } pub(super) struct Retained { pub header: Header, @@ -142,9 +150,22 @@ pub(super) async fn prepare( let protected = crypto .seal_stock_record_for_catalog(input, "operation", header.operation.as_bytes(), 7, &clear) .await?; - Ok(Prepared { protected, parts }) + Ok(Prepared { + protected, + parts, + header, + }) } impl Prepared { + pub async fn insert_record( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + let h = &self.header; + sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)") + .bind(h.actor.participant().as_bytes().as_slice()).bind(h.actor.grant_id().ok_or(OperationError::RecoveryRequired)?.as_bytes().as_slice()).bind(h.operation.as_bytes().as_slice()).bind(h.digest.as_bytes().as_slice()).bind(h.transaction.as_bytes().as_slice()).bind(h.pool.map(|v|v.as_bytes().to_vec())).bind(h.revision.get() as i64).bind(h.head.as_bytes().as_slice()).bind(&self.protected).bind(h.family.code()).bind(h.order.map(|v|v.as_bytes().to_vec())).bind(h.related_operation.map(|v|v.as_bytes().to_vec())).bind(h.subject_grant.map(|v|v.as_bytes().to_vec())).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + self.insert_parts(connection, h.actor, h.operation).await + } /// Called only within the existing owner's SQL transaction. Protection and /// provider callbacks have already completed before entering this method. pub async fn insert_parts( @@ -302,6 +323,8 @@ impl Family { Self::Consent => 1, Self::Acceptance => 2, Self::SigningPlan => 3, + Self::SigningClaim => 4, + Self::SigningEvidence => 5, } } } @@ -415,6 +438,7 @@ pub(super) struct HistoryEntry { pub pools: Vec<radroots_domain::stock::PoolSnapshot>, pub mapping: Option<radroots_domain::stock::OptionPoolMapping>, pub movements: Vec<MovementWitness>, + pub signing: Option<super::issuance::Projection>, } pub(super) async fn history( connection: &mut SqliteConnection, @@ -450,6 +474,7 @@ pub(super) async fn history( _ => return Err(OperationError::RecoveryRequired), }; Ok(Some(HistoryEntry { + signing: None, header, protected: retained.protected, parts_witness, @@ -480,6 +505,7 @@ pub(super) async fn history( return Err(OperationError::RecoveryRequired); } Ok(Some(HistoryEntry { + signing: None, header: retained.frame.header, protected: retained.frame.protected, parts_witness: retained.frame.parts_witness, @@ -488,19 +514,35 @@ pub(super) async fn history( movements: vec![], })) } - Some(2) if matches!(authority.catalog, 9 | 10) => Ok(Some( + Some(2) if matches!(authority.catalog, 9..=11) => Ok(Some( super::inventory::acceptance::codec::read(connection, input, crypto, operation) .await? .ok_or(OperationError::RecoveryRequired)? .into_history(), )), Some(2) => Err(OperationError::UnsupportedOperation), - Some(3) if authority.catalog == 10 => { + Some(3) if matches!(authority.catalog, 10 | 11) => { let retained = super::signing_plan::read_entry(connection, input, crypto, operation) .await? .ok_or(OperationError::RecoveryRequired)?; Ok(Some(retained.into_history())) } + Some(4) if authority.catalog == 11 => Ok(Some( + Box::pin(super::issuance::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )), + Some(5) if authority.catalog == 11 => Ok(Some( + Box::pin(super::issuance::evidence::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )), Some(_) => Err(OperationError::RecoveryRequired), } } @@ -551,6 +593,16 @@ impl HistoryEntry { )?; hash.update([header.parts]); hash.update(self.parts_witness); + 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) => { + return Err(OperationError::RecoveryRequired); + } + (_, Some(_)) => return Err(OperationError::RecoveryRequired), + (_, None) => {} + } if self.movements.len() > 64 || self .movements 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 @@ -413,7 +413,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.v10", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -467,7 +467,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.v10", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), @@ -504,7 +504,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.v10", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 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 @@ -0,0 +1,521 @@ +//! Actual claim transactions; only a newly confirmed claim returns a permit. +use super::*; +#[path = "evidence_tests.rs"] +mod evidence; +use crate::workspace::{StockClaimOutcome, StockClaimRequest, StockSigningAttempt}; +use radroots_signing::issuance::OutcomeKind; + +async fn selector( + r: &Rig, + receipt: &StockAcceptanceReceipt, + recipient: PublicKey, +) -> StockClaimRequest { + StockClaimRequest::new( + r.binding.clone(), + inventory_minimum(r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + recipient, + ) +} +async fn claim( + r: &Rig, + receipt: &StockAcceptanceReceipt, + recipient: PublicKey, +) -> Result<StockClaimOutcome, OperationError> { + r.store + .claim_stock_signing_attempt(selector(r, receipt, recipient).await, r.enrollment.proof()) + .await +} +async fn read( + r: &Rig, + receipt: &StockAcceptanceReceipt, + recipient: PublicKey, +) -> Result<Option<StockSigningAttempt>, OperationError> { + r.store + .stock_signing_attempt(selector(r, receipt, recipient).await, r.enrollment.proof()) + .await +} +async fn ready(r: &Rig) -> StockAcceptanceReceipt { + let (_, receipt) = prepared(r).await; + bound(bind(r, &receipt, 42).await.unwrap()); + receipt +} + +#[tokio::test] +async fn fresh_claim_refuses_damaged_current_pool_backing() { + let r = Rig::new().await; + let receipt = ready(&r).await; + let mut raw = database(&r).await; + sqlx::raw_sql("UPDATE stock_pools SET protected=randomblob(length(protected))") + .execute(&mut raw) + .await + .unwrap(); + assert!( + claim(&r, &receipt, receipt.rumor().recipients()[0]) + .await + .is_err(), + "current backing must be authenticated before a new dispatch permit" + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn fresh_t1_and_claim_accept_legitimate_available_stock_changes_without_reallocating() { + let r = Rig::new().await; + let (_, receipt) = prepared(&r).await; + physical(&r,serde_json::json!({"type":"stock.adjust","context":context(&r,95),"input":{"pool_id":pool(80),"expected_version":"2","direction":"add","amount":"1","reason":"restock available backing"}})).await; + bound(bind(&r, &receipt, 42).await.unwrap()); + physical(&r,serde_json::json!({"type":"stock.adjust","context":context(&r,96),"input":{"pool_id":pool(81),"expected_version":"2","direction":"remove","amount":"1","reason":"remove available backing"}})).await; + assert!(matches!( + claim(&r, &receipt, receipt.rumor().recipients()[0]) + .await + .unwrap(), + StockClaimOutcome::Fresh(_) + )); + assert_pool(&r, 80, 10, 1, 3).await; + let value = r + .store + .pool( + r.binding.clone(), + inventory_minimum(&r).await, + pool(81), + r.enrollment + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap(), + ) + .await + .unwrap() + .unwrap(); + let snapshot = value.snapshot(); + let physical = snapshot.balances().physical(); + assert_eq!(snapshot.version().get(), 3); + assert_eq!(snapshot.balances().introduced().get(), 10); + assert_eq!( + ( + physical.available.get(), + physical.preparatory_hold.get(), + physical.removed.get() + ), + (7, 2, 1) + ); + r.store.close().await.unwrap(); +} +async fn reopen_plain(r: &mut Rig) { + r.store.close().await.unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); +} + +#[tokio::test] +async fn each_recipient_gets_one_confirmed_permit_and_original_reopen_never_redispatches() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let signer = LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { + Ok(150000) + }) + .unwrap(); + let mut originals = Vec::new(); + for recipient in receipt.rumor().recipients() { + assert!(read(&r, &receipt, *recipient).await.unwrap().is_none()); + let before = inventory_minimum(&r).await; + let StockClaimOutcome::Fresh(permit) = claim(&r, &receipt, *recipient).await.unwrap() + else { + panic!("new committed claim must return a permit"); + }; + assert_eq!(permit.report().recipient(), *recipient); + let (intent, report) = permit + .into_signing_intent(CancellationSignal::new()) + .unwrap(); + let actual = signer.sign_exact(intent).await; + assert_eq!(actual.binding(), report.binding()); + let (_, OutcomeKind::Obtained(artifact)) = actual.into_parts() else { + panic!("actual exact signer must obtain bytes"); + }; + artifact.with_json(|raw| assert!(raw.contains("\"sig\""))); + let after = inventory_minimum(&r).await; + assert_eq!(after.revision().get(), before.revision().get() + 1); + let StockClaimOutcome::Existing(again) = claim(&r, &receipt, *recipient).await.unwrap() + else { + panic!("existing claim must not return another permit"); + }; + assert_eq!(again.attempt_id(), report.attempt_id()); + assert_eq!(again.binding(), report.binding()); + assert_eq!(inventory_minimum(&r).await, after); + originals.push(report); + } + assert_ne!(originals[0].attempt_id(), originals[1].attempt_id()); + reopen_plain(&mut r).await; + r.clock.0.store(229, Ordering::SeqCst); + for report in originals { + let StockClaimOutcome::Existing(again) = + claim(&r, &receipt, report.recipient()).await.unwrap() + else { + panic!("reopen must not redispatch"); + }; + assert_eq!(again.attempt(), report.attempt()); + assert_eq!(again.binding(), report.binding()); + assert_eq!( + again.bound_plan().plan().protected_wire(), + report.bound_plan().plan().protected_wire() + ); + } + 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 claim_requires_original_t1_and_refuses_wrong_identity_digest_recipient_and_expiry() { + let r = Rig::new().await; + let (_, receipt) = prepared(&r).await; + let recipient = receipt.rumor().recipients()[0]; + assert_eq!( + claim(&r, &receipt, recipient).await.unwrap_err().code(), + "stale_state" + ); + bound(bind(&r, &receipt, 42).await.unwrap()); + let minimum = inventory_minimum(&r).await; + for (operation, digest, recipient, code) in [ + ( + OperationId::from_bytes([99; 32]), + receipt.attempt().command_digest(), + recipient, + "stale_state", + ), + ( + receipt.attempt().operation_id(), + radroots_domain::CommandDigest::from_bytes([99; 32]), + recipient, + "idempotency_conflict", + ), + ( + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + participant(), + "invalid_command", + ), + ] { + let request = + StockClaimRequest::new(r.binding.clone(), minimum, operation, digest, recipient); + assert_eq!( + r.store + .claim_stock_signing_attempt(request, r.enrollment.proof()) + .await + .unwrap_err() + .code(), + code + ); + } + r.clock.0.store(230, Ordering::SeqCst); + assert_eq!( + claim(&r, &receipt, recipient).await.unwrap_err().code(), + "deadline_exceeded" + ); + r.clock.0.store(150, Ordering::SeqCst); + assert!(read(&r, &receipt, recipient).await.unwrap().is_none()); + assert_eq!(inventory_minimum(&r).await, minimum); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn each_actual_claim_write_failure_rolls_back_without_dispatch_permission() { + for statement in [ + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations WHEN NEW.family=4 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_signing_claims 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 recipient = receipt.rumor().recipients()[0]; + let before = inventory_minimum(&r).await; + let mut raw = database(&r).await; + sqlx::raw_sql(statement).execute(&mut raw).await.unwrap(); + assert_eq!( + claim(&r, &receipt, recipient).await.unwrap_err().code(), + "storage_failure" + ); + assert_eq!(inventory_minimum(&r).await, before); + assert!(read(&r, &receipt, recipient).await.unwrap().is_none()); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut raw) + .await + .unwrap(); + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Fresh(_) + )); + assert_pool(&r, 80, 9, 1, 2).await; + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn unknown_claim_commit_fences_the_owner_and_requires_actual_reopen_reconciliation() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let before = inventory_minimum(&r).await; + let request = selector(&r, &receipt, recipient).await; + let mut raw = database(&r).await; + sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault AFTER INSERT ON stock_signing_claims BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut raw).await.unwrap(); + let StockClaimOutcome::Unknown(anchor) = r + .store + .claim_stock_signing_attempt(request, r.enrollment.proof()) + .await + .unwrap() + else { + panic!("uncertain COMMIT cannot authorize dispatch"); + }; + assert_eq!(anchor.operation_id(), receipt.attempt().operation_id()); + assert!(anchor.transaction_id().is_some()); + let request = StockClaimRequest::new( + r.binding.clone(), + before, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + recipient, + ); + assert_eq!( + r.store + .stock_signing_attempt(request, r.enrollment.proof()) + .await + .unwrap_err() + .code(), + "recovery_required" + ); + r.store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut raw) + .await + .unwrap(); + raw.close().await.unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + assert!(read(&r, &receipt, recipient).await.unwrap().is_none()); + assert_eq!(inventory_minimum(&r).await, before); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn lost_claim_observer_drains_and_reopens_as_existing_without_a_permit() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let request = selector(&r, &receipt, recipient).await; + let provider = reopen(&mut r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + let mut pending = Box::pin( + r.store + .claim_stock_signing_attempt(request, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + drop(pending); + assert!(matches!( + NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone() + ) + .await, + Err(WorkspaceError::WriterActive) + )); + provider.gate.release(); + reopen_plain(&mut r).await; + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn protected_claim_or_projection_damage_never_becomes_permission_to_reissue() { + for statement in [ + "DELETE FROM stock_signing_claims", + "UPDATE stock_signing_claims SET recipient=randomblob(32)", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=4", + "DELETE FROM stock_operation_parts WHERE operation_id IN (SELECT operation_id FROM stock_operations WHERE family=4)", + "PRAGMA foreign_keys=OFF; DELETE FROM stock_operation_parts WHERE operation_id IN (SELECT operation_id FROM stock_operations WHERE family=4); DELETE FROM stock_signing_claims; DELETE FROM stock_operations WHERE family=4", + ] { + let r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Fresh(_) + )); + let request = selector(&r, &receipt, recipient).await; + let mut raw = database(&r).await; + sqlx::raw_sql(statement).execute(&mut raw).await.unwrap(); + assert!( + r.store + .claim_stock_signing_attempt(request, r.enrollment.proof()) + .await + .is_err(), + "{statement}" + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn claim_rechecks_original_plan_projection_grant_root_and_clock_after_provider_io() { + for statement in [ + "UPDATE stock_pools SET protected=randomblob(length(protected))", + "UPDATE stock_grants SET protected=randomblob(length(protected))", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=3", + "UPDATE stock_authority SET protected=randomblob(length(protected))", + "clock_expired", + "clock_rollback", + ] { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let request = selector(&r, &receipt, recipient).await; + let provider = reopen(&mut r).await; + let mut raw = database(&r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + let mut pending = Box::pin( + r.store + .claim_stock_signing_attempt(request, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + match statement { + "clock_expired" => r.clock.0.store(230, Ordering::SeqCst), + "clock_rollback" => r.clock.0.store(149, Ordering::SeqCst), + _ => { + sqlx::raw_sql(statement).execute(&mut raw).await.unwrap(); + } + } + provider.gate.release(); + assert!(pending.await.is_err(), "{statement}"); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_operations WHERE family=4") + .fetch_one(&mut raw) + .await + .unwrap(), + 0 + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn replacement_recovery_only_can_read_original_claims_but_cannot_create_missing_claims() { + let r = Rig::new().await; + let (command, receipt) = prepared(&r).await; + bound(bind(&r, &receipt, 42).await.unwrap()); + let first = receipt.rumor().recipients()[0]; + let missing = receipt.rumor().recipients()[1]; + let StockClaimOutcome::Fresh(permit) = claim(&r, &receipt, first).await.unwrap() else { + panic!("original claim"); + }; + let original = permit.report().clone(); + drop(permit); + r.clock.0.store(250, Ordering::SeqCst); + let child = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(r.enrollment.input()), + "recovery operator".into(), + UnixSeconds::new(290).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + assert!(matches!( + r.store + .enroll_stock_grant( + r.binding.clone(), + inventory_minimum(&r).await, + r.enrollment.proof(), + &child + ) + .await + .unwrap(), + StockGrantOutcome::Committed(_) + )); + let binding = r + .store + .authenticate(child.input().clone(), child.proof()) + .await + .unwrap(); + let consent = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + child.input().grant_id(), + StockConsentMode::RecoverOnly, + StockResources::all_pools(), + UnixSeconds::new(280).unwrap(), + CapturedOrderAcceptance::parse(command.protected_wire()).unwrap(), + ) + .unwrap(); + assert!(matches!( + r.store + .issue_stock_consent( + r.binding.clone(), + inventory_minimum(&r).await, + &consent, + r.enrollment.proof() + ) + .await + .unwrap(), + StockConsentOutcome::Committed(_) + )); + for recipient in [first, missing] { + let request = StockClaimRequest::new( + binding.clone(), + inventory_minimum(&r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + recipient, + ); + if recipient == first { + let StockClaimOutcome::Existing(value) = r + .store + .claim_stock_signing_attempt(request, child.proof()) + .await + .unwrap() + else { + panic!("recovery cannot produce a permit"); + }; + assert_eq!(value.attempt_id(), original.attempt_id()); + assert_eq!(value.binding(), original.binding()); + } else { + assert_eq!( + r.store + .claim_stock_signing_attempt(request, child.proof()) + .await + .unwrap_err() + .code(), + "unauthorized" + ); + } + } + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} 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 @@ -0,0 +1,574 @@ +//! Obtained-byte capture executes on the same real native stock owner. +use super::*; +use crate::workspace::{StockEvidenceCapture, StockEvidenceOutcome, StockEvidenceReceipt}; +use sha2::{Digest, Sha256}; +async fn obtained( + r: &Rig, + receipt: &StockAcceptanceReceipt, + recipient: PublicKey, +) -> (StockSigningAttempt, String) { + let StockClaimOutcome::Fresh(permit) = claim(r, receipt, recipient).await.unwrap() else { + panic!("first claim"); + }; + let (intent, report) = permit + .into_signing_intent(CancellationSignal::new()) + .unwrap(); + let signer = LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { + Ok(150000) + }) + .unwrap(); + let (_, OutcomeKind::Obtained(signed)) = signer.sign_exact(intent).await.into_parts() else { + panic!("real signature"); + }; + (report, signed.with_json(str::to_owned)) +} +fn committed(value: StockEvidenceOutcome) -> StockEvidenceReceipt { + let StockEvidenceOutcome::Committed(value) = value else { + panic!("capture must confirm"); + }; + value +} +#[tokio::test] +async fn original_peer_self_bytes_are_captured_once_reopened_and_preserve_first_optional_time() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let mut values = Vec::new(); + for recipient in receipt.rumor().recipients() { + let (report, raw) = obtained(&r, &receipt, *recipient).await; + let evidence = + StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let before = inventory_minimum(&r).await; + let first = committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + ); + assert_eq!( + first.digest(), + &<[u8; 32]>::from(Sha256::digest(raw.as_bytes())) + ); + assert_eq!(first.signing_attempt_id(), report.attempt_id()); + assert_eq!(first.observed_at_unix_ms(), None); + assert_eq!( + inventory_minimum(&r).await.revision().get(), + before.revision().get() + 1 + ); + let later = + StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, NonZeroU64::new(150000)) + .unwrap(); + assert_eq!( + committed( + r.store + .capture_stock_signing_evidence(&later, r.enrollment.proof()) + .await + .unwrap() + ), + first + ); + values.push((report, raw, first)); + } + reopen_plain(&mut r).await; + for (report, raw, first) in values { + let stored = r + .store + .stock_signing_evidence( + selector(&r, &receipt, report.recipient()).await, + *first.digest(), + r.enrollment.proof(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.receipt(), first); + stored.with_json(|value| assert_eq!(value, raw)); + assert!(matches!( + claim(&r, &receipt, report.recipient()).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + } + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn already_obtained_bytes_survive_expiry_revocation_cancellation_and_missing_clock() { + for mode in ["expired", "clock_unavailable", "revoked", "damaged_pool"] { + let r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = + StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + match mode { + "damaged_pool" => { + let mut rawdb = database(&r).await; + sqlx::raw_sql("UPDATE stock_pools SET protected=randomblob(length(protected))") + .execute(&mut rawdb) + .await + .unwrap(); + rawdb.close().await.unwrap(); + } + "expired" => r.clock.0.store(350, Ordering::SeqCst), + "clock_unavailable" => r.clock.0.store(0, Ordering::SeqCst), + "revoked" => { + 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(); + } + _ => unreachable!(), + } + let first = committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + ); + assert_eq!(first.observed_at_unix_ms(), None); + evidence.with_json(|value| assert_eq!(value, raw)); + assert_eq!( + committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap() + ), + first + ); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn distinct_valid_original_encodings_append_without_replacing_the_first_evidence() { + let r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let mut receipts = Vec::new(); + for (text, at) in [ + (&raw, None), + (&format!("\n{raw}\n"), NonZeroU64::new(160000)), + ] { + let evidence = StockEvidenceCapture::verify(r.binding.clone(), &report, text, at).unwrap(); + let result = committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + ); + let retained = r + .store + .stock_signing_evidence( + selector(&r, &receipt, recipient).await, + *result.digest(), + r.enrollment.proof(), + ) + .await + .unwrap() + .unwrap(); + retained.with_json(|value| assert_eq!(value, text)); + assert_eq!(retained.receipt().observed_at_unix_ms(), at); + receipts.push(result); + } + assert_ne!(receipts[0].digest(), receipts[1].digest()); + assert_ne!( + receipts[0].attempt().transaction_id(), + receipts[1].attempt().transaction_id() + ); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn capture_refuses_wrong_recipient_bad_signature_and_wrong_original_credential() { + let r = Rig::new().await; + let receipt = ready(&r).await; + let (peer, raw) = obtained(&r, &receipt, receipt.rumor().recipients()[0]).await; + let (other, _) = obtained(&r, &receipt, receipt.rumor().recipients()[1]).await; + assert!(StockEvidenceCapture::verify(r.binding.clone(), &other, &raw, None).is_err()); + let mut altered: serde_json::Value = serde_json::from_str(&raw).unwrap(); + altered["sig"] = serde_json::json!("00".repeat(64)); + assert!( + StockEvidenceCapture::verify( + r.binding.clone(), + &peer, + &serde_json::to_string(&altered).unwrap(), + None + ) + .is_err() + ); + let evidence = StockEvidenceCapture::verify(r.binding.clone(), &peer, &raw, None).unwrap(); + let wrong = AttachmentProof::from_protected_input(&[99; 32]).unwrap(); + assert!( + r.store + .capture_stock_signing_evidence(&evidence, &wrong) + .await + .is_err() + ); + evidence.with_json(|value| assert_eq!(value, raw)); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_signing_evidence") + .fetch_one(&mut database(&r).await) + .await + .unwrap(), + 0 + ); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn every_capture_write_failure_preserves_caller_bytes_and_original_holds() { + for statement in [ + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations WHEN NEW.family=5 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_signing_evidence 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 recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = + StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let before = inventory_minimum(&r).await; + let mut rawdb = database(&r).await; + sqlx::raw_sql(statement).execute(&mut rawdb).await.unwrap(); + assert_eq!( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap_err() + .code(), + "storage_failure" + ); + evidence.with_json(|value| assert_eq!(value, raw)); + assert_eq!(inventory_minimum(&r).await, before); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut rawdb) + .await + .unwrap(); + committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + ); + assert!(matches!( + claim(&r, &receipt, recipient).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + assert_pool(&r, 80, 9, 1, 2).await; + rawdb.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn uncertain_capture_keeps_input_and_reopens_for_capture_without_another_signer_claim() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let before = inventory_minimum(&r).await; + let mut rawdb = database(&r).await; + sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault AFTER INSERT ON stock_signing_evidence BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut rawdb).await.unwrap(); + let StockEvidenceOutcome::Unknown(anchor) = r + .store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap() + else { + panic!("COMMIT must be unknown"); + }; + assert!(anchor.transaction_id().is_some()); + evidence.with_json(|value| assert_eq!(value, raw)); + assert_eq!( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap_err() + .code(), + "recovery_required" + ); + r.store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER fault; DROP TABLE deferred_fault") + .execute(&mut rawdb) + .await + .unwrap(); + rawdb.close().await.unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + assert_eq!(inventory_minimum(&r).await, before); + committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + ); + let StockClaimOutcome::Existing(again) = claim(&r, &receipt, recipient).await.unwrap() else { + panic!("capture reconciliation cannot reissue"); + }; + assert_eq!(again.attempt_id(), report.attempt_id()); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn lost_capture_observer_drains_owned_input_and_reopens_the_exact_original_bytes() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let provider = reopen(&mut r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + let mut pending = Box::pin( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + drop(pending); + evidence.with_json(|value| assert_eq!(value, raw)); + provider.gate.release(); + reopen_plain(&mut r).await; + let digest: [u8; 32] = Sha256::digest(raw.as_bytes()).into(); + let retained = r + .store + .stock_signing_evidence( + selector(&r, &receipt, recipient).await, + digest, + r.enrollment.proof(), + ) + .await + .unwrap() + .unwrap(); + retained.with_json(|value| assert_eq!(value, raw)); + assert_pool(&r, 80, 9, 1, 2).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn evidence_projection_or_protected_byte_damage_refuses_read_and_replacement() { + for statement in [ + "DELETE FROM stock_signing_evidence", + "UPDATE stock_signing_evidence SET evidence_digest=randomblob(32)", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=5", + "DELETE FROM stock_operation_parts WHERE operation_id IN (SELECT operation_id FROM stock_operations WHERE family=5)", + ] { + let r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = + StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let first = committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + ); + let request = selector(&r, &receipt, recipient).await; + let mut rawdb = database(&r).await; + sqlx::raw_sql(statement).execute(&mut rawdb).await.unwrap(); + assert!( + r.store + .stock_signing_evidence(request, *first.digest(), r.enrollment.proof()) + .await + .is_err(), + "{statement}" + ); + assert!( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .is_err(), + "{statement}" + ); + evidence.with_json(|value| assert_eq!(value, raw)); + rawdb.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn capture_rechecks_original_claim_plan_root_and_grant_after_provider_io() { + for statement in [ + "UPDATE stock_grants SET protected=randomblob(length(protected))", + "UPDATE stock_signing_claims SET recipient=randomblob(32)", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=3", + "UPDATE stock_authority SET protected=randomblob(length(protected))", + ] { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let evidence = + StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + let provider = reopen(&mut r).await; + let mut rawdb = database(&r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + let mut pending = Box::pin( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + sqlx::raw_sql(statement).execute(&mut rawdb).await.unwrap(); + provider.gate.release(); + assert!(pending.await.is_err(), "{statement}"); + evidence.with_json(|value| assert_eq!(value, raw)); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_operations WHERE family=5") + .fetch_one(&mut rawdb) + .await + .unwrap(), + 0 + ); + rawdb.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn bounded_evidence_pages_recover_all_original_outputs_by_operation_after_reopen() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let recipient = receipt.rumor().recipients()[0]; + let (report, raw) = obtained(&r, &receipt, recipient).await; + let empty = r + .store + .stock_signing_evidence_page( + selector(&r, &receipt, recipient).await, + None, + r.enrollment.proof(), + ) + .await + .unwrap(); + assert!(empty.receipts().is_empty()); + assert_eq!(empty.next(), None); + let base_revision = inventory_minimum(&r).await.revision().get(); + let mut expected = Vec::new(); + for count in 0..33 { + let text = format!("{}{raw}", " ".repeat(count)); + let evidence = + StockEvidenceCapture::verify(r.binding.clone(), &report, &text, None).unwrap(); + expected.push(committed( + r.store + .capture_stock_signing_evidence(&evidence, r.enrollment.proof()) + .await + .unwrap(), + )); + } + drop(raw); + drop(report); + reopen_plain(&mut r).await; + let first = r + .store + .stock_signing_evidence_page( + selector(&r, &receipt, recipient).await, + None, + r.enrollment.proof(), + ) + .await + .unwrap(); + assert_eq!(first.receipts(), &expected[..32]); + assert_eq!( + first.next(), + Some(radroots_domain::Sequence::new(base_revision + 32).unwrap()) + ); + let recovered = r + .store + .stock_signing_evidence( + selector(&r, &receipt, recipient).await, + *expected[0].digest(), + r.enrollment.proof(), + ) + .await + .unwrap() + .unwrap(); + let report = read(&r, &receipt, recipient).await.unwrap().unwrap(); + let mut digests: Vec<_> = expected.iter().map(|value| *value.digest()).collect(); + digests.sort(); + let text = (33..4096) + .map(|count| recovered.with_json(|raw| format!("{}{raw}", " ".repeat(count)))) + .find(|text| <[u8; 32]>::from(Sha256::digest(text.as_bytes())) < digests[31]) + .unwrap(); + let late = StockEvidenceCapture::verify(r.binding.clone(), &report, &text, None).unwrap(); + expected.push(committed( + r.store + .capture_stock_signing_evidence(&late, r.enrollment.proof()) + .await + .unwrap(), + )); + let last = r + .store + .stock_signing_evidence_page( + selector(&r, &receipt, recipient).await, + first.next(), + r.enrollment.proof(), + ) + .await + .unwrap(); + assert_eq!(last.receipts(), &expected[32..]); + assert_eq!(last.next(), None); + for value in first.receipts().iter().chain(last.receipts()) { + let retained = r + .store + .stock_signing_evidence( + selector(&r, &receipt, recipient).await, + *value.digest(), + r.enrollment.proof(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(retained.receipt(), *value); + } + let missing = r + .store + .stock_signing_evidence_page( + selector(&r, &receipt, receipt.rumor().recipients()[1]).await, + None, + r.enrollment.proof(), + ) + .await + .unwrap(); + assert!(missing.receipts().is_empty()); + let mut rawdb = database(&r).await; + sqlx::raw_sql("DELETE FROM stock_signing_evidence WHERE evidence_digest=(SELECT min(evidence_digest) FROM stock_signing_evidence)").execute(&mut rawdb).await.unwrap(); + let request = StockClaimRequest::new( + r.binding.clone(), + receipt.checkpoint(), + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + recipient, + ); + assert!( + r.store + .stock_signing_evidence_page(request, None, r.enrollment.proof()) + .await + .is_err() + ); + rawdb.close().await.unwrap(); + r.store.close().await.unwrap(); +} 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 @@ -1,6 +1,8 @@ //! Actual T1 retention, error windows and original recovery. No stock release //! or firm agreement is inferred from a bound signing plan. use super::*; +#[path = "claim_tests.rs"] +mod claims; use crate::workspace::{StockBoundSigningPlan, StockSigningPlanOutcome, StockSigningPlanRequest}; use radroots_nostr::commerce::VerifiedCommerceSigningPlan; use radroots_protocol::{ @@ -132,6 +134,23 @@ async fn prepared(r: &Rig) -> (CapturedOrderAcceptance, StockAcceptanceReceipt) let receipt = prepare(r, &command).await.unwrap(); (command, receipt) } + +#[tokio::test] +async fn fresh_t1_refuses_damaged_current_pool_backing() { + let r = Rig::new().await; + let (_, receipt) = prepared(&r).await; + let mut raw = database(&r).await; + sqlx::raw_sql("UPDATE stock_pools SET protected=randomblob(length(protected))") + .execute(&mut raw) + .await + .unwrap(); + assert!( + bind(&r, &receipt, 42).await.is_err(), + "current backing must be authenticated before new intent binding" + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); +} #[tokio::test] async fn actual_t1_binds_complete_original_peer_self_plan_and_reopens_without_another_hold_or_signer() { @@ -327,7 +346,7 @@ async fn dropped_t1_observer_keeps_owned_work_and_close_drains_before_original_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v10", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), @@ -362,6 +381,7 @@ async fn dropped_t1_observer_keeps_owned_work_and_close_drains_before_original_r #[tokio::test] async fn t1_final_permission_order_root_and_clock_witnesses_refuse_changes_after_provider_io() { for statement in [ + "UPDATE stock_pools SET protected=randomblob(length(protected))", "UPDATE stock_grants SET protected=randomblob(length(protected))", "UPDATE stock_orders SET protected=randomblob(length(protected))", "UPDATE stock_authority SET protected=randomblob(length(protected))", @@ -380,7 +400,7 @@ async fn t1_final_permission_order_root_and_clock_witnesses_refuse_changes_after let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v10", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 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.v10", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 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.v10", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 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..=10) || authority.public_sources.is_none() { + if !matches!(authority.catalog, 8..=11) || authority.public_sources.is_none() { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; diff --git a/crates/storage_sqlite/src/workspace/stock/schema.rs b/crates/storage_sqlite/src/workspace/stock/schema.rs @@ -1,7 +1,7 @@ //! Exact stock catalogs. Enrollment-only version1 is retained without upgrade. use super::WorkspaceError; use sqlx::SqliteConnection; -pub(super) const CURRENT: i64 = 10; +pub(super) const CURRENT: i64 = 11; 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"; @@ -14,6 +14,7 @@ const HEAD: &str = "CREATE UNIQUE INDEX stock_operation_head_identity ON stock_operations(chain_head)"; const OPERATIONS_V7: &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 2), 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))) STRICT, WITHOUT ROWID"; const OPERATIONS_V10: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 3), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=3 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; +const OPERATIONS_V11: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 5), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 5 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const 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, @@ -24,13 +25,15 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=10 => objects.extend([ + 2..=11 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ( "table", "stock_operations", "stock_operations", - if version >= 10 { + if version >= 11 { + OPERATIONS_V11 + } else if version >= 10 { OPERATIONS_V10 } else if version >= 7 { OPERATIONS_V7 @@ -73,7 +76,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..=10).contains(&version) { + if (6..=11).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)")); @@ -97,7 +100,7 @@ pub(super) fn objects( objects.push(("index","stock_order_operation_position","stock_operations","CREATE INDEX stock_order_operation_position ON stock_operations(order_id,revision) WHERE order_id IS NOT NULL")); objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); } - if matches!(version, 8..=10) { + if matches!(version, 8..=11) { 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(( @@ -118,6 +121,17 @@ pub(super) fn objects( if version >= 10 { objects.push(("index", "stock_signing_plan_identity", "stock_operations", "CREATE UNIQUE INDEX stock_signing_plan_identity ON stock_operations(actor,related_operation) WHERE family=3")); } + if version >= 11 { + objects.push(("table","stock_signing_claims","stock_signing_claims","CREATE TABLE stock_signing_claims (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), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id,recipient), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id), FOREIGN KEY(actor,operation_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + objects.push(( + "index", + "stock_signing_claim_entry", + "stock_signing_claims", + "CREATE UNIQUE INDEX stock_signing_claim_entry ON stock_signing_claims(actor,entry_id)", + )); + objects.push(("table","stock_signing_evidence","stock_signing_evidence","CREATE TABLE stock_signing_evidence (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), evidence_digest BLOB NOT NULL CHECK(length(evidence_digest)=32), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), PRIMARY KEY(actor,operation_id,recipient,evidence_digest), FOREIGN KEY(actor,entry_id) REFERENCES stock_operations(actor,operation_id), FOREIGN KEY(actor,operation_id,recipient) REFERENCES stock_signing_claims(actor,operation_id,recipient)) STRICT, WITHOUT ROWID")); + objects.push(("index","stock_signing_evidence_entry","stock_signing_evidence","CREATE UNIQUE INDEX stock_signing_evidence_entry ON stock_signing_evidence(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 @@ -12,7 +12,7 @@ use radroots_storage::{ inventory::InventoryCheckpointRef, }; use sha2::{Digest, Sha256}; -mod codec; +pub(in crate::workspace::stock) mod codec; pub(super) use codec::read_entry; /// A bounded candidate, with actual encryption and original route verification. @@ -93,17 +93,53 @@ pub enum StockSigningPlanOutcome { Unknown(CommitAttempt), } -struct Authorized { - access: Access, - original: acceptance::codec::Retained, - command: radroots_protocol::command::CapturedOrderAcceptance, - original_proof: MinimumProof, - consent: consent::Retained, - consent_proof: MinimumProof, - plan: Option<codec::Retained>, - plan_proof: MinimumProof, +pub(in crate::workspace::stock) struct Authorized { + pub(in crate::workspace::stock) access: Access, + pub(in crate::workspace::stock) original: acceptance::codec::Retained, + pub(in crate::workspace::stock) command: radroots_protocol::command::CapturedOrderAcceptance, + pub(in crate::workspace::stock) original_proof: MinimumProof, + pub(in crate::workspace::stock) consent: consent::Retained, + pub(in crate::workspace::stock) consent_proof: MinimumProof, + pub(in crate::workspace::stock) plan: Option<codec::Retained>, + pub(in crate::workspace::stock) plan_proof: MinimumProof, } -async fn load( +impl Authorized { + pub(in crate::workspace::stock) async fn confirm( + &self, + connection: &mut SqliteConnection, + namespace: &super::super::fs::Namespace, + clock: &dyn WorkspaceClock, + proof: &AttachmentProof, + fresh: bool, + ) -> Result<WorkspaceBinding, OperationError> { + self.original_proof.confirm(connection).await?; + self.consent_proof.confirm(connection).await?; + self.plan_proof.confirm(connection).await?; + self.original.confirm(connection).await?; + if let Some(plan) = &self.plan { + plan.confirm(connection).await?; + } + let current = self + .access + .confirm(connection, namespace, clock, proof) + .await?; + acceptance::check_consent( + &self.access, + &self.consent, + &self.command, + fresh, + current.observed_at(), + )?; + if fresh + && (current.observed_at() < self.original.receipt.prepared_at() + || current.observed_at() >= self.original.receipt.first_issue_deadline()) + { + return Err(OperationError::DeadlineExceeded); + } + Ok(current) + } +} +pub(in crate::workspace::stock) async fn load( turn: &mut Turn<'_>, binding: &WorkspaceBinding, minimum: InventoryCheckpointRef, @@ -112,7 +148,7 @@ async fn load( proof: &AttachmentProof, ) -> Result<Authorized, OperationError> { let access = turn.access(binding, minimum, proof).await?; - if access.authority.catalog != 10 { + if !matches!(access.authority.catalog, 10 | 11) { return Err(OperationError::UnsupportedOperation); } let original = acceptance::codec::read(turn.connection, turn.selected, turn.crypto, operation) @@ -241,6 +277,12 @@ pub(in crate::workspace) async fn bind( auth.plan.ok_or(OperationError::RecoveryRequired)?.bound, ))); } + let backing = Box::pin(inventory::backing::read( + turn, + &auth.access, + auth.original.receipt.held_pools(), + )) + .await?; let before = auth .access .authority @@ -313,6 +355,7 @@ pub(in crate::workspace) async fn bind( let changed: Result<(), OperationError> = async { auth.original_proof.confirm(&mut tx).await?; auth.consent_proof.confirm(&mut tx).await?; auth.plan_proof.confirm(&mut tx).await?; auth.original.confirm(&mut tx).await?; let current = auth.access.confirm(&mut tx, turn.namespace, turn.clock, &proof).await?; + for pool in &backing { pool.confirm(&mut tx).await?; } acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, current.observed_at())?; if current.observed_at() < bound_at || current.observed_at() >= auth.original.receipt.first_issue_deadline() { return Err(OperationError::DeadlineExceeded); } sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected,family,order_id,related_operation,subject_grant) VALUES(?,?,?,?,?,NULL,?,?,?,3,?,?,NULL)") diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs @@ -155,7 +155,7 @@ pub(in crate::workspace::stock) async fn read_entry( Ok(Some(retained)) } impl Retained { - pub(super) fn identity(&self) -> EntryIdentity { + pub(in crate::workspace::stock) fn identity(&self) -> EntryIdentity { EntryIdentity { operation: self.frame.header.operation, revision: self.frame.header.revision, @@ -163,7 +163,7 @@ impl Retained { protected_digest: Sha256::digest(&self.frame.protected).into(), } } - pub(super) async fn confirm( + pub(in crate::workspace::stock) async fn confirm( &self, connection: &mut SqliteConnection, ) -> Result<(), OperationError> { @@ -191,6 +191,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + signing: None, header: self.frame.header, protected: self.frame.protected, parts_witness: self.frame.parts_witness, 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..=10).contains(&authority.catalog) { + if !(6..=11).contains(&authority.catalog) { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; @@ -113,7 +113,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..=10) { + if !matches!(access.authority.catalog, 8..=11) { return Err(OperationError::UnsupportedOperation); } let prepared = super::history::prepare( @@ -168,7 +168,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..=10) { + if !matches!(access.authority.catalog, 8..=11) { return Err(OperationError::UnsupportedOperation); } let prepared = 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(10)); + assert_eq!(schema::admit(&mut connection).await, Ok(11)); 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(), 10, &root) + .open_stock_root(enrollment.input(), 11, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 10)) + .expose_secret(|bytes| Authority::decode(bytes, 11)) .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(),10).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),11).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(),10).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),11).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] { + for version in [4, 5, 6, 7, 8, 9, 10, 11] { let current = crypto .seal_stock_root(&owner, version, clear) .await @@ -204,7 +204,7 @@ async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_ca assert!(crypto.open_stock_root(&owner, 3, &current).await.is_err()); assert!( crypto - .open_stock_root(&owner, if version == 4 { 5 } else { 4 }, &current) + .open_stock_root(&owner, if version == 4 { 5 } else { version - 1 }, &current) .await .is_err() ); @@ -272,10 +272,14 @@ async fn retained_v9_preserves_prior_families_and_acceptance_admission() { retained_inventory_catalog(9).await; } #[tokio::test] -async fn current_v10_preserves_prior_families_and_adds_signing_plan_retention() { - assert_eq!(schema::CURRENT, 10); +async fn retained_v10_preserves_prior_families_and_signing_plan_retention() { retained_inventory_catalog(10).await; } +#[tokio::test] +async fn current_v11_preserves_prior_families_and_adds_claims_and_obtained_evidence() { + assert_eq!(schema::CURRENT, 11); + retained_inventory_catalog(11).await; +} // Exact catalog fixtures exercise retained/successor codecs; they are not // evidence from a predecessor executable or a factory migration. pub(super) async fn literal_catalog( @@ -336,7 +340,7 @@ pub(super) async fn literal_catalog( if catalog >= 7 { value["inventory"]["orders"] = serde_json::json!("0"); } - if matches!(catalog, 8..=10) { + if matches!(catalog, 8..=11) { value["public_sources"] = serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); } @@ -379,6 +383,7 @@ pub(super) async fn literal_catalog( 8 => "PRAGMA user_version=8", 9 => "PRAGMA user_version=9", 10 => "PRAGMA user_version=10", + 11 => "PRAGMA user_version=11", _ => unreachable!(), }) .execute(&mut *tx) @@ -404,7 +409,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..=10) + matches!(catalog, 8..=11) ); let minimum = authority.inventory_checkpoint().unwrap(); let context = CommandContextData::new( @@ -647,7 +652,7 @@ async fn retained_inventory_catalog(catalog: i64) { .fetch_one(&mut connection) .await .unwrap(); - let old = if matches!(catalog, 7..=10) { + let old = if matches!(catalog, 7..=11) { let retained = ledger::read( &mut connection, &input, @@ -700,7 +705,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..=10) { + if part && !matches!(catalog, 7..=11) { continue; } let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) @@ -773,6 +778,7 @@ async fn retained_inventory_catalog(catalog: i64) { 8 => "PRAGMA user_version=7", 9 => "PRAGMA user_version=8", 10 => "PRAGMA user_version=9", + 11 => "PRAGMA user_version=10", _ => unreachable!(), }) .execute(&mut connection) diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -38,6 +38,33 @@ const QUEUE_MAX_BYTES: usize = 4 * 1024 * 1024; const QUEUE_CAPACITY: usize = 32; type Reply<T, E = WorkspaceError> = oneshot::Sender<Result<T, E>>; enum Job { + StockEvidencePage( + Box<stock::StockClaimRequest>, + Option<radroots_domain::Sequence>, + AttachmentProof, + Reply<stock::StockEvidencePage, OperationError>, + ), + CaptureStockEvidence( + Box<stock::StockEvidenceCapture>, + AttachmentProof, + Reply<stock::StockEvidenceOutcome, OperationError>, + ), + StockEvidence( + Box<stock::StockClaimRequest>, + [u8; 32], + AttachmentProof, + Reply<Option<stock::StockCapturedEvidence>, OperationError>, + ), + ClaimStockSigning( + Box<stock::StockClaimRequest>, + AttachmentProof, + Reply<stock::StockClaimOutcome, OperationError>, + ), + StockSigningAttempt( + Box<stock::StockClaimRequest>, + AttachmentProof, + Reply<Option<stock::StockSigningAttempt>, OperationError>, + ), BindStockSigningPlan( Box<stock::StockSigningPlanRequest>, AttachmentProof, @@ -252,6 +279,21 @@ enum Job { impl Job { fn reject_recovery(self) { match self { + Self::StockEvidencePage(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::CaptureStockEvidence(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockEvidence(_, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::ClaimStockSigning(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockSigningAttempt(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::BindStockSigningPlan(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -509,6 +551,11 @@ impl Handle { | Job::PrepareStockAcceptance(..) | Job::BindStockSigningPlan(..) | Job::StockSigningPlan(..) + | Job::ClaimStockSigning(..) + | Job::StockSigningAttempt(..) + | Job::CaptureStockEvidence(..) + | Job::StockEvidence(..) + | Job::StockEvidencePage(..) | Job::Revoke(..) | Job::StockAuthority(..) ) @@ -725,9 +772,111 @@ impl Handle { }; let _ = reply.send(result); } + Job::StockEvidencePage(request, after, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::evidence::page( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + after, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } + Job::CaptureStockEvidence(evidence, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::evidence::capture( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *evidence, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } + Job::StockEvidence(request, digest, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::evidence::read( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + digest, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } + Job::ClaimStockSigning(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::claim::claim( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } + Job::StockSigningAttempt(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::issuance::claim::read( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } Job::BindStockSigningPlan(request, proof, reply) => { let result = if kind == Kind::SellerStock { - stock::signing_plan::bind( + Box::pin(stock::signing_plan::bind( &mut stock::inventory::Turn { connection, namespace: &namespace, @@ -738,7 +887,7 @@ impl Handle { }, *request, proof, - ) + )) .await } else { Err(OperationError::UnsupportedOperation) @@ -754,7 +903,7 @@ impl Handle { reply, ) => { let result = if kind == Kind::SellerStock { - stock::signing_plan::read( + Box::pin(stock::signing_plan::read( &mut stock::inventory::Turn { connection, namespace: &namespace, @@ -768,7 +917,7 @@ impl Handle { operation, digest, proof, - ) + )) .await } else { Err(OperationError::UnsupportedOperation) @@ -1411,6 +1560,60 @@ impl Handle { ))?; result.await.unwrap_or(Ok(anchor)) } + pub(super) async fn stock_signing_evidence_page( + &self, + request: stock::StockClaimRequest, + after: Option<radroots_domain::Sequence>, + proof: AttachmentProof, + ) -> Result<stock::StockEvidencePage, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockEvidencePage( + Box::new(request), + after, + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } + pub(super) async fn capture_stock_signing_evidence( + &self, + evidence: stock::StockEvidenceCapture, + proof: AttachmentProof, + ) -> Result<stock::StockEvidenceOutcome, OperationError> { + let unknown = stock::StockEvidenceOutcome::Unknown(evidence.attempt()); + let (reply, result) = oneshot::channel(); + self.send(Job::CaptureStockEvidence(Box::new(evidence), proof, reply))?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn stock_signing_evidence( + &self, + request: stock::StockClaimRequest, + digest: [u8; 32], + proof: AttachmentProof, + ) -> Result<Option<stock::StockCapturedEvidence>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockEvidence(Box::new(request), digest, proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } + pub(super) async fn claim_stock_signing_attempt( + &self, + request: stock::StockClaimRequest, + proof: AttachmentProof, + ) -> Result<stock::StockClaimOutcome, OperationError> { + let unknown = stock::StockClaimOutcome::Unknown(request.attempt()); + let (reply, result) = oneshot::channel(); + self.send(Job::ClaimStockSigning(Box::new(request), proof, reply))?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn stock_signing_attempt( + &self, + request: stock::StockClaimRequest, + proof: AttachmentProof, + ) -> Result<Option<stock::StockSigningAttempt>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockSigningAttempt(Box::new(request), proof, reply))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn bind_stock_signing_intents( &self, request: stock::StockSigningPlanRequest, @@ -1535,9 +1738,13 @@ impl Handle { } fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { - Job::RetainStockListing(..) => 256 * 1024, + Job::RetainStockListing(..) | Job::CaptureStockEvidence(..) => 256 * 1024, + Job::StockEvidence(..) | Job::StockEvidencePage(..) => 1024 * 1024, Job::IssueStockConsent(..) | Job::PrepareStockAcceptance(..) => 512 * 1024, - Job::BindStockSigningPlan(..) | Job::StockSigningPlan(..) => 1024 * 1024, + Job::BindStockSigningPlan(..) + | Job::StockSigningPlan(..) + | Job::ClaimStockSigning(..) + | Job::StockSigningAttempt(..) => 1024 * 1024, Job::RetainStockSource(..) => 256 * 1024, Job::ChangeStockGrant(..) | Job::ExecuteInventory(..) => 64 * 1024, Job::CaptureDeliveryObservation(..) => 96 * 1024, 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=10") + sqlx::query("PRAGMA user_version=11") .execute(&mut connection) .await .unwrap(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -151,6 +151,7 @@ struct NativeSellerStockAuthority { operation_identity_requires_protected_ancestry: bool, acceptance_preparation: AcceptancePreparation, signing_plan_binding: SigningPlanBinding, + signing_issuance: SigningIssuance, business_consent_payload_version: u16, business_consent_action: String, business_consent_modes: Vec<String>, @@ -209,6 +210,27 @@ struct AcceptancePreparation { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct SigningIssuance { + fresh_current_backing_projection_required: bool, + evidence_page_max: u32, + claim_family: u32, + evidence_family: u32, + claim_worker_charge_bytes: u32, + capture_worker_charge_bytes: u32, + capture_raw_max_bytes: u32, + first_dispatch_requires_confirmed_commit: bool, + existing_claim_returns_dispatch_permit: bool, + protected_identity_presence_and_absence_required: bool, + capture_requires_original_claim_and_credential: bool, + capture_requires_current_consent: bool, + capture_requires_observation_clock: bool, + capture_preserves_first_optional_time: bool, + capture_retains_distinct_valid_encodings: bool, + agreement_installed: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct SigningPlanBinding { payload_version: u16, journal_family: u16, @@ -399,10 +421,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 == 10 + && stock.schema_version == 11 && stock.retained_enrollment_versions == [1] - && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v10" + && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v11" && stock.public_source_payload_schemas == [ "radroots.seller_stock.public_source_event.v1", @@ -469,6 +491,34 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { .final_permission_and_clock_witnesses_required && !stock.signing_plan_binding.signer_invoked && !stock.signing_plan_binding.agreement_installed + && stock + .signing_issuance + .fresh_current_backing_projection_required + && stock.signing_issuance.evidence_page_max == 32 + && stock.signing_issuance.claim_family == 4 + && stock.signing_issuance.evidence_family == 5 + && stock.signing_issuance.claim_worker_charge_bytes == 1048576 + && stock.signing_issuance.capture_worker_charge_bytes == 262144 + && stock.signing_issuance.capture_raw_max_bytes == 65536 + && stock + .signing_issuance + .first_dispatch_requires_confirmed_commit + && !stock + .signing_issuance + .existing_claim_returns_dispatch_permit + && stock + .signing_issuance + .protected_identity_presence_and_absence_required + && stock + .signing_issuance + .capture_requires_original_claim_and_credential + && !stock.signing_issuance.capture_requires_current_consent + && !stock.signing_issuance.capture_requires_observation_clock + && stock.signing_issuance.capture_preserves_first_optional_time + && stock + .signing_issuance + .capture_retains_distinct_valid_encodings + && !stock.signing_issuance.agreement_installed && stock.business_consent_payload_version == 1 && stock.business_consent_action == "orders.accept" && stock.business_consent_modes == ["execute_and_recover", "recover_only"] @@ -1072,6 +1122,43 @@ mod tests { } #[test] + fn stock_claims_require_confirmed_dispatch_and_clock_independent_original_capture() { + for (field, bad) in [ + ("fresh_current_backing_projection_required", json!(false)), + ("evidence_page_max", json!(33)), + ("claim_family", json!(3)), + ("evidence_family", json!(4)), + ("claim_worker_charge_bytes", json!(16384)), + ("capture_worker_charge_bytes", json!(16384)), + ("capture_raw_max_bytes", json!(65537)), + ("first_dispatch_requires_confirmed_commit", json!(false)), + ("existing_claim_returns_dispatch_permit", json!(true)), + ( + "protected_identity_presence_and_absence_required", + json!(false), + ), + ( + "capture_requires_original_claim_and_credential", + json!(false), + ), + ("capture_requires_current_consent", json!(true)), + ("capture_requires_observation_clock", json!(true)), + ("capture_preserves_first_optional_time", json!(false)), + ("capture_retains_distinct_valid_encodings", json!(false)), + ("agreement_installed", json!(true)), + ] { + assert!( + validate_bytes(&changed( + &format!("/native_seller_stock_authority/signing_issuance/{field}"), + bad + )) + .is_err(), + "{field}" + ); + } + } + + #[test] fn public_sources_require_original_signatures_bounded_parts_and_profile_independent_heads() { for (field, bad) in [ ("schema_version", json!(7)),