lib

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

commit 8d2e9658c36af2266451b5165d2fb4da59653ac3
parent f0a2a8ae95899574e698f93f223c90a0a7837490
Author: triesap <tyson@radroots.org>
Date:   Sun, 25 Oct 2026 01:15:36 +0000

stock: commit owner-private option mappings atomically

- Capture exact mapping keys, quantities and original command digests.
- Enforce owner access and preserve physical pool balances and versions.
- Retain original effects with protected history and mapping CAS checks.
- Verify retained catalogs, interruption recovery and affected platforms.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 43+++++++++++++++++++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_protocol.txt | 27+++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_storage.txt | 3+++
Mcontracts/api_baselines/radroots_storage_sqlite.txt | 1+
Mcontracts/architecture/decisions/shared_sdk_refactor.v1.json | 14++++++++++----
Mcrates/domain/src/listing/reference.rs | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/quantity.rs | 26++++++++++++++++++++++++++
Mcrates/domain/src/stock.rs | 2++
Acrates/domain/src/stock/mapping.rs | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/stock/serialization.rs | 4+++-
Acrates/domain/tests/stock_mapping.rs | 199+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/src/command.rs | 2++
Mcrates/protocol/src/command/inventory.rs | 27+++++++++++++++++++++++++--
Acrates/protocol/src/command/stock_mapping.rs | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/fixtures/option_mapping.v1.json | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/option_mapping.rs | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage/src/inventory.rs | 40++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/crypto.rs | 25+++++++++++++++++++------
Mcrates/storage_sqlite/src/workspace/stock.rs | 164++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/stock/grants.rs | 11++++++-----
Mcrates/storage_sqlite/src/workspace/stock/inventory.rs | 220++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mcrates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs | 77++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcrates/storage_sqlite/src/workspace/stock/inventory/codec.rs | 48++++++++++++++++++++++++++++++++++++++++++++----
Acrates/storage_sqlite/src/workspace/stock/inventory/mapping.rs | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/src/workspace/stock/inventory/plan.rs | 13++++++++++++-
Mcrates/storage_sqlite/src/workspace/stock/schema.rs | 9++++++---
Mcrates/storage_sqlite/src/workspace/stock/tests.rs | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mcrates/storage_sqlite/src/workspace/worker.rs | 45+++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_sqlite/tests/support/option_mapping.rs | 916+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/storage_sqlite/tests/support/pool_creation.rs | 3+++
Mcrates/storage_sqlite/tests/support/stock_authority.rs | 2+-
Mtools/xtask/src/architecture/decision_package.rs | 52++++++++++++++++++++++++++++++++++++++++++++++++----
32 files changed, 2961 insertions(+), 149 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -74,6 +74,8 @@ impl core::fmt::Debug for radroots_domain::listing::ListingCoordinate pub fn radroots_domain::listing::ListingCoordinate::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl serde_core::ser::Serialize for radroots_domain::listing::ListingCoordinate pub fn radroots_domain::listing::ListingCoordinate::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> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::listing::ListingCoordinate +pub fn radroots_domain::listing::ListingCoordinate::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::listing::ListingId(_) impl radroots_domain::listing::ListingId pub const fn radroots_domain::listing::ListingId::as_bytes(&self) -> &[u8; 16] @@ -165,6 +167,18 @@ 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::MappingError +pub radroots_domain::stock::MappingError::InvalidVersion +pub radroots_domain::stock::MappingError::Quantity(radroots_domain::QuantityError) +pub radroots_domain::stock::MappingError::Stock(radroots_domain::stock::StockError) +pub radroots_domain::stock::MappingError::ZeroDraw +impl core::convert::From<radroots_domain::QuantityError> for radroots_domain::stock::MappingError +pub fn radroots_domain::stock::MappingError::from(radroots_domain::QuantityError) -> Self +impl core::convert::From<radroots_domain::stock::StockError> for radroots_domain::stock::MappingError +pub fn radroots_domain::stock::MappingError::from(radroots_domain::stock::StockError) -> Self +impl core::error::Error for radroots_domain::stock::MappingError +impl core::fmt::Display for radroots_domain::stock::MappingError +pub fn radroots_domain::stock::MappingError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_domain::stock::StockError pub radroots_domain::stock::StockError::ConservationViolation pub radroots_domain::stock::StockError::FractionalCount @@ -175,9 +189,34 @@ 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::convert::From<radroots_domain::stock::StockError> for radroots_domain::stock::MappingError +pub fn radroots_domain::stock::MappingError::from(radroots_domain::stock::StockError) -> Self 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 +pub struct radroots_domain::stock::OptionMappingKey +impl radroots_domain::stock::OptionMappingKey +pub const fn radroots_domain::stock::OptionMappingKey::listing(self) -> radroots_domain::listing::ListingCoordinate +pub const fn radroots_domain::stock::OptionMappingKey::new(radroots_domain::listing::ListingCoordinate, radroots_domain::ListingOptionId) -> Self +pub const fn radroots_domain::stock::OptionMappingKey::option_id(self) -> radroots_domain::ListingOptionId +impl core::fmt::Debug for radroots_domain::stock::OptionMappingKey +pub fn radroots_domain::stock::OptionMappingKey::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::stock::OptionPoolMapping +impl radroots_domain::stock::OptionPoolMapping +pub fn radroots_domain::stock::OptionPoolMapping::draw_for_sales(self, radroots_domain::PositiveDecimal) -> core::result::Result<radroots_domain::stock::StockTicks, radroots_domain::stock::MappingError> +pub const fn radroots_domain::stock::OptionPoolMapping::key(self) -> radroots_domain::stock::OptionMappingKey +pub fn radroots_domain::stock::OptionPoolMapping::new(radroots_domain::stock::OptionMappingKey, radroots_domain::PoolId, radroots_domain::stock::PoolUnit, radroots_domain::Quantity, radroots_domain::Sequence) -> core::result::Result<Self, radroots_domain::stock::MappingError> +pub const fn radroots_domain::stock::OptionPoolMapping::per_sale_ticks(self) -> radroots_domain::stock::StockTicks +pub const fn radroots_domain::stock::OptionPoolMapping::per_sale_unit(self) -> radroots_domain::Quantity +pub const fn radroots_domain::stock::OptionPoolMapping::pool_id(self) -> radroots_domain::PoolId +pub const fn radroots_domain::stock::OptionPoolMapping::pool_unit(self) -> radroots_domain::stock::PoolUnit +pub const fn radroots_domain::stock::OptionPoolMapping::version(self) -> radroots_domain::Sequence +impl core::fmt::Debug for radroots_domain::stock::OptionPoolMapping +pub fn radroots_domain::stock::OptionPoolMapping::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_domain::stock::OptionPoolMapping +pub fn radroots_domain::stock::OptionPoolMapping::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> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::stock::OptionPoolMapping +pub fn radroots_domain::stock::OptionPoolMapping::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::stock::PhysicalBalances pub radroots_domain::stock::PhysicalBalances::available: radroots_domain::stock::StockTicks pub radroots_domain::stock::PhysicalBalances::committed_hold: radroots_domain::stock::StockTicks @@ -443,6 +482,8 @@ pub radroots_domain::QuantityError::PrecisionLoss pub radroots_domain::QuantityError::UnitMismatch impl core::convert::From<radroots_domain::AmountError> for radroots_domain::QuantityError pub fn radroots_domain::QuantityError::from(radroots_domain::AmountError) -> Self +impl core::convert::From<radroots_domain::QuantityError> for radroots_domain::stock::MappingError +pub fn radroots_domain::stock::MappingError::from(radroots_domain::QuantityError) -> Self impl core::error::Error for radroots_domain::QuantityError pub fn radroots_domain::QuantityError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)> impl core::fmt::Display for radroots_domain::QuantityError @@ -1044,6 +1085,8 @@ pub fn radroots_domain::Quantity::new(radroots_domain::Decimal, radroots_domain: pub const fn radroots_domain::Quantity::unit(self) -> radroots_domain::listing::MeasurementUnit impl core::fmt::Debug for radroots_domain::Quantity pub fn radroots_domain::Quantity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::Quantity +pub fn radroots_domain::Quantity::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::ReadinessClaim impl radroots_domain::ReadinessClaim pub const fn radroots_domain::ReadinessClaim::agreement(&self) -> radroots_domain::RecordId diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -180,6 +180,7 @@ pub fn radroots_protocol::command::CapturedCommand::fmt(&self, &mut core::fmt::F 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) +pub radroots_protocol::command::CapturedInventoryCommand::MapOption(radroots_protocol::command::CapturedOptionMapping) 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 @@ -187,9 +188,12 @@ pub const fn radroots_protocol::command::CapturedInventoryCommand::correction_in 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 const fn radroots_protocol::command::CapturedInventoryCommand::mapping_input(&self) -> core::option::Option<&radroots_protocol::command::MapOptionInput> 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::CapturedOptionMapping> for radroots_protocol::command::CapturedInventoryCommand +pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedOptionMapping) -> Self 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 @@ -218,6 +222,7 @@ pub const fn radroots_protocol::command::CommandKind::as_str(self) -> &'static s pub enum radroots_protocol::command::InventoryCommandKind pub radroots_protocol::command::InventoryCommandKind::AddStock pub radroots_protocol::command::InventoryCommandKind::CreatePool +pub radroots_protocol::command::InventoryCommandKind::MapOption pub radroots_protocol::command::InventoryCommandKind::RemoveStock pub radroots_protocol::command::InventoryCommandKind::SpoilStock pub struct radroots_protocol::command::CapturedChatCommand @@ -239,6 +244,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::CapturedOptionMapping +impl radroots_protocol::command::CapturedOptionMapping +pub const fn radroots_protocol::command::CapturedOptionMapping::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub const fn radroots_protocol::command::CapturedOptionMapping::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedOptionMapping::digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::command::CapturedOptionMapping::input(&self) -> &radroots_protocol::command::MapOptionInput +pub fn radroots_protocol::command::CapturedOptionMapping::new(radroots_domain::context::CommandContextData, radroots_protocol::command::MapOptionInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::CapturedOptionMapping::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::CapturedOptionMapping::protected_wire(&self) -> &[u8] +impl core::convert::From<radroots_protocol::command::CapturedOptionMapping> for radroots_protocol::command::CapturedInventoryCommand +pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedOptionMapping) -> Self +impl core::fmt::Debug for radroots_protocol::command::CapturedOptionMapping +pub fn radroots_protocol::command::CapturedOptionMapping::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 @@ -294,6 +312,15 @@ 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::MapOptionInput +impl radroots_protocol::command::MapOptionInput +pub const fn radroots_protocol::command::MapOptionInput::expected_mapping_version(&self) -> radroots_domain::context::Sequence +pub const fn radroots_protocol::command::MapOptionInput::key(&self) -> radroots_domain::stock::mapping::OptionMappingKey +pub fn radroots_protocol::command::MapOptionInput::new(radroots_domain::stock::mapping::OptionMappingKey, radroots_domain::identifier::PoolId, radroots_domain::quantity::Quantity, radroots_domain::context::Sequence) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::MapOptionInput::per_sale_unit(&self) -> radroots_domain::quantity::Quantity +pub const fn radroots_protocol::command::MapOptionInput::pool_id(&self) -> radroots_domain::identifier::PoolId +impl core::fmt::Debug for radroots_protocol::command::MapOptionInput +pub fn radroots_protocol::command::MapOptionInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::PoolCorrectionInput impl radroots_protocol::command::PoolCorrectionInput pub const fn radroots_protocol::command::PoolCorrectionInput::amount(&self) -> radroots_domain::amount::PositiveDecimal diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -1382,8 +1382,10 @@ 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_mapping(radroots_storage::command::CommitAttempt, radroots_domain::stock::PoolSnapshot, radroots_domain::stock::mapping::OptionPoolMapping, radroots_storage::inventory::InventoryCheckpointRef) -> core::result::Result<Self, radroots_storage::command::OperationError> 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::mapping(&self) -> core::option::Option<radroots_domain::stock::mapping::OptionPoolMapping> 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 @@ -1401,6 +1403,7 @@ pub fn radroots_storage::inventory::InventoryRequest::fmt(&self, &mut core::fmt: pub trait radroots_storage::inventory::InventoryStore: radroots_storage::workspace::WorkspaceStore 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::option_mapping(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::stock::mapping::OptionMappingKey, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::mapping::OptionPoolMapping>, 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 mod radroots_storage::journal pub use radroots_storage::journal::BoxFuture diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -406,6 +406,7 @@ pub fn radroots_storage_sqlite::workspace::NativeWorkspace::signing_plan(&self, impl radroots_storage::inventory::InventoryStore for radroots_storage_sqlite::workspace::NativeWorkspace 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::option_mapping(&self, radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::stock::mapping::OptionMappingKey, radroots_storage::workspace::AttachmentProof) -> radroots_transport::source::BoxFuture<'_, core::result::Result<core::option::Option<radroots_domain::stock::mapping::OptionPoolMapping>, 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>> 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>> diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -75,16 +75,22 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 4, + "schema_version": 5, "retained_enrollment_versions": [ 1 ], "retained_inventory_versions": [ 2, - 3 + 3, + 4 ], - "authority_payload_schema": "radroots.seller_stock.authority.v4", - "inventory_operation_payload_schema": "radroots.seller_stock.operation.v3", + "authority_payload_schema": "radroots.seller_stock.authority.v5", + "inventory_operation_payload_schema": "radroots.seller_stock.operation.v4", + "mapping_payload_schema": "radroots.seller_stock.mapping.v1", + "mapping_owner_administration_required": true, + "mapping_changes_physical_stock": false, + "mapping_changes_pool_version": false, + "mapping_create_expected_version": 0, "inventory_movement_payload_schema": "radroots.seller_stock.movement.v2", "pool_tick_scale_explicit": true, "pool_tick_scale_encoding": "canonical_integer_string", diff --git a/crates/domain/src/listing/reference.rs b/crates/domain/src/listing/reference.rs @@ -43,6 +43,60 @@ impl serde::Serialize for ListingCoordinate { } } +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for ListingCoordinate { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(serde::Deserialize)] + #[serde(deny_unknown_fields)] + struct Wire { + kind: u16, + #[serde(deserialize_with = "canonical_author")] + author: PublicKey, + d: ListingId, + } + struct Visitor; + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = Wire; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a closed NIP-99 listing coordinate object") + } + fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<Wire, A::Error> { + <Wire as serde::Deserialize>::deserialize( + serde::de::value::MapAccessDeserializer::new(map), + ) + } + } + let wire = deserializer.deserialize_map(Visitor)?; + if wire.kind != 30402 { + return Err(serde::de::Error::custom( + "unsupported listing coordinate kind", + )); + } + Ok(Self::new(wire.author, wire.d)) + } +} + +#[cfg(feature = "serde")] +fn canonical_author<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result<PublicKey, D::Error> { + struct Author; + impl serde::de::Visitor<'_> for Author { + type Value = PublicKey; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a canonical lowercase public key") + } + fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<PublicKey, E> { + let key = PublicKey::from_hex(value).map_err(E::custom)?; + if key.to_hex() != value { + return Err(E::custom("noncanonical listing author")); + } + Ok(key) + } + } + deserializer.deserialize_str(Author) +} + /// Exact revision identity and coordinate; bytes alone authenticate no source. #[derive(Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] diff --git a/crates/domain/src/quantity.rs b/crates/domain/src/quantity.rs @@ -9,6 +9,32 @@ pub struct Quantity { unit: MeasurementUnit, } +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for Quantity { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(serde::Deserialize)] + #[serde(deny_unknown_fields)] + struct Wire { + amount: Decimal, + unit: MeasurementUnit, + } + struct Visitor; + impl<'de> serde::de::Visitor<'de> for Visitor { + type Value = Wire; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a closed exact quantity object") + } + fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<Wire, A::Error> { + <Wire as serde::Deserialize>::deserialize( + serde::de::value::MapAccessDeserializer::new(map), + ) + } + } + let wire = deserializer.deserialize_map(Visitor)?; + Self::new(wire.amount, wire.unit).map_err(serde::de::Error::custom) + } +} + impl Quantity { /// Admits exact values, including explicit zero; each counts are integral. pub fn new(amount: Decimal, unit: MeasurementUnit) -> Result<Self, QuantityError> { diff --git a/crates/domain/src/stock.rs b/crates/domain/src/stock.rs @@ -3,6 +3,8 @@ use crate::{PoolId, Quantity, Sequence, listing::MeasurementUnit}; use core::{fmt, str::FromStr}; +mod mapping; +pub use mapping::{MappingError, OptionMappingKey, OptionPoolMapping}; /// A bounded, input-free stock value failure. #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/crates/domain/src/stock/mapping.rs b/crates/domain/src/stock/mapping.rs @@ -0,0 +1,207 @@ +//! Exact private option-to-pool claims; no store, stock hold or source authority. +use super::{PoolUnit, StockError, StockTicks}; +use crate::{ + ListingOptionId, PoolId, PositiveDecimal, Quantity, QuantityError, Sequence, + listing::ListingCoordinate, +}; +use core::fmt; + +/// The entire listing coordinate and stable option identity of a private mapping. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct OptionMappingKey { + listing: ListingCoordinate, + option: ListingOptionId, +} +impl OptionMappingKey { + /// Captures identity metadata without authenticating an owner or listing. + pub const fn new(listing: ListingCoordinate, option: ListingOptionId) -> Self { + Self { listing, option } + } + /// Returns the complete claimed listing coordinate. + pub const fn listing(self) -> ListingCoordinate { + self.listing + } + /// Returns the stable option identity within that listing. + pub const fn option_id(self) -> ListingOptionId { + self.option + } +} +impl fmt::Debug for OptionMappingKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("OptionMappingKey(<private metadata>)") + } +} + +/// A validated private conversion claim at one positive mapping version. +/// This establishes neither an observed listing nor physical backing. The +/// executor checks current ownership, pool identity and versions separately. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct OptionPoolMapping { + key: OptionMappingKey, + pool: PoolId, + unit: PoolUnit, + per_sale_unit: Quantity, + per_sale_ticks: StockTicks, + version: Sequence, +} +impl OptionPoolMapping { + /// Resolves an explicit positive per-sale draw into the fixed pool precision. + /// Only exact g/kg or mL/L conversion is performed. Package labels, estimated + /// contents and mass/volume assumptions never supply a conversion here. + pub fn new( + key: OptionMappingKey, + pool: PoolId, + unit: PoolUnit, + per_sale_unit: Quantity, + version: Sequence, + ) -> Result<Self, MappingError> { + if version.get() == 0 { + return Err(MappingError::InvalidVersion); + } + if per_sale_unit.amount().is_zero() { + return Err(MappingError::ZeroDraw); + } + let normalized = per_sale_unit.convert(unit.unit())?; + let per_sale_ticks = unit.ticks_for(normalized)?; + if per_sale_ticks == StockTicks::ZERO { + return Err(MappingError::ZeroDraw); + } + Ok(Self { + key, + pool, + unit, + per_sale_unit, + per_sale_ticks, + version, + }) + } + /// Returns the exact private option key. + pub const fn key(self) -> OptionMappingKey { + self.key + } + /// Returns the claimed pool identity. + pub const fn pool_id(self) -> PoolId { + self.pool + } + /// Returns the fixed unit/precision used to validate this mapping. + pub const fn pool_unit(self) -> PoolUnit { + self.unit + } + /// Retains the original explicit quantity, including its declared SI unit. + pub const fn per_sale_unit(self) -> Quantity { + self.per_sale_unit + } + /// Returns the exact integral pool ticks for one declared sale unit. + pub const fn per_sale_ticks(self) -> StockTicks { + self.per_sale_ticks + } + /// Returns a positive mapping version, without authenticating freshness. + pub const fn version(self) -> Sequence { + self.version + } + /// Multiplies a validated positive sale amount without rounding pool ticks. + /// The caller must independently enforce the selected option's sale basis, + /// including integral package purchases. This function reserves no stock. + pub fn draw_for_sales(self, sales: PositiveDecimal) -> Result<StockTicks, MappingError> { + let amount = sales.amount(); + let numerator = u128::from(self.per_sale_ticks.get()) + .checked_mul(u128::from(amount.coefficient())) + .ok_or(StockError::OutOfRange)?; + let denominator = 10_u128.pow(u32::from(amount.scale())); + if !numerator.is_multiple_of(denominator) { + return Err(StockError::PrecisionLoss.into()); + } + let ticks = u64::try_from(numerator / denominator).map_err(|_| StockError::OutOfRange)?; + StockTicks::new(ticks).map_err(MappingError::from) + } +} +impl fmt::Debug for OptionPoolMapping { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("OptionPoolMapping(<private metadata>)") + } +} + +/// Input-free exact mapping validation failure. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum MappingError { + /// A stored mapping version must be positive; version0 denotes absence. + InvalidVersion, + /// One sale unit cannot consume an explicit zero amount. + ZeroDraw, + /// Explicit quantity conversion is incompatible or inexact. + Quantity(QuantityError), + /// Exact ticks or multiplication exceed the physical value contract. + Stock(StockError), +} +impl From<QuantityError> for MappingError { + fn from(value: QuantityError) -> Self { + Self::Quantity(value) + } +} +impl From<StockError> for MappingError { + fn from(value: StockError) -> Self { + Self::Stock(value) + } +} +impl fmt::Display for MappingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidVersion => f.write_str("mapping version must be positive"), + Self::ZeroDraw => f.write_str("mapping draw must be positive"), + Self::Quantity(error) => error.fmt(f), + Self::Stock(error) => error.fmt(f), + } + } +} +impl core::error::Error for MappingError {} + +#[cfg(feature = "serde")] +mod serialization { + use super::*; + use serde::{Deserialize, Serialize}; + #[derive(Serialize, Deserialize)] + #[serde(deny_unknown_fields)] + struct Wire { + listing: ListingCoordinate, + option_id: ListingOptionId, + pool_id: PoolId, + pool_unit: PoolUnit, + per_sale_unit: Quantity, + per_sale_ticks: StockTicks, + version: Sequence, + } + impl Serialize for OptionPoolMapping { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + Wire { + listing: self.key.listing, + option_id: self.key.option, + pool_id: self.pool, + pool_unit: self.unit, + per_sale_unit: self.per_sale_unit, + per_sale_ticks: self.per_sale_ticks, + version: self.version, + } + .serialize(serializer) + } + } + impl<'de> Deserialize<'de> for OptionPoolMapping { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + let wire: Wire = super::super::serialization::object(deserializer)?; + let value = Self::new( + OptionMappingKey::new(wire.listing, wire.option_id), + wire.pool_id, + wire.pool_unit, + wire.per_sale_unit, + wire.version, + ) + .map_err(serde::de::Error::custom)?; + if value.per_sale_ticks() != wire.per_sale_ticks { + return Err(serde::de::Error::custom( + "mapping tick conversion does not match its declared quantity", + )); + } + Ok(value) + } + } +} diff --git a/crates/domain/src/stock/serialization.rs b/crates/domain/src/stock/serialization.rs @@ -136,7 +136,9 @@ impl<'de> Deserialize<'de> for PoolSnapshot { } } -fn object<'de, D: Deserializer<'de>, T: Deserialize<'de>>(deserializer: D) -> Result<T, D::Error> { +pub(super) fn object<'de, D: Deserializer<'de>, T: Deserialize<'de>>( + deserializer: D, +) -> Result<T, D::Error> { struct Visitor<T>(core::marker::PhantomData<T>); impl<'de, T: Deserialize<'de>> de::Visitor<'de> for Visitor<T> { type Value = T; diff --git a/crates/domain/tests/stock_mapping.rs b/crates/domain/tests/stock_mapping.rs @@ -0,0 +1,199 @@ +use radroots_domain::{ + Decimal, ListingOptionId, PoolId, PositiveDecimal, PublicKey, Quantity, QuantityError, + Sequence, + listing::{ListingCoordinate, ListingId, MeasurementUnit}, + stock::{MappingError, OptionMappingKey, OptionPoolMapping, PoolUnit, StockError}, +}; +fn key() -> OptionMappingKey { + OptionMappingKey::new( + ListingCoordinate::new( + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") + .unwrap(), + ListingId::from_bytes([1; 16]), + ), + ListingOptionId::from_bytes([2; 32]), + ) +} +fn quantity(amount: &str, unit: MeasurementUnit) -> Quantity { + Quantity::new(amount.parse::<Decimal>().unwrap(), unit).unwrap() +} +fn mapping( + amount: &str, + unit: MeasurementUnit, + pool_unit: PoolUnit, + version: u64, +) -> Result<OptionPoolMapping, MappingError> { + OptionPoolMapping::new( + key(), + PoolId::from_bytes([3; 32]), + pool_unit, + quantity(amount, unit), + Sequence::new(version).unwrap(), + ) +} +#[test] +fn exact_mapping_preserves_the_declared_si_basis_and_multiplies_without_tick_rounding() { + let value = mapping( + "250", + MeasurementUnit::Gram, + PoolUnit::new(MeasurementUnit::Kilogram, 3).unwrap(), + 1, + ) + .unwrap(); + assert_eq!(value.key(), key()); + assert_eq!(value.pool_id(), PoolId::from_bytes([3; 32])); + assert_eq!( + value.per_sale_unit(), + quantity("250", MeasurementUnit::Gram) + ); + assert_eq!(value.per_sale_ticks().get(), 250); + assert_eq!( + value + .draw_for_sales("2".parse::<PositiveDecimal>().unwrap()) + .unwrap() + .get(), + 500 + ); + assert_eq!( + value.draw_for_sales("1.5".parse().unwrap()).unwrap().get(), + 375 + ); + let volume = mapping( + "250", + MeasurementUnit::Millilitre, + PoolUnit::new(MeasurementUnit::Litre, 3).unwrap(), + 1, + ) + .unwrap(); + assert_eq!(volume.per_sale_ticks().get(), 250); + let one_tick = mapping( + "1", + MeasurementUnit::Each, + PoolUnit::new(MeasurementUnit::Each, 0).unwrap(), + 1, + ) + .unwrap(); + assert_eq!( + one_tick.draw_for_sales("0.5".parse().unwrap()), + Err(MappingError::Stock(StockError::PrecisionLoss)) + ); + assert_eq!( + format!("{value:?}"), + "OptionPoolMapping(<private metadata>)" + ); +} +#[test] +fn zero_absent_versions_unjustified_dimensions_precision_loss_and_capacity_are_refused() { + let kg = PoolUnit::new(MeasurementUnit::Kilogram, 3).unwrap(); + assert_eq!( + mapping("0", MeasurementUnit::Gram, kg, 1), + Err(MappingError::ZeroDraw) + ); + assert_eq!( + mapping("250", MeasurementUnit::Gram, kg, 0), + Err(MappingError::InvalidVersion) + ); + for unit in [ + MeasurementUnit::Litre, + MeasurementUnit::Millilitre, + MeasurementUnit::Each, + ] { + assert_eq!( + mapping("1", unit, kg, 1), + Err(MappingError::Quantity(QuantityError::IncompatibleDimension)) + ); + } + assert_eq!( + mapping( + "1", + MeasurementUnit::Gram, + PoolUnit::new(MeasurementUnit::Kilogram, 0).unwrap(), + 1 + ), + Err(MappingError::Stock(StockError::PrecisionLoss)) + ); + assert_eq!( + mapping("0.000001", MeasurementUnit::Gram, kg, 1), + Err(MappingError::Quantity(QuantityError::PrecisionLoss)) + ); + let large = mapping( + "999999999999", + MeasurementUnit::Kilogram, + PoolUnit::new(MeasurementUnit::Kilogram, 6).unwrap(), + 1, + ) + .unwrap(); + assert_eq!( + large.draw_for_sales("2".parse().unwrap()), + Err(MappingError::Stock(StockError::OutOfRange)) + ); + assert_eq!( + large.draw_for_sales("999999999999".parse().unwrap()), + Err(MappingError::Stock(StockError::OutOfRange)) + ); + assert_eq!( + large + .draw_for_sales("0.000001".parse().unwrap()) + .unwrap() + .get(), + 999999999999 + ); +} +#[cfg(feature = "serde")] +#[test] +fn closed_mapping_codecs_recompute_derived_ticks_and_refuse_coordinate_or_value_aliases() { + use serde_json::json; + let value = mapping( + "250", + MeasurementUnit::Gram, + PoolUnit::new(MeasurementUnit::Kilogram, 3).unwrap(), + 1, + ) + .unwrap(); + let wire = serde_json::to_value(value).unwrap(); + assert_eq!(wire["per_sale_ticks"], json!("250")); + assert_eq!( + serde_json::from_value::<OptionPoolMapping>(wire.clone()).unwrap(), + value + ); + for (path, bad) in [ + ("/per_sale_ticks", json!("251")), + ("/per_sale_ticks", json!(250)), + ("/version", json!("0")), + ("/version", json!(1)), + ("/per_sale_unit/amount", json!("0")), + ("/pool_unit/scale", json!("2")), + ("/listing/kind", json!(1)), + ("/listing/kind", json!(30402.0)), + ("/listing/kind", json!("30402")), + ("/listing", json!([30402, "00".repeat(32), "00".repeat(16)])), + ("/pool_unit", json!(["kg", "3"])), + ] { + let mut changed = wire.clone(); + *changed.pointer_mut(path).unwrap() = bad; + assert!( + serde_json::from_value::<OptionPoolMapping>(changed).is_err(), + "{path}" + ); + } + for field in [ + "listing", + "option_id", + "pool_id", + "pool_unit", + "per_sale_unit", + "per_sale_ticks", + "version", + ] { + let mut changed = wire.clone(); + changed.as_object_mut().unwrap().remove(field); + assert!( + serde_json::from_value::<OptionPoolMapping>(changed).is_err(), + "{field}" + ); + } + let mut changed = wire.clone(); + changed["available"] = json!("999"); + assert!(serde_json::from_value::<OptionPoolMapping>(changed).is_err()); + assert!(serde_json::from_value::<OptionPoolMapping>(json!([wire])).is_err()); +} diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs @@ -52,10 +52,12 @@ mod captured; mod inventory; mod stock; mod stock_correction; +mod stock_mapping; pub use captured::{CapturedCommand, CommandKind}; pub use inventory::{CapturedInventoryCommand, InventoryCommandKind}; pub use stock::{CapturedPoolCreation, CreatePoolInput}; pub use stock_correction::{CapturedPoolCorrection, PoolCorrectionInput}; +pub use stock_mapping::{CapturedOptionMapping, MapOptionInput}; /// 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 @@ -19,6 +19,8 @@ pub enum InventoryCommandKind { RemoveStock, /// Audited physical spoilage. SpoilStock, + /// Owner-private listing option configuration, without a physical movement. + MapOption, } /// Original bounded captured inventory data. Its metadata establishes no grant, /// physical stock, transaction completion or permission to change obligations. @@ -27,6 +29,8 @@ pub enum CapturedInventoryCommand { CreatePool(CapturedPoolCreation), /// Exact adjustment or spoilage profile. CorrectPool(CapturedPoolCorrection), + /// Exact private option mapping configuration. + MapOption(super::CapturedOptionMapping), } impl CapturedInventoryCommand { pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { @@ -38,6 +42,7 @@ impl CapturedInventoryCommand { } let header: Header = parse_object(raw)?; match header.kind.as_str() { + "stock.map_option" => super::CapturedOptionMapping::parse(raw).map(Self::MapOption), "stock.create_pool" => CapturedPoolCreation::parse(raw).map(Self::CreatePool), "stock.adjust" | "stock.spoil" => { CapturedPoolCorrection::parse(raw).map(Self::CorrectPool) @@ -49,29 +54,34 @@ impl CapturedInventoryCommand { match self { Self::CreatePool(v) => v.context(), Self::CorrectPool(v) => v.context(), + Self::MapOption(v) => v.context(), } } pub const fn digest(&self) -> CommandDigest { match self { Self::CreatePool(v) => v.digest(), Self::CorrectPool(v) => v.digest(), + Self::MapOption(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(), + Self::MapOption(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(), + Self::MapOption(v) => v.protected_wire(), } } pub const fn kind(&self) -> InventoryCommandKind { match self { Self::CreatePool(_) => InventoryCommandKind::CreatePool, + Self::MapOption(_) => InventoryCommandKind::MapOption, Self::CorrectPool(v) => match v.input().kind() { AvailableStockCorrection::Add => InventoryCommandKind::AddStock, AvailableStockCorrection::Remove => InventoryCommandKind::RemoveStock, @@ -84,20 +94,28 @@ impl CapturedInventoryCommand { match self { Self::CreatePool(v) => v.input().id(), Self::CorrectPool(v) => v.input().pool_id(), + Self::MapOption(v) => v.input().pool_id(), + } + } + /// Borrows actual mapping configuration, without manufacturing it for other commands. + pub const fn mapping_input(&self) -> Option<&super::MapOptionInput> { + match self { + Self::MapOption(v) => Some(v.input()), + Self::CreatePool(_) | Self::CorrectPool(_) => None, } } /// 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, + Self::CorrectPool(_) | Self::MapOption(_) => 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, + Self::CreatePool(_) | Self::MapOption(_) => None, } } } @@ -106,6 +124,11 @@ impl From<CapturedPoolCreation> for CapturedInventoryCommand { Self::CreatePool(value) } } +impl From<super::CapturedOptionMapping> for CapturedInventoryCommand { + fn from(value: super::CapturedOptionMapping) -> Self { + Self::MapOption(value) + } +} impl From<CapturedPoolCorrection> for CapturedInventoryCommand { fn from(value: CapturedPoolCorrection) -> Self { Self::CorrectPool(value) diff --git a/crates/protocol/src/command/stock_mapping.rs b/crates/protocol/src/command/stock_mapping.rs @@ -0,0 +1,205 @@ +//! Exact owner-private option mapping capture, without ownership or stock 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, ListingOptionId, PoolId, Quantity, + Sequence, listing::ListingCoordinate, stock::OptionMappingKey, +}; +use serde::{Deserialize, Serialize, ser::SerializeStruct}; +use zeroize::Zeroizing; + +/// An explicit private draw claim. Version0 means the mapping must not exist; +/// positive versions compare an existing mapping before an actual update. +pub struct MapOptionInput { + key: OptionMappingKey, + pool: PoolId, + per_sale_unit: Quantity, + expected: Sequence, +} +impl MapOptionInput { + /// Captures a positive declared draw. Pool existence, unit conversion, + /// ownership and freshness are verified by the authoritative executor. + pub fn new( + key: OptionMappingKey, + pool: PoolId, + per_sale_unit: Quantity, + expected: Sequence, + ) -> Result<Self, CommandError> { + if per_sale_unit.amount().is_zero() { + return Err(CommandError::InvalidInput); + } + Ok(Self { + key, + pool, + per_sale_unit, + expected, + }) + } + /// Returns the complete listing/option identity. + pub const fn key(&self) -> OptionMappingKey { + self.key + } + /// Returns the referenced private pool without asserting it exists. + pub const fn pool_id(&self) -> PoolId { + self.pool + } + /// Returns the exact original per-sale-unit quantity. + pub const fn per_sale_unit(&self) -> Quantity { + self.per_sale_unit + } + /// Returns the expected mapping version, including absence at0. + pub const fn expected_mapping_version(&self) -> Sequence { + self.expected + } +} +impl fmt::Debug for MapOptionInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("MapOptionInput(<redacted>)") + } +} + +/// Closed bounded `stock.map_option` data; capturing it reserves no physical stock. +pub struct CapturedOptionMapping { + context: CommandContextData, + input: MapOptionInput, + wire: Zeroizing<Box<[u8]>>, + digest: CommandDigest, + approval: ApprovalIntentDigest, +} +impl CapturedOptionMapping { + /// Retains the complete command and separate canonical command/approval hashes. + pub fn new(context: CommandContextData, input: MapOptionInput) -> 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, + }) + } + /// Validates a duplicate-safe bounded closed command and canonical values. + 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 Input { + listing: ListingCoordinate, + option_id: ListingOptionId, + pool_id: PoolId, + per_sale_unit: Quantity, + expected_mapping_version: Sequence, + } + let root: Root<'_> = parse_object(raw)?; + if root.kind != "stock.map_option" { + return Err(CommandError::UnsupportedCommand); + } + let input: Input = parse_object(root.input.get().as_bytes())?; + Self::new( + root.context, + MapOptionInput::new( + OptionMappingKey::new(input.listing, input.option_id), + input.pool_id, + input.per_sale_unit, + input.expected_mapping_version, + )?, + ) + } + /// Borrows exact captured context; no field is refreshed during replay. + pub const fn context(&self) -> &CommandContextData { + &self.context + } + /// Borrows the private mapping input. + pub const fn input(&self) -> &MapOptionInput { + &self.input + } + /// Borrows bounded canonical protected bytes. + pub fn protected_wire(&self) -> &[u8] { + &self.wire + } + /// Returns the exact command digest, excluding diagnostic correlation only. + pub const fn digest(&self) -> CommandDigest { + self.digest + } + /// Returns the non-circular intent digest without approval or correlation. + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + self.approval + } +} +impl fmt::Debug for CapturedOptionMapping { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedOptionMapping(<redacted>)") + } +} +struct Wire<'a> { + context: &'a CommandContextData, + input: &'a MapOptionInput, + approval: bool, + correlation: bool, +} +impl Serialize for Wire<'_> { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut value = serializer.serialize_struct("OptionMapping", 3)?; + value.serialize_field( + "context", + &Context(self.context, self.approval, self.correlation), + )?; + value.serialize_field("input", &InputWire(self.input))?; + value.serialize_field("type", "stock.map_option")?; + value.end() + } +} +struct InputWire<'a>(&'a MapOptionInput); +impl Serialize for InputWire<'_> { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let v = self.0; + let mut value = serializer.serialize_struct("MapOptionInput", 5)?; + value.serialize_field("expected_mapping_version", &v.expected)?; + value.serialize_field("listing", &Coordinate(v.key.listing()))?; + value.serialize_field("option_id", &v.key.option_id())?; + value.serialize_field("per_sale_unit", &v.per_sale_unit)?; + value.serialize_field("pool_id", &v.pool)?; + value.end() + } +} +struct Coordinate(ListingCoordinate); +impl Serialize for Coordinate { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut value = serializer.serialize_struct("ListingCoordinate", 3)?; + value.serialize_field("author", &self.0.author())?; + value.serialize_field("d", &self.0.d())?; + value.serialize_field("kind", &self.0.kind())?; + value.end() + } +} diff --git a/crates/protocol/tests/fixtures/option_mapping.v1.json b/crates/protocol/tests/fixtures/option_mapping.v1.json @@ -0,0 +1,88 @@ +{ + "provenance": "Synthetic complete option mapping cases. Independent Python sorted ASCII schema keys, compact UTF-8 strings and exact string values implement the governed RFC8785 subset; fixed30402 is the sole numeric field. No Rust serializer/hash helper or product data is consumed.", + "oracle_python": "3.14.7 (main, Sep 29 2026, 14:50:11) [Clang 22.1.3 ]", + "cases": [ + { + "wire": { + "type": "stock.map_option", + "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": { + "listing": { + "kind": 30402, + "author": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "d": "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a" + }, + "option_id": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + "pool_id": "0808080808080808080808080808080808080808080808080808080808080808", + "per_sale_unit": { + "amount": "250", + "unit": "g" + }, + "expected_mapping_version": "0" + } + }, + "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\":{\"expected_mapping_version\":\"0\",\"listing\":{\"author\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"d\":\"0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a\",\"kind\":30402},\"option_id\":\"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\",\"per_sale_unit\":{\"amount\":\"250\",\"unit\":\"g\"},\"pool_id\":\"0808080808080808080808080808080808080808080808080808080808080808\"},\"type\":\"stock.map_option\"}", + "command_digest": "a67c3594862d6ed343ac973f7bde4d92186cff90f2618565b78dd213e8bc4d0c", + "approval_intent_digest": "e5f0c37f4bfe25b69e32fbca9f0ba765295e535921c4263a22a81da549254642" + }, + { + "wire": { + "type": "stock.map_option", + "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": { + "listing": { + "kind": 30402, + "author": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "d": "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a" + }, + "option_id": "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + "pool_id": "0909090909090909090909090909090909090909090909090909090909090909", + "per_sale_unit": { + "amount": "0.5", + "unit": "kg" + }, + "expected_mapping_version": "1" + } + }, + "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\":{\"expected_mapping_version\":\"1\",\"listing\":{\"author\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"d\":\"0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a\",\"kind\":30402},\"option_id\":\"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b\",\"per_sale_unit\":{\"amount\":\"0.5\",\"unit\":\"kg\"},\"pool_id\":\"0909090909090909090909090909090909090909090909090909090909090909\"},\"type\":\"stock.map_option\"}", + "command_digest": "9b4d3d27e915806280c6fd784b9df94d3932944d1e38ecd2cce7f75595d3870a", + "approval_intent_digest": "06aca7ebc1aa1bb63e715ac92c4696ed0e08f15bfccca5df4031a8f0e51f8836" + } + ] +} diff --git a/crates/protocol/tests/option_mapping.rs b/crates/protocol/tests/option_mapping.rs @@ -0,0 +1,122 @@ +#![cfg(feature = "commands")] +use radroots_protocol::command::CapturedOptionMapping; +use serde_json::{Value, json}; +fn cases() -> Value { + serde_json::from_str(include_str!("fixtures/option_mapping.v1.json")).unwrap() +} + +#[test] +fn captured_mapping_matches_independent_canonical_hashes_and_preserves_original_quantities() { + for case in cases()["cases"].as_array().unwrap() { + let captured = + CapturedOptionMapping::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!( + serde_json::from_slice::<Value>(captured.protected_wire()).unwrap(), + case["wire"] + ); + assert_eq!( + CapturedOptionMapping::parse(captured.protected_wire()) + .unwrap() + .digest(), + captured.digest() + ); + assert_eq!(format!("{captured:?}"), "CapturedOptionMapping(<redacted>)"); + } + let first = &cases()["cases"][0]["wire"]; + let captured = CapturedOptionMapping::parse(&serde_json::to_vec(first).unwrap()).unwrap(); + assert_eq!(captured.input().per_sale_unit().amount().to_string(), "250"); + assert_eq!(captured.input().expected_mapping_version().get(), 0); + for (path, value) in [ + ("/input/pool_id", json!("09".repeat(32))), + ("/input/option_id", json!("0c".repeat(32))), + ("/input/per_sale_unit/amount", json!("500")), + ("/input/expected_mapping_version", json!("1")), + ("/input/listing/d", json!("0c".repeat(16))), + ] { + let mut changed = first.clone(); + *changed.pointer_mut(path).unwrap() = value; + assert_ne!( + CapturedOptionMapping::parse(&serde_json::to_vec(&changed).unwrap()) + .unwrap() + .digest(), + captured.digest() + ); + } + let mut correlated = first.clone(); + correlated["context"]["correlation_id"] = json!("mapping-diagnostic"); + assert_eq!( + CapturedOptionMapping::parse(&serde_json::to_vec(&correlated).unwrap()) + .unwrap() + .digest(), + captured.digest() + ); +} + +#[test] +fn mapping_capture_refuses_noncanonical_or_ambiguous_closed_values() { + let wire = &cases()["cases"][0]["wire"]; + let mut uppercase = wire.clone(); + uppercase["input"]["listing"]["author"] = json!( + wire["input"]["listing"]["author"] + .as_str() + .unwrap() + .to_ascii_uppercase() + ); + assert!(CapturedOptionMapping::parse(&serde_json::to_vec(&uppercase).unwrap()).is_err()); + for (path, value) in [ + ("/type", json!("stock.map")), + ("/input/listing/kind", json!(30403)), + ("/input/listing/kind", json!("30402")), + ("/input/listing/kind", json!(30402.0)), + ("/input/listing/d", json!("0A".repeat(16))), + ("/input/per_sale_unit/amount", json!("0")), + ("/input/per_sale_unit/amount", json!(250)), + ("/input/per_sale_unit/amount", json!("250.0")), + ("/input/per_sale_unit/unit", json!("bag")), + ("/input/expected_mapping_version", json!(0)), + ("/input/expected_mapping_version", json!("00")), + ("/input/per_sale_unit", json!(["250", "g"])), + ] { + let mut changed = wire.clone(); + *changed.pointer_mut(path).unwrap() = value; + assert!( + CapturedOptionMapping::parse(&serde_json::to_vec(&changed).unwrap()).is_err(), + "{path}" + ); + } + for field in [ + "listing", + "option_id", + "pool_id", + "per_sale_unit", + "expected_mapping_version", + ] { + let mut changed = wire.clone(); + changed["input"].as_object_mut().unwrap().remove(field); + assert!( + CapturedOptionMapping::parse(&serde_json::to_vec(&changed).unwrap()).is_err(), + "{field}" + ); + } + for (path, name, value) in [ + ("", "extra", json!(true)), + ("/input", "unit", json!("kg")), + ("/input/listing", "revision", json!("0c".repeat(32))), + ("/input/per_sale_unit", "estimate", json!(true)), + ] { + let mut changed = wire.clone(); + changed.pointer_mut(path).unwrap()[name] = value; + assert!(CapturedOptionMapping::parse(&serde_json::to_vec(&changed).unwrap()).is_err()); + } + let raw = serde_json::to_string(wire).unwrap(); + let duplicate=raw.replacen("\"pool_id\":","\"pool_id\":\"0909090909090909090909090909090909090909090909090909090909090909\",\"pool_id\":",1); + assert!(CapturedOptionMapping::parse(duplicate.as_bytes()).is_err()); +} diff --git a/crates/storage/src/inventory.rs b/crates/storage/src/inventory.rs @@ -179,6 +179,7 @@ pub struct InventoryReceipt { attempt: CommitAttempt, pool: PoolSnapshot, kind: InventoryCommandKind, + mapping: Option<radroots_domain::stock::OptionPoolMapping>, checkpoint: InventoryCheckpointRef, } impl InventoryReceipt { @@ -193,6 +194,7 @@ impl InventoryReceipt { || pool.version().get() == 0 || (kind == InventoryCommandKind::CreatePool && pool.version().get() != 1) || (kind != InventoryCommandKind::CreatePool && pool.version().get() < 2) + || kind == InventoryCommandKind::MapOption || checkpoint.revision().get() == 0 { return Err(OperationError::RecoveryRequired); @@ -201,9 +203,38 @@ impl InventoryReceipt { attempt, kind, pool, + mapping: None, checkpoint, }) } + /// Reconstructs mapping-effect metadata only. A qualified host must confirm + /// the original transaction and its unchanged referenced pool separately. + pub fn from_committed_mapping( + attempt: CommitAttempt, + pool: PoolSnapshot, + mapping: radroots_domain::stock::OptionPoolMapping, + checkpoint: InventoryCheckpointRef, + ) -> Result<Self, OperationError> { + if attempt.transaction_id().is_none() + || checkpoint.revision().get() == 0 + || pool.version().get() == 0 + || mapping.pool_id() != pool.id() + || mapping.pool_unit() != pool.unit() + { + return Err(OperationError::RecoveryRequired); + } + Ok(Self { + attempt, + pool, + kind: InventoryCommandKind::MapOption, + mapping: Some(mapping), + checkpoint, + }) + } + /// Original private mapping effect; absent for physical inventory commands. + pub const fn mapping(&self) -> Option<radroots_domain::stock::OptionPoolMapping> { + self.mapping + } /// Exact effect family retained by the original command. pub const fn kind(&self) -> InventoryCommandKind { self.kind @@ -231,6 +262,15 @@ pub enum InventoryOutcome { /// 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 { + /// Reads current owner-private configuration after authenticating retained + /// progress. Physical inventory scopes confer no configuration access. + fn option_mapping( + &self, + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + key: radroots_domain::stock::OptionMappingKey, + proof: AttachmentProof, + ) -> BoxFuture<'_, Result<Option<radroots_domain::stock::OptionPoolMapping>, OperationError>>; fn execute_inventory( &self, request: InventoryRequest, diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -709,7 +709,7 @@ fn stock_root_context( input: &super::AttachmentInput, version: i64, ) -> Result<EnvelopeContext, WorkspaceError> { - if version == 4 { + if matches!(version, 4 | 5) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -722,7 +722,11 @@ fn stock_root_context( return Err(WorkspaceError::InvalidInput); } let mut hash = Sha256::new(); - hash.update(b"radroots.seller_stock.authority_context.v4\0"); + hash.update(if version == 4 { + b"radroots.seller_stock.authority_context.v4\0" + } else { + b"radroots.seller_stock.authority_context.v5\0" + }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); return Ok(EnvelopeContext::new( @@ -730,8 +734,12 @@ fn stock_root_context( .map_err(|_| WorkspaceError::InvalidInput)?, EnvelopeSubject::parse("seller_stock", subject.to_string()) .map_err(|_| WorkspaceError::InvalidInput)?, - PayloadSchemaId::parse("radroots.seller_stock.authority.v4") - .map_err(|_| WorkspaceError::InvalidInput)?, + PayloadSchemaId::parse(if version == 4 { + "radroots.seller_stock.authority.v4" + } else { + "radroots.seller_stock.authority.v5" + }) + .map_err(|_| WorkspaceError::InvalidInput)?, )); } let schema = match version { @@ -758,6 +766,10 @@ fn stock_record_context( "radroots.seller_stock.grant_change", "radroots.seller_stock.grant_change.v1", ), + "mapping" => ( + "radroots.seller_stock.mapping", + "radroots.seller_stock.mapping.v1", + ), "grant" => ( "radroots.seller_stock.grant", "radroots.seller_stock.grant.v2", @@ -799,10 +811,11 @@ fn stock_record_context_for_catalog( ) -> Result<EnvelopeContext, WorkspaceError> { let original = stock_record_context(input, kind, id)?; let schema = match (catalog, kind) { - (2, _) | (3 | 4, "pool") => return Ok(original), + (2, _) | (3..=5, "pool") => return Ok(original), (3, "operation") => "radroots.seller_stock.operation.v2", (4, "operation") => "radroots.seller_stock.operation.v3", - (3 | 4, "movement") => "radroots.seller_stock.movement.v2", + (5, "operation") => "radroots.seller_stock.operation.v4", + (3..=5, "movement") => "radroots.seller_stock.movement.v2", _ => return Err(WorkspaceError::RecoveryRequired), }; Ok(EnvelopeContext::new( diff --git a/crates/storage_sqlite/src/workspace/stock.rs b/crates/storage_sqlite/src/workspace/stock.rs @@ -153,13 +153,75 @@ struct Authority { } #[derive(Clone, Copy, Serialize, Deserialize)] #[serde(deny_unknown_fields)] +struct InventoryCheckpointLegacy { + revision: Sequence, + pools: Sequence, + movements: Sequence, + #[serde(deserialize_with = "required_nullable")] + head: Option<radroots_domain::CheckpointDigest>, +} +#[derive(Clone, Copy)] struct InventoryCheckpoint { revision: Sequence, pools: Sequence, movements: Sequence, + head: Option<radroots_domain::CheckpointDigest>, + mappings: Option<Sequence>, +} +#[derive(Clone, Copy, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct InventoryCheckpointCurrent { + revision: Sequence, + pools: Sequence, + movements: Sequence, + mappings: Sequence, #[serde(deserialize_with = "required_nullable")] head: Option<radroots_domain::CheckpointDigest>, } +impl From<InventoryCheckpointLegacy> for InventoryCheckpoint { + fn from(value: InventoryCheckpointLegacy) -> Self { + Self { + revision: value.revision, + pools: value.pools, + movements: value.movements, + head: value.head, + mappings: None, + } + } +} +impl From<InventoryCheckpointCurrent> for InventoryCheckpoint { + fn from(value: InventoryCheckpointCurrent) -> Self { + Self { + revision: value.revision, + pools: value.pools, + movements: value.movements, + head: value.head, + mappings: Some(value.mappings), + } + } +} +impl InventoryCheckpoint { + fn legacy(self) -> Result<InventoryCheckpointLegacy, WorkspaceError> { + if self.mappings.is_some() { + return Err(WorkspaceError::RecoveryRequired); + } + Ok(InventoryCheckpointLegacy { + revision: self.revision, + pools: self.pools, + movements: self.movements, + head: self.head, + }) + } + fn current(self) -> Result<InventoryCheckpointCurrent, WorkspaceError> { + Ok(InventoryCheckpointCurrent { + revision: self.revision, + pools: self.pools, + movements: self.movements, + head: self.head, + mappings: self.mappings.ok_or(WorkspaceError::RecoveryRequired)?, + }) + } +} fn required_nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( d: D, ) -> Result<Option<T>, D::Error> { @@ -180,7 +242,7 @@ struct InventoryAuthorityWire { input: AttachmentInput, transaction: TransactionId, revocation: Sequence, - inventory: InventoryCheckpoint, + inventory: InventoryCheckpointLegacy, } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -190,11 +252,42 @@ struct AuthorityV4 { administrator: GrantId, transaction: TransactionId, revocation: Sequence, - inventory: InventoryCheckpoint, + inventory: InventoryCheckpointLegacy, + authorization: StockAuthorizationRef, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct AuthorityV5 { + version: u8, + namespace: SellerAuthoritySelection, + administrator: GrantId, + transaction: TransactionId, + revocation: Sequence, + #[serde(deserialize_with = "object")] + inventory: InventoryCheckpointCurrent, authorization: StockAuthorizationRef, } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { + if self.catalog == 5 { + let bytes = serde_json::to_vec(&AuthorityV5 { + version: 5, + namespace: SellerAuthoritySelection::from_attachment(&self.input), + administrator: self.input.grant_id(), + transaction: self.transaction, + revocation: self.revocation, + inventory: self + .inventory + .ok_or(WorkspaceError::RecoveryRequired)? + .current()?, + authorization: self.authorization.ok_or(WorkspaceError::RecoveryRequired)?, + }) + .map_err(|_| WorkspaceError::StorageFailure)?; + if bytes.len() > 16 * 1024 { + return Err(WorkspaceError::Capacity); + } + return Ok(zeroize::Zeroizing::new(bytes)); + } if self.catalog == 4 { let bytes = serde_json::to_vec(&AuthorityV4 { version: 4, @@ -202,7 +295,10 @@ impl Authority { administrator: self.input.grant_id(), transaction: self.transaction, revocation: self.revocation, - inventory: self.inventory.ok_or(WorkspaceError::RecoveryRequired)?, + inventory: self + .inventory + .ok_or(WorkspaceError::RecoveryRequired)? + .legacy()?, authorization: self.authorization.ok_or(WorkspaceError::RecoveryRequired)?, }) .map_err(|_| WorkspaceError::StorageFailure)?; @@ -223,7 +319,7 @@ impl Authority { input: self.input.clone(), transaction: self.transaction, revocation: self.revocation, - inventory, + inventory: inventory.legacy()?, }), } .map_err(|_| WorkspaceError::StorageFailure)?; @@ -257,7 +353,7 @@ impl Authority { input: v.input, transaction: v.transaction, revocation: v.revocation, - inventory: Some(v.inventory), + inventory: Some(v.inventory.into()), authorization: None, } } @@ -274,7 +370,24 @@ impl Authority { input: v.namespace.attachment(v.administrator)?, transaction: v.transaction, revocation: v.revocation, - inventory: Some(v.inventory), + inventory: Some(v.inventory.into()), + authorization: Some(v.authorization), + } + } + 5 => { + let v: AuthorityV5 = closed_record(bytes)?; + if v.version != 5 + || v.authorization.generation() != v.revocation + || (v.inventory.revision.get() == 0) != v.inventory.head.is_none() + { + return Err(WorkspaceError::RecoveryRequired); + } + Self { + catalog, + input: v.namespace.attachment(v.administrator)?, + transaction: v.transaction, + revocation: v.revocation, + inventory: Some(v.inventory.into()), authorization: Some(v.authorization), } } @@ -313,6 +426,7 @@ pub(super) async fn initialize( transaction: initial.transaction, revocation: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?, inventory: Some(InventoryCheckpoint { + mappings: Some(Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?), revision: Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, head: None, pools: Sequence::new(0).map_err(|_| WorkspaceError::InvalidInput)?, @@ -359,7 +473,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=4") + sqlx::query("PRAGMA user_version=5") .execute(&mut *tx) .await .map_err(|_| WorkspaceError::StorageFailure)?; @@ -406,7 +520,7 @@ async fn read( .map_err(|_| WorkspaceError::RecoveryRequired)?; let clear = crypto.open_stock_root(input, catalog, &root).await?; let authority = clear.expose_secret(|bytes| Authority::decode(bytes, catalog))?; - if (if catalog == 4 { + if (if catalog >= 4 { !SellerAuthoritySelection::from_attachment(&authority.input).matches_attachment(input) } else { authority.input != *input @@ -414,7 +528,7 @@ async fn read( { return Err(WorkspaceError::WrongNamespace); } - let record = if catalog == 4 { + let record = if catalog >= 4 { grants::check_state( connection, authority @@ -527,7 +641,7 @@ pub(super) async fn revoke( } let (mut authority, mut record, old_root, old_grant) = read(connection, selected, crypto).await?; - if authority.catalog == 4 { + if authority.catalog >= 4 { return Err(WorkspaceError::Unauthorized); } let expiry = record @@ -625,6 +739,21 @@ async fn unchanged( } impl radroots_storage::inventory::InventoryStore for NativeWorkspace { + fn option_mapping( + &self, + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + key: radroots_domain::stock::OptionMappingKey, + proof: AttachmentProof, + ) -> radroots_transport::BoxFuture< + '_, + Result< + Option<radroots_domain::stock::OptionPoolMapping>, + radroots_storage::command::OperationError, + >, + > { + Box::pin(self.worker.option_mapping(binding, minimum, key, proof)) + } fn execute_inventory( &self, request: radroots_storage::inventory::InventoryRequest, @@ -682,3 +811,18 @@ fn closed_record<'de, T: Deserialize<'de>>(bytes: &'de [u8]) -> Result<T, Worksp } serde_json::from_slice(bytes).map_err(|_| WorkspaceError::RecoveryRequired) } +fn object<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( + deserializer: D, +) -> Result<T, D::Error> { + struct Object<T>(std::marker::PhantomData<T>); + impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for Object<T> { + type Value = T; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a closed object") + } + fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<T, A::Error> { + T::deserialize(serde::de::value::MapAccessDeserializer::new(map)) + } + } + deserializer.deserialize_map(Object(std::marker::PhantomData)) +} diff --git a/crates/storage_sqlite/src/workspace/stock/grants.rs b/crates/storage_sqlite/src/workspace/stock/grants.rs @@ -59,7 +59,7 @@ impl StockRecord { Err(OperationError::Unauthorized) } } - fn administrator(&self) -> bool { + pub(super) fn administrator(&self) -> bool { matches!(self, Self::Scoped(v) if v.administrator()) } } @@ -324,9 +324,10 @@ pub(in crate::workspace) async fn change( } let (mut authority, record, old_root, old_grant) = super::read(turn.connection, change.caller.input(), turn.crypto).await?; - if authority.catalog != 4 { + if !(4..=5).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } + let catalog = authority.catalog; let current = record.authenticate(change.caller.input(), &proof, turn.clock.now()?)?; if current.observed_at() < change.caller.observed_at() { return Err(WorkspaceError::Unavailable); @@ -382,7 +383,7 @@ pub(in crate::workspace) async fn change( .await .map_err(|_| WorkspaceError::StorageFailure)?; let checked: Result<(), WorkspaceError> = async { - super::unchanged(&mut tx, current.input(), 4, &old_root, &old_grant).await?; + super::unchanged(&mut tx, current.input(), catalog, &old_root, &old_grant).await?; check_state(&mut tx, authorization).await?; ancestry .confirm(&mut tx) @@ -471,7 +472,7 @@ pub(in crate::workspace) async fn change( authority.authorization = Some(next); let root = turn .crypto - .seal_stock_root(turn.selected, 4, &authority.encode()?) + .seal_stock_root(turn.selected, catalog, &authority.encode()?) .await?; let retained = ChangeWire { version: 1, @@ -501,7 +502,7 @@ pub(in crate::workspace) async fn change( .map_err(|_| WorkspaceError::StorageFailure)?; let changed: Result<(), WorkspaceError> = async { turn.namespace.validate()?; - super::unchanged(&mut tx, current.input(), 4, &old_root, &old_grant).await?; + super::unchanged(&mut tx, current.input(), catalog, &old_root, &old_grant).await?; check_state(&mut tx, authorization).await?; ancestry .confirm(&mut tx) diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -1,6 +1,7 @@ //! Owner-private inventory effects on the existing connection owner. mod checkpoint; mod codec; +mod mapping; mod plan; use super::*; use checkpoint::{MinimumProof, authenticate_minimum, authenticate_projection}; @@ -53,6 +54,15 @@ pub(super) async fn check_head( .fetch_one(&mut *connection) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; + if let Some(expected) = checkpoint.mappings { + let actual: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_mappings") + .fetch_one(&mut *connection) + .await + .map_err(|_| WorkspaceError::RecoveryRequired)?; + if actual != expected.get() as i64 { + return Err(WorkspaceError::RecoveryRequired); + } + } if pools != checkpoint.pools.get() as i64 || movements != checkpoint.movements.get() as i64 { return Err(WorkspaceError::RecoveryRequired); } @@ -72,6 +82,7 @@ struct Access { current: WorkspaceBinding, minimum_proof: MinimumProof, projection_proof: Option<MinimumProof>, + mapping_read: Option<mapping::MappingRead>, } pub(in crate::workspace) struct Turn<'a> { pub connection: &'a mut SqliteConnection, @@ -104,6 +115,9 @@ impl Turn<'_> { return Err(OperationError::Unauthorized); } same_binding(binding, &current)?; + if current.observed_at() < binding.observed_at() { + return Err(WorkspaceError::Unavailable.into()); + } if authority.authorization != minimum.authorization() { return Err(WorkspaceError::StaleCheckpoint.into()); } @@ -136,6 +150,7 @@ impl Turn<'_> { current, minimum_proof, projection_proof: None, + mapping_read: None, }) } pub async fn create( @@ -149,6 +164,9 @@ impl Turn<'_> { access .record .require(StockAction::ReadOperations, request.command().pool_id())?; + if let Some(input) = request.command().mapping_input() { + mapping::require(&access, input.key())?; + } let context = request.command().context(); let operation = context.operation_id(); let digest = request.command().digest(); @@ -172,23 +190,28 @@ impl Turn<'_> { if request.replay_only() { return Err(OperationError::RecoveryRequired); } - access.record.require( - match request.command().kind() { - radroots_storage::inventory::InventoryCommandKind::CreatePool => { - StockAction::CreatePool - } - radroots_storage::inventory::InventoryCommandKind::AddStock => { - StockAction::AddStock - } - radroots_storage::inventory::InventoryCommandKind::RemoveStock => { - StockAction::RemoveStock - } - radroots_storage::inventory::InventoryCommandKind::SpoilStock => { - StockAction::SpoilStock - } - }, - request.command().pool_id(), - )?; + if request.command().mapping_input().is_none() { + access.record.require( + match request.command().kind() { + radroots_storage::inventory::InventoryCommandKind::MapOption => { + return Err(OperationError::RecoveryRequired); + } + radroots_storage::inventory::InventoryCommandKind::CreatePool => { + StockAction::CreatePool + } + radroots_storage::inventory::InventoryCommandKind::AddStock => { + StockAction::AddStock + } + radroots_storage::inventory::InventoryCommandKind::RemoveStock => { + StockAction::RemoveStock + } + radroots_storage::inventory::InventoryCommandKind::SpoilStock => { + StockAction::SpoilStock + } + }, + request.command().pool_id(), + )?; + } // An original captured command may be replayed under a replacement grant, // but a new effect must have been captured under this current grant. if request.command().context().actor() != access.current.actor() { @@ -228,6 +251,7 @@ impl Turn<'_> { .await?, ); let (pool, quantity, movement_kind) = plan_effect(request.command(), before)?; + let mapping = mapping::prepare(self, &access, &request, pool).await?; let label = if let Some(input) = request.command().creation_input() { input.label() } else { @@ -271,30 +295,46 @@ impl Turn<'_> { digest, Some(transaction), ); - let receipt = InventoryReceipt::from_committed_store( - attempt, - request.command().kind(), - pool, + let receipt_checkpoint = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( self.selected.authority(), revision, Some(head), )? - .with_optional_authorization(access.authority.authorization), - )?; - let protected_pool = self - .crypto - .seal_stock_record( - self.selected, - "pool", - pool.id().as_bytes(), - &encode(&PoolWire { - version: 1, - label, - pool, - })?, + .with_optional_authorization(access.authority.authorization); + let receipt = if let Some(mapping) = &mapping { + InventoryReceipt::from_committed_mapping( + attempt, + pool, + mapping.effect.after, + receipt_checkpoint, + )? + } else { + InventoryReceipt::from_committed_store( + attempt, + request.command().kind(), + pool, + receipt_checkpoint, + )? + }; + let protected_pool = if mapping.is_some() { + None + } else { + Some( + self.crypto + .seal_stock_record( + self.selected, + "pool", + pool.id().as_bytes(), + &encode(&PoolWire { + version: 1, + label, + pool, + })?, + ) + .await?, ) - .await?; + }; let protected_movement = if let Some(id) = movement { Some( self.crypto @@ -348,10 +388,27 @@ impl Turn<'_> { }, catalog, access.authority.authorization, + mapping.as_ref().map(|value| value.effect), )?, ) .await?; access.authority.inventory = Some(InventoryCheckpoint { + mappings: checkpoint + .mappings + .map(|count| { + Sequence::new( + count + .get() + .checked_add(u64::from( + mapping + .as_ref() + .is_some_and(|value| value.effect.before.is_none()), + )) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity) + }) + .transpose()?, revision, head: Some(head), pools: Sequence::new( @@ -394,7 +451,12 @@ impl Turn<'_> { self.namespace.validate()?; let absent:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=?").bind(request.binding().actor().participant().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);} - if let Some(before)=before { + if let Some(mapping)=&mapping { + let original=existing.as_ref().ok_or(OperationError::RecoveryRequired)?; + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=? AND revision=? AND protected=?").bind(pool.id().as_bytes().as_slice()).bind(pool.version().get() as i64).bind(&original.protected).fetch_one(&mut *tx).await.map_err(|_|OperationError::RecoveryRequired)?; + if count!=1 {return Err(OperationError::RecoveryRequired);} + mapping.apply(&mut tx).await?; + } else 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)?; @@ -446,8 +508,10 @@ impl Turn<'_> { check_head(&mut tx,access.authority.inventory.ok_or(OperationError::UnsupportedOperation)?).await?; access.minimum_proof.confirm(&mut tx).await?; if let Some(proof)=&access.projection_proof {proof.confirm(&mut tx).await?;} + if let Some(mapping)=&access.mapping_read {mapping.confirm(&mut tx).await?;} let current=access.record.authenticate(access.current.input(),proof,self.clock.now()?)?; same_binding(&access.current,&current)?; + if current.observed_at()<access.current.observed_at() {return Err(WorkspaceError::Unavailable.into());} if let Some(operation)=absent_operation {let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_operations WHERE actor=? AND operation_id=?").bind(current.actor().participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;if count!=0 {return Err(OperationError::RecoveryRequired);}} if let Some(id)=absent_pool {let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_pools WHERE pool_id=?").bind(id.as_bytes().as_slice()).fetch_one(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?;if count!=0 {return Err(OperationError::RecoveryRequired);}} if let Some(retained)=operation { @@ -494,6 +558,9 @@ impl Turn<'_> { access .record .require(StockAction::ReadOperations, retained.receipt.pool().id())?; + if let Some(mapping) = retained.receipt.mapping() { + mapping::require(&access, mapping.key())?; + } } if let Some(retained) = &result && digest.is_some_and(|d| d != retained.digest) @@ -511,6 +578,39 @@ impl Turn<'_> { .await?; Ok(result.map(|v| v.receipt)) } + pub async fn option_mapping( + &mut self, + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + key: radroots_domain::stock::OptionMappingKey, + proof: AttachmentProof, + ) -> Result<Option<radroots_domain::stock::OptionPoolMapping>, OperationError> { + let mut access = self.access(&binding, minimum, &proof).await?; + mapping::require(&access, key)?; + let retained = mapping::read(self.connection, self.selected, self.crypto, key).await?; + let result = retained.as_ref().map(|value| value.value); + let witness = checkpoint::authenticate_mapping_projection( + self.connection, + self.selected, + self.crypto, + &access.current, + access + .authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?, + key, + result, + ) + .await?; + access.mapping_read = Some(mapping::MappingRead { + key, + retained, + proof: witness, + }); + self.confirm(&access, &proof, None, None, None, None) + .await?; + Ok(result) + } pub async fn pool( &mut self, binding: WorkspaceBinding, @@ -640,8 +740,7 @@ async fn read_operation( &protected, ) .await?; - let (request, decoded) = - clear.expose_secret(|bytes| decode_operation(bytes, catalog, binding))?; + let (request, decoded) = clear.expose_secret(|bytes| decode_operation(bytes, catalog))?; if !SellerAuthoritySelection::from_attachment(request.binding().input()) .matches_attachment(binding.input()) || request.binding().actor().participant() != binding.actor().participant() @@ -657,6 +756,15 @@ async fn read_operation( } let (planned, quantity, movement_kind) = plan_effect(request.command(), decoded.before) .map_err(|_| OperationError::RecoveryRequired)?; + let expected_mapping = mapping::effect( + request.command(), + decoded.pool, + decoded.mapping.and_then(|value| value.before), + ) + .map_err(|_| OperationError::RecoveryRequired)?; + if expected_mapping != decoded.mapping || (catalog < 5 && decoded.mapping.is_some()) { + return Err(OperationError::RecoveryRequired); + } if decoded.version != record_version(catalog)? || request.command().context().operation_id() != operation || decoded.revision.get() == 0 @@ -731,22 +839,28 @@ async fn read_operation( } None }; - 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(), - decoded.revision, - Some(decoded.head), + let attempt = CommitAttempt::new( + input.workspace_id(), + operation, + digest, + Some(decoded.transaction), + ); + let checkpoint = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( + request.command().context().authority(), + decoded.revision, + Some(decoded.head), + )? + .with_optional_authorization(decoded.authorization); + let receipt = if let Some(mapping) = decoded.mapping { + InventoryReceipt::from_committed_mapping(attempt, decoded.pool, mapping.after, checkpoint)? + } else { + InventoryReceipt::from_committed_store( + attempt, + request.command().kind(), + decoded.pool, + checkpoint, )? - .with_optional_authorization(decoded.authorization), - )?; + }; Ok(Some(Retained { original_grant: request.binding().input().grant_id(), previous_head: decoded.previous_head, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -140,6 +140,76 @@ pub(super) async fn authenticate_projection( pool: PoolId, projected: Option<PoolSnapshot>, ) -> Result<MinimumProof, OperationError> { + authenticate_projected( + connection, + input, + crypto, + binding, + current, + Projection::Pool(pool, projected), + ) + .await +} +pub(super) async fn authenticate_mapping_projection( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + current: InventoryCheckpoint, + key: radroots_domain::stock::OptionMappingKey, + projected: Option<radroots_domain::stock::OptionPoolMapping>, +) -> Result<MinimumProof, OperationError> { + authenticate_projected( + connection, + input, + crypto, + binding, + current, + Projection::Mapping(key, projected), + ) + .await +} +enum Projection { + Pool(PoolId, Option<PoolSnapshot>), + Mapping( + radroots_domain::stock::OptionMappingKey, + Option<radroots_domain::stock::OptionPoolMapping>, + ), +} +impl Projection { + fn matches(&self, receipt: &InventoryReceipt) -> Result<bool, OperationError> { + let matched = match self { + Self::Pool(id, projected) if *id == receipt.pool().id() => { + Some(*projected == Some(receipt.pool())) + } + Self::Mapping(key, projected) + if receipt.mapping().is_some_and(|value| value.key() == *key) => + { + Some(*projected == receipt.mapping()) + } + _ => None, + }; + match matched { + Some(true) => Ok(true), + Some(false) => Err(OperationError::RecoveryRequired), + None => Ok(false), + } + } + fn present(&self) -> bool { + match self { + Self::Pool(_, value) => value.is_some(), + Self::Mapping(_, value) => value.is_some(), + } + } +} +async fn authenticate_projected( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + binding: &WorkspaceBinding, + current: InventoryCheckpoint, + projected: Projection, +) -> Result<MinimumProof, OperationError> { let upper = current.revision.get(); let mut expected = current.head; let mut hash = history_hash(); @@ -158,10 +228,7 @@ pub(super) async fn authenticate_projection( return Err(OperationError::RecoveryRequired); } hash_retained(&mut hash, revision, binding, operation, &retained)?; - if retained.receipt.pool().id() == pool { - if projected != Some(retained.receipt.pool()) { - return Err(OperationError::RecoveryRequired); - } + if projected.matches(&retained.receipt)? { return Ok(MinimumProof { lower: revision, upper, @@ -170,7 +237,7 @@ pub(super) async fn authenticate_projection( } expected = retained.previous_head; } - if expected.is_some() || projected.is_some() { + if expected.is_some() || projected.present() { return Err(OperationError::RecoveryRequired); } Ok(MinimumProof { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs @@ -96,19 +96,38 @@ struct OperationV3<'a> { #[serde(borrow)] operation: &'a RawValue, } +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct OperationV4<'a> { + version: u8, + authorization: StockAuthorizationRef, + #[serde(borrow)] + operation: &'a RawValue, + #[serde(deserialize_with = "super::required_nullable")] + mapping: Option<super::mapping::MappingEffect>, +} pub(super) fn encode_operation( value: &OperationWire<'_>, catalog: i64, authorization: Option<StockAuthorizationRef>, + mapping: Option<super::mapping::MappingEffect>, ) -> Result<zeroize::Zeroizing<Vec<u8>>, OperationError> { let clear = super::encode(value)?; - if catalog != 4 { + if catalog < 4 { return Ok(clear); } let raw = RawValue::from_string( String::from_utf8(clear.to_vec()).map_err(|_| OperationError::StorageFailure)?, ) .map_err(|_| OperationError::StorageFailure)?; + if catalog == 5 { + return super::encode(&OperationV4 { + version: 4, + authorization: authorization.ok_or(OperationError::RecoveryRequired)?, + operation: &raw, + mapping, + }); + } super::encode(&OperationV3 { version: 3, authorization: authorization.ok_or(OperationError::RecoveryRequired)?, @@ -116,6 +135,7 @@ pub(super) fn encode_operation( }) } pub(super) struct OperationData { + pub(super) mapping: Option<super::mapping::MappingEffect>, pub(super) authorization: Option<StockAuthorizationRef>, pub(super) version: u8, pub(super) before: Option<PoolSnapshot>, @@ -130,16 +150,32 @@ pub(super) struct OperationData { pub(super) fn decode_operation( bytes: &[u8], catalog: i64, - _binding: &WorkspaceBinding, ) -> Result<(InventoryRequest, OperationData), OperationError> { + decode_inner(bytes, catalog, false) +} +fn decode_inner( + bytes: &[u8], + catalog: i64, + allow_mapping: bool, +) -> Result<(InventoryRequest, OperationData), OperationError> { + if catalog == 5 { + let decoded: OperationV4<'_> = + super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; + if decoded.version != 4 { + return Err(OperationError::RecoveryRequired); + } + let (request, mut data) = decode_inner(decoded.operation.get().as_bytes(), 3, true)?; + data.authorization = Some(decoded.authorization); + data.mapping = decoded.mapping; + return Ok((request, data)); + } if catalog == 4 { let decoded: OperationV3<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 3 { return Err(OperationError::RecoveryRequired); } - let (request, mut data) = - decode_operation(decoded.operation.get().as_bytes(), 3, _binding)?; + let (request, mut data) = decode_inner(decoded.operation.get().as_bytes(), 3, false)?; data.authorization = Some(decoded.authorization); return Ok((request, data)); } @@ -171,9 +207,13 @@ pub(super) fn decode_operation( minimum, decoded.command.get().as_bytes(), )?; + if !allow_mapping && request.command().mapping_input().is_some() { + return Err(OperationError::RecoveryRequired); + } Ok(( request, OperationData { + mapping: None, authorization: None, version: decoded.version, before: prior, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs b/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs @@ -0,0 +1,232 @@ +//! Owner-private configuration on the existing stock transaction owner. +use super::*; +use radroots_domain::stock::{OptionMappingKey, OptionPoolMapping}; + +#[derive(Clone, Copy, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct MappingEffect { + pub before: Option<OptionPoolMapping>, + pub after: OptionPoolMapping, +} +impl<'de> Deserialize<'de> for MappingEffect { + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Wire { + #[serde(deserialize_with = "super::super::required_nullable")] + before: Option<OptionPoolMapping>, + after: OptionPoolMapping, + } + let value: Wire = super::super::object(deserializer)?; + Ok(Self { + before: value.before, + after: value.after, + }) + } +} +pub(super) struct RetainedMapping { + pub value: OptionPoolMapping, + pub protected: Vec<u8>, +} +pub(super) struct MappingRead { + pub key: OptionMappingKey, + pub retained: Option<RetainedMapping>, + pub proof: MinimumProof, +} +impl MappingRead { + pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { + self.proof.confirm(connection).await?; + let key = self.key; + let protected:Option<Vec<u8>>=sqlx::query_scalar("SELECT CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?") + .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.flatten(); + if protected.as_ref() != self.retained.as_ref().map(|value| &value.protected) { + return Err(OperationError::RecoveryRequired); + } + if let Some(retained) = &self.retained { + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=? AND pool_id=? AND revision=?") + .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).bind(retained.value.pool_id().as_bytes().as_slice()).bind(retained.value.version().get() as i64).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 1 { + return Err(OperationError::RecoveryRequired); + } + } else { + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?").bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_one(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + } + Ok(()) + } +} +pub(super) fn require(access: &Access, key: OptionMappingKey) -> Result<(), OperationError> { + if access.authority.catalog != 5 { + return Err(OperationError::UnsupportedOperation); + } + if !access.record.administrator() + || key.listing().author() != access.current.actor().participant() + { + return Err(OperationError::Unauthorized); + } + Ok(()) +} +pub(super) struct MappingPlan { + pub effect: MappingEffect, + pub protected: Vec<u8>, + pub original: Option<Vec<u8>>, + pub proof: MinimumProof, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct MappingWire { + version: u8, + mapping: OptionPoolMapping, +} +pub(super) fn key_id(key: OptionMappingKey) -> [u8; 32] { + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.mapping_key.v1\0"); + hash.update(key.listing().author().as_bytes()); + hash.update(key.listing().d().as_bytes()); + hash.update(key.option_id().as_bytes()); + hash.finalize().into() +} +pub(super) async fn read( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + key: OptionMappingKey, +) -> Result<Option<RetainedMapping>, OperationError> { + let row=sqlx::query("SELECT pool_id,revision,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?") + .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_optional(connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(row) = row else { return Ok(None) }; + let protected: Vec<u8> = row + .try_get::<Option<Vec<u8>>, _>(2) + .map_err(|_| OperationError::RecoveryRequired)? + .ok_or(OperationError::RecoveryRequired)?; + let clear = crypto + .open_stock_record(input, "mapping", &key_id(key), &protected) + .await?; + let wire: MappingWire = clear + .expose_secret(|bytes| super::super::closed_record(bytes)) + .map_err(|_| OperationError::RecoveryRequired)?; + let pool: Vec<u8> = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + let revision: i64 = row + .try_get(1) + .map_err(|_| OperationError::RecoveryRequired)?; + if wire.version != 1 + || wire.mapping.key() != key + || pool != wire.mapping.pool_id().as_bytes() + || revision <= 0 + || revision as u64 != wire.mapping.version().get() + { + return Err(OperationError::RecoveryRequired); + } + Ok(Some(RetainedMapping { + value: wire.mapping, + protected, + })) +} +pub(super) fn effect( + command: &radroots_storage::inventory::CapturedInventoryCommand, + pool: PoolSnapshot, + before: Option<OptionPoolMapping>, +) -> Result<Option<MappingEffect>, OperationError> { + let Some(input) = command.mapping_input() else { + return Ok(None); + }; + if pool.id() != input.pool_id() { + return Err(OperationError::RecoveryRequired); + } + if before.is_some_and(|value| value.key() != input.key()) { + return Err(OperationError::RecoveryRequired); + } + if input.expected_mapping_version().get() + != before.map(|value| value.version().get()).unwrap_or(0) + { + return Err(OperationError::StaleState); + } + let version = Sequence::new( + input + .expected_mapping_version() + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?, + ) + .map_err(|_| WorkspaceError::Capacity)?; + let after = OptionPoolMapping::new( + input.key(), + input.pool_id(), + pool.unit(), + input.per_sale_unit(), + version, + ) + .map_err(|_| OperationError::InvalidCommand)?; + Ok(Some(MappingEffect { before, after })) +} +pub(super) async fn prepare( + turn: &mut Turn<'_>, + access: &Access, + request: &InventoryRequest, + pool: PoolSnapshot, +) -> Result<Option<MappingPlan>, OperationError> { + let Some(input) = request.command().mapping_input() else { + return Ok(None); + }; + require(access, input.key())?; + let original = read(turn.connection, turn.selected, turn.crypto, input.key()).await?; + let before = original.as_ref().map(|value| value.value); + let proof = checkpoint::authenticate_mapping_projection( + turn.connection, + turn.selected, + turn.crypto, + &access.current, + access + .authority + .inventory + .ok_or(OperationError::UnsupportedOperation)?, + input.key(), + before, + ) + .await?; + let effect = + effect(request.command(), pool, before)?.ok_or(OperationError::RecoveryRequired)?; + let protected = turn + .crypto + .seal_stock_record( + turn.selected, + "mapping", + &key_id(input.key()), + &encode(&MappingWire { + version: 1, + mapping: effect.after, + })?, + ) + .await?; + Ok(Some(MappingPlan { + effect, + protected, + original: original.map(|value| value.protected), + proof, + })) +} +impl MappingPlan { + pub async fn apply(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { + self.proof.confirm(connection).await?; + let key = self.effect.after.key(); + if let (Some(before), Some(protected)) = (self.effect.before, self.original.as_ref()) { + let updated=sqlx::query("UPDATE stock_mappings SET pool_id=?,revision=?,protected=? WHERE listing_author=? AND listing_d=? AND option_id=? AND revision=? AND protected=? AND pool_id=?") + .bind(self.effect.after.pool_id().as_bytes().as_slice()).bind(self.effect.after.version().get() as i64).bind(&self.protected).bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).bind(before.version().get() as i64).bind(protected).bind(before.pool_id().as_bytes().as_slice()).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; + if updated.rows_affected() != 1 { + return Err(OperationError::RecoveryRequired); + } + } else { + let count:i64=sqlx::query_scalar("SELECT count(*) FROM stock_mappings WHERE listing_author=? AND listing_d=? AND option_id=?").bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + if count != 0 { + return Err(OperationError::RecoveryRequired); + } + sqlx::query("INSERT INTO stock_mappings(listing_author,listing_d,option_id,pool_id,revision,protected) VALUES(?,?,?,?,?,?)") + .bind(key.listing().author().as_bytes().as_slice()).bind(key.listing().d().as_bytes().as_slice()).bind(key.option_id().as_bytes().as_slice()).bind(self.effect.after.pool_id().as_bytes().as_slice()).bind(self.effect.after.version().get() as i64).bind(&self.protected).execute(connection).await.map_err(|_|OperationError::StorageFailure)?; + } + Ok(()) + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn record_version(catalog: i64) -> Result<u8, OperationError> { match catalog { 2 => Ok(1), - 3 | 4 => Ok(2), + 3..=5 => Ok(2), _ => Err(OperationError::RecoveryRequired), } } @@ -21,6 +21,17 @@ pub(super) fn plan_effect( use radroots_domain::stock::{AvailableStockCorrection, StockError}; use radroots_storage::inventory::CapturedInventoryCommand; match command { + CapturedInventoryCommand::MapOption(command) => { + let pool = before.ok_or(OperationError::StaleState)?; + if pool.id() != command.input().pool_id() { + return Err(OperationError::RecoveryRequired); + } + Ok(( + pool, + radroots_domain::stock::StockTicks::ZERO, + MovementKind::Introduced, + )) + } CapturedInventoryCommand::CreatePool(command) => { if before.is_some() { return Err(OperationError::StaleState); 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 = 4; +pub(super) const CURRENT: i64 = 5; 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..=4 => objects.extend([ + 2..=5 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ("table", "stock_operations", "stock_operations", OPERATIONS), ( @@ -47,7 +47,7 @@ pub(super) fn objects( ]), _ => return Err(WorkspaceError::RecoveryRequired), } - if version == 4 { + if version >= 4 { objects.push(("table", "stock_grant_changes", "stock_grant_changes", "CREATE TABLE stock_grant_changes (transaction_id BLOB PRIMARY KEY CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>1), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(( "index", @@ -57,6 +57,9 @@ pub(super) fn objects( )); objects.push(("index", "stock_actor_operation_identity", "stock_operations", "CREATE UNIQUE INDEX stock_actor_operation_identity ON stock_operations(actor,operation_id)")); } + if version == 5 { + objects.push(("table","stock_mappings","stock_mappings","CREATE TABLE stock_mappings (listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), option_id BLOB NOT NULL CHECK(length(option_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(listing_author,listing_d,option_id)) STRICT, WITHOUT ROWID")); + } Ok(objects) } pub(super) async fn admit(connection: &mut SqliteConnection) -> Result<i64, WorkspaceError> { diff --git a/crates/storage_sqlite/src/workspace/stock/tests.rs b/crates/storage_sqlite/src/workspace/stock/tests.rs @@ -16,7 +16,7 @@ impl WorkspaceClock for Clock { } #[tokio::test] -async fn catalog4_grant_set_reopens_with_original_namespace_after_one_grant_change() { +async fn current_grant_set_reopens_with_original_namespace_after_one_grant_change() { let fixture = CryptoFixture::new(); let path = fixture.root().join("grant-reopen"); let enrollment = StockEnrollment::prepare( @@ -109,7 +109,7 @@ async fn catalog4_grant_set_reopens_with_original_namespace_after_one_grant_chan ) .await .unwrap(); - assert_eq!(schema::admit(&mut connection).await, Ok(4)); + assert_eq!(schema::admit(&mut connection).await, Ok(5)); assert_eq!(schema::integrity(&mut connection).await, Ok(())); let root: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_authority") .fetch_one(&mut connection) @@ -117,12 +117,20 @@ async fn catalog4_grant_set_reopens_with_original_namespace_after_one_grant_chan .unwrap(); let clear = fixture .crypto() - .open_stock_root(enrollment.input(), 4, &root) + .open_stock_root(enrollment.input(), 5, &root) .await .unwrap(); let authority = clear - .expose_secret(|bytes| Authority::decode(bytes, 4)) + .expose_secret(|bytes| Authority::decode(bytes, 5)) .unwrap(); + clear.expose_secret(|bytes| { + let original:serde_json::Value=serde_json::from_slice(bytes).unwrap(); + assert_eq!(original["inventory"]["mappings"],"0"); + for bad in [serde_json::json!([]),serde_json::json!({"revision":"1","pools":"1","movements":"1","head":original["inventory"]["head"]})] { + let mut value=original.clone();value["inventory"]=bad; + assert!(Authority::decode(&serde_json::to_vec(&value).unwrap(),5).is_err()); + } + }); assert_eq!(authority.input, *enrollment.input()); assert_eq!( grants::check_state(&mut connection, authority.authorization.unwrap()).await, @@ -147,7 +155,7 @@ async fn catalog4_grant_set_reopens_with_original_namespace_after_one_grant_chan } #[tokio::test] -async fn root4_context_binds_the_complete_namespace_independently_of_caller_grants() { +async fn current_and_retained_roots_bind_the_complete_namespace_with_distinct_catalog_contexts() { use radroots_storage::workspace::seller_stock::SellerAuthoritySelection; use serde_json::json; let fixture = CryptoFixture::new(); @@ -170,41 +178,52 @@ async fn root4_context_binds_the_complete_namespace_independently_of_caller_gran let caller = namespace.attachment(GrantId::from_bytes([9; 32])).unwrap(); let crypto = fixture.crypto(); let clear = b"synthetic context payload"; - let current = crypto.seal_stock_root(&owner, 4, clear).await.unwrap(); - crypto - .open_stock_root(&caller, 4, &current) - .await - .unwrap() - .expose_secret(|bytes| assert_eq!(bytes, clear)); - let retained = crypto.seal_stock_root(&owner, 3, clear).await.unwrap(); - assert!(crypto.open_stock_root(&caller, 3, &retained).await.is_err()); - assert!(crypto.open_stock_root(&owner, 3, &current).await.is_err()); - let value = serde_json::to_value(namespace).unwrap(); - let other_key = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; - for (path, bad) in [ - ("/workspace_id", json!("0b".repeat(32))), - ("/authority/executor_id", json!("0b".repeat(32))), - ("/authority/generation", json!("2")), - ("/participant", json!(other_key)), - ("/endpoint", json!("local://another-namespace")), - ("/endpoint_identity", json!(other_key)), - ("/checkpoint/digest", json!("0b".repeat(32))), - ("/route_digest", json!("0b".repeat(32))), - ] { - let mut changed = value.clone(); - *changed.pointer_mut(path).unwrap() = bad; - let selected: SellerAuthoritySelection = serde_json::from_value(changed).unwrap(); + for version in [4, 5] { + let current = crypto + .seal_stock_root(&owner, version, clear) + .await + .unwrap(); + crypto + .open_stock_root(&caller, version, &current) + .await + .unwrap() + .expose_secret(|bytes| assert_eq!(bytes, clear)); + let retained = crypto.seal_stock_root(&owner, 3, clear).await.unwrap(); + assert!(crypto.open_stock_root(&caller, 3, &retained).await.is_err()); + assert!(crypto.open_stock_root(&owner, 3, &current).await.is_err()); assert!( crypto - .open_stock_root( - &selected.attachment(GrantId::from_bytes([9; 32])).unwrap(), - 4, - &current - ) + .open_stock_root(&owner, if version == 4 { 5 } else { 4 }, &current) .await - .is_err(), - "{path}" + .is_err() ); + let value = serde_json::to_value(&namespace).unwrap(); + let other_key = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"; + for (path, bad) in [ + ("/workspace_id", json!("0b".repeat(32))), + ("/authority/executor_id", json!("0b".repeat(32))), + ("/authority/generation", json!("2")), + ("/participant", json!(other_key)), + ("/endpoint", json!("local://another-namespace")), + ("/endpoint_identity", json!(other_key)), + ("/checkpoint/digest", json!("0b".repeat(32))), + ("/route_digest", json!("0b".repeat(32))), + ] { + let mut changed = value.clone(); + *changed.pointer_mut(path).unwrap() = bad; + let selected: SellerAuthoritySelection = serde_json::from_value(changed).unwrap(); + assert!( + crypto + .open_stock_root( + &selected.attachment(GrantId::from_bytes([9; 32])).unwrap(), + version, + &current + ) + .await + .is_err(), + "{path}" + ); + } } } @@ -216,6 +235,11 @@ async fn retained_inventory_v2_keeps_original_records_and_refuses_new_correction async fn retained_inventory_v3_preserves_correction_and_original_records_without_upgrade() { retained_inventory_catalog(3).await; } +#[tokio::test] +async fn retained_inventory_v4_preserves_scoped_grants_and_original_effects_without_adding_mappings() + { + retained_inventory_catalog(4).await; +} async fn retained_inventory_catalog(catalog: i64) { use radroots_storage::inventory::{InventoryCommandKind, InventoryOutcome}; let fixture = CryptoFixture::new(); @@ -236,16 +260,37 @@ async fn retained_inventory_catalog(catalog: i64) { ) .unwrap(); // Literal retained catalog/root shapes from published creation/correction source; not predecessor-binary evidence. - let clear=zeroize::Zeroizing::new(serde_json::to_vec(&serde_json::json!({"version":catalog,"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 grant_clear = if catalog == 4 { + StockGrantRecord::from_enrollment(record) + .unwrap() + .encode() + .unwrap() + } else { + record.encode().unwrap() + }; + let grant = if catalog == 4 { + crypto + .seal_stock_record(&input, "grant", input.grant_id().as_bytes(), &grant_clear) + .await + .unwrap() + } else { + crypto + .seal_stock(&input, false, &grant_clear) + .await + .unwrap() + }; + // The v4 namespace, grant2 and operation3 envelopes remain frozen literals. + let value = if catalog == 4 { + serde_json::json!({"version":4,"namespace":SellerAuthoritySelection::from_attachment(&input),"administrator":input.grant_id(),"transaction":TransactionId::from_bytes([9;32]),"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null},"authorization":grants::single_state(input.grant_id(),&grant).unwrap()}) + } else { + serde_json::json!({"version":catalog,"input":input,"transaction":TransactionId::from_bytes([9;32]),"revocation":"1","inventory":{"revision":"0","pools":"0","movements":"0","head":null}}) + }; + let clear = zeroize::Zeroizing::new(serde_json::to_vec(&value).unwrap()); let root = crypto .seal_stock_root(&input, catalog, &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() @@ -270,10 +315,11 @@ async fn retained_inventory_catalog(catalog: i64) { .execute(&mut *tx) .await .unwrap(); - sqlx::query(if catalog == 2 { - "PRAGMA user_version=2" - } else { - "PRAGMA user_version=3" + sqlx::query(match catalog { + 2 => "PRAGMA user_version=2", + 3 => "PRAGMA user_version=3", + 4 => "PRAGMA user_version=4", + _ => unreachable!(), }) .execute(&mut *tx) .await @@ -346,12 +392,28 @@ async fn retained_inventory_catalog(catalog: i64) { .unwrap(), Some(created.clone()) ); + let mut mapping = serde_json::json!({"type":"stock.map_option","context":context,"input":{"listing":{"kind":30402,"author":participant(),"d":"0a".repeat(16)},"option_id":"0b".repeat(32),"pool_id":PoolId::from_bytes([8;32]),"expected_mapping_version":"0","per_sale_unit":{"amount":"1","unit":"each"}}}); + mapping["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([11; 32])); + assert_eq!( + store + .execute_inventory( + InventoryRequest::from_protected_wire( + binding.clone(), + created.checkpoint(), + &serde_json::to_vec(&mapping).unwrap() + ) + .unwrap(), + copy() + ) + .await, + Err(OperationError::UnsupportedOperation) + ); 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])); let correction = store .execute_inventory( InventoryRequest::from_protected_wire( - binding, + binding.clone(), created.checkpoint(), &serde_json::to_vec(&corrected).unwrap(), ) @@ -359,6 +421,7 @@ async fn retained_inventory_catalog(catalog: i64) { copy(), ) .await; + let mut latest = created.checkpoint(); if catalog == 2 { assert!(matches!( correction, @@ -369,11 +432,69 @@ async fn retained_inventory_catalog(catalog: i64) { InventoryOutcome::Committed(value) => { assert_eq!(value.pool().version().get(), 2); assert_eq!(value.pool().balances().physical().available.get(), 2); + latest = value.checkpoint(); } InventoryOutcome::Unknown(_) => panic!("retained correction must confirm"), } } + if catalog == 4 { + let child = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(&input), + "retained-device".into(), + UnixSeconds::new(200).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + let receipt = match store + .enroll_stock_grant(binding.clone(), latest, &proof, &child) + .await + .unwrap() + { + StockGrantOutcome::Committed(value) => value, + _ => panic!("retained grant must confirm"), + }; + latest = latest.with_authorization(receipt.authorization()); + let delegated = store + .authenticate(child.input().clone(), child.proof()) + .await + .unwrap(); + let child_proof = child + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap(); + assert_eq!( + store + .pool(delegated, latest, PoolId::from_bytes([8; 32]), child_proof) + .await + .unwrap() + .unwrap() + .snapshot() + .balances() + .physical() + .available + .get(), + 2 + ); + } store.close().await.unwrap(); + let reopened = + NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) + .await + .unwrap(); + assert_eq!( + reopened + .inventory_operation( + binding, + latest, + OperationId::from_bytes([7; 32]), + None, + copy() + ) + .await + .unwrap(), + Some(created) + ); + reopened.close().await.unwrap(); let mut connection = SqliteConnection::connect_with( &sqlx::sqlite::SqliteConnectOptions::new().filename(path.join("stock_execution_v1.sqlite")), ) @@ -399,6 +520,13 @@ async fn retained_inventory_catalog(catalog: i64) { .unwrap(); old.expose_secret(|bytes| { let value: serde_json::Value = serde_json::from_slice(bytes).unwrap(); + let value = if catalog == 4 { + assert_eq!(value["version"], 3); + assert!(value.get("mapping").is_none()); + value["operation"].clone() + } else { + value + }; assert_eq!(value["version"], if catalog == 2 { 1 } else { 2 }); if catalog == 2 { assert!(value.get("before").is_none()); @@ -406,10 +534,11 @@ async fn retained_inventory_catalog(catalog: i64) { assert_eq!(value["before"], serde_json::Value::Null); } }); - sqlx::query(if catalog == 2 { - "PRAGMA user_version=3" - } else { - "PRAGMA user_version=4" + sqlx::query(match catalog { + 2 => "PRAGMA user_version=3", + 3 => "PRAGMA user_version=4", + 4 => "PRAGMA user_version=5", + _ => unreachable!(), }) .execute(&mut connection) .await diff --git a/crates/storage_sqlite/src/workspace/worker.rs b/crates/storage_sqlite/src/workspace/worker.rs @@ -38,6 +38,13 @@ 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 { + OptionMapping( + Box<WorkspaceBinding>, + radroots_storage::inventory::InventoryCheckpointRef, + radroots_domain::stock::OptionMappingKey, + AttachmentProof, + Reply<Option<radroots_domain::stock::OptionPoolMapping>, OperationError>, + ), ChangeStockGrant( Box<stock::grants::Change>, AttachmentProof, @@ -168,6 +175,9 @@ enum Job { impl Job { fn reject_recovery(self) { match self { + Self::OptionMapping(_, _, _, _, reply) => { + let _ = reply.send(Err(OperationError::RecoveryRequired)); + } Self::ChangeStockGrant(_, _, reply) => { let _ = reply.send(Err(WorkspaceError::RecoveryRequired)); } @@ -377,6 +387,7 @@ impl Handle { | Job::ExecuteInventory(..) | Job::InventoryOperation(..) | Job::Pool(..) + | Job::OptionMapping(..) | Job::Revoke(..) | Job::StockAuthority(..) ) @@ -469,6 +480,23 @@ impl Handle { }; let _ = reply.send(result); } + Job::OptionMapping(binding, minimum, key, proof, reply) => { + let result = if kind == Kind::SellerStock { + stock::inventory::Turn { + connection, + namespace: &namespace, + selected: &input, + crypto: &crypto, + clock: clock.as_ref(), + uncertain: &mut uncertain, + } + .option_mapping(*binding, minimum, key, proof) + .await + } else { + Err(OperationError::UnsupportedOperation) + }; + let _ = reply.send(result); + } Job::Pool(binding, minimum, id, proof, reply) => { let result = if kind == Kind::SellerStock { stock::inventory::Turn { @@ -885,6 +913,23 @@ impl Handle { ))?; result.await.map_err(|_| OperationError::RecoveryRequired)? } + pub(super) async fn option_mapping( + &self, + binding: WorkspaceBinding, + minimum: radroots_storage::inventory::InventoryCheckpointRef, + key: radroots_domain::stock::OptionMappingKey, + proof: AttachmentProof, + ) -> Result<Option<radroots_domain::stock::OptionPoolMapping>, OperationError> { + let (reply, result) = oneshot::channel(); + self.send(Job::OptionMapping( + Box::new(binding), + minimum, + key, + proof, + reply, + ))?; + result.await.map_err(|_| OperationError::RecoveryRequired)? + } pub(super) async fn pool( &self, binding: WorkspaceBinding, diff --git a/crates/storage_sqlite/tests/support/option_mapping.rs b/crates/storage_sqlite/tests/support/option_mapping.rs @@ -0,0 +1,916 @@ +use super::*; +use radroots_domain::{ + ListingOptionId, Sequence, + listing::{ListingCoordinate, ListingId}, + stock::OptionMappingKey, +}; +use radroots_protocol::command::{CapturedOptionMapping, MapOptionInput}; + +#[tokio::test] +async fn admitted_mapping_survives_observer_loss_and_close_drains_before_original_recovery() { + let f = Fixture::new(); + let clock = Arc::new(PausedClock { + state: std::sync::Mutex::new((false, false, false)), + changed: std::sync::Condvar::new(), + }); + let e = StockEnrollment::prepare( + SellerStockConfig::new(key(), key(), "owner", UnixSeconds::new(200).unwrap()).unwrap(), + clock.as_ref(), + ) + .unwrap(); + let store = NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) + .await + .unwrap(); + let binding = store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + let pool = committed( + store + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .await + .unwrap(), + ); + let key = mapping_key(5, 6); + let original = mapping_request(&binding, 7, key, 2, 0, grams("250")); + let digest = original.command().digest(); + clock.arm(); + let mut future = store.execute_inventory(original, proof(e.proof())); + assert!(futures::poll!(future.as_mut()).is_pending()); + clock.entered(); + drop(future); + let mut closing = Box::pin(store.close()); + assert!(futures::poll!(closing.as_mut()).is_pending()); + drop(closing); + assert!(matches!( + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await, + Err(WorkspaceError::WriterActive) + )); + clock.release(); + store.close().await.unwrap(); + let store = + NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) + .await + .unwrap(); + let receipt = store + .inventory_operation( + binding.clone(), + pool.checkpoint(), + OperationId::from_bytes([7; 32]), + Some(digest), + proof(e.proof()), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(receipt.pool(), pool.pool()); + assert_eq!(receipt.mapping().unwrap().version().get(), 1); + assert_eq!( + store + .option_mapping(binding.clone(), receipt.checkpoint(), key, proof(e.proof())) + .await + .unwrap(), + receipt.mapping() + ); + assert_eq!( + committed( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("250")), + proof(e.proof()) + ) + .await + .unwrap() + ), + receipt + ); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn mapping_rechecks_clock_deadline_and_credential_expiry_inside_its_actual_transaction() { + for next in [0, 99, 150, 200] { + let f = Fixture::new(); + let clock = Arc::new(AdmissionClock { + armed: std::sync::atomic::AtomicBool::new(false), + calls: AtomicU64::new(0), + next, + }); + let e = StockEnrollment::prepare( + SellerStockConfig::new(key(), key(), "owner", UnixSeconds::new(200).unwrap()).unwrap(), + clock.as_ref(), + ) + .unwrap(); + let store = + NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) + .await + .unwrap(); + let binding = store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + let pool = committed( + store + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .await + .unwrap(), + ); + clock.armed.store(true, Ordering::SeqCst); + let result = store + .execute_inventory( + mapping_request(&binding, 7, mapping_key(5, 6), 2, 0, grams("250")), + proof(e.proof()), + ) + .await; + match next { + 0 | 99 => assert_eq!( + result, + Err(OperationError::Workspace(WorkspaceError::Unavailable)) + ), + 150 => assert_eq!(result, Err(OperationError::DeadlineExceeded)), + 200 => assert_eq!( + result, + Err(OperationError::Workspace(WorkspaceError::GrantExpired)) + ), + _ => unreachable!(), + } + clock.armed.store(false, Ordering::SeqCst); + assert_eq!( + store + .option_mapping( + binding, + pool.checkpoint(), + mapping_key(5, 6), + proof(e.proof()) + ) + .await + .unwrap(), + None + ); + assert_eq!( + store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap() + .inventory_checkpoint(), + Some(pool.checkpoint()) + ); + store.close().await.unwrap(); + } +} + +fn mapping_key(listing: u8, option: u8) -> OptionMappingKey { + OptionMappingKey::new( + ListingCoordinate::new(key(), ListingId::from_bytes([listing; 16])), + ListingOptionId::from_bytes([option; 32]), + ) +} +fn mapping_request( + binding: &radroots_storage::workspace::WorkspaceBinding, + operation: u8, + key: OptionMappingKey, + pool: u8, + version: u64, + quantity: Quantity, +) -> InventoryRequest { + let selected = binding.input(); + let context = CommandContextData::new( + OperationId::from_bytes([operation; 32]), + binding.actor(), + selected.workspace_id(), + selected.authority(), + selected.route_digest(), + None, + None, + UnixSeconds::new(150).unwrap(), + None, + ) + .unwrap(); + InventoryRequest::new( + binding.clone(), + minimum(binding), + CapturedOptionMapping::new( + context, + MapOptionInput::new( + key, + PoolId::from_bytes([pool; 32]), + quantity, + Sequence::new(version).unwrap(), + ) + .unwrap(), + ) + .unwrap(), + ) + .unwrap() +} +fn grams(amount: &str) -> Quantity { + Quantity::new(amount.parse().unwrap(), MeasurementUnit::Gram).unwrap() +} +#[tokio::test] +async fn mapping_queries_and_original_replay_refuse_initial_and_confirmation_clock_regressions() { + let f = Fixture::new(); + let clock = Arc::new(AdmissionClock { + armed: std::sync::atomic::AtomicBool::new(false), + calls: AtomicU64::new(0), + next: 99, + }); + let e = StockEnrollment::prepare( + SellerStockConfig::new(key(), key(), "owner", UnixSeconds::new(200).unwrap()).unwrap(), + clock.as_ref(), + ) + .unwrap(); + let store = NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) + .await + .unwrap(); + let binding = store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + store + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .await + .unwrap(); + let key = mapping_key(5, 6); + let receipt = committed( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("250")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + for initial in [false, true] { + for choice in 0..3 { + clock.calls.store(u64::from(initial), Ordering::SeqCst); + clock.armed.store(true, Ordering::SeqCst); + let error = match choice { + 0 => store + .option_mapping(binding.clone(), receipt.checkpoint(), key, proof(e.proof())) + .await + .unwrap_err(), + 1 => store + .inventory_operation( + binding.clone(), + receipt.checkpoint(), + OperationId::from_bytes([7; 32]), + None, + proof(e.proof()), + ) + .await + .unwrap_err(), + _ => store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("250")), + proof(e.proof()), + ) + .await + .unwrap_err(), + }; + assert_eq!( + error, + OperationError::Workspace(WorkspaceError::Unavailable) + ); + clock.armed.store(false, Ordering::SeqCst); + } + } + assert_eq!( + store + .option_mapping(binding, receipt.checkpoint(), key, proof(e.proof())) + .await + .unwrap(), + receipt.mapping() + ); + store.close().await.unwrap(); +} +async fn seeded( + f: &Fixture, +) -> ( + NativeWorkspace, + StockEnrollment, + radroots_storage::workspace::WorkspaceBinding, + InventoryReceipt, +) { + let (store, e, binding) = create(f).await; + let pool = committed( + store + .execute_inventory(request(&binding, 1, 2, "Carrots"), proof(e.proof())) + .await + .unwrap(), + ); + (store, e, binding, pool) +} +#[tokio::test] +async fn actual_mapping_create_update_remap_retains_original_effects_and_leaves_physical_stock_unchanged() + { + let f = Fixture::new(); + let (store, e, binding, pool) = seeded(&f).await; + let other = committed( + store + .execute_inventory(request(&binding, 3, 4, "Beets"), proof(e.proof())) + .await + .unwrap(), + ); + let key = mapping_key(5, 6); + let foreign = OptionMappingKey::new( + ListingCoordinate::new( + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5") + .unwrap(), + key.listing().d(), + ), + key.option_id(), + ); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 6, foreign, 2, 0, grams("1")), + proof(e.proof()) + ) + .await, + Err(OperationError::Unauthorized) + ); + let original = mapping_request(&binding, 7, key, 2, 0, grams("250")); + let wire = original.command().protected_wire().to_vec(); + let first = committed( + store + .execute_inventory(original, proof(e.proof())) + .await + .unwrap(), + ); + assert_eq!(first.pool(), pool.pool()); + assert_eq!(first.mapping().unwrap().per_sale_ticks().get(), 250); + let second_key = mapping_key(5, 8); + let second = committed( + store + .execute_inventory( + mapping_request(&binding, 9, second_key, 2, 0, grams("125")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + assert_eq!(second.pool(), pool.pool()); + let updated = committed( + store + .execute_inventory( + mapping_request(&binding, 10, key, 2, 1, grams("500")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + assert_eq!(updated.mapping().unwrap().version().get(), 2); + let remapped = committed( + store + .execute_inventory( + mapping_request(&binding, 11, key, 4, 2, grams("1000")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + assert_eq!(remapped.pool(), other.pool()); + assert_eq!(remapped.mapping().unwrap().version().get(), 3); + // The complete listing coordinate, not just the option ID, forms the key. + let distinct = mapping_key(12, 6); + store + .execute_inventory( + mapping_request(&binding, 13, distinct, 2, 0, grams("10")), + proof(e.proof()), + ) + .await + .unwrap(); + assert_eq!( + store + .option_mapping( + binding.clone(), + remapped.checkpoint(), + key, + proof(e.proof()) + ) + .await + .unwrap(), + remapped.mapping() + ); + assert_eq!( + store + .option_mapping( + binding.clone(), + remapped.checkpoint(), + second_key, + proof(e.proof()) + ) + .await + .unwrap(), + second.mapping() + ); + assert_eq!( + store + .inventory_operation( + binding.clone(), + remapped.checkpoint(), + OperationId::from_bytes([7; 32]), + None, + proof(e.proof()) + ) + .await + .unwrap(), + Some(first.clone()) + ); + assert_eq!( + store + .pool( + binding.clone(), + remapped.checkpoint(), + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await + .unwrap() + .unwrap() + .snapshot(), + pool.pool() + ); + assert_eq!( + store + .pool( + binding.clone(), + remapped.checkpoint(), + PoolId::from_bytes([4; 32]), + proof(e.proof()) + ) + .await + .unwrap() + .unwrap() + .snapshot(), + other.pool() + ); + f.clock.0.store(175, Ordering::SeqCst); + assert_eq!( + committed( + store + .execute_inventory( + InventoryRequest::from_protected_wire( + binding.clone(), + remapped.checkpoint(), + &wire + ) + .unwrap(), + proof(e.proof()) + ) + .await + .unwrap() + ), + first + ); + 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 + .option_mapping( + binding.clone(), + remapped.checkpoint(), + key, + proof(e.proof()) + ) + .await + .unwrap(), + remapped.mapping() + ); + assert_eq!( + store + .inventory_operation( + binding, + remapped.checkpoint(), + OperationId::from_bytes([7; 32]), + None, + proof(e.proof()) + ) + .await + .unwrap(), + Some(first) + ); + store.close().await.unwrap(); + let mut db = database(&f).await; + for (sql, expected) in [ + ("SELECT count(*) FROM stock_pools", 2), + ("SELECT count(*) FROM stock_movements", 2), + ("SELECT count(*) FROM stock_operations", 7), + ("SELECT count(*) FROM stock_mappings", 3), + ] { + let count: i64 = sqlx::query_scalar(sql).fetch_one(&mut db).await.unwrap(); + assert_eq!(count, expected); + } + db.close().await.unwrap(); +} + +#[tokio::test] +async fn mapping_versions_precision_units_and_global_operation_identity_are_enforced() { + let f = Fixture::new(); + let (store, e, binding, _) = seeded(&f).await; + let key = mapping_key(5, 6); + for quantity in [ + grams("0.1"), + Quantity::new("1".parse().unwrap(), MeasurementUnit::Litre).unwrap(), + ] { + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, quantity), + proof(e.proof()) + ) + .await, + Err(OperationError::InvalidCommand) + ); + } + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 1, grams("1")), + proof(e.proof()) + ) + .await, + Err(OperationError::StaleState) + ); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 7, key, 20, 0, grams("1")), + proof(e.proof()) + ) + .await, + Err(OperationError::StaleState) + ); + let first = committed( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("250")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 8, key, 2, 0, grams("1")), + proof(e.proof()) + ) + .await, + Err(OperationError::StaleState) + ); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("500")), + proof(e.proof()) + ) + .await, + Err(OperationError::IdempotencyConflict) + ); + assert_eq!( + store + .execute_inventory( + request(&binding, 7, 10, "duplicate physical identity"), + proof(e.proof()) + ) + .await, + Err(OperationError::IdempotencyConflict) + ); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 1, key, 2, 0, grams("1")), + proof(e.proof()) + ) + .await, + Err(OperationError::IdempotencyConflict) + ); + assert_eq!( + store + .option_mapping( + binding.clone(), + first.checkpoint(), + mapping_key(5, 9), + proof(e.proof()) + ) + .await + .unwrap(), + None + ); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn delegated_full_inventory_does_not_confer_mapping_configuration_read_or_write() { + use radroots_storage::workspace::seller_stock::{SellerAuthoritySelection, StockGrantScope}; + use radroots_storage_sqlite::workspace::{StockGrantEnrollment, StockGrantOutcome}; + let f = Fixture::new(); + let (store, e, owner, _) = seeded(&f).await; + let key = mapping_key(5, 6); + let original = committed( + store + .execute_inventory( + mapping_request(&owner, 7, key, 2, 0, grams("250")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + let child = StockGrantEnrollment::prepare( + &SellerAuthoritySelection::from_attachment(owner.input()), + "inventory-only".into(), + UnixSeconds::new(200).unwrap(), + StockGrantScope::full_inventory(), + ) + .unwrap(); + let state = match store + .enroll_stock_grant(owner.clone(), original.checkpoint(), e.proof(), &child) + .await + .unwrap() + { + StockGrantOutcome::Committed(v) => v.authorization(), + _ => panic!("expected grant"), + }; + let binding = store + .authenticate(child.input().clone(), child.proof()) + .await + .unwrap(); + let current = original.checkpoint().with_authorization(state); + assert_eq!( + store + .option_mapping(binding.clone(), current, key, proof(child.proof())) + .await, + Err(OperationError::Unauthorized) + ); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 8, key, 2, 1, grams("500")), + proof(child.proof()) + ) + .await, + Err(OperationError::Unauthorized) + ); + assert_eq!( + store + .inventory_operation( + binding.clone(), + current, + OperationId::from_bytes([7; 32]), + None, + proof(child.proof()) + ) + .await, + Err(OperationError::Unauthorized) + ); + let replay = InventoryRequest::replay_from_protected_wire( + binding, + current, + mapping_request(&owner, 7, key, 2, 0, grams("250")) + .command() + .protected_wire(), + ) + .unwrap(); + assert_eq!( + store.execute_inventory(replay, proof(child.proof())).await, + Err(OperationError::Unauthorized) + ); + let owner = store + .authenticate(e.input().clone(), e.proof()) + .await + .unwrap(); + assert_eq!( + store + .option_mapping(owner, current, key, proof(e.proof())) + .await + .unwrap(), + original.mapping() + ); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn every_mapping_operation_and_root_write_failure_rolls_back_the_whole_effect() { + for updating in [false, true] { + for (table, event) in [ + ("stock_mappings", if updating { "UPDATE" } else { "INSERT" }), + ("stock_operations", "INSERT"), + ("stock_authority", "UPDATE"), + ] { + let f = Fixture::new(); + let (store, e, binding, pool) = seeded(&f).await; + let key = mapping_key(5, 6); + let previous = if updating { + Some(committed( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("250")), + proof(e.proof()), + ) + .await + .unwrap(), + )) + } else { + None + }; + let minimum = previous.as_ref().unwrap_or(&pool).checkpoint(); + let mut db = database(&f).await; + let trigger = format!( + "CREATE TRIGGER mapping_fault BEFORE {event} ON {table} BEGIN SELECT RAISE(ABORT,'synthetic mapping failure'); END" + ); + sqlx::raw_sql(sqlx::AssertSqlSafe(trigger)) + .execute(&mut db) + .await + .unwrap(); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 8, key, 2, u64::from(updating), grams("500")), + proof(e.proof()) + ) + .await, + Err(OperationError::StorageFailure), + "{table}/{updating}" + ); + sqlx::query("DROP TRIGGER mapping_fault") + .execute(&mut db) + .await + .unwrap(); + assert_eq!( + store + .stock_authority(e.input().clone(), e.proof()) + .await + .unwrap() + .inventory_checkpoint(), + Some(minimum) + ); + assert_eq!( + store + .option_mapping(binding.clone(), minimum, key, proof(e.proof())) + .await + .unwrap(), + previous.as_ref().and_then(|value| value.mapping()) + ); + assert_eq!( + store + .inventory_operation( + binding.clone(), + minimum, + OperationId::from_bytes([8; 32]), + None, + proof(e.proof()) + ) + .await + .unwrap(), + None + ); + assert_eq!( + store + .pool( + binding.clone(), + minimum, + PoolId::from_bytes([2; 32]), + proof(e.proof()) + ) + .await + .unwrap() + .unwrap() + .snapshot(), + pool.pool() + ); + db.close().await.unwrap(); + store.close().await.unwrap(); + } + } +} + +#[tokio::test] +async fn failed_mapping_commit_reports_unknown_fences_the_owner_and_reopens_without_a_partial_effect() + { + let f = Fixture::new(); + let (store, e, binding, pool) = seeded(&f).await; + let key = mapping_key(5, 6); + let original = mapping_request(&binding, 7, key, 2, 0, grams("250")); + let digest = original.command().digest(); + let mut db = database(&f).await; + sqlx::raw_sql("CREATE TABLE mapping_commit_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER mapping_commit_failure AFTER INSERT ON stock_mappings BEGIN INSERT INTO mapping_commit_fault VALUES(2); END").execute(&mut db).await.unwrap(); + let anchor = match store + .execute_inventory(original, proof(e.proof())) + .await + .unwrap() + { + InventoryOutcome::Unknown(value) => value, + _ => panic!("commit must be unknown"), + }; + assert_eq!(anchor.operation_id(), OperationId::from_bytes([7; 32])); + assert_eq!(anchor.command_digest(), digest); + assert!(anchor.transaction_id().is_some()); + assert_eq!( + store + .option_mapping(binding.clone(), pool.checkpoint(), key, proof(e.proof())) + .await, + Err(OperationError::RecoveryRequired) + ); + store.close().await.unwrap(); + sqlx::raw_sql("DROP TRIGGER mapping_commit_failure; DROP TABLE mapping_commit_fault") + .execute(&mut db) + .await + .unwrap(); + db.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(), + pool.checkpoint(), + anchor.operation_id(), + Some(digest), + proof(e.proof()) + ) + .await + .unwrap(), + None + ); + assert_eq!( + store + .option_mapping(binding.clone(), pool.checkpoint(), key, proof(e.proof())) + .await + .unwrap(), + None + ); + let result = committed( + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("250")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + assert_eq!(result.mapping().unwrap().version().get(), 1); + assert_eq!(result.pool(), pool.pool()); + store.close().await.unwrap(); +} + +#[tokio::test] +async fn older_authentic_mapping_projection_cannot_replace_the_latest_protected_configuration() { + let f = Fixture::new(); + let (store, e, binding, _) = seeded(&f).await; + let key = mapping_key(5, 6); + store + .execute_inventory( + mapping_request(&binding, 7, key, 2, 0, grams("250")), + proof(e.proof()), + ) + .await + .unwrap(); + let mut db = database(&f).await; + let old: Vec<u8> = sqlx::query_scalar("SELECT protected FROM stock_mappings") + .fetch_one(&mut db) + .await + .unwrap(); + let latest = committed( + store + .execute_inventory( + mapping_request(&binding, 8, key, 2, 1, grams("500")), + proof(e.proof()), + ) + .await + .unwrap(), + ); + sqlx::query("UPDATE stock_mappings SET revision=1,protected=?") + .bind(old) + .execute(&mut db) + .await + .unwrap(); + assert_eq!( + store + .option_mapping(binding.clone(), latest.checkpoint(), key, proof(e.proof())) + .await, + Err(OperationError::RecoveryRequired) + ); + assert_eq!( + store + .execute_inventory( + mapping_request(&binding, 9, key, 2, 1, grams("1000")), + proof(e.proof()) + ) + .await, + Err(OperationError::RecoveryRequired) + ); + let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations") + .fetch_one(&mut db) + .await + .unwrap(); + assert_eq!(count, 3); + db.close().await.unwrap(); + store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/tests/support/pool_creation.rs b/crates/storage_sqlite/tests/support/pool_creation.rs @@ -1114,3 +1114,6 @@ async fn a_mutable_pool_index_cannot_hide_a_more_recent_protected_pool_effect() #[path = "stock_grants.rs"] mod grants; + +#[path = "option_mapping.rs"] +mod mapping; diff --git a/crates/storage_sqlite/tests/support/stock_authority.rs b/crates/storage_sqlite/tests/support/stock_authority.rs @@ -602,7 +602,7 @@ async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_c clock.release(); assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); store.close().await.unwrap(); - sqlx::query("PRAGMA user_version=4") + sqlx::query("PRAGMA user_version=5") .execute(&mut connection) .await .unwrap(); diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -103,6 +103,11 @@ struct StockCapabilityContract { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct NativeSellerStockAuthority { + mapping_payload_schema: String, + mapping_owner_administration_required: bool, + mapping_changes_physical_stock: bool, + mapping_changes_pool_version: bool, + mapping_create_expected_version: u16, capability_contract: StockCapabilityContract, scope: String, database: String, @@ -316,11 +321,16 @@ 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 == 4 + && stock.schema_version == 5 && stock.retained_enrollment_versions == [1] - && stock.retained_inventory_versions == [2, 3] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v4" - && stock.inventory_operation_payload_schema == "radroots.seller_stock.operation.v3" + && stock.retained_inventory_versions == [2, 3, 4] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v5" + && stock.inventory_operation_payload_schema == "radroots.seller_stock.operation.v4" + && stock.mapping_payload_schema == "radroots.seller_stock.mapping.v1" + && stock.mapping_owner_administration_required + && !stock.mapping_changes_physical_stock + && !stock.mapping_changes_pool_version + && stock.mapping_create_expected_version == 0 && stock.inventory_movement_payload_schema == "radroots.seller_stock.movement.v2" && stock.grant_payload_schema == "radroots.seller_stock.grant.v2" && stock.grant_change_payload_schema == "radroots.seller_stock.grant_change.v1" @@ -891,6 +901,40 @@ mod tests { } #[test] + fn native_mapping_contract_preserves_catalogs_owner_access_and_physical_non_effects() { + for (field, bad) in [ + ("schema_version", json!(4)), + ("retained_inventory_versions", json!([2, 3])), + ( + "mapping_payload_schema", + json!("radroots.seller_stock.mapping.v2"), + ), + ( + "inventory_operation_payload_schema", + json!("radroots.seller_stock.operation.v3"), + ), + ( + "authority_payload_schema", + json!("radroots.seller_stock.authority.v4"), + ), + ("mapping_owner_administration_required", json!(false)), + ("mapping_changes_physical_stock", json!(true)), + ("mapping_changes_pool_version", json!(true)), + ("mapping_create_expected_version", json!(1)), + ("inventory_scope_grants_administration", json!(true)), + ] { + assert!( + validate_bytes(&changed( + &format!("/native_seller_stock_authority/{field}"), + bad + )) + .is_err(), + "{field}" + ); + } + } + + #[test] fn assigned_protocol_kinds_and_target_metadata_cannot_authorize_publication() { assert!(validate_bytes(&changed("/protocol/commerce_kind", json!(8891))).is_err()); assert!(validate_bytes(&changed("/protocol/commerce_kind", json!(null))).is_err());