lib

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

commit 4a3f71ef59572a9fe6beb10b43ee64a5b2c8a300
parent cc96f676e863d23a3f323a8803e3f6cc2cb38414
Author: triesap <tyson@radroots.org>
Date:   Sat, 24 Oct 2026 21:31:30 +0000

storage_sqlite: apply exact private inventory corrections

- Capture correction and spoilage with exact quantities and expected versions.
- Commit protected before-and-after effects, movements and progress together.
- Preserve retained catalogs and fence current catalog and authority snapshots.
- Verify real native and Linux failures, capacity, replay and browser boundaries.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 6++++++
Mcontracts/api_baselines/radroots_protocol.txt | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_storage.txt | 47+++++++++++++++++++++++++----------------------
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 4++--
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 7+++++--
Mcrates/domain/src/stock.rs | 46++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/tests/stock.rs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/src/command.rs | 4++++
Acrates/protocol/src/command/inventory.rs | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/src/command/stock_correction.rs | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/fixtures/pool_correction.v1.json | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/pool_correction.rs | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage/src/command.rs | 2+-
Mcrates/storage/src/inventory.rs | 54++++++++++++++++++++++++++++++++----------------------
Mcrates/storage_sqlite/README.md | 33++++++++++++++++++++++++++-------
Mcrates/storage_sqlite/src/workspace/crypto.rs | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock.rs | 53+++++++++++++++++++++++++++++++++++++----------------
Mcrates/storage_sqlite/src/workspace/stock/inventory.rs | 364++++++++++++++++++++-----------------------------------------------------------
Acrates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/inventory/codec.rs | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/src/workspace/stock/inventory/plan.rs | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/schema.rs | 4++--
Mcrates/storage_sqlite/src/workspace/stock/tests.rs | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcrates/storage_sqlite/src/workspace/worker.rs | 46++++++++++++++++++++++++----------------------
Acrates/storage_sqlite/tests/support/pool_correction.rs | 446+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/tests/support/pool_creation.rs | 116++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
Mcrates/storage_sqlite/tests/support/stock_authority.rs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/xtask/src/architecture/decision_package.rs | 10++++++++--
28 files changed, 2244 insertions(+), 422 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -161,6 +161,10 @@ pub fn radroots_domain::listing::SaleUnit::package_unspecified(&str) -> core::re impl core::fmt::Debug for radroots_domain::listing::SaleUnit pub fn radroots_domain::listing::SaleUnit::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub mod radroots_domain::stock +pub enum radroots_domain::stock::AvailableStockCorrection +pub radroots_domain::stock::AvailableStockCorrection::Add +pub radroots_domain::stock::AvailableStockCorrection::Remove +pub radroots_domain::stock::AvailableStockCorrection::Spoil #[non_exhaustive] pub enum radroots_domain::stock::StockError pub radroots_domain::stock::StockError::ConservationViolation pub radroots_domain::stock::StockError::FractionalCount @@ -170,6 +174,7 @@ pub radroots_domain::stock::StockError::OutOfRange pub radroots_domain::stock::StockError::PrecisionLoss pub radroots_domain::stock::StockError::Underflow pub radroots_domain::stock::StockError::UnitMismatch +pub radroots_domain::stock::StockError::ZeroMovement impl core::error::Error for radroots_domain::stock::StockError impl core::fmt::Display for radroots_domain::stock::StockError pub fn radroots_domain::stock::StockError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result @@ -191,6 +196,7 @@ impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::stock::PhysicalB pub fn radroots_domain::stock::PhysicalBalances::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> 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 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_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -177,6 +177,25 @@ impl core::convert::From<radroots_protocol::listing::CapturedListingCommand> for pub fn radroots_protocol::command::CapturedCommand::from(radroots_protocol::listing::CapturedListingCommand) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedCommand pub fn radroots_protocol::command::CapturedCommand::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_protocol::command::CapturedInventoryCommand +pub radroots_protocol::command::CapturedInventoryCommand::CorrectPool(radroots_protocol::command::CapturedPoolCorrection) +pub radroots_protocol::command::CapturedInventoryCommand::CreatePool(radroots_protocol::command::CapturedPoolCreation) +impl radroots_protocol::command::CapturedInventoryCommand +pub const fn radroots_protocol::command::CapturedInventoryCommand::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub const fn radroots_protocol::command::CapturedInventoryCommand::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedInventoryCommand::correction_input(&self) -> core::option::Option<&radroots_protocol::command::PoolCorrectionInput> +pub const fn radroots_protocol::command::CapturedInventoryCommand::creation_input(&self) -> core::option::Option<&radroots_protocol::command::CreatePoolInput> +pub const fn radroots_protocol::command::CapturedInventoryCommand::digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::command::CapturedInventoryCommand::kind(&self) -> radroots_protocol::command::InventoryCommandKind +pub fn radroots_protocol::command::CapturedInventoryCommand::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::CapturedInventoryCommand::pool_id(&self) -> radroots_domain::identifier::PoolId +pub fn radroots_protocol::command::CapturedInventoryCommand::protected_wire(&self) -> &[u8] +impl core::convert::From<radroots_protocol::command::CapturedPoolCorrection> for radroots_protocol::command::CapturedInventoryCommand +pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedPoolCorrection) -> Self +impl core::convert::From<radroots_protocol::command::CapturedPoolCreation> for radroots_protocol::command::CapturedInventoryCommand +pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedPoolCreation) -> Self +impl core::fmt::Debug for radroots_protocol::command::CapturedInventoryCommand +pub fn radroots_protocol::command::CapturedInventoryCommand::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub enum radroots_protocol::command::ChatKind pub radroots_protocol::command::ChatKind::Inquire pub radroots_protocol::command::ChatKind::Reply @@ -196,6 +215,11 @@ pub radroots_protocol::command::CommandKind::PublishListing pub radroots_protocol::command::CommandKind::Reply impl radroots_protocol::command::CommandKind pub const fn radroots_protocol::command::CommandKind::as_str(self) -> &'static str +pub enum radroots_protocol::command::InventoryCommandKind +pub radroots_protocol::command::InventoryCommandKind::AddStock +pub radroots_protocol::command::InventoryCommandKind::CreatePool +pub radroots_protocol::command::InventoryCommandKind::RemoveStock +pub radroots_protocol::command::InventoryCommandKind::SpoilStock pub struct radroots_protocol::command::CapturedChatCommand impl radroots_protocol::command::CapturedChatCommand pub const fn radroots_protocol::command::CapturedChatCommand::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest @@ -215,6 +239,19 @@ impl core::convert::From<radroots_protocol::command::CapturedChatCommand> for ra pub fn radroots_protocol::command::CapturedCommand::from(radroots_protocol::command::CapturedChatCommand) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedChatCommand pub fn radroots_protocol::command::CapturedChatCommand::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::command::CapturedPoolCorrection +impl radroots_protocol::command::CapturedPoolCorrection +pub const fn radroots_protocol::command::CapturedPoolCorrection::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub const fn radroots_protocol::command::CapturedPoolCorrection::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedPoolCorrection::digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::command::CapturedPoolCorrection::input(&self) -> &radroots_protocol::command::PoolCorrectionInput +pub fn radroots_protocol::command::CapturedPoolCorrection::new(radroots_domain::context::CommandContextData, radroots_protocol::command::PoolCorrectionInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::CapturedPoolCorrection::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::CapturedPoolCorrection::protected_wire(&self) -> &[u8] +impl core::convert::From<radroots_protocol::command::CapturedPoolCorrection> for radroots_protocol::command::CapturedInventoryCommand +pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedPoolCorrection) -> Self +impl core::fmt::Debug for radroots_protocol::command::CapturedPoolCorrection +pub fn radroots_protocol::command::CapturedPoolCorrection::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::CapturedPoolCreation impl radroots_protocol::command::CapturedPoolCreation pub const fn radroots_protocol::command::CapturedPoolCreation::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest @@ -224,6 +261,8 @@ pub const fn radroots_protocol::command::CapturedPoolCreation::input(&self) -> & pub fn radroots_protocol::command::CapturedPoolCreation::new(radroots_domain::context::CommandContextData, radroots_protocol::command::CreatePoolInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> pub fn radroots_protocol::command::CapturedPoolCreation::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> pub fn radroots_protocol::command::CapturedPoolCreation::protected_wire(&self) -> &[u8] +impl core::convert::From<radroots_protocol::command::CapturedPoolCreation> for radroots_protocol::command::CapturedInventoryCommand +pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedPoolCreation) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedPoolCreation pub fn radroots_protocol::command::CapturedPoolCreation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::CreatePoolInput @@ -255,6 +294,16 @@ impl core::fmt::Debug for radroots_protocol::command::ListingRevisionRef pub fn radroots_protocol::command::ListingRevisionRef::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl serde_core::ser::Serialize for radroots_protocol::command::ListingRevisionRef pub fn radroots_protocol::command::ListingRevisionRef::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +pub struct radroots_protocol::command::PoolCorrectionInput +impl radroots_protocol::command::PoolCorrectionInput +pub const fn radroots_protocol::command::PoolCorrectionInput::amount(&self) -> radroots_domain::amount::PositiveDecimal +pub const fn radroots_protocol::command::PoolCorrectionInput::expected_version(&self) -> radroots_domain::context::Sequence +pub const fn radroots_protocol::command::PoolCorrectionInput::kind(&self) -> radroots_domain::stock::AvailableStockCorrection +pub fn radroots_protocol::command::PoolCorrectionInput::new(radroots_domain::identifier::PoolId, radroots_domain::context::Sequence, radroots_domain::stock::AvailableStockCorrection, radroots_domain::amount::PositiveDecimal, &str) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::PoolCorrectionInput::pool_id(&self) -> radroots_domain::identifier::PoolId +pub fn radroots_protocol::command::PoolCorrectionInput::reason(&self) -> &str +impl core::fmt::Debug for radroots_protocol::command::PoolCorrectionInput +pub fn radroots_protocol::command::PoolCorrectionInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::ReplyInput impl radroots_protocol::command::ReplyInput pub fn radroots_protocol::command::ReplyInput::new(radroots_domain::identifier::ThreadId, radroots_identity::key::PublicKey, radroots_domain::identifier::MessageId, &str) -> core::result::Result<Self, radroots_protocol::command::CommandError> diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -1364,36 +1364,39 @@ pub fn radroots_storage::memory::MemoryStorage::source_token(&self) -> radroots_ pub fn radroots_storage::memory::MemoryStorage::status(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::status::EventStoreStatus, radroots_storage::Error>> pub type radroots_storage::event::EventCursor = radroots_storage::event::EventPosition pub mod radroots_storage::inventory -pub enum radroots_storage::inventory::PoolCreationOutcome -pub radroots_storage::inventory::PoolCreationOutcome::Committed(alloc::boxed::Box<radroots_storage::inventory::PoolCreationReceipt>) -pub radroots_storage::inventory::PoolCreationOutcome::Unknown(radroots_storage::command::CommitAttempt) -pub struct radroots_storage::inventory::CreatePoolRequest -impl radroots_storage::inventory::CreatePoolRequest -pub const fn radroots_storage::inventory::CreatePoolRequest::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding -pub const fn radroots_storage::inventory::CreatePoolRequest::command(&self) -> &radroots_protocol::command::stock::CapturedPoolCreation -pub fn radroots_storage::inventory::CreatePoolRequest::from_protected_wire(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, &[u8]) -> core::result::Result<Self, radroots_storage::command::OperationError> -pub const fn radroots_storage::inventory::CreatePoolRequest::minimum_checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef -pub fn radroots_storage::inventory::CreatePoolRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_protocol::command::stock::CapturedPoolCreation) -> core::result::Result<Self, radroots_storage::command::OperationError> -pub fn radroots_storage::inventory::CreatePoolRequest::retained_copy(&self) -> core::result::Result<Self, radroots_storage::command::OperationError> -impl core::fmt::Debug for radroots_storage::inventory::CreatePoolRequest -pub fn radroots_storage::inventory::CreatePoolRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub use radroots_storage::inventory::CapturedInventoryCommand +pub use radroots_storage::inventory::InventoryCommandKind +pub enum radroots_storage::inventory::InventoryOutcome +pub radroots_storage::inventory::InventoryOutcome::Committed(alloc::boxed::Box<radroots_storage::inventory::InventoryReceipt>) +pub radroots_storage::inventory::InventoryOutcome::Unknown(radroots_storage::command::CommitAttempt) pub struct radroots_storage::inventory::InventoryCheckpointRef impl radroots_storage::inventory::InventoryCheckpointRef pub const fn radroots_storage::inventory::InventoryCheckpointRef::authority(self) -> radroots_domain::context::AuthorityRef pub fn radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata(radroots_domain::context::AuthorityRef, radroots_domain::context::Sequence, core::option::Option<radroots_domain::identifier::CheckpointDigest>) -> core::result::Result<Self, radroots_storage::workspace::WorkspaceError> pub const fn radroots_storage::inventory::InventoryCheckpointRef::head(self) -> core::option::Option<radroots_domain::identifier::CheckpointDigest> pub const fn radroots_storage::inventory::InventoryCheckpointRef::revision(self) -> radroots_domain::context::Sequence -pub struct radroots_storage::inventory::PoolCreationReceipt -impl radroots_storage::inventory::PoolCreationReceipt -pub const fn radroots_storage::inventory::PoolCreationReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt -pub const fn radroots_storage::inventory::PoolCreationReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef -pub fn radroots_storage::inventory::PoolCreationReceipt::from_committed_store(radroots_storage::command::CommitAttempt, radroots_domain::stock::PoolSnapshot, radroots_storage::inventory::InventoryCheckpointRef) -> core::result::Result<Self, radroots_storage::command::OperationError> -pub const fn radroots_storage::inventory::PoolCreationReceipt::pool(&self) -> radroots_domain::stock::PoolSnapshot -pub const fn radroots_storage::inventory::PoolCreationReceipt::transaction_id(&self) -> core::option::Option<radroots_domain::identifier::TransactionId> +pub struct radroots_storage::inventory::InventoryReceipt +impl radroots_storage::inventory::InventoryReceipt +pub const fn radroots_storage::inventory::InventoryReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage::inventory::InventoryReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage::inventory::InventoryReceipt::from_committed_store(radroots_storage::command::CommitAttempt, radroots_protocol::command::inventory::InventoryCommandKind, radroots_domain::stock::PoolSnapshot, radroots_storage::inventory::InventoryCheckpointRef) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::InventoryReceipt::kind(&self) -> radroots_protocol::command::inventory::InventoryCommandKind +pub const fn radroots_storage::inventory::InventoryReceipt::pool(&self) -> radroots_domain::stock::PoolSnapshot +pub const fn radroots_storage::inventory::InventoryReceipt::transaction_id(&self) -> core::option::Option<radroots_domain::identifier::TransactionId> +pub struct radroots_storage::inventory::InventoryRequest +impl radroots_storage::inventory::InventoryRequest +pub const fn radroots_storage::inventory::InventoryRequest::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding +pub const fn radroots_storage::inventory::InventoryRequest::command(&self) -> &radroots_protocol::command::inventory::CapturedInventoryCommand +pub fn radroots_storage::inventory::InventoryRequest::from_protected_wire(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, &[u8]) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::InventoryRequest::minimum_checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef +pub fn radroots_storage::inventory::InventoryRequest::new(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, impl core::convert::Into<radroots_protocol::command::inventory::CapturedInventoryCommand>) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage::inventory::InventoryRequest::retained_copy(&self) -> core::result::Result<Self, radroots_storage::command::OperationError> +impl core::fmt::Debug for radroots_storage::inventory::InventoryRequest +pub fn radroots_storage::inventory::InventoryRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub trait radroots_storage::inventory::InventoryStore: radroots_storage::workspace::WorkspaceStore -pub fn radroots_storage::inventory::InventoryStore::create_pool(&self, radroots_storage::inventory::CreatePoolRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::PoolCreationOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::execute_inventory(&self, radroots_storage::inventory::InventoryRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::InventoryOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage::inventory::InventoryStore::inventory_operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::InventoryReceipt>, radroots_storage::command::OperationError>> pub fn radroots_storage::inventory::InventoryStore::pool(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::PoolId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::PoolView>, radroots_storage::command::OperationError>> -pub fn radroots_storage::inventory::InventoryStore::pool_creation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::PoolCreationReceipt>, radroots_storage::command::OperationError>> pub mod radroots_storage::journal pub use radroots_storage::journal::BoxFuture pub use radroots_storage::journal::EventId diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -398,9 +398,9 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::record_delivery_obse pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_attempt(&self, radroots_storage::command::issuance::ClaimAttemptRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::issuance::SigningAttempt>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_plan(&self, radroots_storage::workspace::WorkspaceBinding, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::command::BoundSigningPlan>, radroots_storage::command::OperationError>> impl radroots_storage::inventory::InventoryStore for radroots_storage_sqlite::workspace::NativeWorkspace -pub fn radroots_storage_sqlite::workspace::NativeWorkspace::create_pool(&self, radroots_storage::inventory::CreatePoolRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::PoolCreationOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::execute_inventory(&self, radroots_storage::inventory::InventoryRequest, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::inventory::InventoryOutcome, radroots_storage::command::OperationError>> +pub fn radroots_storage_sqlite::workspace::NativeWorkspace::inventory_operation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::InventoryReceipt>, radroots_storage::command::OperationError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::pool(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::PoolId, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::PoolView>, radroots_storage::command::OperationError>> -pub fn radroots_storage_sqlite::workspace::NativeWorkspace::pool_creation(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, core::option::Option<radroots_domain::identifier::CommandDigest>, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_storage::inventory::PoolCreationReceipt>, radroots_storage::command::OperationError>> impl radroots_storage::workspace::WorkspaceStore for radroots_storage_sqlite::workspace::NativeWorkspace pub fn radroots_storage_sqlite::workspace::NativeWorkspace::authenticate(&self, radroots_storage::workspace::AttachmentInput, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<radroots_storage::workspace::WorkspaceBinding, radroots_storage::workspace::WorkspaceError>> pub fn radroots_storage_sqlite::workspace::NativeWorkspace::close_workspace(&self) -> radroots_transport::source::BoxFuture<'_, core::result::Result<(), radroots_storage::workspace::WorkspaceError>> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -72,9 +72,12 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 2, + "schema_version": 3, "retained_enrollment_versions": [1], - "authority_payload_schema": "radroots.seller_stock.authority.v2", + "retained_inventory_versions": [2], + "authority_payload_schema": "radroots.seller_stock.authority.v3", + "inventory_operation_payload_schema": "radroots.seller_stock.operation.v2", + "inventory_movement_payload_schema": "radroots.seller_stock.movement.v2", "pool_tick_scale_explicit": true, "pool_tick_scale_encoding": "canonical_integer_string", "inventory_checkpoint_minimum_required": true, diff --git a/crates/domain/src/stock.rs b/crates/domain/src/stock.rs @@ -24,6 +24,8 @@ pub enum StockError { PrecisionLoss, /// The seven physical categories do not sum to introduced stock. ConservationViolation, + /// An audited physical movement cannot have zero quantity. + ZeroMovement, } impl fmt::Display for StockError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -38,6 +40,7 @@ impl fmt::Display for StockError { Self::ConservationViolation => { "physical stock categories do not conserve introduced stock" } + Self::ZeroMovement => "physical movement quantity must be positive", }) } } @@ -206,6 +209,17 @@ pub struct PoolBalances { introduced: StockTicks, physical: PhysicalBalances, } +/// Claimed owner-private correction of available stock. Permission, current +/// versions and any held-stock obligation policy belong to the executor. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AvailableStockCorrection { + /// Increase cumulative introduced stock and currently available backing. + Add, + /// Move currently available physical backing to cumulative removed stock. + Remove, + /// Move currently available physical backing to cumulative waste. + Spoil, +} impl PoolBalances { /// Admits only an exact sum of the seven disjoint physical categories. /// Future promises and obligation deficits cannot be counted as stock. @@ -238,6 +252,38 @@ impl PoolBalances { pub const fn physical(self) -> PhysicalBalances { self.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. + /// Failure returns no changed value and preserves the original snapshot. + pub fn correct_available( + self, + kind: AvailableStockCorrection, + quantity: StockTicks, + ) -> Result<Self, StockError> { + if quantity == StockTicks::ZERO { + return Err(StockError::ZeroMovement); + } + let mut physical = self.physical; + let introduced = match kind { + AvailableStockCorrection::Add => { + let introduced = self.introduced.checked_add(quantity)?; + physical.available = physical.available.checked_add(quantity)?; + introduced + } + AvailableStockCorrection::Remove | AvailableStockCorrection::Spoil => { + physical.available = physical.available.checked_sub(quantity)?; + let cumulative = if kind == AvailableStockCorrection::Remove { + &mut physical.removed + } else { + &mut physical.waste + }; + *cumulative = cumulative.checked_add(quantity)?; + self.introduced + } + }; + Self::new(introduced, physical) + } } impl fmt::Debug for PoolBalances { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/domain/tests/stock.rs b/crates/domain/tests/stock.rs @@ -8,6 +8,97 @@ fn ticks(value: u64) -> StockTicks { } #[test] +fn available_corrections_conserve_audited_totals_without_touching_backed_claims() { + use radroots_domain::stock::AvailableStockCorrection::{Add, Remove, Spoil}; + let original = PoolBalances::new( + ticks(100), + 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), + }, + ) + .unwrap(); + let added = original.correct_available(Add, ticks(7)).unwrap(); + assert_eq!(added.introduced(), ticks(107)); + assert_eq!( + added.physical(), + PhysicalBalances { + available: ticks(37), + ..original.physical() + } + ); + let removed = added.correct_available(Remove, ticks(11)).unwrap(); + assert_eq!(removed.introduced(), ticks(107)); + assert_eq!( + removed.physical(), + PhysicalBalances { + available: ticks(26), + removed: ticks(21), + ..original.physical() + } + ); + let wasted = removed.correct_available(Spoil, ticks(26)).unwrap(); + assert_eq!(wasted.introduced(), ticks(107)); + assert_eq!( + wasted.physical(), + PhysicalBalances { + available: StockTicks::ZERO, + removed: ticks(21), + waste: ticks(36), + ..original.physical() + } + ); + for kind in [Remove, Spoil] { + assert_eq!( + original.correct_available(kind, ticks(31)), + Err(StockError::Underflow) + ); + assert_eq!( + wasted.correct_available(kind, ticks(1)), + Err(StockError::Underflow) + ); + } + for kind in [Add, Remove, Spoil] { + assert_eq!( + original.correct_available(kind, StockTicks::ZERO), + Err(StockError::ZeroMovement) + ); + } + assert_eq!(original.physical().available, ticks(30)); +} + +#[test] +fn introduced_capacity_is_not_reused_after_removal_or_spoilage() { + use radroots_domain::stock::AvailableStockCorrection::{Add, Remove, Spoil}; + let full = PoolBalances::new( + StockTicks::MAX, + PhysicalBalances { + available: StockTicks::MAX, + ..PhysicalBalances::ZERO + }, + ) + .unwrap(); + for kind in [Remove, Spoil] { + let depleted = full.correct_available(kind, StockTicks::MAX).unwrap(); + assert_eq!(depleted.physical().available, StockTicks::ZERO); + assert_eq!(depleted.introduced(), StockTicks::MAX); + assert_eq!( + depleted.correct_available(Add, ticks(1)), + Err(StockError::OutOfRange) + ); + } + assert_eq!( + full.correct_available(Add, ticks(1)), + Err(StockError::OutOfRange) + ); +} + +#[test] fn tick_bounds_and_canonical_integer_strings_never_round_or_wrap() { for value in [ 0, diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs @@ -49,9 +49,13 @@ impl fmt::Display for CommandError { impl core::error::Error for CommandError {} mod captured; +mod inventory; mod stock; +mod stock_correction; pub use captured::{CapturedCommand, CommandKind}; +pub use inventory::{CapturedInventoryCommand, InventoryCommandKind}; pub use stock::{CapturedPoolCreation, CreatePoolInput}; +pub use stock_correction::{CapturedPoolCorrection, PoolCorrectionInput}; /// A captured public listing reference. This descriptor verifies neither its /// source event nor its availability, terms or stock backing. diff --git a/crates/protocol/src/command/inventory.rs b/crates/protocol/src/command/inventory.rs @@ -0,0 +1,118 @@ +//! Closed owner-private inventory command dispatch, without host authority. +use super::{ + CapturedPoolCorrection, CapturedPoolCreation, CommandError, check_frame, parse_object, +}; +use alloc::string::String; +use radroots_domain::{ + ApprovalIntentDigest, CommandContextData, CommandDigest, stock::AvailableStockCorrection, +}; +use serde::Deserialize; + +/// Effect class claimed by an exact captured owner-private inventory command. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum InventoryCommandKind { + /// Creation of a new fixed-unit pool. + CreatePool, + /// Positive correction of introduced stock. + AddStock, + /// Audited removal of physical stock. + RemoveStock, + /// Audited physical spoilage. + SpoilStock, +} +/// Original bounded captured inventory data. Its metadata establishes no grant, +/// physical stock, transaction completion or permission to change obligations. +pub enum CapturedInventoryCommand { + /// Original exact pool-creation profile. + CreatePool(CapturedPoolCreation), + /// Exact adjustment or spoilage profile. + CorrectPool(CapturedPoolCorrection), +} +impl CapturedInventoryCommand { + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + #[derive(Deserialize)] + struct Header { + #[serde(rename = "type")] + kind: String, + } + let header: Header = parse_object(raw)?; + match header.kind.as_str() { + "stock.create_pool" => CapturedPoolCreation::parse(raw).map(Self::CreatePool), + "stock.adjust" | "stock.spoil" => { + CapturedPoolCorrection::parse(raw).map(Self::CorrectPool) + } + _ => Err(CommandError::UnsupportedCommand), + } + } + pub const fn context(&self) -> &CommandContextData { + match self { + Self::CreatePool(v) => v.context(), + Self::CorrectPool(v) => v.context(), + } + } + pub const fn digest(&self) -> CommandDigest { + match self { + Self::CreatePool(v) => v.digest(), + Self::CorrectPool(v) => v.digest(), + } + } + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + match self { + Self::CreatePool(v) => v.approval_intent_digest(), + Self::CorrectPool(v) => v.approval_intent_digest(), + } + } + pub fn protected_wire(&self) -> &[u8] { + match self { + Self::CreatePool(v) => v.protected_wire(), + Self::CorrectPool(v) => v.protected_wire(), + } + } + pub const fn kind(&self) -> InventoryCommandKind { + match self { + Self::CreatePool(_) => InventoryCommandKind::CreatePool, + Self::CorrectPool(v) => match v.input().kind() { + AvailableStockCorrection::Add => InventoryCommandKind::AddStock, + AvailableStockCorrection::Remove => InventoryCommandKind::RemoveStock, + AvailableStockCorrection::Spoil => InventoryCommandKind::SpoilStock, + }, + } + } + /// Referenced private pool identity, without authenticating its existence. + pub const fn pool_id(&self) -> radroots_domain::PoolId { + match self { + Self::CreatePool(v) => v.input().id(), + Self::CorrectPool(v) => v.input().pool_id(), + } + } + /// Borrows actual creation data; correction commands never fabricate it. + pub const fn creation_input(&self) -> Option<&super::CreatePoolInput> { + match self { + Self::CreatePool(v) => Some(v.input()), + Self::CorrectPool(_) => None, + } + } + /// Borrows actual correction data; creation commands never fabricate it. + pub const fn correction_input(&self) -> Option<&super::PoolCorrectionInput> { + match self { + Self::CorrectPool(v) => Some(v.input()), + Self::CreatePool(_) => None, + } + } +} +impl From<CapturedPoolCreation> for CapturedInventoryCommand { + fn from(value: CapturedPoolCreation) -> Self { + Self::CreatePool(value) + } +} +impl From<CapturedPoolCorrection> for CapturedInventoryCommand { + fn from(value: CapturedPoolCorrection) -> Self { + Self::CorrectPool(value) + } +} +impl core::fmt::Debug for CapturedInventoryCommand { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("CapturedInventoryCommand(<redacted>)") + } +} diff --git a/crates/protocol/src/command/stock_correction.rs b/crates/protocol/src/command/stock_correction.rs @@ -0,0 +1,230 @@ +//! Exact owner-private correction claims, without inventory permission or effects. +use super::{COMMAND_MAX_BYTES, CommandError, Context, check_frame, hash, parse_object}; +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::fmt; +use radroots_domain::{ + ApprovalIntentDigest, CommandContextData, CommandDigest, PoolId, PositiveDecimal, Sequence, + stock::AvailableStockCorrection, +}; +use serde::{Deserialize, Serialize, ser::SerializeStruct}; +use zeroize::Zeroizing; + +/// Positive correction quantity in the referenced pool's fixed unit. Resolving +/// that unit, current version and affected obligations belongs to the executor. +pub struct PoolCorrectionInput { + pool: PoolId, + expected: Sequence, + kind: AvailableStockCorrection, + amount: PositiveDecimal, + reason: Zeroizing<String>, +} +impl PoolCorrectionInput { + pub fn new( + pool: PoolId, + expected: Sequence, + kind: AvailableStockCorrection, + amount: PositiveDecimal, + reason: &str, + ) -> Result<Self, CommandError> { + if expected.get() == 0 { + return Err(CommandError::InvalidInput); + } + if reason.len() > 4096 || reason.chars().count() > 1024 { + return Err(CommandError::LimitExceeded); + } + Ok(Self { + pool, + expected, + kind, + amount, + reason: Zeroizing::new(String::from(reason)), + }) + } + pub const fn pool_id(&self) -> PoolId { + self.pool + } + pub const fn expected_version(&self) -> Sequence { + self.expected + } + pub const fn kind(&self) -> AvailableStockCorrection { + self.kind + } + pub const fn amount(&self) -> PositiveDecimal { + self.amount + } + pub fn reason(&self) -> &str { + &self.reason + } +} +impl fmt::Debug for PoolCorrectionInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PoolCorrectionInput(<redacted>)") + } +} + +/// Complete bounded `stock.adjust` or `stock.spoil` commitment. Construction +/// acquires no host and does not authorize changes to physical backing. +pub struct CapturedPoolCorrection { + context: CommandContextData, + input: PoolCorrectionInput, + wire: Zeroizing<Box<[u8]>>, + digest: CommandDigest, + approval: ApprovalIntentDigest, +} +impl CapturedPoolCorrection { + pub fn new( + context: CommandContextData, + input: PoolCorrectionInput, + ) -> Result<Self, CommandError> { + let encode = |approval, correlation| -> Result<Zeroizing<Vec<u8>>, CommandError> { + let bytes = Zeroizing::new( + serde_json::to_vec(&Wire { + context: &context, + input: &input, + approval, + correlation, + }) + .map_err(|_| CommandError::InvalidInput)?, + ); + if bytes.len() > COMMAND_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + Ok(bytes) + }; + let wire = Zeroizing::new(Box::from(encode(true, true)?.as_slice())); + let digest = + CommandDigest::from_bytes(hash(b"radroots.command.v1\0", &encode(true, false)?)); + let approval = ApprovalIntentDigest::from_bytes(hash( + b"radroots.approval.v1\0", + &encode(false, false)?, + )); + Ok(Self { + context, + input, + wire, + digest, + approval, + }) + } + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Root<'a> { + #[serde(rename = "type")] + kind: String, + context: CommandContextData, + #[serde(borrow)] + input: &'a serde_json::value::RawValue, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Adjust { + amount: PositiveDecimal, + direction: String, + expected_version: Sequence, + pool_id: PoolId, + reason: String, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Spoil { + amount: PositiveDecimal, + expected_version: Sequence, + pool_id: PoolId, + reason: String, + } + let root: Root<'_> = parse_object(raw)?; + let input = match root.kind.as_str() { + "stock.adjust" => { + let v: Adjust = parse_object(root.input.get().as_bytes())?; + let kind = match v.direction.as_str() { + "add" => AvailableStockCorrection::Add, + "remove" => AvailableStockCorrection::Remove, + _ => return Err(CommandError::InvalidInput), + }; + PoolCorrectionInput::new(v.pool_id, v.expected_version, kind, v.amount, &v.reason)? + } + "stock.spoil" => { + let v: Spoil = parse_object(root.input.get().as_bytes())?; + PoolCorrectionInput::new( + v.pool_id, + v.expected_version, + AvailableStockCorrection::Spoil, + v.amount, + &v.reason, + )? + } + _ => return Err(CommandError::UnsupportedCommand), + }; + Self::new(root.context, input) + } + pub const fn context(&self) -> &CommandContextData { + &self.context + } + pub const fn input(&self) -> &PoolCorrectionInput { + &self.input + } + pub fn protected_wire(&self) -> &[u8] { + &self.wire + } + pub const fn digest(&self) -> CommandDigest { + self.digest + } + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + self.approval + } +} +impl fmt::Debug for CapturedPoolCorrection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedPoolCorrection(<redacted>)") + } +} +struct Wire<'a> { + context: &'a CommandContextData, + input: &'a PoolCorrectionInput, + approval: bool, + correlation: bool, +} +impl Serialize for Wire<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut object = s.serialize_struct("PoolCorrection", 3)?; + object.serialize_field( + "context", + &Context(self.context, self.approval, self.correlation), + )?; + object.serialize_field("input", &InputWire(self.input))?; + object.serialize_field( + "type", + if self.input.kind == AvailableStockCorrection::Spoil { + "stock.spoil" + } else { + "stock.adjust" + }, + )?; + object.end() + } +} +struct InputWire<'a>(&'a PoolCorrectionInput); +impl Serialize for InputWire<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let v = self.0; + let direction = match v.kind { + AvailableStockCorrection::Add => Some("add"), + AvailableStockCorrection::Remove => Some("remove"), + AvailableStockCorrection::Spoil => None, + }; + let mut object = s.serialize_struct( + "PoolCorrectionInput", + if direction.is_some() { 5 } else { 4 }, + )?; + object.serialize_field("amount", &v.amount)?; + if let Some(direction) = direction { + object.serialize_field("direction", direction)?; + } + object.serialize_field("expected_version", &v.expected)?; + object.serialize_field("pool_id", &v.pool)?; + object.serialize_field("reason", v.reason())?; + object.end() + } +} diff --git a/crates/protocol/tests/fixtures/pool_correction.v1.json b/crates/protocol/tests/fixtures/pool_correction.v1.json @@ -0,0 +1,107 @@ +{ + "provenance": "Synthetic complete correction cases. Independent Python sorted ASCII schema keys, compact UTF-8 strings and string-only exact numbers implement this RFC8785 subset, not general JCS. Exact command/approval domain prefixes include NUL. No Rust serializer or hashing helper is called.", + "oracle_python": "3.14.7 (main, Sep 29 2026, 14:50:11) [Clang 22.1.3 ]", + "cases": [ + { + "wire": { + "type": "stock.adjust", + "context": { + "actor": { + "grant_id": "0303030303030303030303030303030303030303030303030303030303030303", + "organization": null, + "participant": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "role": "seller" + }, + "approval": null, + "authority": { + "executor_id": "0202020202020202020202020202020202020202020202020202020202020202", + "generation": "1" + }, + "correlation_id": null, + "expected": null, + "not_after": "200", + "operation_id": "0707070707070707070707070707070707070707070707070707070707070707", + "route_digest": "0606060606060606060606060606060606060606060606060606060606060606", + "workspace_id": "0101010101010101010101010101010101010101010101010101010101010101" + }, + "input": { + "amount": "0.125", + "expected_version": "1", + "pool_id": "0808080808080808080808080808080808080808080808080808080808080808", + "reason": "counted 🥕\nexactly", + "direction": "add" + } + }, + "semantic_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":null,\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0707070707070707070707070707070707070707070707070707070707070707\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"amount\":\"0.125\",\"direction\":\"add\",\"expected_version\":\"1\",\"pool_id\":\"0808080808080808080808080808080808080808080808080808080808080808\",\"reason\":\"counted 🥕\\nexactly\"},\"type\":\"stock.adjust\"}", + "command_digest": "5ed1baa9b3d079d98af6bc920cd177706cb7f59387f8cecf84d26f4a02bb048f", + "approval_intent_digest": "2077afe3aa23f87ab4d80c4008c2558bd0f9437f1a29bc8ca2744bf327fb889d" + }, + { + "wire": { + "type": "stock.adjust", + "context": { + "actor": { + "grant_id": "0303030303030303030303030303030303030303030303030303030303030303", + "organization": null, + "participant": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "role": "seller" + }, + "approval": null, + "authority": { + "executor_id": "0202020202020202020202020202020202020202020202020202020202020202", + "generation": "1" + }, + "correlation_id": null, + "expected": null, + "not_after": "200", + "operation_id": "0707070707070707070707070707070707070707070707070707070707070707", + "route_digest": "0606060606060606060606060606060606060606060606060606060606060606", + "workspace_id": "0101010101010101010101010101010101010101010101010101010101010101" + }, + "input": { + "amount": "0.125", + "expected_version": "1", + "pool_id": "0808080808080808080808080808080808080808080808080808080808080808", + "reason": "counted 🥕\nexactly", + "direction": "remove" + } + }, + "semantic_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":null,\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0707070707070707070707070707070707070707070707070707070707070707\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"amount\":\"0.125\",\"direction\":\"remove\",\"expected_version\":\"1\",\"pool_id\":\"0808080808080808080808080808080808080808080808080808080808080808\",\"reason\":\"counted 🥕\\nexactly\"},\"type\":\"stock.adjust\"}", + "command_digest": "b881441b181d078638642d53cfec15933d0e21febab551951e50fb4773954761", + "approval_intent_digest": "fe748a41fd6b3230013b2d125866007c6cbc0388ec1f4917ebdcd29403c2ffec" + }, + { + "wire": { + "type": "stock.spoil", + "context": { + "actor": { + "grant_id": "0303030303030303030303030303030303030303030303030303030303030303", + "organization": null, + "participant": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "role": "seller" + }, + "approval": null, + "authority": { + "executor_id": "0202020202020202020202020202020202020202020202020202020202020202", + "generation": "1" + }, + "correlation_id": null, + "expected": null, + "not_after": "200", + "operation_id": "0707070707070707070707070707070707070707070707070707070707070707", + "route_digest": "0606060606060606060606060606060606060606060606060606060606060606", + "workspace_id": "0101010101010101010101010101010101010101010101010101010101010101" + }, + "input": { + "amount": "0.125", + "expected_version": "1", + "pool_id": "0808080808080808080808080808080808080808080808080808080808080808", + "reason": "counted 🥕\nexactly" + } + }, + "semantic_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":null,\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"expected\":null,\"not_after\":\"200\",\"operation_id\":\"0707070707070707070707070707070707070707070707070707070707070707\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"amount\":\"0.125\",\"expected_version\":\"1\",\"pool_id\":\"0808080808080808080808080808080808080808080808080808080808080808\",\"reason\":\"counted 🥕\\nexactly\"},\"type\":\"stock.spoil\"}", + "command_digest": "43a6ab75f03e70446c88765da779d9a761df5f32513c5107f372dda70d1594e8", + "approval_intent_digest": "3745ab07f5927c7033d67ffa21469cfb97bf778b35babb95da173820cb9c9b75" + } + ] +} diff --git a/crates/protocol/tests/pool_correction.rs b/crates/protocol/tests/pool_correction.rs @@ -0,0 +1,174 @@ +#![cfg(feature = "commands")] +use radroots_domain::{PoolId, PositiveDecimal, Sequence, stock::AvailableStockCorrection}; +use radroots_protocol::command::{CapturedPoolCorrection, PoolCorrectionInput}; +use serde_json::json; +fn wire(kind: &str) -> serde_json::Value { + let fixture: serde_json::Value = + serde_json::from_str(include_str!("fixtures/pool_creation.v1.json")).unwrap(); + let mut input = json!({"pool_id":"08".repeat(32),"expected_version":"1","amount":"0.125","reason":"counted during harvest"}); + if kind == "stock.adjust" { + input["direction"] = json!("add"); + } + json!({"type":kind,"context":fixture["wire"]["context"],"input":input}) +} + +#[test] +fn correction_hashes_match_independent_vectors_and_common_dispatch_retains_the_exact_family() { + use radroots_protocol::command::{CapturedInventoryCommand, InventoryCommandKind}; + let vectors: serde_json::Value = + serde_json::from_str(include_str!("fixtures/pool_correction.v1.json")).unwrap(); + for (case, kind) in vectors["cases"].as_array().unwrap().iter().zip([ + InventoryCommandKind::AddStock, + InventoryCommandKind::RemoveStock, + InventoryCommandKind::SpoilStock, + ]) { + let captured = + CapturedInventoryCommand::parse(&serde_json::to_vec(&case["wire"]).unwrap()).unwrap(); + assert_eq!( + captured.digest().to_string(), + case["command_digest"].as_str().unwrap() + ); + assert_eq!( + captured.approval_intent_digest().to_string(), + case["approval_intent_digest"].as_str().unwrap() + ); + assert_eq!(captured.kind(), kind); + assert_eq!(captured.pool_id(), PoolId::from_bytes([8; 32])); + assert!(captured.creation_input().is_none()); + assert_eq!( + captured.correction_input().unwrap().reason(), + "counted 🥕\nexactly" + ); + } + let original: serde_json::Value = + serde_json::from_str(include_str!("fixtures/pool_creation.v1.json")).unwrap(); + let created = + CapturedInventoryCommand::parse(&serde_json::to_vec(&original["wire"]).unwrap()).unwrap(); + assert_eq!(created.kind(), InventoryCommandKind::CreatePool); + assert_eq!( + created.digest().to_string(), + original["command_digest"].as_str().unwrap() + ); + assert!(created.creation_input().is_some()); + assert!(created.correction_input().is_none()); + assert!(CapturedInventoryCommand::parse(br#"{"type":"inbox.inquire"}"#).is_err()); +} +#[test] +fn adjustment_and_spoilage_capture_exact_semantics_without_unit_conversion() { + for (kind, correction) in [ + ("stock.adjust", AvailableStockCorrection::Add), + ("stock.spoil", AvailableStockCorrection::Spoil), + ] { + let raw = wire(kind); + let captured = CapturedPoolCorrection::parse(&serde_json::to_vec(&raw).unwrap()).unwrap(); + assert_eq!(captured.input().kind(), correction); + assert_eq!( + captured.input().amount(), + "0.125".parse::<PositiveDecimal>().unwrap() + ); + assert_eq!(captured.input().expected_version().get(), 1); + assert_eq!( + serde_json::from_slice::<serde_json::Value>(captured.protected_wire()).unwrap(), + raw + ); + assert_eq!( + CapturedPoolCorrection::parse(captured.protected_wire()) + .unwrap() + .digest(), + captured.digest() + ); + for (path, value) in [ + ("/input/amount", json!("0.25")), + ("/input/expected_version", json!("2")), + ("/input/pool_id", json!("09".repeat(32))), + ("/input/reason", json!("counted 🥕\nexactly")), + ] { + let mut changed = raw.clone(); + *changed.pointer_mut(path).unwrap() = value; + assert_ne!( + CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()) + .unwrap() + .digest(), + captured.digest(), + "{path}" + ); + } + } + let mut changed = wire("stock.adjust"); + changed["input"]["direction"] = json!("remove"); + let removed = CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).unwrap(); + assert_eq!(removed.input().kind(), AvailableStockCorrection::Remove); + assert_ne!( + removed.digest(), + CapturedPoolCorrection::parse(&serde_json::to_vec(&wire("stock.adjust")).unwrap()) + .unwrap() + .digest() + ); +} +#[test] +fn closed_correction_inputs_refuse_unknown_fields_numeric_values_and_zero_movements() { + for kind in ["stock.adjust", "stock.spoil"] { + let original = wire(kind); + for (path, value) in [ + ("/input/amount", json!("0")), + ("/input/amount", json!(0.125)), + ("/input/amount", json!("0.1250")), + ("/input/expected_version", json!(1)), + ("/input/expected_version", json!("0")), + ("/input/expected_version", json!("01")), + ("/input/reason", json!("🧺".repeat(1025))), + ] { + let mut changed = original.clone(); + *changed.pointer_mut(path).unwrap() = value; + assert!( + CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).is_err(), + "{path}" + ); + } + for field in ["pool_id", "expected_version", "amount", "reason"] { + let mut changed = original.clone(); + changed["input"].as_object_mut().unwrap().remove(field); + assert!( + CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).is_err(), + "{field}" + ); + } + let mut changed = original.clone(); + changed["input"]["ignored"] = json!(true); + assert!(CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).is_err()); + let mut changed = original.clone(); + changed["input"] = json!(["08".repeat(32), "1", "0.125", "reason"]); + assert!(CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).is_err()); + } + let mut changed = wire("stock.spoil"); + changed["input"]["direction"] = json!("remove"); + assert!(CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).is_err()); + let mut changed = wire("stock.adjust"); + changed["input"]["direction"] = json!("spoil"); + assert!(CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).is_err()); +} +#[test] +fn reasons_are_exact_bounded_private_text_and_diagnostic_correlation_is_excluded() { + let raw = wire("stock.adjust"); + let base = CapturedPoolCorrection::parse(&serde_json::to_vec(&raw).unwrap()).unwrap(); + let input = PoolCorrectionInput::new( + PoolId::from_bytes([8; 32]), + Sequence::new(1).unwrap(), + AvailableStockCorrection::Add, + "0.125".parse().unwrap(), + &"🧺".repeat(1024), + ) + .unwrap(); + assert_eq!(input.reason().chars().count(), 1024); + assert!(!format!("{input:?}").contains('🧺')); + let mut changed = raw.clone(); + changed["context"]["correlation_id"] = json!("display-only"); + let changed = CapturedPoolCorrection::parse(&serde_json::to_vec(&changed).unwrap()).unwrap(); + assert_eq!(changed.digest(), base.digest()); + assert_eq!( + changed.approval_intent_digest(), + base.approval_intent_digest() + ); + assert_ne!(changed.protected_wire(), base.protected_wire()); + assert!(!format!("{base:?}").contains("harvest")); +} diff --git a/crates/storage/src/command.rs b/crates/storage/src/command.rs @@ -63,7 +63,7 @@ pub enum OperationError { DeadlineExceeded, /// The retained operation identity binds a different command commitment. IdempotencyConflict, - /// The selected publication coordinate has another retained decision/head. + /// The selected state, pool version or retained decision has changed. StaleState, /// A known storage failure preceded writes or had confirmed rollback. StorageFailure, diff --git a/crates/storage/src/inventory.rs b/crates/storage/src/inventory.rs @@ -5,21 +5,22 @@ use crate::{ workspace::{AttachmentProof, WorkspaceBinding, WorkspaceScope, WorkspaceStore}, }; use radroots_domain::{CommandDigest, OperationId, PoolId, TransactionId, stock::PoolSnapshot}; -use radroots_protocol::command::CapturedPoolCreation; +pub use radroots_protocol::command::{CapturedInventoryCommand, InventoryCommandKind}; use radroots_transport::BoxFuture; -/// Exact captured owner-private creation and original authenticated observation. -pub struct CreatePoolRequest { +/// Exact captured owner-private inventory command and original authenticated observation. +pub struct InventoryRequest { binding: WorkspaceBinding, minimum: InventoryCheckpointRef, - command: CapturedPoolCreation, + command: CapturedInventoryCommand, } -impl CreatePoolRequest { +impl InventoryRequest { pub fn new( binding: WorkspaceBinding, minimum: InventoryCheckpointRef, - command: CapturedPoolCreation, + command: impl Into<CapturedInventoryCommand>, ) -> Result<Self, OperationError> { + let command = command.into(); let context = command.context(); let selection = binding.input(); if binding.scope() != WorkspaceScope::SellerStockOwner { @@ -59,7 +60,7 @@ impl CreatePoolRequest { Self::new( binding, minimum, - CapturedPoolCreation::parse(wire).map_err(|_| OperationError::RecoveryRequired)?, + CapturedInventoryCommand::parse(wire).map_err(|_| OperationError::RecoveryRequired)?, ) } /// Independently retained acknowledged minimum, never guessed from a cache. @@ -69,21 +70,21 @@ impl CreatePoolRequest { pub const fn binding(&self) -> &WorkspaceBinding { &self.binding } - pub const fn command(&self) -> &CapturedPoolCreation { + pub const fn command(&self) -> &CapturedInventoryCommand { &self.command } pub fn retained_copy(&self) -> Result<Self, OperationError> { Self::new( self.binding.clone(), self.minimum, - CapturedPoolCreation::parse(self.command.protected_wire()) + CapturedInventoryCommand::parse(self.command.protected_wire()) .map_err(|_| OperationError::RecoveryRequired)?, ) } } -impl core::fmt::Debug for CreatePoolRequest { +impl core::fmt::Debug for InventoryRequest { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str("CreatePoolRequest(<redacted>)") + f.write_str("InventoryRequest(<redacted>)") } } /// A claimed acknowledged inventory checkpoint. The trusted host must retain @@ -119,32 +120,41 @@ impl InventoryCheckpointRef { self.head } } -/// Confirmed owner-private effect, without any signature or publication claim. +/// Confirmed owner-private inventory effect, without any signature or publication claim. #[derive(Clone, Debug, Eq, PartialEq)] -pub struct PoolCreationReceipt { +pub struct InventoryReceipt { attempt: CommitAttempt, pool: PoolSnapshot, + kind: InventoryCommandKind, checkpoint: InventoryCheckpointRef, } -impl PoolCreationReceipt { +impl InventoryReceipt { /// Reconstructs only metadata. A host must confirm its actual transaction. pub fn from_committed_store( attempt: CommitAttempt, + kind: InventoryCommandKind, pool: PoolSnapshot, checkpoint: InventoryCheckpointRef, ) -> Result<Self, OperationError> { if attempt.transaction_id().is_none() - || pool.version().get() != 1 + || pool.version().get() == 0 + || (kind == InventoryCommandKind::CreatePool && pool.version().get() != 1) + || (kind != InventoryCommandKind::CreatePool && pool.version().get() < 2) || checkpoint.revision().get() == 0 { return Err(OperationError::RecoveryRequired); } Ok(Self { attempt, + kind, pool, checkpoint, }) } + /// Exact effect family retained by the original command. + pub const fn kind(&self) -> InventoryCommandKind { + self.kind + } /// Checkpoint retained by the trusted host for subsequent recovery admission. pub const fn checkpoint(&self) -> InventoryCheckpointRef { self.checkpoint @@ -161,26 +171,26 @@ impl PoolCreationReceipt { } /// Unknown completion retains the original operation/digest/transaction anchor. #[derive(Clone, Debug, Eq, PartialEq)] -pub enum PoolCreationOutcome { - Committed(Box<PoolCreationReceipt>), +pub enum InventoryOutcome { + Committed(Box<InventoryReceipt>), Unknown(CommitAttempt), } /// Native and browser hosts enforce these same atomic rules, never a memory /// success placeholder. No signing or network work occurs in these methods. pub trait InventoryStore: WorkspaceStore { - fn create_pool( + fn execute_inventory( &self, - request: CreatePoolRequest, + request: InventoryRequest, proof: AttachmentProof, - ) -> BoxFuture<'_, Result<PoolCreationOutcome, OperationError>>; - fn pool_creation( + ) -> BoxFuture<'_, Result<InventoryOutcome, OperationError>>; + fn inventory_operation( &self, binding: WorkspaceBinding, minimum: InventoryCheckpointRef, operation: OperationId, digest: Option<CommandDigest>, proof: AttachmentProof, - ) -> BoxFuture<'_, Result<Option<PoolCreationReceipt>, OperationError>>; + ) -> BoxFuture<'_, Result<Option<InventoryReceipt>, OperationError>>; fn pool( &self, binding: WorkspaceBinding, diff --git a/crates/storage_sqlite/README.md b/crates/storage_sqlite/README.md @@ -338,14 +338,17 @@ worker until close and explicit reopen. This enrollment boundary provides no pool allocation, old-order recovery, transfer, signing or business confirmation; ordinary outbox journal jobs are refused on the stock namespace. -## Owner-private pool creation +## Owner-private inventory transactions -The current stock factory creates exact catalog version2 and protected authority -payload version2. Retained enrollment-only version1 still authenticates and +The current stock factory creates exact catalog version3 and protected authority +payload version3. 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. Current operation/movement payloads use explicit +version2 codecs; retained version2 stores keep their exact version1 codecs. No namespace is automatically migrated. Ordinary outbox catalogs are separate. -`InventoryStore` admits `CreatePoolRequest` with the exact captured command, +`InventoryStore` admits `InventoryRequest` with the exact captured command, current stock-owner binding, credential and independently retained minimum inventory checkpoint. The backend verifies that minimum against its protected root and authenticated retained history before reads, replay or new writes. @@ -361,8 +364,8 @@ transfer qualification remain separate requirements. from0 through6 alongside its unit and exact `initial_quantity`. Each counts require scale0. The command digest includes precision and every semantic context field; correlation remains diagnostic. No implicit conversion or rounding occurs. -A confirmed owner-private receipt identifies the original transaction, initial -pool effect and acknowledged checkpoint. Its pool snapshot describes that +A confirmed `InventoryReceipt` identifies the exact command effect class, +original transaction, pool effect and acknowledged checkpoint. Its snapshot describes that original effect; use the current pool query for a later projection. One `BEGIN IMMEDIATE` transaction CAS-checks protected authority and grant, @@ -372,4 +375,20 @@ No signer or network work occurs. An empty pool has zero stock and no physical movement. Replay returns the original effect before fresh deadline checks. Known failures confirm rollback; unknown completion fences the owner until reopen and reconciliation by its original operation and digest. Firm holds, -allocation, correction/deficit policy, commerce and transfer are still pending. +allocation, held-stock correction/deficit policy, commerce and transfer are still pending. + +`stock.adjust` captures an explicit add/remove direction and `stock.spoil` +captures physical waste. Both retain a positive exact amount, expected pool +version and private reason. The pool's fixed unit/precision resolves exact ticks; +neither command converts or rounds. Available backing moves to cumulative waste +or removed stock; positive corrections increase cumulative introduced stock. +Depletion never frees lifetime introduced capacity or silently spends held or +quarantined backing. Held-stock depletion still needs the qualified obligation +and deficit transition; an available-stock underflow is refused. + +The same native transaction retains the original before/after projection, +command and movement, updates the exact protected pool by version/bytes CAS, +and advances protected progress. Replay reauthenticates and returns that original +effect before comparing fresh versions or deadlines. Catalog identity is +rechecked with protected snapshots inside the transaction, after provider IO. +The ordinary facade and complete commerce behavior remain in implementation. diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -169,6 +169,36 @@ impl WorkspaceCrypto { ) .await } + pub(super) async fn seal_stock_record_for_catalog( + &self, + input: &super::AttachmentInput, + kind: &str, + id: &[u8; 32], + catalog: i64, + clear: &[u8], + ) -> Result<Vec<u8>, WorkspaceError> { + self.seal_bound( + stock_record_context_for_catalog(input, kind, id, catalog)?, + PRIVATE_PAYLOAD_MAX_BYTES, + clear, + ) + .await + } + pub(super) async fn open_stock_record_for_catalog( + &self, + input: &super::AttachmentInput, + kind: &str, + id: &[u8; 32], + catalog: i64, + protected: &[u8], + ) -> Result<SecretMaterial, WorkspaceError> { + self.open_bound( + stock_record_context_for_catalog(input, kind, id, catalog)?, + PRIVATE_PAYLOAD_MAX_BYTES, + protected, + ) + .await + } pub(super) async fn seal_stock_record( &self, input: &super::AttachmentInput, @@ -682,6 +712,7 @@ fn stock_root_context( let schema = match version { 1 => "radroots.seller_stock.authority.v1", 2 => "radroots.seller_stock.authority.v2", + 3 => "radroots.seller_stock.authority.v3", _ => return Err(WorkspaceError::RecoveryRequired), }; let original = stock_context(input, true)?; @@ -726,3 +757,23 @@ fn stock_record_context( PayloadSchemaId::parse(schema).map_err(|_| WorkspaceError::InvalidInput)?, )) } + +fn stock_record_context_for_catalog( + input: &super::AttachmentInput, + kind: &str, + id: &[u8; 32], + catalog: i64, +) -> Result<EnvelopeContext, WorkspaceError> { + let original = stock_record_context(input, kind, id)?; + let schema = match (catalog, kind) { + (2, _) | (3, "pool") => return Ok(original), + (3, "operation") => "radroots.seller_stock.operation.v2", + (3, "movement") => "radroots.seller_stock.movement.v2", + _ => return Err(WorkspaceError::RecoveryRequired), + }; + Ok(EnvelopeContext::new( + original.purpose().clone(), + original.subject().clone(), + PayloadSchemaId::parse(schema).map_err(|_| WorkspaceError::RecoveryRequired)?, + )) +} diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -138,6 +138,7 @@ impl NativeWorkspace { } } struct Authority { + catalog: i64, input: AttachmentInput, transaction: TransactionId, revocation: Sequence, @@ -167,7 +168,7 @@ struct AuthorityV1 { } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] -struct AuthorityV2 { +struct InventoryAuthorityWire { version: u8, input: AttachmentInput, transaction: TransactionId, @@ -183,8 +184,8 @@ impl Authority { transaction: self.transaction, revocation: self.revocation, }), - Some(inventory) => serde_json::to_vec(&AuthorityV2 { - version: 2, + Some(inventory) => serde_json::to_vec(&InventoryAuthorityWire { + version: self.catalog as u8, input: self.input.clone(), transaction: self.transaction, revocation: self.revocation, @@ -202,19 +203,22 @@ impl Authority { return Err(WorkspaceError::RecoveryRequired); } Self { + catalog, input: v.input, transaction: v.transaction, revocation: v.revocation, inventory: None, } } - 2 => { - let v: AuthorityV2 = closed_record(bytes)?; - if v.version != 2 || (v.inventory.revision.get() == 0) != v.inventory.head.is_none() + 2 | 3 => { + let v: InventoryAuthorityWire = closed_record(bytes)?; + if i64::from(v.version) != catalog + || (v.inventory.revision.get() == 0) != v.inventory.head.is_none() { return Err(WorkspaceError::RecoveryRequired); } Self { + catalog, input: v.input, transaction: v.transaction, revocation: v.revocation, @@ -229,7 +233,7 @@ impl Authority { Ok(value) } fn version(&self) -> i64 { - if self.inventory.is_some() { 2 } else { 1 } + self.catalog } } pub(super) struct Initial { @@ -250,6 +254,7 @@ pub(super) async fn initialize( namespace.validate()?; if let Some(initial) = initial { let authority = Authority { + catalog: schema::CURRENT, input: input.clone(), transaction: initial.transaction, revocation: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?, @@ -293,7 +298,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=2") + sqlx::query("PRAGMA user_version=3") .execute(&mut *tx) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -372,7 +377,7 @@ pub(super) async fn authenticate( .map_err(|_| WorkspaceError::StorageFailure)?; let checked = async { namespace.validate()?; - unchanged(&mut tx, expected, &root, &grant).await?; + unchanged(&mut tx, expected, authority.version(), &root, &grant).await?; record.authenticate(selected, proof, clock.now()?) } .await; @@ -440,6 +445,14 @@ pub(super) async fn revoke( .await .map_err(|_| WorkspaceError::StorageFailure)?; let changed: Result<(), WorkspaceError> = async { + unchanged( + &mut tx, + expected, + authority.version(), + &old_root, + &old_grant, + ) + .await?; // Current clock and both exact protected snapshots fence the write after provider IO. record.authenticate_retained_capture(selected, proof)?; let now = clock.now()?; @@ -482,9 +495,17 @@ pub(super) async fn revoke( async fn unchanged( connection: &mut SqliteConnection, input: &AttachmentInput, + catalog: i64, root: &[u8], grant: &[u8], ) -> Result<(), WorkspaceError> { + let current: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if current != catalog { + return Err(WorkspaceError::RecoveryRequired); + } let matched: i64 = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM stock_authority WHERE singleton=1 AND protected=?) AND EXISTS(SELECT 1 FROM stock_grants WHERE grant_id=? AND protected=?)") .bind(root).bind(input.grant_id().as_bytes().as_slice()).bind(grant).fetch_one(connection).await.map_err(|_| WorkspaceError::StorageFailure)?; if matched != 1 { @@ -494,20 +515,20 @@ async fn unchanged( } impl radroots_storage::inventory::InventoryStore for NativeWorkspace { - fn create_pool( + fn execute_inventory( &self, - request: radroots_storage::inventory::CreatePoolRequest, + request: radroots_storage::inventory::InventoryRequest, proof: AttachmentProof, ) -> radroots_transport::BoxFuture< '_, Result< - radroots_storage::inventory::PoolCreationOutcome, + radroots_storage::inventory::InventoryOutcome, radroots_storage::command::OperationError, >, > { - Box::pin(self.worker.create_pool(request, proof)) + Box::pin(self.worker.execute_inventory(request, proof)) } - fn pool_creation( + fn inventory_operation( &self, binding: WorkspaceBinding, minimum: radroots_storage::inventory::InventoryCheckpointRef, @@ -517,13 +538,13 @@ impl radroots_storage::inventory::InventoryStore for NativeWorkspace { ) -> radroots_transport::BoxFuture< '_, Result< - Option<radroots_storage::inventory::PoolCreationReceipt>, + Option<radroots_storage::inventory::InventoryReceipt>, radroots_storage::command::OperationError, >, > { Box::pin( self.worker - .pool_creation(binding, minimum, operation, digest, proof), + .inventory_operation(binding, minimum, operation, digest, proof), ) } fn pool( diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -1,12 +1,18 @@ -//! Owner-private pool creation on the existing connection owner. +//! Owner-private inventory effects on the existing connection owner. +mod checkpoint; +mod codec; +mod plan; use super::*; +use checkpoint::{MinimumProof, authenticate_minimum}; +use codec::{Movement, MovementKind, OperationWire, decode_operation}; +use plan::{plan_effect, record_version}; use radroots_domain::{ CheckpointDigest, CommandDigest, OperationId, PoolId, UnixSeconds, stock::{PhysicalBalances, PoolBalances, PoolSnapshot}, }; use radroots_storage::{ command::{CommitAttempt, OperationError, protected::same_binding}, - inventory::{CreatePoolRequest, PoolCreationOutcome, PoolCreationReceipt}, + inventory::{InventoryOutcome, InventoryReceipt, InventoryRequest}, }; use serde_json::value::RawValue; use sha2::{Digest, Sha256}; @@ -107,9 +113,9 @@ impl Turn<'_> { } pub async fn create( &mut self, - request: CreatePoolRequest, + request: InventoryRequest, proof: AttachmentProof, - ) -> Result<PoolCreationOutcome, OperationError> { + ) -> Result<InventoryOutcome, OperationError> { let mut access = self .access(request.binding(), request.minimum_checkpoint(), &proof) .await?; @@ -131,7 +137,7 @@ impl Turn<'_> { } self.confirm(&access, &proof, Some(&retained), None, None, None) .await?; - return Ok(PoolCreationOutcome::Committed(Box::new(retained.receipt))); + return Ok(InventoryOutcome::Committed(Box::new(retained.receipt))); } if access.current.observed_at() < request.binding().observed_at() { return Err(WorkspaceError::Unavailable.into()); @@ -139,30 +145,30 @@ impl Turn<'_> { if access.current.observed_at() >= context.not_after() { return Err(OperationError::DeadlineExceeded); } - let input = request.command().input(); - if read_pool(self.connection, self.selected, self.crypto, input.id()) - .await? - .is_some() - { - return Err(OperationError::StaleState); + let catalog = access.authority.version(); + if catalog < 3 && request.command().correction_input().is_some() { + return Err(OperationError::UnsupportedOperation); } - let zero = - radroots_domain::Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?; - let pool = PoolSnapshot::new( - input.id(), - input.unit(), - PoolBalances::new( - input.initial_ticks(), - PhysicalBalances { - available: input.initial_ticks(), - ..PhysicalBalances::ZERO - }, - ) - .map_err(|_| OperationError::InvalidCommand)?, - zero, - ); + let existing = read_pool( + self.connection, + self.selected, + self.crypto, + request.command().pool_id(), + ) + .await?; + let before = existing.as_ref().map(|v| v.pool); + let (pool, quantity, movement_kind) = plan_effect(request.command(), before)?; + let label = if let Some(input) = request.command().creation_input() { + input.label() + } else { + existing + .as_ref() + .ok_or(OperationError::StaleState)? + .view + .label() + }; let transaction = TransactionId::from_bytes(super::super::random()?); - let movement = if input.initial_ticks() == radroots_domain::stock::StockTicks::ZERO { + let movement = if quantity == radroots_domain::stock::StockTicks::ZERO { None } else { Some(super::super::random()?) @@ -195,8 +201,9 @@ impl Turn<'_> { digest, Some(transaction), ); - let receipt = PoolCreationReceipt::from_committed_store( + let receipt = InventoryReceipt::from_committed_store( attempt, + request.command().kind(), pool, radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( self.selected.authority(), @@ -212,7 +219,7 @@ impl Turn<'_> { pool.id().as_bytes(), &encode(&PoolWire { version: 1, - label: input.label(), + label, pool, })?, ) @@ -220,17 +227,18 @@ impl Turn<'_> { let protected_movement = if let Some(id) = movement { Some( self.crypto - .seal_stock_record( + .seal_stock_record_for_catalog( self.selected, "movement", &id, + catalog, &encode(&Movement { - version: 1, + version: record_version(catalog)?, operation, digest, pool: pool.id(), - quantity: input.initial_ticks(), - kind: MovementKind::Introduced, + quantity, + kind: movement_kind, })?, ) .await?, @@ -242,12 +250,14 @@ impl Turn<'_> { .map_err(|_| OperationError::InvalidCommand)?; let protected_operation = self .crypto - .seal_stock_record( + .seal_stock_record_for_catalog( self.selected, "operation", operation.as_bytes(), + catalog, &encode(&OperationWire { - version: 1, + version: record_version(catalog)?, + before: if catalog == 3 { Some(before) } else { None }, selection: request.binding().input(), scope: request.binding().scope(), principal: request.binding().principal_id(), @@ -273,7 +283,7 @@ impl Turn<'_> { checkpoint .pools .get() - .checked_add(1) + .checked_add(u64::from(before.is_none())) .ok_or(WorkspaceError::Capacity)?, ) .map_err(|_| WorkspaceError::Capacity)?, @@ -288,7 +298,7 @@ impl Turn<'_> { }); let root = self .crypto - .seal_stock_root(self.selected, 2, &access.authority.encode()?) + .seal_stock_root(self.selected, catalog, &access.authority.encode()?) .await?; self.namespace.validate()?; let mut tx = self @@ -297,7 +307,7 @@ impl Turn<'_> { .await .map_err(|_| OperationError::StorageFailure)?; let changed:Result<(),OperationError>=async { - super::unchanged(&mut tx,self.selected,&access.root,&access.grant).await?; + super::unchanged(&mut tx,self.selected,access.authority.version(),&access.root,&access.grant).await?; check_head(&mut tx,checkpoint).await?; access.minimum_proof.confirm(&mut tx).await?; let current=access.record.authenticate(request.binding().input(),&proof,self.clock.now()?)?; @@ -307,9 +317,16 @@ impl Turn<'_> { self.namespace.validate()?; let absent:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND grant_id=? AND operation_id=?").bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; if absent!=0 {return Err(OperationError::StaleState);} - let existing:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=?").bind(pool.id().as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; - if existing!=0 {return Err(OperationError::StaleState);} - sqlx::query("INSERT INTO stock_pools(pool_id,revision,protected) VALUES(?,1,?)").bind(pool.id().as_bytes().as_slice()).bind(protected_pool).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if let Some(before)=before { + let original=existing.as_ref().ok_or(OperationError::RecoveryRequired)?; + let updated=sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=? AND revision=? AND protected=?") + .bind(pool.version().get() as i64).bind(protected_pool).bind(pool.id().as_bytes().as_slice()).bind(before.version().get() as i64).bind(&original.protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if updated.rows_affected()!=1 {return Err(OperationError::StaleState);} + } else { + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=?").bind(pool.id().as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + if count!=0 {return Err(OperationError::StaleState);} + sqlx::query("INSERT INTO stock_pools(pool_id,revision,protected) VALUES(?,?,?)").bind(pool.id().as_bytes().as_slice()).bind(pool.version().get() as i64).bind(protected_pool).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; + } sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected) VALUES(?,?,?,?,?,?,?,?,?)") .bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(digest.as_bytes().as_slice()).bind(transaction.as_bytes().as_slice()).bind(pool.id().as_bytes().as_slice()).bind(revision.get() as i64).bind(head.as_bytes().as_slice()).bind(protected_operation).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; if let (Some(id),Some(protected))=(movement,protected_movement) { @@ -321,15 +338,15 @@ impl Turn<'_> { if let Err(error) = changed { if tx.rollback().await.is_err() { *self.uncertain = true; - return Ok(PoolCreationOutcome::Unknown(attempt)); + return Ok(InventoryOutcome::Unknown(attempt)); } return Err(error); } if tx.commit().await.is_err() { *self.uncertain = true; - return Ok(PoolCreationOutcome::Unknown(attempt)); + return Ok(InventoryOutcome::Unknown(attempt)); } - Ok(PoolCreationOutcome::Committed(Box::new(receipt))) + Ok(InventoryOutcome::Committed(Box::new(receipt))) } async fn confirm( &mut self, @@ -347,7 +364,7 @@ impl Turn<'_> { .map_err(|_| OperationError::StorageFailure)?; let checked:Result<(),OperationError>=async { self.namespace.validate()?; - super::unchanged(&mut tx,self.selected,&access.root,&access.grant).await?; + super::unchanged(&mut tx,self.selected,access.authority.version(),&access.root,&access.grant).await?; check_head(&mut tx,access.authority.inventory.ok_or(OperationError::UnsupportedOperation)?).await?; access.minimum_proof.confirm(&mut tx).await?; let current=access.record.authenticate(access.current.input(),proof,self.clock.now()?)?; @@ -381,7 +398,7 @@ impl Turn<'_> { operation: OperationId, digest: Option<CommandDigest>, proof: AttachmentProof, - ) -> Result<Option<PoolCreationReceipt>, OperationError> { + ) -> Result<Option<InventoryReceipt>, OperationError> { let access = self.access(&binding, minimum, &proof).await?; let result = read_operation( self.connection, @@ -484,78 +501,11 @@ async fn read_pool( protected, })) } -#[derive(Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -enum MovementKind { - Introduced, -} -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Movement { - version: u8, - operation: OperationId, - digest: CommandDigest, - pool: PoolId, - quantity: radroots_domain::stock::StockTicks, - kind: MovementKind, -} -#[derive(Serialize)] -struct OperationWire<'a> { - version: u8, - selection: &'a AttachmentInput, - scope: WorkspaceScope, - principal: &'a str, - grant_revision: Sequence, - grant_expires_at: UnixSeconds, - observed_at: UnixSeconds, - minimum_revision: Sequence, - minimum_head: Option<CheckpointDigest>, - transaction: TransactionId, - revision: Sequence, - previous_head: Option<CheckpointDigest>, - head: CheckpointDigest, - command: &'a RawValue, - pool: PoolSnapshot, - movement: Option<[u8; 32]>, -} -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct OperationDecode<'a> { - version: u8, - selection: AttachmentInput, - scope: WorkspaceScope, - principal: String, - grant_revision: Sequence, - grant_expires_at: UnixSeconds, - observed_at: UnixSeconds, - minimum_revision: Sequence, - #[serde(deserialize_with = "super::required_nullable")] - minimum_head: Option<CheckpointDigest>, - transaction: TransactionId, - revision: Sequence, - #[serde(deserialize_with = "super::required_nullable")] - previous_head: Option<CheckpointDigest>, - head: CheckpointDigest, - #[serde(borrow)] - command: &'a RawValue, - pool: PoolSnapshot, - #[serde(deserialize_with = "super::required_nullable")] - movement: Option<[u8; 32]>, -} -struct OperationData { - version: u8, - transaction: TransactionId, - revision: Sequence, - previous_head: Option<CheckpointDigest>, - head: CheckpointDigest, - pool: PoolSnapshot, - movement: Option<[u8; 32]>, -} struct Retained { previous_head: Option<CheckpointDigest>, movement: Option<[u8; 32]>, movement_protected: Option<Vec<u8>>, - receipt: PoolCreationReceipt, + receipt: InventoryReceipt, digest: CommandDigest, protected: Vec<u8>, } @@ -573,62 +523,31 @@ async fn read_operation( .try_get::<Option<Vec<u8>>, _>(5) .map_err(|_| OperationError::RecoveryRequired)? .ok_or(OperationError::RecoveryRequired)?; + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; let clear = crypto - .open_stock_record(input, "operation", operation.as_bytes(), &protected) + .open_stock_record_for_catalog( + input, + "operation", + operation.as_bytes(), + catalog, + &protected, + ) .await?; - let (request, decoded) = clear.expose_secret(|bytes| -> Result<_, OperationError> { - let decoded: OperationDecode<'_> = - super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; - let captured = WorkspaceBinding::from_authenticated_host( - decoded.selection, - decoded.scope, - binding.actor(), - decoded.principal, - decoded.grant_revision, - decoded.grant_expires_at, - decoded.observed_at, - )?; - let minimum = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( - captured.input().authority(), - decoded.minimum_revision, - decoded.minimum_head, - )?; - let request = CreatePoolRequest::from_protected_wire( - captured, - minimum, - decoded.command.get().as_bytes(), - )?; - Ok(( - request, - OperationData { - version: decoded.version, - transaction: decoded.transaction, - revision: decoded.revision, - previous_head: decoded.previous_head, - head: decoded.head, - pool: decoded.pool, - movement: decoded.movement, - }, - )) - })?; + let (request, decoded) = + clear.expose_secret(|bytes| decode_operation(bytes, catalog, binding))?; same_binding(request.binding(), binding)?; let digest = request.command().digest(); - let pool_input = request.command().input(); - let physical = decoded.pool.balances().physical(); - if decoded.version != 1 + let (planned, quantity, movement_kind) = plan_effect(request.command(), decoded.before) + .map_err(|_| OperationError::RecoveryRequired)?; + if decoded.version != record_version(catalog)? || request.command().context().operation_id() != operation || decoded.revision.get() == 0 || (decoded.revision.get() == 1) != decoded.previous_head.is_none() - || decoded.pool.version().get() != 1 - || decoded.pool.id() != pool_input.id() - || decoded.pool.unit() != pool_input.unit() - || decoded.pool.balances().introduced() != pool_input.initial_ticks() - || physical.available != pool_input.initial_ticks() - || physical - != (PhysicalBalances { - available: pool_input.initial_ticks(), - ..PhysicalBalances::ZERO - }) + || decoded.pool != planned + || (catalog == 2 && decoded.before.is_some()) { return Err(OperationError::RecoveryRequired); } @@ -677,34 +596,36 @@ async fn read_operation( let movement_protected = if let Some(id) = decoded.movement { let protected:Vec<u8>=sqlx::query_scalar("SELECT protected FROM stock_movements WHERE movement_id=? AND actor=? AND grant_id=? AND operation_id=? AND pool_id=? AND length(protected) BETWEEN 1 AND 262144").bind(id.as_slice()).bind(binding.actor().participant().as_bytes().as_slice()).bind(binding.input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(decoded.pool.id().as_bytes().as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; let clear = crypto - .open_stock_record(input, "movement", &id, &protected) + .open_stock_record_for_catalog(input, "movement", &id, catalog, &protected) .await?; let movement: Movement = clear .expose_secret(|bytes| super::closed_record(bytes)) .map_err(|_| OperationError::RecoveryRequired)?; - if movement.version != 1 + if movement.version != record_version(catalog)? || movement.operation != operation || movement.digest != digest || movement.pool != decoded.pool.id() - || movement.quantity != pool_input.initial_ticks() + || movement.quantity != quantity + || movement.kind != movement_kind || movement.quantity == radroots_domain::stock::StockTicks::ZERO { return Err(OperationError::RecoveryRequired); } Some(protected) } else { - if pool_input.initial_ticks() != radroots_domain::stock::StockTicks::ZERO { + if quantity != radroots_domain::stock::StockTicks::ZERO { return Err(OperationError::RecoveryRequired); } None }; - let receipt = PoolCreationReceipt::from_committed_store( + let receipt = InventoryReceipt::from_committed_store( CommitAttempt::new( input.workspace_id(), operation, digest, Some(decoded.transaction), ), + request.command().kind(), decoded.pool, radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( request.command().context().authority(), @@ -768,110 +689,3 @@ fn chain_head(value: ChainInput<'_>) -> Result<CheckpointDigest, OperationError> h.update(movement.unwrap_or([0; 32])); Ok(CheckpointDigest::from_bytes(h.finalize().into())) } - -/// Constant-memory witness of the exact protected ancestry checked before IO -/// enters the write transaction. The transaction rereads every bound SQL row; -/// no key-provider callback or decryption runs while it owns the SQL lock. -struct MinimumProof { - lower: u64, - upper: u64, - digest: [u8; 32], -} -impl MinimumProof { - async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { - let mut hash = history_hash(); - for revision in (self.lower..=self.upper).rev() { - let row=sqlx::query("SELECT actor,grant_id,operation_id,command_digest,transaction_id,pool_id,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_operations WHERE revision=?") - .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; - hash.update(revision.to_be_bytes()); - for column in 0..7 { - let bytes: Vec<u8> = row - .try_get(column) - .map_err(|_| OperationError::RecoveryRequired)?; - if bytes.len() != 32 { - return Err(OperationError::RecoveryRequired); - } - hash.update(bytes); - } - let protected: Vec<u8> = row - .try_get::<Option<Vec<u8>>, _>(7) - .map_err(|_| OperationError::RecoveryRequired)? - .ok_or(OperationError::RecoveryRequired)?; - hash.update((protected.len() as u64).to_be_bytes()); - hash.update(protected); - } - let actual: [u8; 32] = hash.finalize().into(); - if actual != self.digest { - return Err(OperationError::RecoveryRequired); - } - Ok(()) - } -} -fn history_hash() -> Sha256 { - let mut hash = Sha256::new(); - hash.update(b"radroots.seller_stock.ancestry_snapshot.v1\0"); - hash -} -async fn authenticate_minimum( - connection: &mut SqliteConnection, - input: &AttachmentInput, - crypto: &WorkspaceCrypto, - binding: &WorkspaceBinding, - current: InventoryCheckpoint, - minimum: radroots_storage::inventory::InventoryCheckpointRef, -) -> Result<MinimumProof, OperationError> { - if minimum.authority() != input.authority() { - return Err(WorkspaceError::StaleAuthority.into()); - } - if minimum.revision().get() > current.revision.get() { - return Err(WorkspaceError::StaleCheckpoint.into()); - } - let lower = minimum.revision().get().max(1); - let upper = current.revision.get(); - let mut hash = history_hash(); - let mut expected = current.head; - for revision in (lower..=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)?; - let operation = OperationId::from_bytes( - id.try_into() - .map_err(|_| OperationError::RecoveryRequired)?, - ); - let retained = read_operation(connection, input, crypto, binding, operation) - .await? - .ok_or(OperationError::RecoveryRequired)?; - let receipt = &retained.receipt; - if receipt.checkpoint().revision().get() != revision - || receipt.checkpoint().head() != expected - { - return Err(WorkspaceError::StaleCheckpoint.into()); - } - if revision == minimum.revision().get() && expected != minimum.head() { - return Err(WorkspaceError::StaleCheckpoint.into()); - } - hash.update(revision.to_be_bytes()); - hash.update(binding.actor().participant().as_bytes()); - hash.update(binding.input().grant_id().as_bytes()); - hash.update(operation.as_bytes()); - hash.update(retained.digest.as_bytes()); - hash.update( - receipt - .transaction_id() - .ok_or(OperationError::RecoveryRequired)? - .as_bytes(), - ); - hash.update(receipt.pool().id().as_bytes()); - hash.update(expected.ok_or(OperationError::RecoveryRequired)?.as_bytes()); - hash.update((retained.protected.len() as u64).to_be_bytes()); - hash.update(&retained.protected); - expected = retained.previous_head; - } - if minimum.revision().get() == 0 && expected.is_some() { - return Err(WorkspaceError::StaleCheckpoint.into()); - } - Ok(MinimumProof { - lower, - upper, - digest: hash.finalize().into(), - }) -} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -0,0 +1,111 @@ +use super::*; + +/// Constant-memory witness of the exact protected ancestry checked before IO +/// enters the write transaction. The transaction rereads every bound SQL row; +/// no key-provider callback or decryption runs while it owns the SQL lock. +pub(super) struct MinimumProof { + lower: u64, + upper: u64, + digest: [u8; 32], +} +impl MinimumProof { + pub(super) async fn confirm( + &self, + connection: &mut SqliteConnection, + ) -> Result<(), OperationError> { + let mut hash = history_hash(); + for revision in (self.lower..=self.upper).rev() { + let row=sqlx::query("SELECT actor,grant_id,operation_id,command_digest,transaction_id,pool_id,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_operations WHERE revision=?") + .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; + hash.update(revision.to_be_bytes()); + for column in 0..7 { + let bytes: Vec<u8> = row + .try_get(column) + .map_err(|_| OperationError::RecoveryRequired)?; + if bytes.len() != 32 { + return Err(OperationError::RecoveryRequired); + } + hash.update(bytes); + } + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(7) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + hash.update((protected.len() as u64).to_be_bytes()); + hash.update(protected); + } + let actual: [u8; 32] = hash.finalize().into(); + if actual != self.digest { + return Err(OperationError::RecoveryRequired); + } + Ok(()) + } +} +fn history_hash() -> Sha256 { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.ancestry_snapshot.v1\0"); + hash +} +pub(super) async fn authenticate_minimum( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + current: InventoryCheckpoint, + minimum: radroots_storage::inventory::InventoryCheckpointRef, +) -> Result<MinimumProof, OperationError> { + if minimum.authority() != input.authority() { + return Err(WorkspaceError::StaleAuthority.into()); + } + if minimum.revision().get() > current.revision.get() { + return Err(WorkspaceError::StaleCheckpoint.into()); + } + let lower = minimum.revision().get().max(1); + let upper = current.revision.get(); + let mut hash = history_hash(); + let mut expected = current.head; + for revision in (lower..=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)?; + let operation = OperationId::from_bytes( + id.try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let retained = read_operation(connection, input, crypto, binding, operation) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let receipt = &retained.receipt; + if receipt.checkpoint().revision().get() != revision + || receipt.checkpoint().head() != expected + { + return Err(WorkspaceError::StaleCheckpoint.into()); + } + if revision == minimum.revision().get() && expected != minimum.head() { + return Err(WorkspaceError::StaleCheckpoint.into()); + } + hash.update(revision.to_be_bytes()); + hash.update(binding.actor().participant().as_bytes()); + hash.update(binding.input().grant_id().as_bytes()); + hash.update(operation.as_bytes()); + hash.update(retained.digest.as_bytes()); + hash.update( + receipt + .transaction_id() + .ok_or(OperationError::RecoveryRequired)? + .as_bytes(), + ); + hash.update(receipt.pool().id().as_bytes()); + hash.update(expected.ok_or(OperationError::RecoveryRequired)?.as_bytes()); + hash.update((retained.protected.len() as u64).to_be_bytes()); + hash.update(&retained.protected); + expected = retained.previous_head; + } + if minimum.revision().get() == 0 && expected.is_some() { + return Err(WorkspaceError::StaleCheckpoint.into()); + } + Ok(MinimumProof { + lower, + upper, + digest: hash.finalize().into(), + }) +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs @@ -0,0 +1,159 @@ +use super::*; + +#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum MovementKind { + Introduced, + Removed, + Wasted, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Movement { + pub(super) version: u8, + pub(super) operation: OperationId, + pub(super) digest: CommandDigest, + pub(super) pool: PoolId, + pub(super) quantity: radroots_domain::stock::StockTicks, + pub(super) kind: MovementKind, +} +#[derive(Serialize)] +pub(super) struct OperationWire<'a> { + pub(super) version: u8, + #[serde(skip_serializing_if = "Option::is_none")] + pub(super) before: Option<Option<PoolSnapshot>>, + pub(super) selection: &'a AttachmentInput, + pub(super) scope: WorkspaceScope, + pub(super) principal: &'a str, + pub(super) grant_revision: Sequence, + pub(super) grant_expires_at: UnixSeconds, + pub(super) observed_at: UnixSeconds, + pub(super) minimum_revision: Sequence, + pub(super) minimum_head: Option<CheckpointDigest>, + pub(super) transaction: TransactionId, + pub(super) revision: Sequence, + pub(super) previous_head: Option<CheckpointDigest>, + pub(super) head: CheckpointDigest, + pub(super) command: &'a RawValue, + pub(super) pool: PoolSnapshot, + pub(super) movement: Option<[u8; 32]>, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct OperationDecode<'a> { + pub(super) version: u8, + pub(super) selection: AttachmentInput, + pub(super) scope: WorkspaceScope, + pub(super) principal: String, + pub(super) grant_revision: Sequence, + pub(super) grant_expires_at: UnixSeconds, + pub(super) observed_at: UnixSeconds, + pub(super) minimum_revision: Sequence, + #[serde(deserialize_with = "super::required_nullable")] + pub(super) minimum_head: Option<CheckpointDigest>, + pub(super) transaction: TransactionId, + pub(super) revision: Sequence, + #[serde(deserialize_with = "super::required_nullable")] + pub(super) previous_head: Option<CheckpointDigest>, + pub(super) head: CheckpointDigest, + #[serde(borrow)] + pub(super) command: &'a RawValue, + pub(super) pool: PoolSnapshot, + #[serde(deserialize_with = "super::required_nullable")] + pub(super) movement: Option<[u8; 32]>, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct OperationDecodeV2<'a> { + pub(super) version: u8, + #[serde(deserialize_with = "super::required_nullable")] + pub(super) before: Option<PoolSnapshot>, + pub(super) selection: AttachmentInput, + pub(super) scope: WorkspaceScope, + pub(super) principal: String, + pub(super) grant_revision: Sequence, + pub(super) grant_expires_at: UnixSeconds, + pub(super) observed_at: UnixSeconds, + pub(super) minimum_revision: Sequence, + #[serde(deserialize_with = "super::required_nullable")] + pub(super) minimum_head: Option<CheckpointDigest>, + pub(super) transaction: TransactionId, + pub(super) revision: Sequence, + #[serde(deserialize_with = "super::required_nullable")] + pub(super) previous_head: Option<CheckpointDigest>, + pub(super) head: CheckpointDigest, + #[serde(borrow)] + pub(super) command: &'a RawValue, + pub(super) pool: PoolSnapshot, + #[serde(deserialize_with = "super::required_nullable")] + pub(super) movement: Option<[u8; 32]>, +} +pub(super) struct OperationData { + pub(super) version: u8, + pub(super) before: Option<PoolSnapshot>, + pub(super) transaction: TransactionId, + pub(super) revision: Sequence, + pub(super) previous_head: Option<CheckpointDigest>, + pub(super) head: CheckpointDigest, + pub(super) pool: PoolSnapshot, + pub(super) movement: Option<[u8; 32]>, +} + +pub(super) fn decode_operation( + bytes: &[u8], + catalog: i64, + binding: &WorkspaceBinding, +) -> Result<(InventoryRequest, OperationData), OperationError> { + macro_rules! captured { + ($decoded:expr,$prior:expr) => {{ + let decoded = $decoded; + let prior = $prior; + let captured = WorkspaceBinding::from_authenticated_host( + decoded.selection, + decoded.scope, + binding.actor(), + decoded.principal, + decoded.grant_revision, + decoded.grant_expires_at, + decoded.observed_at, + )?; + let minimum = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( + captured.input().authority(), + decoded.minimum_revision, + decoded.minimum_head, + )?; + let request = InventoryRequest::from_protected_wire( + captured, + minimum, + decoded.command.get().as_bytes(), + )?; + Ok(( + request, + OperationData { + version: decoded.version, + before: prior, + transaction: decoded.transaction, + revision: decoded.revision, + previous_head: decoded.previous_head, + head: decoded.head, + pool: decoded.pool, + movement: decoded.movement, + }, + )) + }}; + } + match catalog { + 2 => { + let decoded: OperationDecode<'_> = + super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; + captured!(decoded, None) + } + 3 => { + let decoded: OperationDecodeV2<'_> = + super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; + let prior = decoded.before; + captured!(decoded, prior) + } + _ => Err(OperationError::RecoveryRequired), + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs @@ -0,0 +1,90 @@ +use super::*; + +pub(super) fn record_version(catalog: i64) -> Result<u8, OperationError> { + match catalog { + 2 => Ok(1), + 3 => Ok(2), + _ => Err(OperationError::RecoveryRequired), + } +} +pub(super) fn plan_effect( + command: &radroots_storage::inventory::CapturedInventoryCommand, + before: Option<PoolSnapshot>, +) -> Result< + ( + PoolSnapshot, + radroots_domain::stock::StockTicks, + MovementKind, + ), + OperationError, +> { + use radroots_domain::stock::{AvailableStockCorrection, StockError}; + use radroots_storage::inventory::CapturedInventoryCommand; + match command { + CapturedInventoryCommand::CreatePool(command) => { + if before.is_some() { + return Err(OperationError::StaleState); + } + let input = command.input(); + let quantity = input.initial_ticks(); + let balances = PoolBalances::new( + quantity, + PhysicalBalances { + available: quantity, + ..PhysicalBalances::ZERO + }, + ) + .map_err(|_| OperationError::InvalidCommand)?; + Ok(( + PoolSnapshot::new( + input.id(), + input.unit(), + balances, + Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, + ), + quantity, + MovementKind::Introduced, + )) + } + CapturedInventoryCommand::CorrectPool(command) => { + let input = command.input(); + let before = before.ok_or(OperationError::StaleState)?; + if before.id() != input.pool_id() || before.version() != input.expected_version() { + return Err(OperationError::StaleState); + } + let quantity = before + .unit() + .ticks_for( + radroots_domain::Quantity::new(input.amount().amount(), before.unit().unit()) + .map_err(|_| OperationError::InvalidCommand)?, + ) + .map_err(|_| OperationError::InvalidCommand)?; + let balances = before + .balances() + .correct_available(input.kind(), quantity) + .map_err(|error| match error { + StockError::Underflow => OperationError::StaleState, + StockError::OutOfRange => WorkspaceError::Capacity.into(), + _ => OperationError::InvalidCommand, + })?; + let version = Sequence::new( + before + .version() + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let movement = match input.kind() { + AvailableStockCorrection::Add => MovementKind::Introduced, + AvailableStockCorrection::Remove => MovementKind::Removed, + AvailableStockCorrection::Spoil => MovementKind::Wasted, + }; + Ok(( + PoolSnapshot::new(before.id(), before.unit(), balances, version), + quantity, + movement, + )) + } + } +} 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 = 2; +pub(super) const CURRENT: i64 = 3; 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"; @@ -22,7 +22,7 @@ pub(super) fn objects( ]; match version { 1 => {} - 2 => objects.extend([ + 2 | 3 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ("table", "stock_operations", "stock_operations", OPERATIONS), ( diff --git a/crates/storage_sqlite/src/workspace/stock/tests.rs b/crates/storage_sqlite/src/workspace/stock/tests.rs @@ -6,7 +6,7 @@ use crate::workspace::{ use radroots_domain::{CommandContextData, OperationId, PoolId, UnixSeconds}; use radroots_storage::{ command::OperationError, - inventory::{CreatePoolRequest, InventoryCheckpointRef, InventoryStore}, + inventory::{InventoryCheckpointRef, InventoryRequest, InventoryStore}, }; struct Clock; impl WorkspaceClock for Clock { @@ -14,6 +14,184 @@ impl WorkspaceClock for Clock { Ok(UnixSeconds::new(100).unwrap()) } } + +#[tokio::test] +async fn retained_inventory_v2_keeps_original_records_and_refuses_new_correction_without_upgrade() { + use radroots_storage::inventory::{InventoryCommandKind, InventoryOutcome}; + let fixture = CryptoFixture::new(); + let path = fixture.root().join("retained-v2"); + let (input, proof, record) = SellerStockConfig::new( + participant(), + participant(), + "retained-stock-owner", + UnixSeconds::new(200).unwrap(), + ) + .unwrap() + .enroll( + UnixSeconds::new(100).unwrap(), + WorkspaceId::from_bytes([1; 32]), + ExecutorId::from_bytes([2; 32]), + GrantId::from_bytes([3; 32]), + AttachmentProof::from_protected_input(&[0xA3; 32]).unwrap(), + ) + .unwrap(); + // Literal catalog2/root2 shape from cc96f676, not predecessor-binary evidence. + let clear=zeroize::Zeroizing::new(serde_json::to_vec(&serde_json::json!({"version":2,"input":input,"transaction":TransactionId::from_bytes([9;32]),"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null}})).unwrap()); + let crypto = fixture.crypto(); + let root = crypto.seal_stock_root(&input, 2, &clear).await.unwrap(); + let grant = crypto + .seal_stock(&input, false, &record.encode().unwrap()) + .await + .unwrap(); + let namespace = Namespace::acquire_kind(&path, true, Kind::SellerStock).unwrap(); + let mut connection = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(namespace.database_path()) + .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) + .synchronous(sqlx::sqlite::SqliteSynchronous::Full), + ) + .await + .unwrap(); + let mut tx = connection.begin_with("BEGIN IMMEDIATE").await.unwrap(); + for (_, _, _, sql) in schema::objects(2).unwrap() { + sqlx::raw_sql(sql).execute(&mut *tx).await.unwrap(); + } + sqlx::query("INSERT INTO stock_authority(singleton,protected) VALUES(1,?)") + .bind(root) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("INSERT INTO stock_grants(grant_id,protected) VALUES(?,?)") + .bind(input.grant_id().as_bytes().as_slice()) + .bind(grant) + .execute(&mut *tx) + .await + .unwrap(); + sqlx::query("PRAGMA user_version=2") + .execute(&mut *tx) + .await + .unwrap(); + tx.commit().await.unwrap(); + connection.close().await.unwrap(); + drop(namespace); + let store = + NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) + .await + .unwrap(); + let binding = store.authenticate(input.clone(), &proof).await.unwrap(); + let minimum = store + .stock_authority(input.clone(), &proof) + .await + .unwrap() + .inventory_checkpoint() + .unwrap(); + let context = CommandContextData::new( + OperationId::from_bytes([7; 32]), + binding.actor(), + input.workspace_id(), + input.authority(), + input.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let wire = serde_json::json!({"type":"stock.create_pool","context":context,"input":{"id":PoolId::from_bytes([8;32]),"label":"retained","unit":"each","tick_scale":"0","initial_quantity":"1"}}); + let copy = || { + proof + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap() + }; + let created = match store + .execute_inventory( + InventoryRequest::from_protected_wire( + binding.clone(), + minimum, + &serde_json::to_vec(&wire).unwrap(), + ) + .unwrap(), + copy(), + ) + .await + .unwrap() + { + InventoryOutcome::Committed(receipt) => *receipt, + InventoryOutcome::Unknown(_) => panic!("retained creation must confirm"), + }; + assert_eq!(created.kind(), InventoryCommandKind::CreatePool); + assert_eq!(created.pool().balances().physical().available.get(), 1); + store.close().await.unwrap(); + let store = + NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) + .await + .unwrap(); + assert_eq!( + store + .inventory_operation( + binding.clone(), + created.checkpoint(), + OperationId::from_bytes([7; 32]), + Some(created.attempt().command_digest()), + copy() + ) + .await + .unwrap(), + Some(created.clone()) + ); + let mut corrected = serde_json::json!({"type":"stock.adjust","context":context,"input":{"pool_id":PoolId::from_bytes([8;32]),"expected_version":"1","direction":"add","amount":"1","reason":"new correction profile"}}); + corrected["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([10; 32])); + assert!(matches!( + store + .execute_inventory( + InventoryRequest::from_protected_wire( + binding, + created.checkpoint(), + &serde_json::to_vec(&corrected).unwrap() + ) + .unwrap(), + copy() + ) + .await, + Err(OperationError::UnsupportedOperation) + )); + store.close().await.unwrap(); + let mut connection = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new().filename(path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + assert_eq!(schema::admit(&mut connection).await.unwrap(), 2); + let protected: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_operations") + .fetch_one(&mut connection) + .await + .unwrap(); + let old = fixture + .crypto() + .open_stock_record( + &input, + "operation", + OperationId::from_bytes([7; 32]).as_bytes(), + &protected, + ) + .await + .unwrap(); + old.expose_secret(|bytes| { + let value: serde_json::Value = serde_json::from_slice(bytes).unwrap(); + assert_eq!(value["version"], 1); + assert!(value.get("before").is_none()); + }); + sqlx::query("PRAGMA user_version=3") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + assert!( + NativeWorkspace::open_seller_stock(&path, input, fixture.crypto(), Arc::new(Clock)) + .await + .is_err() + ); +} #[tokio::test] async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() { let fixture = CryptoFixture::new(); @@ -99,7 +277,7 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() ) .unwrap(); let wire = serde_json::json!({"type":"stock.create_pool","context":context,"input":{"id":PoolId::from_bytes([8;32]),"label":"retained","unit":"each","tick_scale":"0","initial_quantity":"1"}}); - let request = CreatePoolRequest::from_protected_wire( + let request = InventoryRequest::from_protected_wire( binding, InventoryCheckpointRef::from_host_metadata( input.authority(), @@ -114,7 +292,7 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() .with_secret(|b| AttachmentProof::from_protected_input(b)) .unwrap(); assert!(matches!( - store.create_pool(request, copy).await, + store.execute_inventory(request, copy).await, Err(OperationError::UnsupportedOperation) )); store.close().await.unwrap(); diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -38,18 +38,18 @@ 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 { - CreatePool( - Box<radroots_storage::inventory::CreatePoolRequest>, + ExecuteInventory( + Box<radroots_storage::inventory::InventoryRequest>, AttachmentProof, - Reply<radroots_storage::inventory::PoolCreationOutcome, OperationError>, + Reply<radroots_storage::inventory::InventoryOutcome, OperationError>, ), - PoolCreation( + InventoryOperation( Box<WorkspaceBinding>, radroots_storage::inventory::InventoryCheckpointRef, OperationId, Option<CommandDigest>, AttachmentProof, - Reply<Option<radroots_storage::inventory::PoolCreationReceipt>, OperationError>, + Reply<Option<radroots_storage::inventory::InventoryReceipt>, OperationError>, ), Pool( Box<WorkspaceBinding>, @@ -163,10 +163,10 @@ enum Job { impl Job { fn reject_recovery(self) { match self { - Self::CreatePool(_, _, reply) => { + Self::ExecuteInventory(_, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } - Self::PoolCreation(_, _, _, _, _, reply) => { + Self::InventoryOperation(_, _, _, _, _, reply) => { let _ = reply.send(Err(OperationError::RecoveryRequired)); } Self::Pool(_, _, _, _, reply) => { @@ -365,8 +365,8 @@ impl Handle { && !matches!( &job, Job::Authenticate(..) - | Job::CreatePool(..) - | Job::PoolCreation(..) + | Job::ExecuteInventory(..) + | Job::InventoryOperation(..) | Job::Pool(..) | Job::Revoke(..) | Job::StockAuthority(..) @@ -399,7 +399,7 @@ impl Handle { continue; }; match job { - Job::CreatePool(request, proof, reply) => { + Job::ExecuteInventory(request, proof, reply) => { let result = if kind == Kind::SellerStock { stock::inventory::Turn { connection, @@ -416,7 +416,7 @@ impl Handle { }; let _ = reply.send(result); } - Job::PoolCreation( + Job::InventoryOperation( binding, minimum, operation, @@ -805,11 +805,11 @@ impl Handle { self.send(Job::StockAuthority(input, proof, reply))?; result.await.map_err(|_| WorkspaceError::RecoveryRequired)? } - pub(super) async fn create_pool( + pub(super) async fn execute_inventory( &self, - request: radroots_storage::inventory::CreatePoolRequest, + request: radroots_storage::inventory::InventoryRequest, proof: AttachmentProof, - ) -> Result<radroots_storage::inventory::PoolCreationOutcome, OperationError> { + ) -> Result<radroots_storage::inventory::InventoryOutcome, OperationError> { let c = request.command().context(); let anchor = CommitAttempt::new( c.workspace_id(), @@ -818,21 +818,23 @@ impl Handle { None, ); let (reply, result) = oneshot::channel(); - self.send(Job::CreatePool(Box::new(request), proof, reply))?; - result.await.unwrap_or(Ok( - radroots_storage::inventory::PoolCreationOutcome::Unknown(anchor), - )) + self.send(Job::ExecuteInventory(Box::new(request), proof, reply))?; + result + .await + .unwrap_or(Ok(radroots_storage::inventory::InventoryOutcome::Unknown( + anchor, + ))) } - pub(super) async fn pool_creation( + pub(super) async fn inventory_operation( &self, binding: WorkspaceBinding, minimum: radroots_storage::inventory::InventoryCheckpointRef, operation: OperationId, digest: Option<CommandDigest>, proof: AttachmentProof, - ) -> Result<Option<radroots_storage::inventory::PoolCreationReceipt>, OperationError> { + ) -> Result<Option<radroots_storage::inventory::InventoryReceipt>, OperationError> { let (reply, result) = oneshot::channel(); - self.send(Job::PoolCreation( + self.send(Job::InventoryOperation( Box::new(binding), minimum, operation, @@ -855,7 +857,7 @@ impl Handle { } fn send(&self, job: Job) -> Result<(), WorkspaceError> { let bytes = match &job { - Job::CreatePool(..) => 64 * 1024, + Job::ExecuteInventory(..) => 64 * 1024, Job::CaptureDeliveryObservation(..) => 96 * 1024, Job::PrepareDelivery(..) => 1024 * 1024, Job::BindPlan(..) => 1024 * 1024, diff --git a/crates/storage_sqlite/tests/support/pool_correction.rs b/crates/storage_sqlite/tests/support/pool_correction.rs @@ -0,0 +1,446 @@ +use super::*; + +#[tokio::test] +async fn real_lifetime_introduced_capacity_is_not_reused_when_available_stock_is_depleted() { + use radroots_domain::stock::{ + AvailableStockCorrection::{Add, Remove, Spoil}, + StockTicks, + }; + let f = Fixture::new(); + let (store, e, binding) = create(&f).await; + let selection = binding.input(); + let context = CommandContextData::new( + OperationId::from_bytes([1; 32]), + binding.actor(), + selection.workspace_id(), + selection.authority(), + selection.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + let input = CreatePoolInput::new( + PoolId::from_bytes([2; 32]), + "capacity", + PoolUnit::new(MeasurementUnit::Kilogram, 6).unwrap(), + Quantity::new("999999999999".parse().unwrap(), MeasurementUnit::Kilogram).unwrap(), + ) + .unwrap(); + let original = InventoryRequest::new( + binding.clone(), + minimum(&binding), + CapturedPoolCreation::new(context, input).unwrap(), + ) + .unwrap(); + store + .execute_inventory(original, proof(e.proof())) + .await + .unwrap(); + let full = committed( + store + .execute_inventory(correction(&binding, 3, 1, Add, "1"), proof(e.proof())) + .await + .unwrap(), + ); + assert_eq!(full.pool().balances().introduced(), StockTicks::MAX); + store + .execute_inventory( + correction(&binding, 4, 2, Remove, "999999999999"), + proof(e.proof()), + ) + .await + .unwrap(); + let depleted = committed( + store + .execute_inventory(correction(&binding, 5, 3, Spoil, "1"), proof(e.proof())) + .await + .unwrap(), + ); + assert_eq!( + depleted.pool().balances().physical().available, + StockTicks::ZERO + ); + assert_eq!(depleted.pool().balances().introduced(), StockTicks::MAX); + assert_eq!( + store + .execute_inventory( + correction(&binding, 9, 4, Add, "0.000001"), + proof(e.proof()) + ) + .await, + Err(OperationError::Workspace(WorkspaceError::Capacity)) + ); + assert_eq!( + store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap() + .inventory_checkpoint(), + Some(depleted.checkpoint()) + ); + assert!( + store + .inventory_operation( + binding, + depleted.checkpoint(), + OperationId::from_bytes([9; 32]), + None, + proof(e.proof()) + ) + .await + .unwrap() + .is_none() + ); + store.close().await.unwrap(); +} + +fn correction( + binding: &radroots_storage::workspace::WorkspaceBinding, + operation: u8, + version: u64, + kind: radroots_domain::stock::AvailableStockCorrection, + amount: &str, +) -> InventoryRequest { + let selection = binding.input(); + let context = CommandContextData::new( + OperationId::from_bytes([operation; 32]), + binding.actor(), + selection.workspace_id(), + selection.authority(), + selection.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + InventoryRequest::new( + binding.clone(), + minimum(binding), + radroots_protocol::command::CapturedPoolCorrection::new( + context, + radroots_protocol::command::PoolCorrectionInput::new( + PoolId::from_bytes([2; 32]), + radroots_domain::Sequence::new(version).unwrap(), + kind, + amount.parse().unwrap(), + "verified harvest correction", + ) + .unwrap(), + ) + .unwrap(), + ) + .unwrap() +} + +#[tokio::test] +async fn actual_corrections_and_spoilage_conserve_stock_reopen_and_replay_original_effects() { + use radroots_domain::stock::AvailableStockCorrection::{Add, Remove, Spoil}; + use radroots_storage::inventory::InventoryCommandKind; + let f = Fixture::new(); + let (store, e, binding) = create(&f).await; + let created = committed( + store + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .await + .unwrap(), + ); + let added = committed( + store + .execute_inventory(correction(&binding, 3, 1, Add, "0.125"), proof(e.proof())) + .await + .unwrap(), + ); + assert_eq!(added.kind(), InventoryCommandKind::AddStock); + assert_eq!(added.pool().balances().introduced().get(), 375); + assert_eq!(added.pool().balances().physical().available.get(), 375); + assert_eq!(added.pool().version().get(), 2); + let removed = committed( + store + .execute_inventory(correction(&binding, 4, 2, Remove, "0.05"), proof(e.proof())) + .await + .unwrap(), + ); + assert_eq!(removed.kind(), InventoryCommandKind::RemoveStock); + assert_eq!(removed.pool().balances().introduced().get(), 375); + assert_eq!(removed.pool().balances().physical().available.get(), 325); + assert_eq!(removed.pool().balances().physical().removed.get(), 50); + let spoiled = committed( + store + .execute_inventory(correction(&binding, 5, 3, Spoil, "0.075"), proof(e.proof())) + .await + .unwrap(), + ); + assert_eq!(spoiled.kind(), InventoryCommandKind::SpoilStock); + assert_eq!(spoiled.pool().version().get(), 4); + assert_eq!(spoiled.pool().balances().introduced().get(), 375); + assert_eq!(spoiled.pool().balances().physical().available.get(), 250); + assert_eq!(spoiled.pool().balances().physical().waste.get(), 75); + assert_eq!(spoiled.pool().balances().physical().removed.get(), 50); + for (version, kind, amount, expected) in [ + (1, Add, "1", OperationError::StaleState), + (4, Remove, "1", OperationError::StaleState), + (4, Spoil, "0.000001", OperationError::InvalidCommand), + ] { + assert_eq!( + store + .execute_inventory( + correction(&binding, 9, version, kind, amount), + proof(e.proof()) + ) + .await, + Err(expected) + ); + } + f.clock.0.store(175, Ordering::SeqCst); + assert_eq!( + committed( + store + .execute_inventory(correction(&binding, 3, 1, Add, "0.125"), proof(e.proof())) + .await + .unwrap() + ), + added + ); + assert_eq!( + store + .execute_inventory(correction(&binding, 3, 1, Add, "0.25"), proof(e.proof())) + .await, + Err(OperationError::IdempotencyConflict) + ); + assert_eq!( + store + .pool( + binding.clone(), + spoiled.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await + .unwrap() + .unwrap() + .snapshot(), + spoiled.pool() + ); + assert_eq!(created.kind(), InventoryCommandKind::CreatePool); + store.close().await.unwrap(); + let store = + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await + .unwrap(); + assert_eq!( + store + .inventory_operation( + binding.clone(), + spoiled.checkpoint(), + OperationId::from_bytes([3; 32]), + Some(added.attempt().command_digest()), + proof(e.proof()) + ) + .await + .unwrap(), + Some(added) + ); + assert_eq!( + store + .pool( + binding, + spoiled.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await + .unwrap() + .unwrap() + .label(), + "Carrots" + ); + store.close().await.unwrap(); + let mut conn = database(&f).await; + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_pools") + .fetch_one(&mut conn) + .await + .unwrap(), + 1 + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_operations") + .fetch_one(&mut conn) + .await + .unwrap(), + 4 + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_movements") + .fetch_one(&mut conn) + .await + .unwrap(), + 4 + ); + let protected: Vec<u8> = + sqlx::query_scalar("SELECT protected FROM stock_operations WHERE operation_id=?") + .bind(OperationId::from_bytes([3; 32]).as_bytes().as_slice()) + .fetch_one(&mut conn) + .await + .unwrap(); + assert!(!String::from_utf8_lossy(&protected).contains("verified harvest")); + conn.close().await.unwrap(); +} + +#[tokio::test] +async fn every_actual_correction_write_failure_rolls_back_the_original_pool_and_receipt() { + use radroots_domain::stock::AvailableStockCorrection::Add; + for trigger in [ + "CREATE TRIGGER correction_fault BEFORE UPDATE ON stock_pools BEGIN SELECT RAISE(ABORT,'isolated correction fault'); END", + "CREATE TRIGGER correction_fault BEFORE INSERT ON stock_operations BEGIN SELECT RAISE(ABORT,'isolated correction fault'); END", + "CREATE TRIGGER correction_fault BEFORE INSERT ON stock_movements BEGIN SELECT RAISE(ABORT,'isolated correction fault'); END", + "CREATE TRIGGER correction_fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'isolated correction fault'); END", + ] { + let f = Fixture::new(); + let (store, e, binding) = create(&f).await; + let original = committed( + store + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .await + .unwrap(), + ); + let mut conn = database(&f).await; + sqlx::raw_sql(trigger).execute(&mut conn).await.unwrap(); + assert!(matches!( + store + .execute_inventory(correction(&binding, 3, 1, Add, "0.125"), proof(e.proof())) + .await, + Err(OperationError::StorageFailure) + )); + assert_eq!( + store + .pool( + binding.clone(), + original.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await + .unwrap() + .unwrap() + .snapshot(), + original.pool() + ); + assert!( + store + .inventory_operation( + binding.clone(), + original.checkpoint(), + OperationId::from_bytes([3; 32]), + None, + proof(e.proof()) + ) + .await + .unwrap() + .is_none() + ); + sqlx::raw_sql("DROP TRIGGER correction_fault") + .execute(&mut conn) + .await + .unwrap(); + conn.close().await.unwrap(); + store.close().await.unwrap(); + let store = NativeWorkspace::open_seller_stock( + &f.path, + e.input().clone(), + f.crypto(), + f.clock.clone(), + ) + .await + .unwrap(); + assert_eq!( + store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap() + .inventory_checkpoint(), + Some(original.checkpoint()) + ); + store.close().await.unwrap(); + } +} + +#[tokio::test] +async fn actual_correction_commit_failure_preserves_original_anchor_and_requires_reopen() { + use radroots_domain::stock::AvailableStockCorrection::Spoil; + let f = Fixture::new(); + let (store, e, binding) = create(&f).await; + let original = committed( + store + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .await + .unwrap(), + ); + let mut conn = database(&f).await; + sqlx::raw_sql("CREATE TABLE deferred_correction_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER correction_commit_fault AFTER INSERT ON stock_movements BEGIN INSERT INTO deferred_correction_fault VALUES(2); END").execute(&mut conn).await.unwrap(); + let command = correction(&binding, 3, 1, Spoil, "0.125"); + let digest = command.command().digest(); + let unknown = match store + .execute_inventory(command, proof(e.proof())) + .await + .unwrap() + { + InventoryOutcome::Unknown(anchor) => anchor, + InventoryOutcome::Committed(_) => panic!("actual COMMIT must fail"), + }; + assert_eq!(unknown.command_digest(), digest); + assert_eq!(unknown.operation_id(), OperationId::from_bytes([3; 32])); + assert!(unknown.transaction_id().is_some()); + assert!(matches!( + store + .pool( + binding.clone(), + original.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await, + Err(OperationError::RecoveryRequired) + )); + store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER correction_commit_fault; DROP TABLE deferred_correction_fault") + .execute(&mut conn) + .await + .unwrap(); + conn.close().await.unwrap(); + let store = + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await + .unwrap(); + assert!( + store + .inventory_operation( + binding.clone(), + original.checkpoint(), + OperationId::from_bytes([3; 32]), + Some(digest), + proof(e.proof()) + ) + .await + .unwrap() + .is_none() + ); + assert_eq!( + store + .pool( + binding, + original.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await + .unwrap() + .unwrap() + .snapshot(), + original.pool() + ); + store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/tests/support/pool_creation.rs b/crates/storage_sqlite/tests/support/pool_creation.rs @@ -7,8 +7,8 @@ use radroots_protocol::command::{CapturedPoolCreation, CreatePoolInput}; use radroots_storage::{ command::OperationError, inventory::{ - CreatePoolRequest, InventoryCheckpointRef, InventoryStore, PoolCreationOutcome, - PoolCreationReceipt, + InventoryCheckpointRef, InventoryOutcome, InventoryReceipt, InventoryRequest, + InventoryStore, }, }; use radroots_storage_sqlite::workspace::{SellerStockConfig, StockEnrollment}; @@ -31,7 +31,7 @@ fn request( operation: u8, pool: u8, label: &str, -) -> CreatePoolRequest { +) -> InventoryRequest { let input = binding.input(); let context = CommandContextData::new( OperationId::from_bytes([operation; 32]), @@ -50,7 +50,7 @@ fn request( MeasurementUnit::Kilogram, ) .unwrap(); - CreatePoolRequest::new( + InventoryRequest::new( binding.clone(), minimum(binding), CapturedPoolCreation::new( @@ -95,10 +95,10 @@ async fn create( .unwrap(); (store, enrollment, binding) } -fn committed(outcome: PoolCreationOutcome) -> PoolCreationReceipt { +fn committed(outcome: InventoryOutcome) -> InventoryReceipt { match outcome { - PoolCreationOutcome::Committed(receipt) => *receipt, - PoolCreationOutcome::Unknown(_) => panic!("expected confirmed inventory commit"), + InventoryOutcome::Committed(receipt) => *receipt, + InventoryOutcome::Unknown(_) => panic!("expected confirmed inventory commit"), } } async fn database(f: &Fixture) -> sqlx::SqliteConnection { @@ -111,12 +111,18 @@ async fn database(f: &Fixture) -> sqlx::SqliteConnection { .unwrap() } #[tokio::test] -async fn real_pool_creation_commits_reopens_and_replays_original_effect_after_command_expiry() { +async fn real_inventory_operation_commits_reopens_and_replays_original_effect_after_command_expiry() +{ let f = Fixture::new(); let (store, e, binding) = create(&f).await; let original = request(&binding, 1, 2, "Carrots"); let digest = original.command().digest(); - let receipt = committed(store.create_pool(original, proof(e.proof())).await.unwrap()); + let receipt = committed( + store + .execute_inventory(original, proof(e.proof())) + .await + .unwrap(), + ); assert_eq!(receipt.pool().balances().physical().available.get(), 250); assert_eq!(receipt.pool().balances().introduced().get(), 250); assert_eq!(receipt.pool().unit().scale(), 3); @@ -139,7 +145,7 @@ async fn real_pool_creation_commits_reopens_and_replays_original_effect_after_co ); assert_eq!( store - .pool_creation( + .inventory_operation( binding.clone(), minimum(&binding), OperationId::from_bytes([1; 32]), @@ -154,7 +160,7 @@ async fn real_pool_creation_commits_reopens_and_replays_original_effect_after_co assert_eq!( committed( store - .create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) .await .unwrap() ), @@ -162,13 +168,13 @@ async fn real_pool_creation_commits_reopens_and_replays_original_effect_after_co ); assert!(matches!( store - .create_pool(request(&binding, 1, 2, "Changed"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Changed"), proof(e.proof())) .await, Err(OperationError::IdempotencyConflict) )); assert!(matches!( store - .create_pool(request(&binding, 3, 4, "Late"), proof(e.proof())) + .execute_inventory(request(&binding, 3, 4, "Late"), proof(e.proof())) .await, Err(OperationError::DeadlineExceeded) )); @@ -179,7 +185,7 @@ async fn real_pool_creation_commits_reopens_and_replays_original_effect_after_co .unwrap(); assert_eq!( store - .pool_creation( + .inventory_operation( binding.clone(), minimum(&binding), OperationId::from_bytes([1; 32]), @@ -236,7 +242,7 @@ async fn each_actual_inventory_write_failure_rolls_back_pool_journal_movement_an .unwrap(); assert!( store - .create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) .await .is_err(), "{table}" @@ -290,15 +296,19 @@ async fn actual_inventory_commit_failure_is_unknown_and_fenced_until_reopen() { sqlx::raw_sql("CREATE TABLE deferred_inventory_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER inventory_commit_fault AFTER INSERT ON stock_movements BEGIN INSERT INTO deferred_inventory_fault VALUES(2); END").execute(&mut connection).await.unwrap(); let original = request(&binding, 1, 2, "Carrots"); let digest = original.command().digest(); - let anchor = match store.create_pool(original, proof(e.proof())).await.unwrap() { - PoolCreationOutcome::Unknown(anchor) => anchor, - PoolCreationOutcome::Committed(_) => panic!("COMMIT must fail"), + let anchor = match store + .execute_inventory(original, proof(e.proof())) + .await + .unwrap() + { + InventoryOutcome::Unknown(anchor) => anchor, + InventoryOutcome::Committed(_) => panic!("COMMIT must fail"), }; assert_eq!(anchor.command_digest(), digest); assert!(anchor.transaction_id().is_some()); assert!(matches!( store - .pool_creation( + .inventory_operation( binding.clone(), minimum(&binding), OperationId::from_bytes([1; 32]), @@ -320,7 +330,7 @@ async fn actual_inventory_commit_failure_is_unknown_and_fenced_until_reopen() { .unwrap(); assert!( store - .pool_creation( + .inventory_operation( binding.clone(), minimum(&binding), OperationId::from_bytes([1; 32]), @@ -351,7 +361,7 @@ async fn sealed_root_detects_missing_inventory_history_instead_of_fresh_stock() let (store, e, binding) = create(&f).await; committed( store - .create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) .await .unwrap(), ); @@ -395,7 +405,7 @@ async fn acknowledged_minimum_refuses_a_complete_older_database_snapshot() { .unwrap(); let receipt = committed( store - .create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) .await .unwrap(), ); @@ -429,7 +439,7 @@ async fn acknowledged_minimum_refuses_a_complete_older_database_snapshot() { )); assert!(matches!( store - .pool_creation( + .inventory_operation( binding.clone(), acknowledged, OperationId::from_bytes([1; 32]), @@ -440,14 +450,14 @@ async fn acknowledged_minimum_refuses_a_complete_older_database_snapshot() { Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint)) )); let captured = request(&binding, 3, 4, "New stock"); - let captured = CreatePoolRequest::new( + let captured = InventoryRequest::new( binding, acknowledged, CapturedPoolCreation::parse(captured.command().protected_wire()).unwrap(), ) .unwrap(); assert!(matches!( - store.create_pool(captured, proof(e.proof())).await, + store.execute_inventory(captured, proof(e.proof())).await, Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint)) )); store.close().await.unwrap(); @@ -489,13 +499,18 @@ async fn an_empty_pool_is_a_zero_genesis_without_a_fictitious_movement() { ) .unwrap(); let digest = command.digest(); - let request = CreatePoolRequest::new(binding.clone(), minimum(&binding), command).unwrap(); - let receipt = committed(store.create_pool(request, proof(e.proof())).await.unwrap()); + let request = InventoryRequest::new(binding.clone(), minimum(&binding), command).unwrap(); + let receipt = committed( + store + .execute_inventory(request, proof(e.proof())) + .await + .unwrap(), + ); assert_eq!(receipt.pool().balances().introduced().get(), 0); assert_eq!(receipt.checkpoint().revision().get(), 1); assert_eq!( store - .pool_creation( + .inventory_operation( binding.clone(), minimum(&binding), OperationId::from_bytes([7; 32]), @@ -588,7 +603,7 @@ async fn expiry_or_clock_failure_inside_inventory_transaction_has_no_effect() { .unwrap(); clock.armed.store(true, Ordering::SeqCst); let result = store - .create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) .await; match next { 0 => assert!(matches!( @@ -652,7 +667,7 @@ async fn admitted_inventory_work_survives_observer_and_close_cancellation() { let original = request(&binding, 1, 2, "Carrots"); let digest = original.command().digest(); clock.arm(); - let mut future = store.create_pool(original, proof(e.proof())); + let mut future = store.execute_inventory(original, proof(e.proof())); assert!(futures::poll!(future.as_mut()).is_pending()); clock.entered(); drop(future); @@ -671,7 +686,7 @@ async fn admitted_inventory_work_survives_observer_and_close_cancellation() { .await .unwrap(); let receipt = store - .pool_creation( + .inventory_operation( binding.clone(), minimum(&binding), OperationId::from_bytes([1; 32]), @@ -692,14 +707,14 @@ async fn current_credentials_guard_pool_reads_replay_and_new_effects_after_revoc let (store, e, binding) = create(&f).await; let receipt = committed( store - .create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) .await .unwrap(), ); let wrong = || AttachmentProof::from_protected_input(&[0xB7; 32]).unwrap(); assert!(matches!( store - .create_pool(request(&binding, 1, 2, "Carrots"), wrong()) + .execute_inventory(request(&binding, 1, 2, "Carrots"), wrong()) .await, Err(OperationError::Workspace(WorkspaceError::Unauthorized)) )); @@ -716,7 +731,7 @@ async fn current_credentials_guard_pool_reads_replay_and_new_effects_after_revoc )); assert!(matches!( store - .pool_creation( + .inventory_operation( binding.clone(), receipt.checkpoint(), OperationId::from_bytes([1; 32]), @@ -729,13 +744,13 @@ async fn current_credentials_guard_pool_reads_replay_and_new_effects_after_revoc store.revoke(e.input().clone(), e.proof()).await.unwrap(); assert!(matches!( store - .create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) .await, Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) )); assert!(matches!( store - .create_pool(request(&binding, 3, 4, "New"), proof(e.proof())) + .execute_inventory(request(&binding, 3, 4, "New"), proof(e.proof())) .await, Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) )); @@ -752,7 +767,7 @@ async fn current_credentials_guard_pool_reads_replay_and_new_effects_after_revoc )); assert!(matches!( store - .pool_creation( + .inventory_operation( binding, receipt.checkpoint(), OperationId::from_bytes([1; 32]), @@ -773,12 +788,13 @@ async fn current_credentials_guard_pool_reads_replay_and_new_effects_after_revoc } #[tokio::test] -async fn simultaneous_pool_creations_serialize_identity_and_preserve_earlier_checkpoint_ancestry() { +async fn simultaneous_inventory_operations_serialize_identity_and_preserve_earlier_checkpoint_ancestry() + { let f = Fixture::new(); let (store, e, binding) = create(&f).await; let (left, right) = tokio::join!( - store.create_pool(request(&binding, 1, 2, "Carrots"), proof(e.proof())), - store.create_pool(request(&binding, 3, 2, "Competing"), proof(e.proof())) + store.execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())), + store.execute_inventory(request(&binding, 3, 2, "Competing"), proof(e.proof())) ); let first = match (left, right) { (Ok(value), Err(OperationError::StaleState)) @@ -786,19 +802,24 @@ async fn simultaneous_pool_creations_serialize_identity_and_preserve_earlier_che other => panic!("one serialized creation must win: {other:?}"), }; let next = request(&binding, 5, 6, "Parsnips"); - let next = CreatePoolRequest::new( + let next = InventoryRequest::new( binding.clone(), first.checkpoint(), CapturedPoolCreation::parse(next.command().protected_wire()).unwrap(), ) .unwrap(); - let second = committed(store.create_pool(next, proof(e.proof())).await.unwrap()); + let second = committed( + store + .execute_inventory(next, proof(e.proof())) + .await + .unwrap(), + ); assert_eq!(first.checkpoint().revision().get(), 1); assert_eq!(second.checkpoint().revision().get(), 2); assert_ne!(first.checkpoint().head(), second.checkpoint().head()); assert_eq!( store - .pool_creation( + .inventory_operation( binding.clone(), second.checkpoint(), first.attempt().operation_id(), @@ -884,7 +905,7 @@ async fn acknowledged_branch_cannot_be_satisfied_by_unprotected_history_index_fi .unwrap(); let acknowledged = committed( store - .create_pool(request(&binding, 1, 2, "First branch"), proof(e.proof())) + .execute_inventory(request(&binding, 1, 2, "First branch"), proof(e.proof())) .await .unwrap(), ) @@ -897,11 +918,11 @@ async fn acknowledged_branch_cannot_be_satisfied_by_unprotected_history_index_fi .await .unwrap(); store - .create_pool(request(&binding, 3, 4, "Other branch"), proof(e.proof())) + .execute_inventory(request(&binding, 3, 4, "Other branch"), proof(e.proof())) .await .unwrap(); store - .create_pool( + .execute_inventory( request(&binding, 5, 6, "Later other branch"), proof(e.proof()), ) @@ -933,3 +954,6 @@ async fn acknowledged_branch_cannot_be_satisfied_by_unprotected_history_index_fi )); store.close().await.unwrap(); } + +#[path = "pool_correction.rs"] +mod correction; diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -510,3 +510,63 @@ async fn prepared_enrollment_cannot_create_a_second_authority_namespace() { ); store.close().await.unwrap(); } + +#[tokio::test] +async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_completion() { + for revocation in [false, true] { + let f = Fixture::new(); + let e = enrollment(&f); + let clock = Arc::new(PausedClock { + state: std::sync::Mutex::new((false, false, false)), + changed: std::sync::Condvar::new(), + }); + let store = + NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) + .await + .unwrap(); + clock.arm(); + let mut operation: std::pin::Pin< + Box<dyn std::future::Future<Output = Result<(), WorkspaceError>> + '_>, + > = if revocation { + Box::pin(store.revoke(e.input().clone(), e.proof())) + } else { + Box::pin(async { + store + .authenticate(e.input().clone(), e.proof()) + .await + .map(|_| ()) + }) + }; + assert!(futures::poll!(operation.as_mut()).is_pending()); + clock.entered(); + let mut connection = sqlx::SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(f.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + sqlx::query("PRAGMA user_version=2") + .execute(&mut connection) + .await + .unwrap(); + clock.release(); + assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); + store.close().await.unwrap(); + sqlx::query("PRAGMA user_version=3") + .execute(&mut connection) + .await + .unwrap(); + connection.close().await.unwrap(); + let reopened = reopen(&f, &e).await; + assert_eq!( + reopened + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap() + .revocation_generation() + .get(), + 1 + ); + reopened.close().await.unwrap(); + } +} diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -101,7 +101,10 @@ struct NativeSellerStockAuthority { lock: String, schema_version: u16, retained_enrollment_versions: Vec<u16>, + retained_inventory_versions: Vec<u16>, authority_payload_schema: String, + inventory_operation_payload_schema: String, + inventory_movement_payload_schema: String, pool_tick_scale_explicit: bool, pool_tick_scale_encoding: String, inventory_checkpoint_minimum_required: bool, @@ -288,9 +291,12 @@ 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 == 2 + && stock.schema_version == 3 && stock.retained_enrollment_versions == [1] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v2" + && stock.retained_inventory_versions == [2] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v3" + && stock.inventory_operation_payload_schema == "radroots.seller_stock.operation.v2" + && stock.inventory_movement_payload_schema == "radroots.seller_stock.movement.v2" && stock.pool_tick_scale_explicit && stock.pool_tick_scale_encoding == "canonical_integer_string" && stock.inventory_checkpoint_minimum_required