lib

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

commit 4323d26a431503ca918d009cfc7f85d50901efa2
parent 3dea9f6dde94f6b000308b34ac7b53cb3f381d1d
Author: triesap <tyson@radroots.org>
Date:   Sun, 25 Oct 2026 17:18:10 +0000

storage: install initial stock-backed agreements atomically

- Bind original peer evidence to immutable agreement and recipient work.
- Convert exact preparatory quantities with authenticated pool movements.
- Preserve original recovery, consent and uncertain-owner boundaries.
- Verify native, Linux, portable domain and additive public APIs.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 1+
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 30++++++++++++++++++++++++++++++
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 22+++++++++++++++++++---
Mcrates/domain/src/stock.rs | 13+++++++++++++
Mcrates/domain/tests/stock.rs | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/README.md | 25+++++++++++++++++++++----
Mcrates/storage_sqlite/src/workspace/crypto.rs | 20++++++++++++++------
Mcrates/storage_sqlite/src/workspace/mod.rs | 9+++++----
Mcrates/storage_sqlite/src/workspace/stock.rs | 12++++++++----
Mcrates/storage_sqlite/src/workspace/stock/consent.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/consent/test_provider.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/grants.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory.rs | 5+++--
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs | 12++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs | 174++++++++++++++++++++++++++++++++++++++++++++++---------------------------------
Mcrates/storage_sqlite/src/workspace/stock/inventory/codec.rs | 4++--
Acrates/storage_sqlite/src/workspace/stock/inventory/installation.rs | 525+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs | 305++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/inventory/installation/projection.rs | 120+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/inventory/mapping.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/inventory/plan.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/issuance.rs | 10+++++++++-
Mcrates/storage_sqlite/src/workspace/stock/issuance/claim.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs | 1+
Mcrates/storage_sqlite/src/workspace/stock/issuance/evidence.rs | 6+++---
Mcrates/storage_sqlite/src/workspace/stock/issuance/evidence/codec.rs | 1+
Mcrates/storage_sqlite/src/workspace/stock/ledger.rs | 62+++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcrates/storage_sqlite/src/workspace/stock/public_source/acceptance_tests.rs | 6+++---
Mcrates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs | 6++++--
Acrates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs | 495+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/public_source/signing_tests.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/test_provider.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/public_source/transaction.rs | 2+-
Mcrates/storage_sqlite/src/workspace/stock/schema.rs | 35++++++++++++++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/stock/signing_plan.rs | 13+++++++++----
Mcrates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs | 1+
Mcrates/storage_sqlite/src/workspace/stock/snapshot.rs | 42++++++++++++++++++++++++++++++++----------
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 | 89++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcrates/storage_sqlite/tests/support/stock_authority.rs | 2+-
Mtools/xtask/src/architecture/decision_package.rs | 82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
44 files changed, 2066 insertions(+), 181 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -323,6 +323,7 @@ pub struct radroots_domain::stock::PoolBalances impl radroots_domain::stock::PoolBalances pub fn radroots_domain::stock::PoolBalances::correct_available(self, radroots_domain::stock::AvailableStockCorrection, radroots_domain::stock::StockTicks) -> core::result::Result<Self, radroots_domain::stock::StockError> pub fn radroots_domain::stock::PoolBalances::hold_available(self, radroots_domain::stock::StockTicks) -> core::result::Result<Self, radroots_domain::stock::StockError> +pub fn radroots_domain::stock::PoolBalances::install_preparatory(self, radroots_domain::stock::StockTicks) -> core::result::Result<Self, radroots_domain::stock::StockError> pub const fn radroots_domain::stock::PoolBalances::introduced(self) -> radroots_domain::stock::StockTicks pub fn radroots_domain::stock::PoolBalances::new(radroots_domain::stock::StockTicks, radroots_domain::stock::PhysicalBalances) -> core::result::Result<Self, radroots_domain::stock::StockError> pub const fn radroots_domain::stock::PoolBalances::physical(self) -> radroots_domain::stock::PhysicalBalances diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -391,6 +391,9 @@ pub radroots_storage_sqlite::workspace::StockEvidenceOutcome::Unknown(radroots_s 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) +pub enum radroots_storage_sqlite::workspace::StockInstallationOutcome +pub radroots_storage_sqlite::workspace::StockInstallationOutcome::Installed(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockInstallationReceipt>) +pub radroots_storage_sqlite::workspace::StockInstallationOutcome::Unknown(radroots_storage::command::CommitAttempt) pub enum radroots_storage_sqlite::workspace::StockListingOutcome pub radroots_storage_sqlite::workspace::StockListingOutcome::Committed(alloc::boxed::Box<radroots_storage_sqlite::workspace::StockListingReceipt>) pub radroots_storage_sqlite::workspace::StockListingOutcome::Unknown @@ -438,6 +441,9 @@ pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::initialize_sel pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::open_seller_stock(&std::path::Path, radroots_storage::workspace::AttachmentInput, radroots_storage_sqlite::workspace::WorkspaceCrypto, alloc::sync::Arc<dyn radroots_storage::workspace::WorkspaceClock>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_authority(&self, radroots_storage::workspace::AttachmentInput, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockAuthorityReceipt, radroots_storage::workspace::WorkspaceError> impl radroots_storage_sqlite::workspace::NativeWorkspace +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::install_stock_agreement(&self, radroots_storage_sqlite::workspace::StockInstallationRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockInstallationOutcome, radroots_storage::command::OperationError> +pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_agreement_installation(&self, radroots_storage_sqlite::workspace::StockInstallationRequest, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockInstallationReceipt>, radroots_storage::command::OperationError> +impl radroots_storage_sqlite::workspace::NativeWorkspace pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::issue_stock_consent(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, &radroots_storage_sqlite::workspace::StockConsentCapture, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<radroots_storage_sqlite::workspace::StockConsentOutcome, radroots_storage::command::OperationError> pub async fn radroots_storage_sqlite::workspace::NativeWorkspace::stock_consent(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::GrantId, &radroots_storage::workspace::AttachmentProof) -> core::result::Result<core::option::Option<radroots_storage_sqlite::workspace::StockConsentReceipt>, radroots_storage::command::OperationError> impl radroots_storage_sqlite::workspace::NativeWorkspace @@ -613,6 +619,22 @@ pub const fn radroots_storage_sqlite::workspace::StockHistorySnapshot::scope(&se pub const fn radroots_storage_sqlite::workspace::StockHistorySnapshot::source_checkpoint(&self) -> radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockHistorySnapshot pub fn radroots_storage_sqlite::workspace::StockHistorySnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockInstallationReceipt +impl radroots_storage_sqlite::workspace::StockInstallationReceipt +pub const fn radroots_storage_sqlite::workspace::StockInstallationReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage_sqlite::workspace::StockInstallationReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub const fn radroots_storage_sqlite::workspace::StockInstallationReceipt::installed_at(&self) -> radroots_domain::context::UnixSeconds +pub fn radroots_storage_sqlite::workspace::StockInstallationReceipt::installed_pools(&self) -> &[radroots_domain::stock::PoolSnapshot] +pub const fn radroots_storage_sqlite::workspace::StockInstallationReceipt::order_id(&self) -> radroots_domain::identifier::OrderId +pub const fn radroots_storage_sqlite::workspace::StockInstallationReceipt::publication_work(&self) -> &[radroots_storage_sqlite::workspace::StockPublicationWork; 2] +pub const fn radroots_storage_sqlite::workspace::StockInstallationReceipt::record_id(&self) -> radroots_domain::identifier::RecordId +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockInstallationReceipt +pub fn radroots_storage_sqlite::workspace::StockInstallationReceipt::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockInstallationRequest +impl radroots_storage_sqlite::workspace::StockInstallationRequest +pub const fn radroots_storage_sqlite::workspace::StockInstallationRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> Self +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockInstallationRequest +pub fn radroots_storage_sqlite::workspace::StockInstallationRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockListingCapture impl radroots_storage_sqlite::workspace::StockListingCapture pub const fn radroots_storage_sqlite::workspace::StockListingCapture::listing_revision(&self) -> radroots_domain::listing::reference::ListingRevision @@ -639,11 +661,19 @@ pub fn radroots_storage_sqlite::workspace::StockListingSnapshot::fmt(&self, &mut pub struct radroots_storage_sqlite::workspace::StockOperationSnapshot impl radroots_storage_sqlite::workspace::StockOperationSnapshot pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage_sqlite::workspace::StockOperationSnapshot::installation(&self) -> core::option::Option<&radroots_storage_sqlite::workspace::StockInstallationReceipt> pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::preparation(&self) -> &radroots_storage_sqlite::workspace::StockAcceptanceReceipt pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::recipients(&self) -> &[radroots_storage_sqlite::workspace::StockRecipientSnapshot; 2] pub const fn radroots_storage_sqlite::workspace::StockOperationSnapshot::signing_plan(&self) -> core::option::Option<&radroots_storage_sqlite::workspace::StockBoundSigningPlan> impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockOperationSnapshot pub fn radroots_storage_sqlite::workspace::StockOperationSnapshot::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_storage_sqlite::workspace::StockPublicationWork +impl radroots_storage_sqlite::workspace::StockPublicationWork +pub const fn radroots_storage_sqlite::workspace::StockPublicationWork::evidence_digest(&self) -> core::option::Option<&[u8; 32]> +pub const fn radroots_storage_sqlite::workspace::StockPublicationWork::recipient(self) -> radroots_identity::key::PublicKey +pub const fn radroots_storage_sqlite::workspace::StockPublicationWork::seal_id(&self) -> &[u8; 32] +impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockPublicationWork +pub fn radroots_storage_sqlite::workspace::StockPublicationWork::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockRecipientSnapshot impl radroots_storage_sqlite::workspace::StockRecipientSnapshot pub const fn radroots_storage_sqlite::workspace::StockRecipientSnapshot::claim(&self) -> core::option::Option<radroots_storage_sqlite::workspace::StockClaimReference> 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": 11, + "schema_version": 12, "retained_enrollment_versions": [ 1 ], @@ -88,9 +88,10 @@ 7, 8, 9, - 10 + 10, + 11 ], - "authority_payload_schema": "radroots.seller_stock.authority.v11", + "authority_payload_schema": "radroots.seller_stock.authority.v12", "public_source_payload_schemas": [ "radroots.seller_stock.public_source_event.v1", "radroots.seller_stock.public_source_head.v1", @@ -240,6 +241,21 @@ "capture_preserves_first_optional_time": true, "capture_retains_distinct_valid_encodings": true, "agreement_installed": false + }, + "initial_agreement_installation": { + "payload_version": 1, + "journal_family": 6, + "worker_charge_bytes": 1048576, + "required_peer_evidence": true, + "missing_self_copy_blocks_installation": false, + "original_order_fence_immutable": true, + "exact_original_hold_quantities_required": true, + "current_exact_recovery_consent_required": true, + "atomic_pool_agreement_and_work_required": true, + "recipient_work_count": 2, + "unknown_commit_fences_owner": true, + "signer_or_transport_invoked": false, + "relay_delivery_claimed": false } }, "provenance": { diff --git a/crates/domain/src/stock.rs b/crates/domain/src/stock.rs @@ -271,6 +271,19 @@ impl PoolBalances { physical.preparatory_hold = physical.preparatory_hold.checked_add(quantity)?; Self::new(self.introduced, physical) } + /// Proposes conversion of this exact positive preparatory quantity into + /// installed physical backing. Other orders' holds and lifetime introduced + /// stock remain unchanged. The executor must authenticate original allocation + /// and peer evidence and commit every affected pool with installation. + pub fn install_preparatory(self, quantity: StockTicks) -> Result<Self, StockError> { + if quantity == StockTicks::ZERO { + return Err(StockError::ZeroMovement); + } + let mut physical = self.physical; + physical.preparatory_hold = physical.preparatory_hold.checked_sub(quantity)?; + physical.committed_hold = physical.committed_hold.checked_add(quantity)?; + Self::new(self.introduced, physical) + } /// Proposes a nonzero, exact correction against available backing only. /// Held or quarantined stock is never silently substituted for available /// stock. Depleting it needs a separate obligation/deficit transition. diff --git a/crates/domain/tests/stock.rs b/crates/domain/tests/stock.rs @@ -8,6 +8,55 @@ fn ticks(value: u64) -> StockTicks { } #[test] +fn installation_moves_only_exact_preparatory_backing_and_preserves_all_other_categories() { + let physical = PhysicalBalances { + available: ticks(30), + preparatory_hold: ticks(10), + committed_hold: ticks(20), + physical_quarantine: ticks(5), + consumed: ticks(15), + waste: ticks(10), + removed: ticks(10), + }; + let original = PoolBalances::new(ticks(100), physical).unwrap(); + let installed = original.install_preparatory(ticks(3)).unwrap(); + assert_eq!(installed.introduced(), ticks(100)); + assert_eq!( + installed.physical(), + PhysicalBalances { + preparatory_hold: ticks(7), + committed_hold: ticks(23), + ..physical + } + ); + assert_eq!( + original.install_preparatory(ticks(11)), + Err(StockError::Underflow) + ); + assert_eq!( + original.install_preparatory(StockTicks::ZERO), + Err(StockError::ZeroMovement) + ); + let maximum = PoolBalances::new( + StockTicks::MAX, + PhysicalBalances { + preparatory_hold: StockTicks::MAX, + ..PhysicalBalances::ZERO + }, + ) + .unwrap(); + assert_eq!( + maximum + .install_preparatory(StockTicks::MAX) + .unwrap() + .physical() + .committed_hold, + StockTicks::MAX + ); + assert_eq!(original.physical(), physical); +} + +#[test] fn proposed_holds_conserve_stock_and_cannot_borrow_other_physical_categories() { let physical = PhysicalBalances { available: ticks(30), diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -316,7 +316,7 @@ protected credential and original creation transaction ID without touching the namespace. Retain those values through protected host handling before awaiting `NativeWorkspace::initialize_seller_stock`. This explicit factory uses `stock_execution_v1.sqlite` and `.stock_execution_v1.lock` in a new owner-only -directory. Its exact version-11 catalog has separate protected authority and +directory. Its exact version-12 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 version11 and protected authority -payload version11. Retained enrollment-only version1 still authenticates and +The current stock factory creates exact catalog version12 and protected authority +payload version12. 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–10 retain their exact original codecs and +new correction commands. Catalogs1–11 retain their exact original codecs and capabilities; current multipart operation framing uses version5. No namespace is automatically migrated. Ordinary outbox catalogs are separate. @@ -435,3 +435,20 @@ from installation. Current RecoverOnly consent can inspect original progress after the first-issue deadline. Evidence selectors, page row sets, counts and absence facts are compared again after provider work inside the final read transaction. A recovery view never returns a fresh dispatch permit. + + +Initial seller agreement installation uses `install_stock_agreement` on the same +bounded native owner. Exact catalog/root12 retains formats1–11 without upgrading +them. The original preparation fence remains immutable. Separate authenticated +agreement and per-recipient work indexes bind original T0/T1 and retained S. +Installation requires actual peer seal evidence; a missing self copy remains +waiting work and cannot justify releasing the peer obligation. One transaction +converts only the original allocation quantities from preparatory to committed +holds, appends movements, installs the original record and creates both work +references. Current exact recovery consent and all original/current pool and +identity witnesses are confirmed after provider IO. No signer or transport runs +under the transaction. Replaying or reopening returns the original installation; +uncertain commit fences the owner until drain/reopen. `stock_operation_snapshot` +reports installation separately from signing and delivery facts. This initial +primitive does not implement amendments, handovers, releases, deficits, browser +stock or complete ordinary caller orchestration. 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..=11) { + if matches!(version, 4..=12) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -736,8 +736,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v9\0" } else if version == 10 { b"radroots.seller_stock.authority_context.v10\0".as_slice() - } else { + } else if version == 11 { b"radroots.seller_stock.authority_context.v11\0".as_slice() + } else { + b"radroots.seller_stock.authority_context.v12\0".as_slice() }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -760,8 +762,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v9" } else if version == 10 { "radroots.seller_stock.authority.v10" - } else { + } else if version == 11 { "radroots.seller_stock.authority.v11" + } else { + "radroots.seller_stock.authority.v12" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -814,6 +818,10 @@ fn stock_record_context( "radroots.seller_stock.order", "radroots.seller_stock.order.v1", ), + "installation_movement" => ( + "radroots.seller_stock.installation_movement", + "radroots.seller_stock.installation_movement.v1", + ), "acceptance_movement" => ( "radroots.seller_stock.acceptance_movement", "radroots.seller_stock.acceptance_movement.v1", @@ -871,12 +879,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..=11, "pool") => return Ok(original), + (2, _) | (3..=12, "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..=11, "operation") => "radroots.seller_stock.operation.v5", - (3..=11, "movement") => "radroots.seller_stock.movement.v2", + (7..=12, "operation") => "radroots.seller_stock.operation.v5", + (3..=12, "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 @@ -29,11 +29,12 @@ pub use stock::{ StockConsentOutcome, StockConsentReceipt, StockDispatchPermit, StockEnrollment, StockEvidenceCapture, StockEvidenceOutcome, StockEvidencePage, StockEvidenceReceipt, StockGrantEnrollment, StockGrantOutcome, StockGrantReceipt, StockHistorySnapshot, + StockInstallationOutcome, StockInstallationReceipt, StockInstallationRequest, StockListingCapture, StockListingOutcome, StockListingReceipt, StockListingSnapshot, - StockOperationSnapshot, StockRecipientSnapshot, StockRequestSnapshot, StockSigningAttempt, - StockSigningPlanOutcome, StockSigningPlanRequest, StockSigningProgress, StockSnapshotRequest, - StockSourceCapture, StockSourceOutcome, StockSourceProfile, StockSourceReceipt, - StockSourceSnapshot, + StockOperationSnapshot, StockPublicationWork, StockRecipientSnapshot, StockRequestSnapshot, + StockSigningAttempt, StockSigningPlanOutcome, StockSigningPlanRequest, StockSigningProgress, + StockSnapshotRequest, StockSourceCapture, StockSourceOutcome, StockSourceProfile, + StockSourceReceipt, StockSourceSnapshot, }; mod worker; diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -16,6 +16,10 @@ pub(in crate::workspace) mod grants; pub use inventory::acceptance::{ StockAcceptanceOutcome, StockAcceptanceReceipt, StockAcceptanceRequest, }; +pub use inventory::installation::{ + StockInstallationOutcome, StockInstallationReceipt, StockInstallationRequest, + StockPublicationWork, +}; pub(in crate::workspace) mod issuance; mod ledger; pub use issuance::{ @@ -434,10 +438,10 @@ struct AuthorityV8 { } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { - if !matches!(self.catalog, 8..=11) && self.public_sources.is_some() { + if !matches!(self.catalog, 8..=12) && self.public_sources.is_some() { return Err(WorkspaceError::RecoveryRequired); } - if matches!(self.catalog, 8..=11) { + if matches!(self.catalog, 8..=12) { let public_sources = self .public_sources .ok_or(WorkspaceError::RecoveryRequired)?; @@ -689,7 +693,7 @@ impl Authority { public_sources: None, } } - 8..=11 => { + 8..=12 => { let value: AuthorityV8 = closed_record(bytes)?; value.public_sources.validate()?; if i64::from(value.version) != catalog @@ -819,7 +823,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=11") + sqlx::query("PRAGMA user_version=12") .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..=11) { + if !matches!(access.authority.catalog, 7..=12) { 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..=11) { + if !matches!(access.authority.catalog, 7..=12) { 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.v11" + if request.context().payload_schema().as_str() == "radroots.seller_stock.authority.v12" { 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..=11).contains(&authority.catalog) { + if !(4..=12).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 @@ -3,6 +3,7 @@ pub(in crate::workspace) mod acceptance; pub(in crate::workspace::stock) mod backing; pub(super) mod checkpoint; mod codec; +pub(in crate::workspace) mod installation; mod mapping; mod plan; use super::*; @@ -450,7 +451,7 @@ impl Turn<'_> { access.authority.authorization, mapping.as_ref().map(|value| value.effect), )?; - let framed = if matches!(catalog, 7..=11) { + let framed = if matches!(catalog, 7..=12) { Some( super::ledger::prepare( self.crypto, @@ -864,7 +865,7 @@ pub(super) async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let (frame, request, decoded) = if matches!(catalog, 7..=11) { + let (frame, request, decoded) = if matches!(catalog, 7..=12) { 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..=11) { + if !matches!(access.authority.catalog, 9..=12) { 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 @@ -17,6 +17,17 @@ pub(in crate::workspace::stock) struct Retained { order_cipher: Vec<u8>, } impl Retained { + pub(in crate::workspace::stock) fn held_allocations( + &self, + ) -> Result<Vec<(PoolId, radroots_domain::stock::StockTicks)>, OperationError> { + let body: Body = super::super::super::closed_record(&self.frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + Ok(body + .effects + .iter() + .map(|effect| (effect.before().id(), effect.quantity())) + .collect()) + } pub fn command(&self) -> Result<CapturedOrderAcceptance, OperationError> { let body: Body = super::super::super::closed_record(&self.frame.body) .map_err(|_| OperationError::RecoveryRequired)?; @@ -73,6 +84,7 @@ impl Retained { } pub fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + installation: None, signing: None, header: self.frame.header, protected: self.frame.protected, 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..=5).contains(&family) { + if !(0..=6).contains(&family) { return Err(OperationError::RecoveryRequired); } let subject: Option<Vec<u8>> = row @@ -87,6 +87,21 @@ impl MinimumProof { ); } } + if self.multipart { + let family: i64 = sqlx::query_scalar( + "SELECT family FROM stock_operations WHERE actor=? AND operation_id=?", + ) + .bind(actor.as_slice()) + .bind(operation.as_slice()) + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if family == 6 { + hash.update( + super::installation::raw_projection(connection, &actor, &operation).await?, + ); + } + } hash_current_movements(&mut hash, connection, &actor, &operation).await?; } let actual: [u8; 32] = hash.finalize().into(); @@ -115,7 +130,7 @@ pub(super) async fn authenticate_order_absence( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - if !matches!(authority.catalog, 9..=11) { + if !matches!(authority.catalog, 9..=12) { return Err(OperationError::UnsupportedOperation); } let upper = current.revision.get(); @@ -128,10 +143,11 @@ pub(super) async fn authenticate_order_absence( id.try_into() .map_err(|_| OperationError::RecoveryRequired)?, ); - let entry = - super::super::ledger::history(connection, input, crypto, binding, authority, operation) - .await? - .ok_or(OperationError::RecoveryRequired)?; + let entry = Box::pin(super::super::ledger::history( + connection, input, crypto, binding, authority, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; if entry.header.revision.get() != revision || Some(entry.header.head) != previous { return Err(OperationError::RecoveryRequired); } @@ -171,6 +187,10 @@ pub(in crate::workspace::stock) enum IdentityTarget { operation: OperationId, expected: Option<EntryIdentity>, }, + Installation { + operation: OperationId, + expected: Option<EntryIdentity>, + }, SigningClaim { operation: OperationId, recipient: radroots_domain::PublicKey, @@ -188,7 +208,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - let multipart = matches!(authority.catalog, 7..=11); + let multipart = matches!(authority.catalog, 7..=12); let upper = current.revision.get(); let mut previous = current.head; let mut hash = history_hash(multipart); @@ -199,67 +219,70 @@ pub(in crate::workspace::stock) async fn authenticate_identity( id.try_into() .map_err(|_| OperationError::RecoveryRequired)?, ); - let (identity, predecessor, natural, signing_plan, signing_claim) = if multipart { - let entry = super::super::ledger::history( - connection, input, crypto, binding, authority, operation, - ) - .await? - .ok_or(OperationError::RecoveryRequired)?; - if entry.header.revision.get() != revision || Some(entry.header.head) != previous { - return Err(OperationError::RecoveryRequired); - } - entry.hash(&mut hash)?; - ( - EntryIdentity { - operation, - revision: entry.header.revision, - head: entry.header.head, - protected_digest: Sha256::digest(&entry.protected).into(), - }, - entry.header.previous, - if entry.header.family == super::super::ledger::Family::Consent { - entry - .header - .related_operation - .zip(entry.header.subject_grant) - } else { - None - }, - if entry.header.family == super::super::ledger::Family::SigningPlan { - entry.header.related_operation - } 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) + let (identity, predecessor, natural, signing_plan, signing_claim, installation) = + if multipart { + let entry = Box::pin(super::super::ledger::history( + connection, input, crypto, binding, authority, operation, + )) .await? .ok_or(OperationError::RecoveryRequired)?; - let checkpoint = entry.receipt.checkpoint(); - if checkpoint.revision().get() != revision || checkpoint.head() != previous { - return Err(OperationError::RecoveryRequired); - } - hash_retained(&mut hash, revision, binding, operation, &entry)?; - ( - EntryIdentity { - operation, - revision: checkpoint.revision(), - head: checkpoint.head().ok_or(OperationError::RecoveryRequired)?, - protected_digest: Sha256::digest(&entry.protected).into(), - }, - entry.previous_head, - None, - None, - None, - ) - }; + if entry.header.revision.get() != revision || Some(entry.header.head) != previous { + return Err(OperationError::RecoveryRequired); + } + entry.hash(&mut hash)?; + ( + EntryIdentity { + operation, + revision: entry.header.revision, + head: entry.header.head, + protected_digest: Sha256::digest(&entry.protected).into(), + }, + entry.header.previous, + if entry.header.family == super::super::ledger::Family::Consent { + entry + .header + .related_operation + .zip(entry.header.subject_grant) + } else { + None + }, + if entry.header.family == super::super::ledger::Family::SigningPlan { + entry.header.related_operation + } else { + None + }, + if entry.header.family == super::super::ledger::Family::SigningClaim { + entry + .signing + .map(|value| (value.operation, value.recipient)) + } else { + None + }, + entry.installation.map(|value| value.operation), + ) + } else { + let entry = read_operation(connection, input, crypto, binding, operation) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let checkpoint = entry.receipt.checkpoint(); + if checkpoint.revision().get() != revision || checkpoint.head() != previous { + return Err(OperationError::RecoveryRequired); + } + hash_retained(&mut hash, revision, binding, operation, &entry)?; + ( + EntryIdentity { + operation, + revision: checkpoint.revision(), + head: checkpoint.head().ok_or(OperationError::RecoveryRequired)?, + protected_digest: Sha256::digest(&entry.protected).into(), + }, + entry.previous_head, + None, + None, + None, + None, + ) + }; let (matched, expected) = match &target { IdentityTarget::Operation(wanted, expected) => (*wanted == operation, *expected), IdentityTarget::Consent { @@ -271,6 +294,10 @@ pub(in crate::workspace::stock) async fn authenticate_identity( operation: wanted, expected, } => (signing_plan == Some(*wanted), *expected), + IdentityTarget::Installation { + operation: wanted, + expected, + } => (installation == Some(*wanted), *expected), IdentityTarget::SigningClaim { operation: wanted, recipient, @@ -294,7 +321,8 @@ pub(in crate::workspace::stock) async fn authenticate_identity( IdentityTarget::Operation(_, expected) | IdentityTarget::Consent { expected, .. } | IdentityTarget::SigningPlan { expected, .. } - | IdentityTarget::SigningClaim { expected, .. } => expected, + | IdentityTarget::SigningClaim { expected, .. } + | IdentityTarget::Installation { expected, .. } => expected, }; if previous.is_some() || expected.is_some() { return Err(OperationError::RecoveryRequired); @@ -325,7 +353,7 @@ pub(in crate::workspace::stock) async fn authenticate_minimum( } let lower = minimum.revision().get().max(1); let upper = current.revision.get(); - let multipart = matches!(authority.catalog, 7..=11); + let multipart = matches!(authority.catalog, 7..=12); let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { @@ -336,9 +364,9 @@ pub(in crate::workspace::stock) async fn authenticate_minimum( .map_err(|_| OperationError::RecoveryRequired)?, ); if multipart { - let retained = super::super::ledger::history( + let retained = Box::pin(super::super::ledger::history( connection, input, crypto, binding, authority, operation, - ) + )) .await? .ok_or(OperationError::RecoveryRequired)?; if retained.header.revision.get() != revision || Some(retained.header.head) != expected @@ -573,7 +601,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..=11); + let multipart = matches!(authority.catalog, 7..=12); 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)?; @@ -582,9 +610,9 @@ async fn authenticate_projected( .map_err(|_| OperationError::RecoveryRequired)?, ); if multipart { - let retained = super::super::ledger::history( + let retained = Box::pin(super::super::ledger::history( connection, input, crypto, binding, authority, operation, - ) + )) .await? .ok_or(OperationError::RecoveryRequired)?; if retained.header.revision.get() != revision || Some(retained.header.head) != expected 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..=11) { + if matches!(catalog, 5..=12) { 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..=11) { + if matches!(catalog, 5..=12) { let decoded: OperationV4<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 4 { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs @@ -0,0 +1,525 @@ +//! Initial T2 installation. Original preparation and issuance remain immutable. +use super::super::{issuance::evidence::selection, ledger, signing_plan}; +use super::*; +use checkpoint::{EntryIdentity, IdentityTarget}; +use radroots_domain::{OrderId, PublicKey, RecordId, stock::StockTicks}; +mod codec; +mod projection; +pub(in crate::workspace::stock) use codec::read_entry; +pub(in crate::workspace::stock) use projection::{Projection, raw_projection}; + +/// Captured original-operation selector; does not establish permission or evidence. +pub struct StockInstallationRequest { + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, +} +impl StockInstallationRequest { + pub const fn new( + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + operation: OperationId, + digest: CommandDigest, + ) -> Self { + Self { + binding, + minimum, + operation, + digest, + } + } + pub(in crate::workspace) fn attempt(&self) -> CommitAttempt { + CommitAttempt::new( + self.binding.input().workspace_id(), + self.operation, + self.digest, + None, + ) + } +} +impl std::fmt::Debug for StockInstallationRequest { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockInstallationRequest(<redacted>)") + } +} + +/// Immutable recipient work. An absent artifact remains waiting for original +/// issuance evidence; installation does not claim wrapping or relay delivery. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct StockPublicationWork { + recipient: PublicKey, + seal: [u8; 32], + evidence: Option<[u8; 32]>, +} +impl StockPublicationWork { + pub const fn recipient(self) -> PublicKey { + self.recipient + } + pub const fn seal_id(&self) -> &[u8; 32] { + &self.seal + } + pub const fn evidence_digest(&self) -> Option<&[u8; 32]> { + self.evidence.as_ref() + } +} +impl std::fmt::Debug for StockPublicationWork { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockPublicationWork(<redacted>)") + } +} + +/// Confirmed initial agreement and exact per-recipient work. This is business +/// installation evidence, independent of signing dispatch and delivery status. +#[derive(Clone)] +pub struct StockInstallationReceipt { + attempt: CommitAttempt, + entry: EntryIdentity, + order: OrderId, + record: RecordId, + at: UnixSeconds, + checkpoint: radroots_storage::inventory::InventoryCheckpointRef, + pools: Vec<PoolSnapshot>, + work: [StockPublicationWork; 2], +} +impl StockInstallationReceipt { + pub const fn attempt(&self) -> CommitAttempt { + self.attempt + } + pub const fn order_id(&self) -> OrderId { + self.order + } + pub const fn record_id(&self) -> RecordId { + self.record + } + pub const fn installed_at(&self) -> UnixSeconds { + self.at + } + pub const fn checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef { + self.checkpoint + } + pub fn installed_pools(&self) -> &[PoolSnapshot] { + &self.pools + } + pub const fn publication_work(&self) -> &[StockPublicationWork; 2] { + &self.work + } +} +impl std::fmt::Debug for StockInstallationReceipt { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StockInstallationReceipt(<redacted>)") + } +} +#[derive(Debug)] +pub enum StockInstallationOutcome { + Installed(Box<StockInstallationReceipt>), + Unknown(CommitAttempt), +} +#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct EvidenceRef { + entry: OperationId, + revision: Sequence, + digest: [u8; 32], +} +#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Work { + recipient: PublicKey, + intent: [u8; 32], + seal: [u8; 32], + #[serde(deserialize_with = "super::required_nullable")] + evidence: Option<EvidenceRef>, +} +#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Effect { + before: PoolSnapshot, + after: PoolSnapshot, + quantity: StockTicks, + movement: [u8; 32], +} +fn after(before: PoolSnapshot, quantity: StockTicks) -> Result<PoolSnapshot, OperationError> { + let balances = before + .balances() + .install_preparatory(quantity) + .map_err(|_| OperationError::RecoveryRequired)?; + let version = Sequence::new( + before + .version() + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + Ok(PoolSnapshot::new( + before.id(), + before.unit(), + balances, + version, + )) +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Body { + version: u8, + operation: OperationId, + plan_entry: OperationId, + plan_head: CheckpointDigest, + record: RecordId, + installed_at: UnixSeconds, + authorization: radroots_storage::workspace::seller_stock::StockAuthorizationRef, + effects: Vec<Effect>, + work: [Work; 2], +} +pub(in crate::workspace::stock) async fn existing( + turn: &mut Turn<'_>, + auth: &signing_plan::Authorized, + operation: OperationId, +) -> Result<(Option<codec::Retained>, MinimumProof), OperationError> { + let id: Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_agreements WHERE actor=? AND operation_id=?").bind(turn.selected.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let retained = match id { + Some(id) => Some( + Box::pin(read_entry( + turn.connection, + turn.selected, + turn.crypto, + OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ), + )) + .await? + .ok_or(OperationError::RecoveryRequired)?, + ), + None => None, + }; + let proof = checkpoint::authenticate_identity( + turn.connection, + turn.selected, + turn.crypto, + &auth.access.current, + &auth.access.authority, + IdentityTarget::Installation { + operation, + expected: retained.as_ref().map(|value| value.receipt.entry), + }, + ) + .await?; + Ok((retained, proof)) +} +pub(in crate::workspace) async fn install( + turn: &mut Turn<'_>, + request: StockInstallationRequest, + proof: AttachmentProof, +) -> Result<StockInstallationOutcome, OperationError> { + let auth = Box::pin(signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + )) + .await?; + if auth.access.authority.catalog != 12 { + return Err(OperationError::UnsupportedOperation); + } + let (old, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; + if let Some(old) = old { + Box::pin(confirm_read(turn, &auth, &identity, Some(&old), &proof)).await?; + return Ok(StockInstallationOutcome::Installed(Box::new(old.receipt))); + } + let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; + let recipients = *plan.bound.preparation().rumor().recipients(); + let mut selections = Vec::with_capacity(2); + let mut work = Vec::with_capacity(2); + let mut peer = false; + for (index, recipient) in recipients.into_iter().enumerate() { + let summary = selection::Summary::read( + turn.connection, + turn.selected.participant(), + request.operation, + recipient, + ) + .await?; + let selected = if let Some(selected) = summary.first { + let obtained = Box::pin(selection::open( + turn.connection, + turn.selected, + turn.crypto, + request.operation, + recipient, + selected, + )) + .await?; + if recipient != turn.selected.participant() { + peer = true; + } + Some(EvidenceRef { + entry: obtained.frame.header.operation, + revision: obtained.frame.header.revision, + digest: selected.digest, + }) + } else { + None + }; + work.push(Work { + recipient, + intent: plan.bound.intent_digests()[index], + seal: plan.bound.plan().seals()[index].event_id(), + evidence: selected, + }); + selections.push((recipient, summary)); + } + if !peer { + return Err(OperationError::InvalidEvidence); + } + let backing = Box::pin(super::backing::read( + turn, + &auth.access, + auth.original.receipt.held_pools(), + )) + .await?; + let allocations = auth.original.held_allocations()?; + let mut originals = Vec::with_capacity(allocations.len()); + let mut effects = Vec::with_capacity(allocations.len()); + for (pool, quantity) in allocations { + let original = read_pool(turn.connection, turn.selected, turn.crypto, pool) + .await? + .ok_or(OperationError::RecoveryRequired)?; + effects.push(Effect { + before: original.pool, + after: after(original.pool, quantity)?, + quantity, + movement: super::super::super::random()?, + }); + originals.push(original); + } + let 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 transaction = TransactionId::from_bytes(super::super::super::random()?); + let entry = OperationId::from_bytes(super::super::super::random()?); + let body = Body { + version: 1, + operation: request.operation, + plan_entry: plan.frame.header.operation, + plan_head: plan.frame.header.head, + record: plan.bound.preparation().rumor().record_id(), + installed_at: auth.access.current.observed_at(), + authorization: auth + .access + .authority + .authorization + .ok_or(OperationError::RecoveryRequired)?, + effects, + work: work + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + }; + let clear = encode(&body)?; + let mut header = ledger::Header { + version: 5, + family: ledger::Family::Installation, + namespace: SellerAuthoritySelection::from_attachment(turn.selected), + actor: auth.access.current.actor(), + operation: entry, + digest: request.digest, + transaction, + revision, + previous: before.head, + head: CheckpointDigest::from_bytes([0; 32]), + pool: None, + order: Some(auth.original.receipt.order_id()), + related_operation: Some(request.operation), + subject_grant: None, + bytes: 0, + parts: 0, + body_digest: [0; 32], + }; + header.head = codec::head(&header, &clear); + let projection = Projection::new(&header, &body)?; + let head = header.head; + let framed = ledger::prepare(turn.crypto, turn.selected, header, &clear).await?; + let receipt = codec::receipt(turn.selected, &framed.header, &body, &framed.protected)?; + let mut pool_bytes = Vec::with_capacity(body.effects.len()); + let mut movement_bytes = Vec::with_capacity(body.effects.len()); + for (effect, original) in body.effects.iter().zip(&originals) { + pool_bytes.push( + turn.crypto + .seal_stock_record( + turn.selected, + "pool", + effect.after.id().as_bytes(), + &encode(&PoolWire { + version: 1, + label: original.view.label(), + pool: effect.after, + })?, + ) + .await?, + ); + movement_bytes.push( + turn.crypto + .seal_stock_record( + turn.selected, + "installation_movement", + &effect.movement, + &encode(&codec::Movement { + version: 1, + operation: entry, + digest: request.digest, + record: body.record, + effect: *effect, + })?, + ) + .await?, + ); + } + let movements = Sequence::new( + before + .movements + .get() + .checked_add(body.effects.len() as u64) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let mut next = auth.access.authority.clone(); + next.inventory = Some(InventoryCheckpoint { + revision, + head: Some(head), + movements, + ..before + }); + let root = turn + .crypto + .seal_stock_root(turn.selected, next.catalog, &next.encode()?) + .await?; + let anchor = receipt.attempt; + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let changed:Result<(),OperationError>=async { + identity.confirm(&mut tx).await?; + let current=auth.confirm(&mut tx,turn.namespace,turn.clock,&proof,false).await?; + if current.observed_at()<body.installed_at {return Err(WorkspaceError::Unavailable.into());} + for backing in &backing {backing.confirm(&mut tx).await?;} + for (recipient,summary) in &selections {summary.confirm(&mut tx,turn.selected.participant(),request.operation,*recipient).await?;} + framed.insert_record(&mut tx).await?; + projection.insert(&mut tx,turn.selected.participant(),entry).await?; + for (index,(effect,original)) in body.effects.iter().zip(&originals).enumerate() { + let changed=sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=? AND revision=? AND protected=?").bind(effect.after.version().get() as i64).bind(&pool_bytes[index]).bind(effect.before.id().as_bytes().as_slice()).bind(effect.before.version().get() as i64).bind(&original.protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if changed.rows_affected()!=1 {return Err(OperationError::StaleState);} + sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)").bind(effect.movement.as_slice()).bind(turn.selected.participant().as_bytes().as_slice()).bind(current.input().grant_id().as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(effect.before.id().as_bytes().as_slice()).bind(&movement_bytes[index]).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + } + let changed=sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?").bind(root).bind(&auth.access.root).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if changed.rows_affected()!=1 {return Err(OperationError::RecoveryRequired);}turn.namespace.validate()?;Ok(()) + }.await; + if let Err(error) = changed { + if tx.rollback().await.is_err() { + *turn.uncertain = true; + return Ok(StockInstallationOutcome::Unknown(anchor)); + } + return Err(error); + } + if tx.commit().await.is_err() { + *turn.uncertain = true; + return Ok(StockInstallationOutcome::Unknown(anchor)); + } + Ok(StockInstallationOutcome::Installed(Box::new(receipt))) +} +pub(in crate::workspace) async fn read( + turn: &mut Turn<'_>, + request: StockInstallationRequest, + proof: AttachmentProof, +) -> Result<Option<StockInstallationReceipt>, OperationError> { + let auth = Box::pin(signing_plan::load( + turn, + &request.binding, + request.minimum, + request.operation, + request.digest, + &proof, + )) + .await?; + if auth.access.authority.catalog != 12 { + return Err(OperationError::UnsupportedOperation); + } + let (retained, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; + Box::pin(confirm_read( + turn, + &auth, + &identity, + retained.as_ref(), + &proof, + )) + .await?; + Ok(retained.map(|value| value.receipt)) +} +async fn confirm_read( + turn: &mut Turn<'_>, + auth: &signing_plan::Authorized, + identity: &MinimumProof, + retained: Option<&codec::Retained>, + proof: &AttachmentProof, +) -> Result<(), OperationError> { + let mut tx = turn + .connection + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|_| OperationError::StorageFailure)?; + let result: Result<(), OperationError> = async { + identity.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); + } + result +} +impl NativeWorkspace { + pub async fn install_stock_agreement( + &self, + request: StockInstallationRequest, + proof: &AttachmentProof, + ) -> Result<StockInstallationOutcome, OperationError> { + self.worker + .install_stock_agreement( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } + pub async fn stock_agreement_installation( + &self, + request: StockInstallationRequest, + proof: &AttachmentProof, + ) -> Result<Option<StockInstallationReceipt>, OperationError> { + self.worker + .stock_agreement_installation( + request, + proof.with_secret(|bytes| AttachmentProof::from_protected_input(bytes))?, + ) + .await + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs @@ -0,0 +1,305 @@ +//! Independently reconstruct every installed effect from original T0/T1/S. +use super::*; +#[derive(Serialize, Deserialize, Eq, PartialEq)] +#[serde(deny_unknown_fields)] +pub(super) struct Movement { + pub version: u8, + pub operation: OperationId, + pub digest: CommandDigest, + pub record: RecordId, + pub effect: Effect, +} +pub(in crate::workspace::stock) struct Retained { + pub frame: ledger::Retained, + pub receipt: StockInstallationReceipt, + projection: Projection, + movements: Vec<ledger::MovementWitness>, +} +pub(super) fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest { + let mut h = Sha256::new(); + h.update(b"radroots.seller_stock.installation_chain.v1\0"); + h.update(header.namespace.workspace_id().as_bytes()); + h.update(header.namespace.authority().executor_id().as_bytes()); + h.update( + header + .namespace + .authority() + .generation() + .get() + .to_be_bytes(), + ); + h.update(header.namespace.route_digest().as_bytes()); + h.update(header.actor.participant().as_bytes()); + h.update( + header + .actor + .grant_id() + .map(|v| *v.as_bytes()) + .unwrap_or([0; 32]), + ); + h.update(header.operation.as_bytes()); + h.update(header.digest.as_bytes()); + h.update(header.transaction.as_bytes()); + h.update(header.revision.get().to_be_bytes()); + h.update([u8::from(header.previous.is_some())]); + h.update(header.previous.map(|v| *v.as_bytes()).unwrap_or([0; 32])); + h.update(Sha256::digest(body)); + CheckpointDigest::from_bytes(h.finalize().into()) +} +pub(super) fn receipt( + input: &AttachmentInput, + header: &ledger::Header, + body: &Body, + protected: &[u8], +) -> Result<StockInstallationReceipt, OperationError> { + Ok(StockInstallationReceipt { + attempt: CommitAttempt::new( + input.workspace_id(), + body.operation, + header.digest, + Some(header.transaction), + ), + entry: EntryIdentity { + operation: header.operation, + revision: header.revision, + head: header.head, + protected_digest: Sha256::digest(protected).into(), + }, + order: header.order.ok_or(OperationError::RecoveryRequired)?, + record: body.record, + at: body.installed_at, + checkpoint: radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( + input.authority(), + header.revision, + Some(header.head), + )? + .with_authorization(body.authorization), + pools: body.effects.iter().map(|value| value.after).collect(), + work: body.work.map(|value| StockPublicationWork { + recipient: value.recipient, + seal: value.seal, + evidence: value.evidence.map(|v| v.digest), + }), + }) +} +pub(in crate::workspace::stock) async fn read_entry( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + operation: OperationId, +) -> Result<Option<Retained>, OperationError> { + let Some(frame) = ledger::read(connection, input, crypto, operation).await? else { + return Ok(None); + }; + if frame.header.family != ledger::Family::Installation { + return Err(OperationError::RecoveryRequired); + } + let body: Body = super::super::super::closed_record(&frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + if body.version != 1 + || body.effects.len() > 64 + || body + .effects + .windows(2) + .any(|p| p[0].before.id() >= p[1].before.id()) + || head(&frame.header, &frame.body) != frame.header.head + { + return Err(OperationError::RecoveryRequired); + } + let plan = Box::pin(signing_plan::read_entry( + connection, + input, + crypto, + body.plan_entry, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let original = Box::pin(super::super::acceptance::codec::read( + connection, + input, + crypto, + body.operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let header = &frame.header; + if header.related_operation != Some(body.operation) + || header.order != Some(original.receipt.order_id()) + || header.actor.participant() != original.frame.header.actor.participant() + || header.digest != original.frame.header.digest + || header.revision <= plan.frame.header.revision + || plan.frame.header.head != body.plan_head + || plan.bound.plan().operation_id() != body.operation + || plan.bound.plan().command_digest() != header.digest + || plan.bound.preparation().rumor().record_id() != body.record + || body.installed_at < plan.bound.bound_at() + { + return Err(OperationError::RecoveryRequired); + } + let allocations = original.held_allocations()?; + if allocations.len() != body.effects.len() { + return Err(OperationError::RecoveryRequired); + } + for ((pool, quantity), effect) in allocations.into_iter().zip(&body.effects) { + if pool != effect.before.id() + || quantity != effect.quantity + || effect.before.version().get() == 0 + || after(effect.before, quantity)? != effect.after + { + return Err(OperationError::RecoveryRequired); + } + } + let recipients = plan.bound.preparation().rumor().recipients(); + let mut peer = false; + for (index, work) in body.work.iter().enumerate() { + if work.recipient != recipients[index] + || work.intent != plan.bound.intent_digests()[index] + || work.seal != plan.bound.plan().seals()[index].event_id() + { + return Err(OperationError::RecoveryRequired); + } + if let Some(selected) = work.evidence { + let obtained = Box::pin(selection::open( + connection, + input, + crypto, + body.operation, + work.recipient, + selection::Selected { + entry: selected.entry, + revision: selected.revision, + digest: selected.digest, + }, + )) + .await?; + if obtained.frame.header.revision >= header.revision { + return Err(OperationError::RecoveryRequired); + } + if work.recipient != input.participant() { + peer = true; + } + } + } + if !peer { + return Err(OperationError::RecoveryRequired); + } + let mut movements = Vec::with_capacity(body.effects.len()); + for effect in &body.effects { + let row=sqlx::query("SELECT actor,grant_id,operation_id,pool_id,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_movements WHERE movement_id=?").bind(effect.movement.as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let expected = [ + *header.actor.participant().as_bytes(), + *header + .actor + .grant_id() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + *header.operation.as_bytes(), + *effect.before.id().as_bytes(), + ]; + for (index, wanted) in expected.into_iter().enumerate() { + let actual: Vec<u8> = row + .try_get(index) + .map_err(|_| OperationError::RecoveryRequired)?; + if actual != wanted { + return Err(OperationError::RecoveryRequired); + } + } + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(4) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let clear = crypto + .open_stock_record(input, "installation_movement", &effect.movement, &protected) + .await?; + let movement: Movement = clear + .expose_secret(|bytes| super::super::super::closed_record(bytes)) + .map_err(|_| OperationError::RecoveryRequired)?; + if movement + != (Movement { + version: 1, + operation: header.operation, + digest: header.digest, + record: body.record, + effect: *effect, + }) + { + return Err(OperationError::RecoveryRequired); + } + movements.push(ledger::MovementWitness { + id: effect.movement, + pool: effect.before.id(), + grant: header + .actor + .grant_id() + .ok_or(OperationError::RecoveryRequired)?, + protected, + }); + } + movements.sort_by_key(|value| value.id); + if movements.windows(2).any(|pair| pair[0].id >= pair[1].id) { + return Err(OperationError::RecoveryRequired); + } + let projection = Projection::new(header, &body)?; + let receipt = receipt(input, header, &body, &frame.protected)?; + let retained = Retained { + frame, + receipt, + projection, + movements, + }; + 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(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if count != self.movements.len() as i64 { + return Err(OperationError::RecoveryRequired); + } + for movement in &self.movements { + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE movement_id=? AND actor=? AND grant_id=? AND operation_id=? AND pool_id=? AND protected=?").bind(movement.id.as_slice()).bind(self.frame.header.actor.participant().as_bytes().as_slice()).bind(movement.grant.as_bytes().as_slice()).bind(self.frame.header.operation.as_bytes().as_slice()).bind(movement.pool.as_bytes().as_slice()).bind(&movement.protected).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 1 { + return Err(OperationError::RecoveryRequired); + } + } + Ok(()) + } + pub(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: self.receipt.pools, + mapping: None, + movements: self.movements, + signing: None, + installation: Some(self.projection), + } + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation/projection.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation/projection.rs @@ -0,0 +1,120 @@ +//! Body-derived immutable agreement and complete recipient-work index witness. +use super::*; +#[derive(Clone, Copy)] +pub(in crate::workspace::stock) struct Projection { + pub operation: OperationId, + order: OrderId, + record: RecordId, + recipients: [PublicKey; 2], +} +impl Projection { + pub(super) fn new(header: &ledger::Header, body: &Body) -> Result<Self, OperationError> { + Ok(Self { + operation: body.operation, + order: header.order.ok_or(OperationError::RecoveryRequired)?, + record: body.record, + recipients: body.work.map(|value| value.recipient), + }) + } + pub(in crate::workspace::stock) fn digest( + self, + actor: PublicKey, + entry: OperationId, + ) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"radroots.seller_stock.installation_projection.v1\0"); + h.update(actor.as_bytes()); + h.update(entry.as_bytes()); + h.update(self.operation.as_bytes()); + h.update(self.order.as_bytes()); + h.update(1_u64.to_be_bytes()); + h.update(self.record.as_bytes()); + for recipient in self.recipients { + h.update(recipient.as_bytes()); + } + h.finalize().into() + } + pub(super) async fn confirm( + self, + connection: &mut SqliteConnection, + actor: PublicKey, + entry: OperationId, + ) -> Result<(), OperationError> { + if raw_projection(connection, actor.as_bytes(), entry.as_bytes()).await? + != self.digest(actor, entry) + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } + pub(super) async fn insert( + self, + connection: &mut SqliteConnection, + actor: PublicKey, + entry: OperationId, + ) -> Result<(), OperationError> { + sqlx::query("INSERT INTO stock_agreements(order_id,commit_sequence,actor,operation_id,entry_id,record_id) VALUES(?,1,?,?,?,?)").bind(self.order.as_bytes().as_slice()).bind(actor.as_bytes().as_slice()).bind(self.operation.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(self.record.as_bytes().as_slice()).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + for recipient in self.recipients { + sqlx::query("INSERT INTO stock_publication_work(actor,operation_id,recipient,installation_entry) VALUES(?,?,?,?)").bind(actor.as_bytes().as_slice()).bind(self.operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + } + Ok(()) + } +} +pub(in crate::workspace::stock) async fn raw_projection( + connection: &mut SqliteConnection, + actor: &[u8; 32], + entry: &[u8; 32], +) -> Result<[u8; 32], OperationError> { + let row=sqlx::query("SELECT order_id,commit_sequence,operation_id,record_id FROM stock_agreements WHERE actor=? AND entry_id=?").bind(actor.as_slice()).bind(entry.as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + let field = |index| { + let value: Vec<u8> = row + .try_get(index) + .map_err(|_| OperationError::RecoveryRequired)?; + value + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + let sequence: i64 = row + .try_get(1) + .map_err(|_| OperationError::RecoveryRequired)?; + if sequence != 1 { + return Err(OperationError::RecoveryRequired); + } + let operation = OperationId::from_bytes(field(2)?); + let rows=sqlx::query("SELECT operation_id,recipient FROM stock_publication_work WHERE actor=? AND installation_entry=? ORDER BY recipient LIMIT 3").bind(actor.as_slice()).bind(entry.as_slice()).fetch_all(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if rows.len() != 2 { + return Err(OperationError::RecoveryRequired); + } + let mut recipients = Vec::with_capacity(2); + for row in rows { + let value: Vec<u8> = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + if value != operation.as_bytes() { + return Err(OperationError::RecoveryRequired); + } + let value: Vec<u8> = row + .try_get(1) + .map_err(|_| OperationError::RecoveryRequired)?; + recipients.push( + PublicKey::from_bytes( + value + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ) + .map_err(|_| OperationError::RecoveryRequired)?, + ); + } + let projection = Projection { + operation, + order: OrderId::from_bytes(field(0)?), + record: RecordId::from_bytes(field(3)?), + recipients: recipients + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + }; + Ok(projection.digest( + PublicKey::from_bytes(*actor).map_err(|_| OperationError::RecoveryRequired)?, + OperationId::from_bytes(*entry), + )) +} 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..=11).contains(&access.authority.catalog) { + if !(5..=12).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..=11 => Ok(2), + 3..=12 => 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 @@ -27,9 +27,17 @@ pub(super) async fn check_counts(connection: &mut SqliteConnection) -> Result<() 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)?; + 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(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; if claims != entries || evidence != captures { return Err(WorkspaceError::RecoveryRequired); } + if catalog >= 12 { + let (agreements, installs, work):(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM stock_agreements),(SELECT count(*) FROM stock_operations WHERE family=6),(SELECT count(*) FROM stock_publication_work)").fetch_one(connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + if agreements != installs + || work != installs.checked_mul(2).ok_or(WorkspaceError::Capacity)? + { + 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 @@ -256,7 +256,7 @@ pub(in crate::workspace) async fn claim( &proof, ) .await?; - if auth.access.authority.catalog != 11 { + if auth.access.authority.catalog < 11 { return Err(OperationError::UnsupportedOperation); } let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; @@ -415,7 +415,7 @@ pub(in crate::workspace) async fn read( &proof, ) .await?; - if auth.access.authority.catalog != 11 { + if auth.access.authority.catalog < 11 { return Err(OperationError::UnsupportedOperation); } let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim/codec.rs @@ -142,6 +142,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + installation: None, header: self.frame.header, protected: self.frame.protected, parts_witness: self.frame.parts_witness, diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/evidence.rs b/crates/storage_sqlite/src/workspace/stock/issuance/evidence.rs @@ -169,7 +169,7 @@ pub(in crate::workspace) async fn page( &proof, ) .await?; - if auth.access.authority.catalog != 11 { + if auth.access.authority.catalog < 11 { return Err(OperationError::UnsupportedOperation); } let minimum = InventoryCheckpointRef::from_host_metadata( @@ -262,7 +262,7 @@ pub(in crate::workspace) async fn capture( } let (authority, record, root, grant) = super::super::read(turn.connection, input, turn.crypto).await?; - if authority.catalog != 11 { + if authority.catalog < 11 { return Err(OperationError::UnsupportedOperation); } record.authenticate_retained_capture(input, &proof)?; @@ -456,7 +456,7 @@ pub(in crate::workspace) async fn read( &proof, ) .await?; - if auth.access.authority.catalog != 11 { + if auth.access.authority.catalog < 11 { return Err(OperationError::UnsupportedOperation); } let claim = claim::existing(turn, &auth, request.operation, request.recipient).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 @@ -200,6 +200,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + installation: None, header: self.frame.header, protected: self.frame.protected, parts_witness: self.frame.parts_witness, diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -21,6 +21,7 @@ pub(super) enum Family { SigningPlan, SigningClaim, SigningEvidence, + Installation, } #[derive(Serialize, Deserialize)] @@ -73,6 +74,7 @@ impl Header { | Family::SigningPlan | Family::SigningClaim | Family::SigningEvidence + | Family::Installation ) != self.related_operation.is_some() || (self.family == Family::Consent) != self.subject_grant.is_some() || self.bytes == 0 @@ -325,6 +327,7 @@ impl Family { Self::SigningPlan => 3, Self::SigningClaim => 4, Self::SigningEvidence => 5, + Self::Installation => 6, } } } @@ -439,6 +442,7 @@ pub(super) struct HistoryEntry { pub mapping: Option<radroots_domain::stock::OptionPoolMapping>, pub movements: Vec<MovementWitness>, pub signing: Option<super::issuance::Projection>, + pub installation: Option<super::inventory::installation::Projection>, } pub(super) async fn history( connection: &mut SqliteConnection, @@ -458,10 +462,11 @@ pub(super) async fn history( match family { None => Ok(None), Some(0) => { - let retained = - super::inventory::read_operation(connection, input, crypto, binding, operation) - .await? - .ok_or(OperationError::RecoveryRequired)?; + let retained = Box::pin(super::inventory::read_operation( + connection, input, crypto, binding, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; let (header, parts_witness) = retained.frame.ok_or(OperationError::RecoveryRequired)?; let movements = match (retained.movement, retained.movement_protected) { (Some(id), Some(protected)) => vec![MovementWitness { @@ -474,6 +479,7 @@ pub(super) async fn history( _ => return Err(OperationError::RecoveryRequired), }; Ok(Some(HistoryEntry { + installation: None, signing: None, header, protected: retained.protected, @@ -484,13 +490,13 @@ pub(super) async fn history( })) } Some(1) => { - let retained = super::consent::read( + let retained = Box::pin(super::consent::read( connection, input, crypto, authority.input.grant_id(), operation, - ) + )) .await? .ok_or(OperationError::RecoveryRequired)?; let count: i64 = sqlx::query_scalar( @@ -505,6 +511,7 @@ pub(super) async fn history( return Err(OperationError::RecoveryRequired); } Ok(Some(HistoryEntry { + installation: None, signing: None, header: retained.frame.header, protected: retained.frame.protected, @@ -514,20 +521,24 @@ pub(super) async fn history( movements: vec![], })) } - 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) if matches!(authority.catalog, 9..=12) => Ok(Some( + Box::pin(super::inventory::acceptance::codec::read( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), )), Some(2) => Err(OperationError::UnsupportedOperation), - Some(3) if matches!(authority.catalog, 10 | 11) => { - let retained = super::signing_plan::read_entry(connection, input, crypto, operation) - .await? - .ok_or(OperationError::RecoveryRequired)?; + Some(3) if matches!(authority.catalog, 10..=12) => { + let retained = Box::pin(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( + Some(4) if authority.catalog >= 11 => Ok(Some( Box::pin(super::issuance::read_entry( connection, input, crypto, operation, )) @@ -535,7 +546,7 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), - Some(5) if authority.catalog == 11 => Ok(Some( + Some(5) if authority.catalog >= 11 => Ok(Some( Box::pin(super::issuance::evidence::read_entry( connection, input, crypto, operation, )) @@ -543,6 +554,14 @@ pub(super) async fn history( .ok_or(OperationError::RecoveryRequired)? .into_history(), )), + Some(6) if authority.catalog == 12 => Ok(Some( + Box::pin(super::inventory::installation::read_entry( + connection, input, crypto, operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)? + .into_history(), + )), Some(_) => Err(OperationError::RecoveryRequired), } } @@ -603,6 +622,15 @@ impl HistoryEntry { (_, Some(_)) => return Err(OperationError::RecoveryRequired), (_, None) => {} } + match (header.family, self.installation) { + (Family::Installation, Some(projection)) => { + hash.update(projection.digest(header.actor.participant(), header.operation)) + } + (Family::Installation, None) | (_, 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.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 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.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 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.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); let mut pending = Box::pin( r.store .prepare_stock_acceptance(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/claim_tests.rs @@ -323,7 +323,7 @@ async fn lost_claim_observer_drains_and_reopens_as_existing_without_a_permit() { let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), @@ -400,7 +400,7 @@ async fn claim_rechecks_original_plan_projection_grant_root_and_clock_after_prov let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); let mut pending = Box::pin( r.store .claim_stock_signing_attempt(request, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/evidence_tests.rs @@ -1,5 +1,7 @@ //! Obtained-byte capture executes on the same real native stock owner. use super::*; +#[path = "installation_tests.rs"] +mod installations; #[path = "snapshot_tests.rs"] mod snapshots; use crate::workspace::{StockEvidenceCapture, StockEvidenceOutcome, StockEvidenceReceipt}; @@ -340,7 +342,7 @@ async fn lost_capture_observer_drains_owned_input_and_reopens_the_exact_original let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), @@ -428,7 +430,7 @@ async fn capture_rechecks_original_claim_plan_root_and_grant_after_provider_io() let mut rawdb = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); let mut pending = Box::pin( r.store .capture_stock_signing_evidence(&evidence, r.enrollment.proof()), diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs @@ -0,0 +1,495 @@ +//! Real T2 transactions over original T0/T1 and authenticated peer evidence. +use super::*; +use crate::workspace::{ + StockInstallationOutcome, StockInstallationReceipt, StockInstallationRequest, + StockSnapshotRequest, +}; +async fn request(r: &Rig, receipt: &StockAcceptanceReceipt) -> StockInstallationRequest { + StockInstallationRequest::new( + r.binding.clone(), + inventory_minimum(r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ) +} +async fn install( + r: &Rig, + receipt: &StockAcceptanceReceipt, +) -> Result<StockInstallationOutcome, OperationError> { + r.store + .install_stock_agreement(request(r, receipt).await, r.enrollment.proof()) + .await +} +fn installed(value: StockInstallationOutcome) -> StockInstallationReceipt { + let StockInstallationOutcome::Installed(value) = value else { + panic!("installation must confirm") + }; + *value +} +async fn retain( + r: &Rig, + receipt: &StockAcceptanceReceipt, + recipient: PublicKey, +) -> StockEvidenceReceipt { + let (report, raw) = obtained(r, receipt, recipient).await; + let captured = StockEvidenceCapture::verify(r.binding.clone(), &report, &raw, None).unwrap(); + committed( + r.store + .capture_stock_signing_evidence(&captured, r.enrollment.proof()) + .await + .unwrap(), + ) +} +fn peer(r: &Rig, receipt: &StockAcceptanceReceipt) -> PublicKey { + *receipt + .rumor() + .recipients() + .iter() + .find(|recipient| **recipient != r.enrollment.input().participant()) + .unwrap() +} +async fn balances(r: &Rig, id: u8, available: u64, preparatory: u64, committed: u64, version: u64) { + let value = r + .store + .pool( + r.binding.clone(), + inventory_minimum(r).await, + pool(id), + r.enrollment + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap(), + ) + .await + .unwrap() + .unwrap(); + let actual = value.snapshot(); + let physical = actual.balances().physical(); + assert_eq!( + ( + physical.available.get(), + physical.preparatory_hold.get(), + physical.committed_hold.get(), + actual.version().get() + ), + (available, preparatory, committed, version) + ); + assert!( + radroots_domain::stock::PoolBalances::new(actual.balances().introduced(), physical).is_ok() + ); +} +#[tokio::test] +async fn peer_only_t2_installs_original_agreement_and_two_work_items_once_across_reopen() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let peer = peer(&r, &receipt); + let evidence = retain(&r, &receipt, peer).await; + let before = inventory_minimum(&r).await; + let first = installed(install(&r, &receipt).await.unwrap()); + assert_eq!(first.record_id(), receipt.rumor().record_id()); + assert_eq!(first.order_id(), receipt.order_id()); + assert_eq!( + first.attempt().operation_id(), + receipt.attempt().operation_id() + ); + assert_eq!( + first.checkpoint().revision().get(), + before.revision().get() + 1 + ); + assert_eq!(first.publication_work().len(), 2); + for work in first.publication_work() { + assert_eq!( + work.evidence_digest(), + if work.recipient() == peer { + Some(evidence.digest()) + } else { + None + } + ); + } + assert_eq!(format!("{first:?}"), "StockInstallationReceipt(<redacted>)"); + balances(&r, 80, 9, 0, 1, 3).await; + balances(&r, 81, 8, 0, 2, 3).await; + let current = inventory_minimum(&r).await; + let again = installed(install(&r, &receipt).await.unwrap()); + assert_eq!(first.attempt(), again.attempt()); + assert_eq!(inventory_minimum(&r).await, current); + reopen_plain(&mut r).await; + let recovered = r + .store + .stock_agreement_installation(request(&r, &receipt).await, r.enrollment.proof()) + .await + .unwrap() + .unwrap(); + assert_eq!(recovered.attempt(), first.attempt()); + assert_eq!(recovered.publication_work(), first.publication_work()); + let snapshot = r + .store + .stock_operation_snapshot( + StockSnapshotRequest::new( + r.binding.clone(), + inventory_minimum(&r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ), + r.enrollment.proof(), + ) + .await + .unwrap(); + assert_eq!(snapshot.installation().unwrap().attempt(), first.attempt()); + assert!(matches!( + claim(&r, &receipt, peer).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + let mut db = database(&r).await; + for (sql, expected) in [ + ("SELECT count(*) FROM stock_agreements", 1), + ("SELECT count(*) FROM stock_publication_work", 2), + ("SELECT count(*) FROM stock_orders WHERE revision=1", 1), + ("SELECT count(*) FROM stock_operations WHERE family=6", 1), + ] { + assert_eq!( + sqlx::query_scalar::<_, i64>(sql) + .fetch_one(&mut db) + .await + .unwrap(), + expected + ); + } + db.close().await.unwrap(); + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn no_evidence_or_self_only_evidence_never_installs_or_releases_the_peer_obligation() { + let r = Rig::new().await; + let receipt = ready(&r).await; + let before = inventory_minimum(&r).await; + assert_eq!( + install(&r, &receipt).await.unwrap_err(), + OperationError::InvalidEvidence + ); + assert_eq!(inventory_minimum(&r).await, before); + retain(&r, &receipt, r.enrollment.input().participant()).await; + let before = inventory_minimum(&r).await; + assert_eq!( + install(&r, &receipt).await.unwrap_err(), + OperationError::InvalidEvidence + ); + assert_eq!(inventory_minimum(&r).await, before); + assert!( + r.store + .stock_agreement_installation(request(&r, &receipt).await, r.enrollment.proof()) + .await + .unwrap() + .is_none() + ); + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + retain(&r, &receipt, peer(&r, &receipt)).await; + let value = installed(install(&r, &receipt).await.unwrap()); + assert!( + value + .publication_work() + .iter() + .all(|value| value.evidence_digest().is_some()) + ); + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn obtained_peer_installs_after_first_issue_expiry_and_preserves_available_corrections() { + let r = Rig::new().await; + let (command, receipt) = prepared(&r).await; + bound(bind(&r, &receipt, 42).await.unwrap()); + retain(&r, &receipt, peer(&r, &receipt)).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":"available correction before installation"}})).await; + r.clock.0.store(250, Ordering::SeqCst); + assert_eq!( + install(&r, &receipt).await.unwrap_err(), + OperationError::DeadlineExceeded + ); + let child = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(r.enrollment.input()), + "recovery operator".into(), + UnixSeconds::new(290).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + assert!(matches!( + r.store + .enroll_stock_grant( + r.binding.clone(), + inventory_minimum(&r).await, + r.enrollment.proof(), + &child + ) + .await + .unwrap(), + StockGrantOutcome::Committed(_) + )); + let binding = r + .store + .authenticate(child.input().clone(), child.proof()) + .await + .unwrap(); + let consent = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + child.input().grant_id(), + StockConsentMode::RecoverOnly, + StockResources::all_pools(), + UnixSeconds::new(280).unwrap(), + CapturedOrderAcceptance::parse(command.protected_wire()).unwrap(), + ) + .unwrap(); + assert!(matches!( + r.store + .issue_stock_consent( + r.binding.clone(), + inventory_minimum(&r).await, + &consent, + r.enrollment.proof() + ) + .await + .unwrap(), + StockConsentOutcome::Committed(_) + )); + let selected = StockInstallationRequest::new( + binding, + inventory_minimum(&r).await, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ); + let first = installed( + r.store + .install_stock_agreement(selected, child.proof()) + .await + .unwrap(), + ); + assert_eq!(first.installed_at().get(), 250); + balances(&r, 80, 10, 0, 1, 4).await; + balances(&r, 81, 8, 0, 2, 3).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn explicit_future_promise_installs_without_manufacturing_physical_stock_or_movements() { + let r = Rig::new().await; + r.retain(&r.capture("listing_fixed")).await; + super::super::super::super::super::retain(&r, "request_future_promise").await; + let snapshot = inspect_named(&r, "request_future_promise").await; + let command = command_snapshot(&r, 90, false, &snapshot); + consent(&r, &command).await; + let receipt = prepare(&r, &command).await.unwrap(); + bound(bind(&r, &receipt, 42).await.unwrap()); + retain(&r, &receipt, peer(&r, &receipt)).await; + let first = installed(install(&r, &receipt).await.unwrap()); + assert!(first.installed_pools().is_empty()); + let mut db = database(&r).await; + for sql in [ + "SELECT count(*) FROM stock_pools", + "SELECT count(*) FROM stock_movements", + ] { + assert_eq!( + sqlx::query_scalar::<_, i64>(sql) + .fetch_one(&mut db) + .await + .unwrap(), + 0 + ); + } + assert_eq!( + installed(install(&r, &receipt).await.unwrap()).attempt(), + first.attempt() + ); + db.close().await.unwrap(); + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn every_t2_write_failure_rolls_back_all_pool_agreement_and_work_effects() { + for statement in [ + "CREATE TRIGGER fault BEFORE INSERT ON stock_operations WHEN NEW.family=6 BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_operation_parts WHEN (SELECT family FROM stock_operations WHERE operation_id=NEW.operation_id)=6 BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_agreements BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_publication_work WHEN (SELECT count(*) FROM stock_publication_work)=1 BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_pools WHEN OLD.pool_id=(SELECT max(pool_id) FROM stock_pools) BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE INSERT ON stock_movements BEGIN SELECT RAISE(ABORT,'fault'); END", + "CREATE TRIGGER fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'fault'); END", + ] { + let r = Rig::new().await; + let receipt = ready(&r).await; + retain(&r, &receipt, peer(&r, &receipt)).await; + let before = inventory_minimum(&r).await; + let mut db = database(&r).await; + sqlx::raw_sql(statement).execute(&mut db).await.unwrap(); + assert_eq!( + install(&r, &receipt).await.unwrap_err().code(), + "storage_failure", + "{statement}" + ); + assert_eq!(inventory_minimum(&r).await, before); + assert_pool(&r, 80, 9, 1, 2).await; + assert_pool(&r, 81, 8, 2, 2).await; + assert_eq!(sqlx::query_scalar::<_,i64>("SELECT (SELECT count(*) FROM stock_agreements)+(SELECT count(*) FROM stock_publication_work)").fetch_one(&mut db).await.unwrap(),0); + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut db) + .await + .unwrap(); + installed(install(&r, &receipt).await.unwrap()); + db.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn uncertain_t2_fences_owner_and_reopens_original_evidence_without_another_signature() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + let peer = peer(&r, &receipt); + retain(&r, &receipt, peer).await; + let selected = request(&r, &receipt).await; + let before = inventory_minimum(&r).await; + let mut db = 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_agreements BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut db).await.unwrap(); + let StockInstallationOutcome::Unknown(anchor) = r + .store + .install_stock_agreement(selected, r.enrollment.proof()) + .await + .unwrap() + else { + panic!("COMMIT must be uncertain") + }; + assert_eq!(anchor.operation_id(), receipt.attempt().operation_id()); + assert!(anchor.transaction_id().is_some()); + let stale = StockInstallationRequest::new( + r.binding.clone(), + before, + receipt.attempt().operation_id(), + receipt.attempt().command_digest(), + ); + assert_eq!( + r.store + .stock_agreement_installation(stale, 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 db) + .await + .unwrap(); + db.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); + installed(install(&r, &receipt).await.unwrap()); + assert!(matches!( + claim(&r, &receipt, peer).await.unwrap(), + StockClaimOutcome::Existing(_) + )); + balances(&r, 80, 9, 0, 1, 3).await; + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn lost_t2_observer_drains_and_reopens_one_atomic_installation() { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + retain(&r, &receipt, peer(&r, &receipt)).await; + let selected = request(&r, &receipt).await; + let provider = reopen(&mut r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + let mut pending = Box::pin( + r.store + .install_stock_agreement(selected, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + drop(pending); + provider.gate.release(); + reopen_plain(&mut r).await; + let first = r + .store + .stock_agreement_installation(request(&r, &receipt).await, r.enrollment.proof()) + .await + .unwrap() + .unwrap(); + assert_eq!( + installed(install(&r, &receipt).await.unwrap()).attempt(), + first.attempt() + ); + balances(&r, 80, 9, 0, 1, 3).await; + r.store.close().await.unwrap(); +} +#[tokio::test] +async fn late_t2_backing_or_grant_or_evidence_change_never_commits_partial_installation() { + for statement in [ + "UPDATE stock_grants SET protected=randomblob(length(protected))", + "UPDATE stock_pools SET protected=randomblob(length(protected))", + "UPDATE stock_signing_evidence SET evidence_digest=randomblob(32)", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=3", + ] { + let mut r = Rig::new().await; + let receipt = ready(&r).await; + retain(&r, &receipt, peer(&r, &receipt)).await; + let selected = request(&r, &receipt).await; + let provider = reopen(&mut r).await; + let mut db = database(&r).await; + provider + .gate + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); + let mut pending = Box::pin( + r.store + .install_stock_agreement(selected, r.enrollment.proof()), + ); + assert!(futures::poll!(pending.as_mut()).is_pending()); + provider.gate.entered(); + sqlx::raw_sql(statement).execute(&mut db).await.unwrap(); + provider.gate.release(); + assert!(pending.await.is_err(), "{statement}"); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_agreements") + .fetch_one(&mut db) + .await + .unwrap(), + 0 + ); + db.close().await.unwrap(); + r.store.close().await.unwrap(); + } +} +#[tokio::test] +async fn installed_projection_and_original_graph_damage_are_not_treated_as_fresh_absence() { + for statement in [ + "DELETE FROM stock_publication_work", + "UPDATE stock_publication_work SET recipient=randomblob(32)", + "UPDATE stock_agreements SET record_id=randomblob(32)", + "UPDATE stock_agreements SET commit_sequence=2", + "UPDATE stock_operations SET protected=randomblob(length(protected)) WHERE family=6", + "UPDATE stock_movements SET protected=randomblob(length(protected)) WHERE operation_id IN(SELECT operation_id FROM stock_operations WHERE family=6)", + "DELETE FROM stock_signing_evidence", + ] { + let r = Rig::new().await; + let receipt = ready(&r).await; + retain(&r, &receipt, peer(&r, &receipt)).await; + installed(install(&r, &receipt).await.unwrap()); + let selected = request(&r, &receipt).await; + let mut db = database(&r).await; + sqlx::raw_sql(statement).execute(&mut db).await.unwrap(); + assert!( + r.store + .stock_agreement_installation(selected, r.enrollment.proof()) + .await + .is_err(), + "{statement}" + ); + db.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 @@ -346,7 +346,7 @@ async fn dropped_t1_observer_keeps_owned_work_and_close_drains_before_original_r let provider = reopen(&mut r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 0); let mut pending = Box::pin( r.store .bind_stock_signing_intents(request, r.enrollment.proof()), @@ -400,7 +400,7 @@ async fn t1_final_permission_order_root_and_clock_witnesses_refuse_changes_after let mut raw = database(&r).await; provider .gate - .arm(Direction::Wrap, "radroots.seller_stock.authority.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 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.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 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.v11", 0); + .arm(Direction::Wrap, "radroots.seller_stock.authority.v12", 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..=11) || authority.public_sources.is_none() { + if !matches!(authority.catalog, 8..=12) || 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 = 11; +pub(super) const CURRENT: i64 = 12; 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"; @@ -15,6 +15,7 @@ const HEAD: &str = 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 OPERATIONS_V12: &str = "CREATE TABLE stock_operations (actor BLOB NOT NULL CHECK(length(actor)=32), grant_id BLOB NOT NULL REFERENCES stock_grants(grant_id), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), command_digest BLOB NOT NULL CHECK(length(command_digest)=32), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), pool_id BLOB REFERENCES stock_pools(pool_id) DEFERRABLE INITIALLY DEFERRED, revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), family INTEGER NOT NULL DEFAULT 0 CHECK(family BETWEEN 0 AND 6), order_id BLOB CHECK(order_id IS NULL OR length(order_id)=32), related_operation BLOB CHECK(related_operation IS NULL OR length(related_operation)=32), subject_grant BLOB REFERENCES stock_grants(grant_id) CHECK(subject_grant IS NULL OR length(subject_grant)=32), PRIMARY KEY(actor,grant_id,operation_id), CHECK((family=0 AND pool_id IS NOT NULL AND order_id IS NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family=1 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NOT NULL) OR (family=2 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NULL AND subject_grant IS NULL) OR (family BETWEEN 3 AND 6 AND pool_id IS NULL AND order_id IS NOT NULL AND related_operation IS NOT NULL AND subject_grant IS NULL))) STRICT, WITHOUT ROWID"; const 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, @@ -25,13 +26,15 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=11 => objects.extend([ + 2..=12 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ( "table", "stock_operations", "stock_operations", - if version >= 11 { + if version >= 12 { + OPERATIONS_V12 + } else if version >= 11 { OPERATIONS_V11 } else if version >= 10 { OPERATIONS_V10 @@ -76,7 +79,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..=11).contains(&version) { + if (6..=12).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)")); @@ -100,7 +103,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..=11) { + if matches!(version, 8..=12) { 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(( @@ -132,6 +135,28 @@ pub(super) fn objects( 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)")); } + if version >= 12 { + objects.push(("table","stock_agreements","stock_agreements","CREATE TABLE stock_agreements (order_id BLOB NOT NULL CHECK(length(order_id)=32), commit_sequence INTEGER NOT NULL CHECK(commit_sequence>0), actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), entry_id BLOB NOT NULL CHECK(length(entry_id)=32), record_id BLOB NOT NULL CHECK(length(record_id)=32), PRIMARY KEY(order_id,commit_sequence), 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_agreement_operation", + "stock_agreements", + "CREATE UNIQUE INDEX stock_agreement_operation ON stock_agreements(actor,operation_id)", + )); + objects.push(( + "index", + "stock_agreement_entry", + "stock_agreements", + "CREATE UNIQUE INDEX stock_agreement_entry ON stock_agreements(actor,entry_id)", + )); + objects.push(( + "index", + "stock_agreement_record", + "stock_agreements", + "CREATE UNIQUE INDEX stock_agreement_record ON stock_agreements(record_id)", + )); + objects.push(("table","stock_publication_work","stock_publication_work","CREATE TABLE stock_publication_work (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), recipient BLOB NOT NULL CHECK(length(recipient)=32), installation_entry BLOB NOT NULL CHECK(length(installation_entry)=32), PRIMARY KEY(actor,operation_id,recipient), FOREIGN KEY(actor,installation_entry) REFERENCES stock_operations(actor,operation_id), FOREIGN KEY(actor,operation_id) REFERENCES stock_agreements(actor,operation_id)) STRICT, WITHOUT ROWID")); + } Ok(objects) } pub(super) async fn admit(connection: &mut SqliteConnection) -> Result<i64, WorkspaceError> { diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan.rs @@ -148,12 +148,17 @@ pub(in crate::workspace::stock) async fn load( proof: &AttachmentProof, ) -> Result<Authorized, OperationError> { let access = turn.access(binding, minimum, proof).await?; - if !matches!(access.authority.catalog, 10 | 11) { + if !matches!(access.authority.catalog, 10..=12) { return Err(OperationError::UnsupportedOperation); } - let original = acceptance::codec::read(turn.connection, turn.selected, turn.crypto, operation) - .await? - .ok_or(OperationError::StaleState)?; + let original = Box::pin(acceptance::codec::read( + turn.connection, + turn.selected, + turn.crypto, + operation, + )) + .await? + .ok_or(OperationError::StaleState)?; if original.frame.header.digest != digest { return Err(OperationError::IdempotencyConflict); } diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan/codec.rs @@ -191,6 +191,7 @@ impl Retained { } pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { ledger::HistoryEntry { + installation: None, signing: None, header: self.frame.header, protected: self.frame.protected, diff --git a/crates/storage_sqlite/src/workspace/stock/snapshot.rs b/crates/storage_sqlite/src/workspace/stock/snapshot.rs @@ -108,8 +108,12 @@ pub struct StockOperationSnapshot { plan: Option<StockBoundSigningPlan>, checkpoint: InventoryCheckpointRef, recipients: [StockRecipientSnapshot; 2], + installation: Option<super::StockInstallationReceipt>, } impl StockOperationSnapshot { + pub fn installation(&self) -> Option<&super::StockInstallationReceipt> { + self.installation.as_ref() + } pub const fn preparation(&self) -> &StockAcceptanceReceipt { &self.preparation } @@ -134,16 +138,16 @@ pub(in crate::workspace) async fn read( request: StockSnapshotRequest, proof: AttachmentProof, ) -> Result<StockOperationSnapshot, OperationError> { - let auth = signing_plan::load( + let auth = Box::pin(signing_plan::load( turn, &request.binding, request.minimum, request.operation, request.digest, &proof, - ) + )) .await?; - if auth.access.authority.catalog != 11 { + if auth.access.authority.catalog < 11 { return Err(OperationError::UnsupportedOperation); } let mut reports = Vec::with_capacity(2); @@ -151,7 +155,7 @@ pub(in crate::workspace) async fn read( let mut summaries = Vec::with_capacity(2); for recipient in auth.original.receipt.rumor().recipients() { let (retained, claim_proof) = - claim::existing(turn, &auth, request.operation, *recipient).await?; + Box::pin(claim::existing(turn, &auth, request.operation, *recipient)).await?; let reference = retained.as_ref().map(|value| StockClaimReference { id: value.report.attempt_id(), transaction: value.report.transaction_id(), @@ -167,14 +171,14 @@ pub(in crate::workspace) async fn read( .await?; let first = if let Some(selected) = summary.first { Some( - selection::open( + Box::pin(selection::open( turn.connection, turn.selected, turn.crypto, request.operation, *recipient, selected, - ) + )) .await? .value .receipt(), @@ -207,6 +211,18 @@ pub(in crate::workspace) async fn read( claims.push(claim_proof); summaries.push(summary); } + let installation = if auth.access.authority.catalog == 12 { + Some( + Box::pin(super::inventory::installation::existing( + turn, + &auth, + request.operation, + )) + .await?, + ) + } else { + None + }; let before = auth .access .authority @@ -217,14 +233,14 @@ pub(in crate::workspace) async fn read( Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, None, )?; - let witness = checkpoint::authenticate_minimum( + let witness = Box::pin(checkpoint::authenticate_minimum( turn.connection, turn.selected, turn.crypto, &auth.access.current, &auth.access.authority, minimum, - ) + )) .await?; let mut tx = turn .connection @@ -233,6 +249,12 @@ pub(in crate::workspace) async fn read( .map_err(|_| OperationError::StorageFailure)?; let checked: Result<(), OperationError> = async { witness.confirm(&mut tx).await?; + if let Some((retained, identity)) = &installation { + identity.confirm(&mut tx).await?; + if let Some(retained) = retained { + retained.confirm(&mut tx).await?; + } + } for (index, report) in reports.iter().enumerate() { claims[index].confirm(&mut tx).await?; summaries[index] @@ -244,8 +266,7 @@ pub(in crate::workspace) async fn read( ) .await?; } - auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false) - .await?; + Box::pin(auth.confirm(&mut tx, turn.namespace, turn.clock, &proof, false)).await?; Ok(()) } .await; @@ -266,6 +287,7 @@ pub(in crate::workspace) async fn read( .ok_or(OperationError::RecoveryRequired)?, ); Ok(StockOperationSnapshot { + installation: installation.and_then(|(retained, _)| retained.map(|value| value.receipt)), preparation: auth.original.receipt, plan: auth.plan.map(|value| value.bound), checkpoint, 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..=11).contains(&authority.catalog) { + if !(6..=12).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..=11) { + if !matches!(access.authority.catalog, 8..=12) { 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..=11) { + if !matches!(access.authority.catalog, 8..=12) { 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(11)); + assert_eq!(schema::admit(&mut connection).await, Ok(12)); 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(), 11, &root) + .open_stock_root(enrollment.input(), 12, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 11)) + .expose_secret(|bytes| Authority::decode(bytes, 12)) .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(),11).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),12).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(),11).is_err()); + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),12).is_err()); } }); assert_eq!(authority.input, *enrollment.input()); @@ -189,7 +189,7 @@ async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_ca let caller = namespace.attachment(GrantId::from_bytes([9; 32])).unwrap(); let crypto = fixture.crypto(); let clear = b"synthetic context payload"; - for version in [4, 5, 6, 7, 8, 9, 10, 11] { + for version in [4, 5, 6, 7, 8, 9, 10, 11, 12] { let current = crypto .seal_stock_root(&owner, version, clear) .await @@ -276,8 +276,8 @@ 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); +async fn retained_v11_preserves_prior_families_and_adds_claims_and_obtained_evidence() { + assert_eq!(schema::CURRENT, 12); retained_inventory_catalog(11).await; } // Exact catalog fixtures exercise retained/successor codecs; they are not @@ -340,7 +340,7 @@ pub(super) async fn literal_catalog( if catalog >= 7 { value["inventory"]["orders"] = serde_json::json!("0"); } - if matches!(catalog, 8..=11) { + if matches!(catalog, 8..=12) { value["public_sources"] = serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); } @@ -384,6 +384,7 @@ pub(super) async fn literal_catalog( 9 => "PRAGMA user_version=9", 10 => "PRAGMA user_version=10", 11 => "PRAGMA user_version=11", + 12 => "PRAGMA user_version=12", _ => unreachable!(), }) .execute(&mut *tx) @@ -409,7 +410,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..=11) + matches!(catalog, 8..=12) ); let minimum = authority.inventory_checkpoint().unwrap(); let context = CommandContextData::new( @@ -652,7 +653,7 @@ async fn retained_inventory_catalog(catalog: i64) { .fetch_one(&mut connection) .await .unwrap(); - let old = if matches!(catalog, 7..=11) { + let old = if matches!(catalog, 7..=12) { let retained = ledger::read( &mut connection, &input, @@ -705,7 +706,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..=11) { + if part && !matches!(catalog, 7..=12) { continue; } let (authority, _, _, _) = read(&mut connection, &input, &fixture.crypto()) @@ -779,6 +780,7 @@ async fn retained_inventory_catalog(catalog: i64) { 9 => "PRAGMA user_version=8", 10 => "PRAGMA user_version=9", 11 => "PRAGMA user_version=10", + 12 => "PRAGMA user_version=11", _ => unreachable!(), }) .execute(&mut connection) @@ -905,3 +907,9 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() assert_eq!(schema::admit(&mut connection).await.unwrap(), 1); connection.close().await.unwrap(); } + +#[tokio::test] +async fn current_v12_retains_v11_and_installs_separate_agreement_and_publication_indexes() { + assert_eq!(schema::CURRENT, 12); + retained_inventory_catalog(12).await; +} diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -38,6 +38,16 @@ 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 { + InstallStockAgreement( + Box<stock::StockInstallationRequest>, + AttachmentProof, + Reply<stock::StockInstallationOutcome, OperationError>, + ), + StockAgreementInstallation( + Box<stock::StockInstallationRequest>, + AttachmentProof, + Reply<Option<stock::StockInstallationReceipt>, OperationError>, + ), StockSnapshot( Box<stock::StockSnapshotRequest>, AttachmentProof, @@ -284,6 +294,12 @@ enum Job { impl Job { fn reject_recovery(self) { match self { + Self::InstallStockAgreement(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } + Self::StockAgreementInstallation(_, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::StockSnapshot(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } @@ -565,6 +581,8 @@ impl Handle { | Job::StockEvidence(..) | Job::StockEvidencePage(..) | Job::StockSnapshot(..) + | Job::InstallStockAgreement(..) + | Job::StockAgreementInstallation(..) | Job::Revoke(..) | Job::StockAuthority(..) ) @@ -781,6 +799,46 @@ impl Handle { }; let _ = reply.send(result); } + Job::InstallStockAgreement(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::installation::install( + &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::StockAgreementInstallation(request, proof, reply) => { + let result = if kind == Kind::SellerStock { + Box::pin(stock::inventory::installation::read( + &mut stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + }, + *request, + proof, + )) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } Job::StockSnapshot(request, proof, reply) => { let result = if kind == Kind::SellerStock { Box::pin(stock::snapshot::read( @@ -1589,6 +1647,29 @@ impl Handle { ))?; result.await.unwrap_or(Ok(anchor)) } + pub(super) async fn install_stock_agreement( + &self, + request: stock::StockInstallationRequest, + proof: AttachmentProof, + ) -> Result<stock::StockInstallationOutcome, OperationError> { + let unknown = stock::StockInstallationOutcome::Unknown(request.attempt()); + let (reply, result) = oneshot::channel(); + self.send(Job::InstallStockAgreement(Box::new(request), proof, reply))?; + result.await.unwrap_or(Ok(unknown)) + } + pub(super) async fn stock_agreement_installation( + &self, + request: stock::StockInstallationRequest, + proof: AttachmentProof, + ) -> Result<Option<stock::StockInstallationReceipt>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::StockAgreementInstallation( + Box::new(request), + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn stock_operation_snapshot( &self, request: stock::StockSnapshotRequest, @@ -1777,9 +1858,11 @@ impl Handle { fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { Job::RetainStockListing(..) | Job::CaptureStockEvidence(..) => 256 * 1024, - Job::StockEvidence(..) | Job::StockEvidencePage(..) | Job::StockSnapshot(..) => { - 1024 * 1024 - } + Job::StockEvidence(..) + | Job::StockEvidencePage(..) + | Job::StockSnapshot(..) + | Job::InstallStockAgreement(..) + | Job::StockAgreementInstallation(..) => 1024 * 1024, Job::IssueStockConsent(..) | Job::PrepareStockAcceptance(..) => 512 * 1024, Job::BindStockSigningPlan(..) | Job::StockSigningPlan(..) diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -602,7 +602,7 @@ async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_c clock.release(); assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); store.close().await.unwrap(); - sqlx::query("PRAGMA user_version=11") + sqlx::query("PRAGMA user_version=12") .execute(&mut connection) .await .unwrap(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -152,6 +152,7 @@ struct NativeSellerStockAuthority { acceptance_preparation: AcceptancePreparation, signing_plan_binding: SigningPlanBinding, signing_issuance: SigningIssuance, + initial_agreement_installation: InitialAgreementInstallation, business_consent_payload_version: u16, business_consent_action: String, business_consent_modes: Vec<String>, @@ -210,6 +211,24 @@ struct AcceptancePreparation { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct InitialAgreementInstallation { + payload_version: u32, + journal_family: u32, + worker_charge_bytes: u32, + required_peer_evidence: bool, + missing_self_copy_blocks_installation: bool, + original_order_fence_immutable: bool, + exact_original_hold_quantities_required: bool, + current_exact_recovery_consent_required: bool, + atomic_pool_agreement_and_work_required: bool, + recipient_work_count: u32, + unknown_commit_fences_owner: bool, + signer_or_transport_invoked: bool, + relay_delivery_claimed: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct SigningIssuance { coherent_operation_snapshot_required: bool, final_evidence_selectors_and_page_rows_required: bool, @@ -424,10 +443,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 == 11 + && stock.schema_version == 12 && stock.retained_enrollment_versions == [1] - && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v11" + && stock.retained_inventory_versions == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v12" && stock.public_source_payload_schemas == [ "radroots.seller_stock.public_source_event.v1", @@ -529,6 +548,33 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { .signing_issuance .capture_retains_distinct_valid_encodings && !stock.signing_issuance.agreement_installed + && stock.initial_agreement_installation.payload_version == 1 + && stock.initial_agreement_installation.journal_family == 6 + && stock.initial_agreement_installation.worker_charge_bytes == 1048576 + && stock.initial_agreement_installation.required_peer_evidence + && !stock + .initial_agreement_installation + .missing_self_copy_blocks_installation + && stock + .initial_agreement_installation + .original_order_fence_immutable + && stock + .initial_agreement_installation + .exact_original_hold_quantities_required + && stock + .initial_agreement_installation + .current_exact_recovery_consent_required + && stock + .initial_agreement_installation + .atomic_pool_agreement_and_work_required + && stock.initial_agreement_installation.recipient_work_count == 2 + && stock + .initial_agreement_installation + .unknown_commit_fences_owner + && !stock + .initial_agreement_installation + .signer_or_transport_invoked + && !stock.initial_agreement_installation.relay_delivery_claimed && stock.business_consent_payload_version == 1 && stock.business_consent_action == "orders.accept" && stock.business_consent_modes == ["execute_and_recover", "recover_only"] @@ -1178,6 +1224,36 @@ mod tests { } #[test] + fn initial_installation_requires_peer_evidence_exact_conservation_and_atomic_recipient_work() { + for (field, bad) in [ + ("payload_version", json!(2)), + ("journal_family", json!(7)), + ("worker_charge_bytes", json!(1048577)), + ("required_peer_evidence", json!(false)), + ("missing_self_copy_blocks_installation", json!(true)), + ("original_order_fence_immutable", json!(false)), + ("exact_original_hold_quantities_required", json!(false)), + ("current_exact_recovery_consent_required", json!(false)), + ("atomic_pool_agreement_and_work_required", json!(false)), + ("recipient_work_count", json!(3)), + ("unknown_commit_fences_owner", json!(false)), + ("signer_or_transport_invoked", json!(true)), + ("relay_delivery_claimed", json!(true)), + ] { + assert!( + validate_bytes(&changed( + &format!( + "/native_seller_stock_authority/initial_agreement_installation/{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)),