commit cedc4ed20b6d15644b4179c65fc5016f74031a92 parent ffb204d4797d5403b90dd42a84dcc7274f2e0edd Author: triesap <tyson@radroots.org> Date: Fri, 30 Oct 2026 05:14:05 +0000 stock: install authorized replacement terms atomically - Resolve complete replacement terms against authenticated current agreements and original allocations. - Hold positive deltas at preparation and release authorized residuals only at installation. - Retain catalog 1–19 formats and protect catalog 20 obligation changes through the existing executor. - Verify ordinary callers, stock conservation, rollback, recovery, portable APIs and native platform behavior. Diffstat:
61 files changed, 3552 insertions(+), 264 deletions(-)
diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt @@ -161,12 +161,14 @@ pub use radroots::orders::AcceptanceRecipient pub use radroots::orders::AcceptanceRewrapStatus pub use radroots::orders::AcceptanceStatus pub use radroots::orders::AcceptanceUnissuedReceipt +pub use radroots::orders::InstallTermsInput pub use radroots::orders::InstalledAcceptance pub struct radroots::orders::Orders<'a> impl<'a> radroots::orders::Orders<'a> pub async fn radroots::orders::Orders<'a>::accept(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_acceptance::AcceptOrderInput) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots::orders::Orders<'a>::acceptance_rewrap_status(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_domain::identifier::OperationId) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceRewrapStatus> pub async fn radroots::orders::Orders<'a>::acceptance_status(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> +pub async fn radroots::orders::Orders<'a>::install_terms(&self, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_terms::InstallTermsInput) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots::orders::Orders<'a>::resume_acceptance(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots::orders::Orders<'a>::resume_acceptance_rewrap(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_domain::identifier::OperationId) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceRewrapStatus> pub async fn radroots::orders::Orders<'a>::rewrap_acceptance(&self, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest, radroots_identity::key::PublicKey, radroots_domain::identifier::OperationId) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceRewrapStatus> diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -442,6 +442,13 @@ pub fn radroots_domain::stock::PoolView::new(&str, radroots_domain::stock::PoolS pub const fn radroots_domain::stock::PoolView::snapshot(&self) -> radroots_domain::stock::PoolSnapshot impl core::fmt::Debug for radroots_domain::stock::PoolView pub fn radroots_domain::stock::PoolView::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::stock::ReplacementAllocationPlan +impl radroots_domain::stock::ReplacementAllocationPlan +pub fn radroots_domain::stock::ReplacementAllocationPlan::additional_allocations(&self) -> &[radroots_domain::stock::StockAllocation] +pub fn radroots_domain::stock::ReplacementAllocationPlan::pending_releases(&self) -> &[radroots_domain::stock::StockAllocation] +pub fn radroots_domain::stock::ReplacementAllocationPlan::preparatory_holds(&self) -> &[radroots_domain::stock::PoolHoldProposal] +impl core::fmt::Debug for radroots_domain::stock::ReplacementAllocationPlan +pub fn radroots_domain::stock::ReplacementAllocationPlan::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::stock::StockAllocation impl radroots_domain::stock::StockAllocation pub const fn radroots_domain::stock::StockAllocation::line_id(self) -> radroots_domain::AgreementLineId @@ -472,6 +479,9 @@ pub fn radroots_domain::stock::StockTicks::serialize<S: serde_core::ser::Seriali impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::stock::StockTicks pub fn radroots_domain::stock::StockTicks::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub fn radroots_domain::stock::plan_allocations(&radroots_domain::Terms, &[radroots_domain::stock::OptionPoolMapping], &[radroots_domain::stock::PoolSnapshot], core::option::Option<&[radroots_domain::stock::AllocationClaim]>) -> core::result::Result<(alloc::vec::Vec<radroots_domain::stock::StockAllocation>, alloc::vec::Vec<radroots_domain::stock::PoolHoldProposal>), radroots_domain::stock::AllocationPlanError> +pub fn radroots_domain::stock::plan_replacement_allocations(&[radroots_domain::stock::StockAllocation], &[radroots_domain::stock::StockAllocation], &[radroots_domain::stock::PoolSnapshot]) -> core::result::Result<radroots_domain::stock::ReplacementAllocationPlan, radroots_domain::stock::AllocationPlanError> +pub fn radroots_domain::stock::resolve_allocations(&radroots_domain::Terms, &[radroots_domain::stock::OptionPoolMapping], &[radroots_domain::stock::PoolSnapshot], core::option::Option<&[radroots_domain::stock::AllocationClaim]>) -> core::result::Result<alloc::vec::Vec<radroots_domain::stock::StockAllocation>, radroots_domain::stock::AllocationPlanError> +pub fn radroots_domain::stock::resolve_replacement_allocations(&radroots_domain::Terms, &[radroots_domain::stock::OptionPoolMapping], &[radroots_domain::stock::PoolSnapshot], core::option::Option<&[radroots_domain::stock::AllocationClaim]>, &[radroots_domain::stock::StockAllocation]) -> core::result::Result<alloc::vec::Vec<radroots_domain::stock::StockAllocation>, radroots_domain::stock::AllocationPlanError> #[non_exhaustive] pub enum radroots_domain::ActorRole pub radroots_domain::ActorRole::Buyer pub radroots_domain::ActorRole::Coordinator diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt @@ -139,6 +139,7 @@ pub async fn radroots_execution::session::ClientSession<H>::stock_pool(&self, al pub async fn radroots_execution::session::ClientSession<H>::stock_preparation_abort(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<core::option::Option<radroots_storage::inventory::abort::StockAbortReceipt>> impl<H: radroots_execution::session::SessionHost + 'static> radroots_execution::session::ClientSession<H> pub async fn radroots_execution::session::ClientSession<H>::accept_stock_order(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_acceptance::AcceptOrderInput) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> +pub async fn radroots_execution::session::ClientSession<H>::install_stock_terms(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_execution::workspace::CommandContext, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::source::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::source::StockListingCheckpointRef, radroots_protocol::command::order_terms::InstallTermsInput) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots_execution::session::ClientSession<H>::resume_stock_acceptance(&self, alloc::sync::Arc<dyn radroots_storage::inventory::InventoryStore>, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::ExecutionResult<radroots_execution::session::commerce::AcceptanceStatus> pub async fn radroots_execution::session::ClientSession<H>::stock_acceptance_status(&self, alloc::sync::Arc<dyn radroots_execution::session::commerce::AcceptanceStore>, &radroots_execution::workspace::WorkspaceSession, radroots_storage::inventory::InventoryCheckpointRef, radroots_domain::identifier::OperationId, radroots_domain::identifier::CommandDigest) -> radroots_execution::Result<radroots_execution::session::commerce::AcceptanceStatus> impl<H: radroots_execution::session::SessionHost + 'static> radroots_execution::session::ClientSession<H> diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -476,6 +476,7 @@ pub const radroots_protocol::commerce::RECORD_MAX_BYTES: usize pub const radroots_protocol::commerce::SIGNING_PLAN_MAX_BYTES: usize pub fn radroots_protocol::commerce::decode(&[u8]) -> core::result::Result<radroots_protocol::commerce::DecodedRecord, radroots_protocol::commerce::RecordWireError> pub fn radroots_protocol::commerce::initial_commitment_rumor(&radroots_protocol::command::CapturedOrderAcceptance, &radroots_protocol::commerce::DecodedRecord, core::option::Option<(radroots_domain::identifier::RecordId, radroots_domain::context::Sequence)>, radroots_domain::context::UnixSeconds) -> core::result::Result<radroots_protocol::commerce::EncodedCommerceRumor, radroots_protocol::commerce::RecordWireError> +pub fn radroots_protocol::commerce::replacement_commitment_rumor(&radroots_protocol::command::CapturedTermsInstallation, &radroots_protocol::commerce::DecodedRecord, &radroots_protocol::commerce::DecodedRecord, &radroots_protocol::commerce::DecodedRecord, (radroots_domain::identifier::RecordId, radroots_domain::context::Sequence), radroots_domain::context::UnixSeconds) -> core::result::Result<radroots_protocol::commerce::EncodedCommerceRumor, radroots_protocol::commerce::RecordWireError> pub mod radroots_protocol::error pub mod radroots_protocol::error::v1 pub enum radroots_protocol::error::v1::Class diff --git a/contracts/architecture/decisions/shared_sdk_refactor.v1.json b/contracts/architecture/decisions/shared_sdk_refactor.v1.json @@ -82,7 +82,7 @@ "adapter": "radroots_nostr.signing.LocalSigner", "native_authorizer": "NativeWorkspace.authorize_stock_exact_replay", "captured_replay": "local_replay_safe", - "native_catalog": 19, + "native_catalog": 20, "worker_charge_bytes": 1048576, "existing_protected_claim_required": true, "current_execute_consent_required": true, @@ -111,7 +111,7 @@ "scope": "seller_stock_owner", "database": "stock_execution_v1.sqlite", "lock": ".stock_execution_v1.lock", - "schema_version": 19, + "schema_version": 20, "retained_enrollment_versions": [ 1 ], @@ -132,9 +132,10 @@ 15, 16, 17, - 18 + 18, + 19 ], - "authority_payload_schema": "radroots.seller_stock.authority.v19", + "authority_payload_schema": "radroots.seller_stock.authority.v20", "public_source_payload_schemas": [ "radroots.seller_stock.public_source_event.v1", "radroots.seller_stock.public_source_head.v1", @@ -401,7 +402,8 @@ 16, 17, 18, - 19 + 19, + 20 ], "untracked_claimed_catalogs": [ 13, @@ -423,7 +425,8 @@ 16, 17, 18, - 19 + 19, + 20 ], "retained_unsupported_catalogs": [ 1, @@ -464,7 +467,8 @@ "supported_catalogs": [ 17, 18, - 19 + 19, + 20 ], "retained_unsupported_catalogs": [ 1, @@ -539,7 +543,8 @@ "payload_prefix_bytes": 117, "supported_catalogs": [ 18, - 19 + 19, + 20 ], "retained_unsupported_catalogs": [ 1, @@ -1106,7 +1111,10 @@ "model_owner": "radroots_storage.inventory.StockSnapshot", "facade_method": "Stock.inspect", "storage_port": "InventoryStore.inspect_stock", - "supported_catalogs": [19], + "supported_catalogs": [ + 19, + 20 + ], "worker_charge_bytes": 1048576, "same_checkpoint_required": true, "original_allocation_required": true, @@ -1126,7 +1134,7 @@ "loss_deletes_obligation": false, "native_atomic_allocation_and_identity_required": true, "native_correction": { - "catalog": 19, + "catalog": 20, "selection": "available_then_original_installation_and_allocation_order", "max_affected_allocations": 32, "protected_original_allocation_required": true, @@ -1135,6 +1143,28 @@ "worker_charge_bytes": 1048576, "preparatory_loss_implicit": false, "quarantine_loss_implicit": false + }, + "native_terms_installation": { + "catalog": 20, + "facade_method": "Orders.install_terms", + "execution_method": "ClientSession.install_stock_terms", + "source_owner": "radroots_domain.causal.prepare_replacement_terms", + "allocation_owner": "radroots_domain.stock.resolve_replacement_allocations", + "delta_owner": "radroots_domain.stock.plan_replacement_allocations", + "current_installed_base_required": true, + "original_allocations_required": true, + "positive_hold_phase": "T0", + "negative_release_phase": "T2", + "pending_negatives_finance_holds": false, + "old_commitment_retained_while_pending": true, + "changed_residual_requires_new_admission": true, + "release_composition": "original_installation_order_deficit_then_backed", + "quantity_storage": "protected_installation_body", + "index_plaintext_quantities": false, + "automatic_changed_multi_pool_split": "requires_explicit_complete_allocation", + "same_signing_and_recovery_owner": true, + "unknown_issuance_releases_stock": false, + "retained_catalog_auto_upgrade": false } }, "execution": { diff --git a/crates/domain/src/stock.rs b/crates/domain/src/stock.rs @@ -7,12 +7,17 @@ mod allocation; mod mapping; mod movements; mod obligation; +mod replacement; pub use allocation::{ AllocationClaim, AllocationPlanError, PoolHoldProposal, StockAllocation, plan_allocations, + resolve_allocations, }; pub use mapping::{MappingError, OptionMappingKey, OptionPoolMapping}; pub use movements::{HeldStockCategory, HeldStockLoss}; pub use obligation::ObligationBacking; +pub use replacement::{ + ReplacementAllocationPlan, plan_replacement_allocations, resolve_replacement_allocations, +}; /// A bounded, input-free stock value failure. #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/crates/domain/src/stock/allocation.rs b/crates/domain/src/stock/allocation.rs @@ -201,12 +201,39 @@ pub fn plan_allocations( pools: &[PoolSnapshot], explicit: Option<&[AllocationClaim]>, ) -> Result<(Vec<StockAllocation>, Vec<PoolHoldProposal>), AllocationPlanError> { + let result = resolve_allocations(terms, mappings, pools, explicit)?; + let available: BTreeMap<_, _> = pools.iter().map(|pool| (pool.id(), *pool)).collect(); + let mut totals = BTreeMap::new(); + for allocation in &result { + let total = totals.entry(allocation.pool).or_insert(StockTicks::ZERO); + *total = total + .checked_add(allocation.ticks) + .map_err(|_| AllocationPlanError::Capacity)?; + } + let mut effects = Vec::new(); + for (id, quantity) in totals { + effects.push(PoolHoldProposal::new(available[&id], quantity)?); + } + Ok((result, effects)) +} + +/// Resolves complete line/pool quantities using the supplied exact mappings, +/// units and versions, without requiring or proposing new available stock. +/// An amendment executor supplies retained mappings for existing draws. It +/// must separately compare current residual/original allocations and acquire +/// positive deltas; successful resolution alone grants no physical backing. +pub fn resolve_allocations( + terms: &Terms, + mappings: &[OptionPoolMapping], + pools: &[PoolSnapshot], + explicit: Option<&[AllocationClaim]>, +) -> Result<Vec<StockAllocation>, AllocationPlanError> { match terms.supply() { SupplyCommitment::FuturePromise(_) => { if explicit.is_some() || !mappings.is_empty() || !pools.is_empty() { return Err(AllocationPlanError::InvalidInput); } - return Ok((vec![], vec![])); + return Ok(vec![]); } SupplyCommitment::StockBacked => {} } @@ -315,19 +342,5 @@ pub fn plan_allocations( return Err(AllocationPlanError::InvalidInput); } result.sort_by_key(|value| (value.pool, value.line)); - let mut totals = BTreeMap::new(); - for allocation in &result { - if allocation.ticks == StockTicks::ZERO { - return Err(AllocationPlanError::InvalidInput); - } - let total = totals.entry(allocation.pool).or_insert(StockTicks::ZERO); - *total = total - .checked_add(allocation.ticks) - .map_err(|_| AllocationPlanError::Capacity)?; - } - let mut effects = Vec::new(); - for (id, quantity) in totals { - effects.push(PoolHoldProposal::new(available[&id], quantity)?); - } - Ok((result, effects)) + Ok(result) } diff --git a/crates/domain/src/stock/replacement.rs b/crates/domain/src/stock/replacement.rs @@ -0,0 +1,220 @@ +//! Net amendment claims. Negative changes cannot finance preparatory holds. +use super::{ + AllocationClaim, AllocationPlanError, OptionPoolMapping, PoolHoldProposal, PoolSnapshot, + StockAllocation, StockTicks, +}; +use crate::{Decimal, Quantity, SupplyCommitment, Terms}; +use alloc::{collections::BTreeMap, vec::Vec}; +use core::fmt; + +/// Resolves complete replacement draws against retained original line/pool +/// quantities. Automatic allocation keeps an existing single pool, even when +/// a listing mapping now names another pool. An unchanged multi-pool draw is +/// retained exactly; changing its split requires explicit complete allocation. +/// Mappings for existing lines must come from the retained preparation, with +/// consumed quantities and original provenance separately checked by execution. +pub fn resolve_replacement_allocations( + terms: &Terms, + mappings: &[OptionPoolMapping], + pools: &[PoolSnapshot], + explicit: Option<&[AllocationClaim]>, + current: &[StockAllocation], +) -> Result<Vec<StockAllocation>, AllocationPlanError> { + plan_replacement_allocations(current, current, pools)?; + let observed = if matches!(terms.supply(), SupplyCommitment::FuturePromise(_)) { + &[][..] + } else { + pools + }; + let desired = super::resolve_allocations(terms, mappings, observed, explicit)?; + if current.len() > 64 { + return Err(AllocationPlanError::Capacity); + } + if explicit.is_some() { + return Ok(desired); + } + let pools: BTreeMap<_, _> = pools.iter().map(|pool| (pool.id(), *pool)).collect(); + let mut result = Vec::new(); + for target in desired { + let originals: Vec<_> = current + .iter() + .filter(|old| old.line_id() == target.line_id()) + .copied() + .collect(); + let target_pool = pools + .get(&target.pool_id()) + .ok_or(AllocationPlanError::StaleState)?; + let quantity = Quantity::new( + Decimal::from_parts(target.ticks().get(), target_pool.unit().scale()) + .map_err(|_| AllocationPlanError::Capacity)?, + target_pool.unit().unit(), + ) + .map_err(|_| AllocationPlanError::InvalidInput)?; + match originals.as_slice() { + [] => result.push(target), + [original] => { + let original_pool = pools + .get(&original.pool_id()) + .ok_or(AllocationPlanError::StaleState)?; + let converted = quantity + .convert(original_pool.unit().unit()) + .map_err(|_| AllocationPlanError::InvalidInput)?; + result.push(StockAllocation::new( + target.line_id(), + original.pool_id(), + original_pool + .unit() + .ticks_for(converted) + .map_err(|_| AllocationPlanError::InvalidInput)?, + )?); + } + _ => { + let mut quantity = Quantity::new( + Decimal::from_parts(0, 0).map_err(|_| AllocationPlanError::InvalidInput)?, + target_pool.unit().unit(), + ) + .map_err(|_| AllocationPlanError::InvalidInput)?; + for original in &originals { + let original_pool = pools + .get(&original.pool_id()) + .ok_or(AllocationPlanError::StaleState)?; + let converted = Quantity::new( + Decimal::from_parts(original.ticks().get(), original_pool.unit().scale()) + .map_err(|_| AllocationPlanError::Capacity)?, + original_pool.unit().unit(), + ) + .and_then(|value| value.convert(target_pool.unit().unit())) + .map_err(|_| AllocationPlanError::InvalidInput)?; + quantity = quantity + .checked_add(converted) + .map_err(|_| AllocationPlanError::Capacity)?; + } + if target_pool + .unit() + .ticks_for(quantity) + .map_err(|_| AllocationPlanError::InvalidInput)? + != target.ticks() + { + return Err(AllocationPlanError::Unsupported); + } + result.extend(originals); + } + } + } + if result.len() > 64 { + return Err(AllocationPlanError::Capacity); + } + result.sort_by_key(|value| (value.pool_id(), value.line_id())); + Ok(result) +} + +/// Checked net changes over claimed current and desired residual draws. +/// Original provenance, retained mappings, already consumed quantities and +/// deficit/backing composition must be authenticated by the executor. This +/// value neither acquires positives nor releases negatives or heals deficits. +pub struct ReplacementAllocationPlan { + additional: Vec<StockAllocation>, + releases: Vec<StockAllocation>, + holds: Vec<PoolHoldProposal>, +} +impl ReplacementAllocationPlan { + /// Positive residual differences to acquire before replacement issuance. + pub fn additional_allocations(&self) -> &[StockAllocation] { + &self.additional + } + /// Negative residual differences to resolve against original allocations + /// only when the mutually authorized replacement actually installs. + pub fn pending_releases(&self) -> &[StockAllocation] { + &self.releases + } + /// Atomic available-to-preparatory proposals, without spending any pending + /// negative delta. Current pool/permission checks still belong to the store. + pub fn preparatory_holds(&self) -> &[PoolHoldProposal] { + &self.holds + } +} +impl fmt::Debug for ReplacementAllocationPlan { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ReplacementAllocationPlan(<private proposal>)") + } +} + +/// Compares complete aggregate current and desired residual line/pool draws. +/// Inputs contain at most64 unique positive pairs each and96 distinct versioned +/// pools. They are already normalized to each pool's fixed ticks; resolving +/// full new terms and subtracting consumed quantities happens before this call. +/// Current includes deficits as outstanding obligations: unchanged quantities +/// never receive replacement backing implicitly. All positive pool holds must +/// succeed together; negative deltas remain data and never alter these holds. +pub fn plan_replacement_allocations( + current: &[StockAllocation], + desired: &[StockAllocation], + pools: &[PoolSnapshot], +) -> Result<ReplacementAllocationPlan, AllocationPlanError> { + if current.len() > 64 || desired.len() > 64 || pools.len() > 96 { + return Err(AllocationPlanError::Capacity); + } + let mut observed = BTreeMap::new(); + for pool in pools { + if pool.version().get() == 0 || observed.insert(pool.id(), *pool).is_some() { + return Err(AllocationPlanError::InvalidInput); + } + } + let mut before = BTreeMap::new(); + let mut after = BTreeMap::new(); + for (values, target) in [(current, &mut before), (desired, &mut after)] { + for value in values { + if !observed.contains_key(&value.pool_id()) { + return Err(AllocationPlanError::StaleState); + } + if target + .insert((value.pool_id(), value.line_id()), value.ticks()) + .is_some() + { + return Err(AllocationPlanError::InvalidInput); + } + } + } + let mut keys: Vec<_> = before.keys().chain(after.keys()).copied().collect(); + keys.sort(); + keys.dedup(); + let mut additional = Vec::new(); + let mut releases = Vec::new(); + let mut quantities = BTreeMap::new(); + for (pool, line) in keys { + let old = before + .get(&(pool, line)) + .copied() + .unwrap_or(StockTicks::ZERO); + let new = after + .get(&(pool, line)) + .copied() + .unwrap_or(StockTicks::ZERO); + if new > old { + let quantity = new + .checked_sub(old) + .map_err(|_| AllocationPlanError::InvalidInput)?; + additional.push(StockAllocation::new(line, pool, quantity)?); + let total = quantities.entry(pool).or_insert(StockTicks::ZERO); + *total = total + .checked_add(quantity) + .map_err(|_| AllocationPlanError::Capacity)?; + } else if old > new { + releases.push(StockAllocation::new( + line, + pool, + old.checked_sub(new) + .map_err(|_| AllocationPlanError::InvalidInput)?, + )?); + } + } + let mut holds = Vec::with_capacity(quantities.len()); + for (pool, quantity) in quantities { + holds.push(PoolHoldProposal::new(observed[&pool], quantity)?); + } + Ok(ReplacementAllocationPlan { + additional, + releases, + holds, + }) +} diff --git a/crates/domain/tests/stock_replacement.rs b/crates/domain/tests/stock_replacement.rs @@ -0,0 +1,232 @@ +use radroots_domain::{AgreementLineId, PoolId, Sequence, listing::MeasurementUnit, stock::*}; + +fn ticks(value: u64) -> StockTicks { + StockTicks::new(value).unwrap() +} +fn allocation(line: u8, pool: u8, quantity: u64) -> StockAllocation { + StockAllocation::new( + AgreementLineId::from_bytes([line; 32]), + PoolId::from_bytes([pool; 32]), + ticks(quantity), + ) + .unwrap() +} +fn pool(id: u8, available: u64, committed: u64) -> PoolSnapshot { + PoolSnapshot::new( + PoolId::from_bytes([id; 32]), + PoolUnit::new(MeasurementUnit::Each, 0).unwrap(), + PoolBalances::new( + ticks(available + committed), + PhysicalBalances { + available: ticks(available), + committed_hold: ticks(committed), + ..PhysicalBalances::ZERO + }, + ) + .unwrap(), + Sequence::new(7).unwrap(), + ) +} + +#[test] +fn positive_differences_hold_before_issuance_and_leave_original_commitments_untouched() { + let before = pool(1, 10, 3); + let plan = + plan_replacement_allocations(&[allocation(1, 1, 3)], &[allocation(1, 1, 5)], &[before]) + .unwrap(); + assert_eq!(plan.additional_allocations(), &[allocation(1, 1, 2)]); + assert!(plan.pending_releases().is_empty()); + let hold = plan.preparatory_holds()[0]; + assert_eq!(hold.before(), before); + assert_eq!(hold.after().balances().physical().available, ticks(8)); + assert_eq!( + hold.after().balances().physical().preparatory_hold, + ticks(2) + ); + assert_eq!(hold.after().balances().physical().committed_hold, ticks(3)); + assert_eq!( + hold.after().balances().introduced(), + before.balances().introduced() + ); + assert_eq!(before.balances().physical().available, ticks(10)); +} + +#[test] +fn negative_changes_are_only_pending_original_draws_not_available_stock_or_version_steps() { + let before = pool(1, 2, 5); + let plan = + plan_replacement_allocations(&[allocation(1, 1, 5)], &[allocation(1, 1, 2)], &[before]) + .unwrap(); + assert_eq!(plan.pending_releases(), &[allocation(1, 1, 3)]); + assert!(plan.additional_allocations().is_empty()); + assert!(plan.preparatory_holds().is_empty()); + assert_eq!(before.version().get(), 7); + assert_eq!(before.balances().physical().available, ticks(2)); + assert_eq!(before.balances().physical().committed_hold, ticks(5)); +} + +#[test] +fn neither_same_pool_line_swaps_nor_cross_pool_releases_can_finance_positive_holds() { + for (current, desired, pools) in [ + ( + vec![allocation(1, 1, 3)], + vec![allocation(2, 1, 3)], + vec![pool(1, 0, 3)], + ), + ( + vec![allocation(1, 1, 3)], + vec![allocation(1, 2, 3)], + vec![pool(1, 0, 3), pool(2, 2, 0)], + ), + ] { + assert_eq!( + plan_replacement_allocations(¤t, &desired, &pools).unwrap_err(), + AllocationPlanError::StaleState + ); + } + let current = [allocation(1, 1, 3)]; + let desired = [allocation(2, 1, 3)]; + let plan = plan_replacement_allocations(¤t, &desired, &[pool(1, 3, 3)]).unwrap(); + assert_eq!( + plan.preparatory_holds()[0] + .after() + .balances() + .physical() + .available, + ticks(0) + ); + assert_eq!( + plan.preparatory_holds()[0] + .after() + .balances() + .physical() + .committed_hold, + ticks(3) + ); + assert_eq!(plan.pending_releases(), ¤t); +} + +#[test] +fn unchanged_obligations_do_not_cure_deficits_or_replace_original_pool_identity() { + let outstanding = [allocation(1, 1, 5)]; + let original = pool(1, 10, 3); // The other two obligation ticks have no backing. + let plan = plan_replacement_allocations(&outstanding, &outstanding, &[original]).unwrap(); + assert!(plan.additional_allocations().is_empty()); + assert!(plan.pending_releases().is_empty()); + assert!(plan.preparatory_holds().is_empty()); + assert_eq!(original.balances().physical().committed_hold, ticks(3)); + let changed = [allocation(1, 2, 5)]; + let plan = + plan_replacement_allocations(&outstanding, &changed, &[original, pool(2, 5, 0)]).unwrap(); + assert_eq!(plan.pending_releases(), &outstanding); + assert_eq!(plan.additional_allocations(), &changed); + assert_eq!( + plan.preparatory_holds()[0].before().id(), + changed[0].pool_id() + ); +} + +#[test] +fn complete_multi_pool_plan_is_stable_sorted_and_aggregates_only_additional_ticks() { + let current = [allocation(2, 2, 3), allocation(1, 1, 2)]; + let desired = [ + allocation(3, 2, 1), + allocation(2, 2, 5), + allocation(1, 1, 1), + ]; + let pools = [pool(2, 10, 3), pool(1, 4, 2)]; + let plan = plan_replacement_allocations(¤t, &desired, &pools).unwrap(); + assert_eq!( + plan.additional_allocations(), + &[allocation(2, 2, 2), allocation(3, 2, 1)] + ); + assert_eq!(plan.pending_releases(), &[allocation(1, 1, 1)]); + assert_eq!(plan.preparatory_holds().len(), 1); + assert_eq!(plan.preparatory_holds()[0].quantity(), ticks(3)); + let reverse = plan_replacement_allocations( + ¤t.into_iter().rev().collect::<Vec<_>>(), + &desired.into_iter().rev().collect::<Vec<_>>(), + &pools.into_iter().rev().collect::<Vec<_>>(), + ) + .unwrap(); + assert_eq!( + plan.additional_allocations(), + reverse.additional_allocations() + ); + assert_eq!(plan.pending_releases(), reverse.pending_releases()); + assert_eq!(plan.preparatory_holds(), reverse.preparatory_holds()); +} + +#[test] +fn duplicate_unknown_stale_and_over_budget_data_never_make_partial_plans() { + let value = allocation(1, 1, 1); + for (current, desired, pools) in [ + (vec![value, value], vec![], vec![pool(1, 4, 2)]), + (vec![], vec![value, value], vec![pool(1, 4, 2)]), + (vec![value], vec![], vec![]), + (vec![], vec![value], vec![]), + (vec![], vec![value], vec![pool(1, 4, 2), pool(1, 4, 2)]), + ] { + assert!(plan_replacement_allocations(¤t, &desired, &pools).is_err()); + } + assert_eq!( + plan_replacement_allocations(&vec![value; 65], &[], &[pool(1, 4, 2)]).unwrap_err(), + AllocationPlanError::Capacity + ); + assert_eq!( + plan_replacement_allocations(&[], &vec![value; 65], &[pool(1, 4, 2)]).unwrap_err(), + AllocationPlanError::Capacity + ); + assert_eq!( + plan_replacement_allocations(&[], &[], &vec![pool(1, 4, 2); 97]).unwrap_err(), + AllocationPlanError::Capacity + ); + let old = pool(1, 4, 2); + let absent = PoolSnapshot::new( + old.id(), + old.unit(), + old.balances(), + Sequence::new(0).unwrap(), + ); + assert!(plan_replacement_allocations(&[], &[value], &[absent]).is_err()); +} + +#[test] +fn bounded_small_state_grid_conserves_each_positive_hold_without_crediting_any_release() { + for old in 0..=5 { + for new in 0..=5 { + let current = if old == 0 { + vec![] + } else { + vec![allocation(1, 1, old)] + }; + let desired = if new == 0 { + vec![] + } else { + vec![allocation(1, 1, new)] + }; + let before = pool(1, 5, old); + let plan = plan_replacement_allocations(¤t, &desired, &[before]).unwrap(); + if new > old { + let effect = plan.preparatory_holds()[0]; + assert_eq!(effect.quantity(), ticks(new - old)); + assert_eq!( + effect.after().balances().physical().available, + ticks(5 - (new - old)) + ); + assert_eq!( + effect.after().balances().physical().committed_hold, + ticks(old) + ); + assert_eq!(effect.after().balances().introduced(), ticks(5 + old)); + } else { + assert!(plan.preparatory_holds().is_empty()); + } + if old > new { + assert_eq!(plan.pending_releases(), &[allocation(1, 1, old - new)]); + } else { + assert!(plan.pending_releases().is_empty()); + } + } + } +} diff --git a/crates/execution/src/session/client_commerce.rs b/crates/execution/src/session/client_commerce.rs @@ -11,7 +11,9 @@ use crate::{ }; use alloc::boxed::Box; use radroots_domain::{CommandDigest, OperationId}; -use radroots_protocol::command::{AcceptOrderInput, CapturedOrderAcceptance}; +use radroots_protocol::command::{ + AcceptOrderInput, CapturedOrderAcceptance, CapturedTermsInstallation, InstallTermsInput, +}; use radroots_storage::{ command::OperationError, inventory::{ @@ -78,6 +80,59 @@ impl<H: SessionHost + 'static> ClientSession<H> { ) .await } + /// Installs complete mutually authorized replacement terms through the + /// same owned T0/T1/S/T2 and original delivery/recovery pipeline. Pending + /// preparation preserves the old agreement and its original obligations. + #[allow(clippy::too_many_arguments)] + pub async fn install_stock_terms( + &self, + inventory: Shared<dyn InventoryStore>, + store: Shared<dyn AcceptanceStore>, + scope: &WorkspaceSession, + context: CommandContext, + minimum: InventoryCheckpointRef, + sources: StockSourceCheckpointRef, + listings: StockListingCheckpointRef, + input: InstallTermsInput, + ) -> crate::ExecutionResult<AcceptanceStatus> { + let operation = context.data().operation_id(); + if !scope.owns_context(&context) { + return Err(Error::operation( + OperationError::Unauthorized, + OperationContext::proposed(Some(operation)), + ) + .into()); + } + self.submit_acceptance( + inventory, + store, + scope, + operation, + RunMode::Command, + move |binding| { + let command = CapturedTermsInstallation::new(context.data().clone(), input) + .map_err(|_| OperationError::InvalidCommand)?; + let digest = command.digest(); + let request = StockAcceptanceRequest::capture_terms( + binding.clone(), + minimum, + sources, + listings, + &command, + )?; + Ok(( + AcceptanceSelection { + binding, + minimum, + operation, + digest, + }, + Some(request), + )) + }, + ) + .await + } /// Resumes only original retained inputs. Non-replayable existing claims /// remain unknown; a qualified original local replay requires its actual /// current host permit and original deadline. This never releases stock. diff --git a/crates/protocol/src/commerce.rs b/crates/protocol/src/commerce.rs @@ -19,6 +19,8 @@ mod signing_plan; pub use signing_plan::{CommerceSigningPlan, SIGNING_PLAN_MAX_BYTES}; mod initial_commitment; pub use initial_commitment::initial_commitment_rumor; +mod replacement_commitment; +pub use replacement_commitment::replacement_commitment_rumor; mod payload; pub use decode::{DecodedRecord, decode}; mod rumor; diff --git a/crates/protocol/src/commerce/replacement_commitment.rs b/crates/protocol/src/commerce/replacement_commitment.rs @@ -0,0 +1,126 @@ +//! Deterministic replacement intent from captured original-source claims. +use super::{DecodedRecord, EncodedCommerceRumor, RecordWireError}; +use crate::{command::CapturedTermsInstallation, terms::EncodedTerms}; +use alloc::vec; +use radroots_domain::{ + ActorRole, AgreementCommitment, CommerceContent, CommerceHeader, CommercePayload, RecordId, + Sequence, SourceId, UnixSeconds, +}; + +/// Builds the exact next seller commitment from complete mutually authorized +/// replacement data. This does not authenticate the original records or prove +/// that the base, residual, author heads, authority or stock are current. The +/// executor must independently admit and freeze those inputs before T1. +pub fn replacement_commitment_rumor( + command: &CapturedTermsInstallation, + base: &DecodedRecord, + proposal: &DecodedRecord, + authorization: &DecodedRecord, + seller_head: (RecordId, Sequence), + created_at: UnixSeconds, +) -> Result<EncodedCommerceRumor, RecordWireError> { + let invalid = RecordWireError::InvalidInput; + let expected = command.context().expected().ok_or(invalid)?; + let CommercePayload::AgreementCommitted(base_commitment) = base.content().payload() else { + return Err(invalid); + }; + let CommercePayload::TermsProposed(proposed) = proposal.content().payload() else { + return Err(invalid); + }; + let CommercePayload::TermsAuthorized(authorized) = authorization.content().payload() else { + return Err(invalid); + }; + let original = base.content().header(); + if command.context().actor().role() != ActorRole::Seller + || command.context().actor().participant() != original.seller() + || original.author() != original.seller() + || original.order_id() != Some(expected.order_id()) + || expected.agreement() != Some(base.record_id()) + || expected.seller_sequence() != base_commitment.seller_sequence() + || base_commitment.authority() != command.context().authority() + || proposed.base_agreement() != Some(base.record_id()) + || proposal.record_id() != command.input().proposal() + || authorization.record_id() != command.input().authorization() + || authorized.proposal() != proposal.record_id() + || authorized.terms_digest() != command.input().terms_digest() + || EncodedTerms::capture(proposed.terms())?.digest() != command.input().terms_digest() + || proposal.content().header().author() == authorization.content().header().author() + || expected.buyer_head().is_none() + || seller_head.1.get() < original.author_sequence().get() + || created_at.get() == 0 + || created_at >= command.context().not_after() + || created_at >= proposed.expires_at() + || created_at >= authorized.expires_at() + { + return Err(invalid); + } + for record in [base, proposal, authorization] { + let header = record.content().header(); + if header.thread_id() != original.thread_id() + || header.order_id() != original.order_id() + || header.buyer() != original.buyer() + || header.seller() != original.seller() + || header.created_at() > created_at + || (header.author() != original.buyer() && header.author() != original.seller()) + || (header.author() == original.seller() && header.author_sequence() > seller_head.1) + || (record.record_id() == seller_head.0 + && (header.author() != original.seller() + || header.author_sequence() != seller_head.1)) + || (expected.buyer_head() == Some(record.record_id()) + && header.author() != original.buyer()) + { + return Err(invalid); + } + } + let author_sequence = Sequence::new( + seller_head + .1 + .get() + .checked_add(1) + .ok_or(RecordWireError::LimitExceeded)?, + ) + .map_err(|_| RecordWireError::LimitExceeded)?; + let seller_sequence = Sequence::new( + base_commitment + .seller_sequence() + .get() + .checked_add(1) + .ok_or(RecordWireError::LimitExceeded)?, + ) + .map_err(|_| RecordWireError::LimitExceeded)?; + let mut parents = vec![ + base.record_id(), + proposal.record_id(), + authorization.record_id(), + seller_head.0, + ]; + parents.extend(expected.buyer_head()); + parents.sort(); + parents.dedup(); + let header = CommerceHeader::new( + original.thread_id(), + original.order_id(), + original.seller(), + original.buyer(), + original.seller(), + created_at, + author_sequence, + Some(seller_head.0), + parents + .into_iter() + .map(|id| SourceId::from_bytes(id.into_bytes())) + .collect(), + ) + .map_err(|_| invalid)?; + let commitment = AgreementCommitment::new( + Some(base.record_id()), + authorization.record_id(), + command.input().terms_digest(), + command.context().authority(), + seller_sequence, + ) + .map_err(|_| invalid)?; + let content = CommerceContent::new(header, CommercePayload::AgreementCommitted(commitment)) + .map_err(|_| invalid)?; + EncodedCommerceRumor::capture(&content) +} diff --git a/crates/protocol/tests/replacement_commitment.rs b/crates/protocol/tests/replacement_commitment.rs @@ -0,0 +1,297 @@ +#![cfg(feature = "commerce")] +use radroots_domain::{ + CommerceContent, CommerceHeader, CommercePayload, PublicKey, RecordId, Sequence, SourceId, + TermsAuthorization, TermsProposal, UnixSeconds, +}; +use radroots_protocol::{ + command::CapturedTermsInstallation, + commerce::{self, DecodedRecord, EncodedRecord}, + terms::EncodedTerms, +}; +use serde_json::{Value, json}; + +fn time(value: u64) -> UnixSeconds { + UnixSeconds::new(value).unwrap() +} +fn decoded(content: &CommerceContent) -> DecodedRecord { + commerce::decode(EncodedRecord::capture(content).unwrap().protected_wire()).unwrap() +} +struct Fixture { + command: CapturedTermsInstallation, + base: DecodedRecord, + proposal: DecodedRecord, + authorization: DecodedRecord, + head: (RecordId, Sequence), +} +fn fixture(buyer_proposes: bool) -> Fixture { + let original: Value = + serde_json::from_str(include_str!("fixtures/commerce_signing.v1.json")).unwrap(); + let request = commerce::decode(original["request_wire"].as_str().unwrap().as_bytes()).unwrap(); + let base = commerce::decode(original["record_wire"].as_str().unwrap().as_bytes()).unwrap(); + let CommercePayload::Request(requested) = request.content().payload() else { + panic!() + }; + let terms = requested.terms(); + let header = base.content().header(); + let make = |author: PublicKey, + previous: &DecodedRecord, + sequence: u64, + payload: CommercePayload, + extra: &[RecordId]| { + let mut parents: Vec<_> = terms + .lines() + .iter() + .map(|line| SourceId::from_bytes(line.source().event_id().into_bytes())) + .collect(); + parents.extend( + [previous.record_id(), base.record_id()] + .into_iter() + .chain(extra.iter().copied()) + .map(|id| SourceId::from_bytes(id.into_bytes())), + ); + parents.sort(); + parents.dedup(); + decoded( + &CommerceContent::new( + CommerceHeader::new( + header.thread_id(), + header.order_id(), + author, + header.buyer(), + header.seller(), + time(452), + Sequence::new(sequence).unwrap(), + Some(previous.record_id()), + parents, + ) + .unwrap(), + payload, + ) + .unwrap(), + ) + }; + let proposer = if buyer_proposes { + header.buyer() + } else { + header.seller() + }; + let authorizer = if buyer_proposes { + header.seller() + } else { + header.buyer() + }; + let proposal = make( + proposer, + if buyer_proposes { &request } else { &base }, + 2, + CommercePayload::TermsProposed( + TermsProposal::new( + Some(base.record_id()), + terms.clone(), + time(700), + "complete replacement", + ) + .unwrap(), + ), + &[], + ); + let authorization = make( + authorizer, + if buyer_proposes { &base } else { &request }, + 2, + CommercePayload::TermsAuthorized(TermsAuthorization::new( + proposal.record_id(), + EncodedTerms::capture(terms).unwrap().digest(), + time(650), + )), + &[proposal.record_id()], + ); + let seller = if buyer_proposes { + &authorization + } else { + &proposal + }; + let buyer = if buyer_proposes { + &proposal + } else { + &authorization + }; + let head = ( + seller.record_id(), + seller.content().header().author_sequence(), + ); + let mut wire: Value = serde_json::from_str(original["command_wire"].as_str().unwrap()).unwrap(); + wire["type"] = json!("orders.install_terms"); + wire["input"] = json!({"proposal":proposal.record_id(),"authorization":authorization.record_id(),"terms_digest":EncodedTerms::capture(terms).unwrap().digest(),"allocation":{"type":"automatic"}}); + wire["context"]["approval"] = Value::Null; + wire["context"]["not_after"] = json!("600"); + wire["context"]["expected"]["agreement"] = json!(base.record_id()); + wire["context"]["expected"]["seller_sequence"] = json!("1"); + wire["context"]["expected"]["buyer_head"] = json!(buyer.record_id()); + let command = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + Fixture { + command, + base, + proposal, + authorization, + head, + } +} + +#[test] +fn either_participant_proposes_and_the_next_seller_record_binds_all_originals() { + for buyer_proposes in [false, true] { + let f = fixture(buyer_proposes); + let rumor = commerce::replacement_commitment_rumor( + &f.command, + &f.base, + &f.proposal, + &f.authorization, + f.head, + time(453), + ) + .unwrap(); + let wire: Value = serde_json::from_str(rumor.protected_wire()).unwrap(); + let record = commerce::decode(wire["content"].as_str().unwrap().as_bytes()).unwrap(); + let header = record.content().header(); + assert_eq!(header.author_sequence().get(), 3); + assert_eq!(header.author_previous(), Some(f.head.0)); + assert_eq!(header.author(), f.base.content().header().seller()); + assert_eq!(header.created_at(), time(453)); + for id in [ + f.base.record_id(), + f.proposal.record_id(), + f.authorization.record_id(), + f.head.0, + f.command + .context() + .expected() + .unwrap() + .buyer_head() + .unwrap(), + ] { + assert!( + header + .parents() + .contains(&SourceId::from_bytes(id.into_bytes())) + ); + } + let CommercePayload::AgreementCommitted(commitment) = record.content().payload() else { + panic!() + }; + assert_eq!(commitment.base_agreement(), Some(f.base.record_id())); + assert_eq!(commitment.authorization(), f.authorization.record_id()); + assert_eq!(commitment.terms_digest(), f.command.input().terms_digest()); + assert_eq!(commitment.seller_sequence().get(), 2); + assert_eq!(commitment.authority(), f.command.context().authority()); + assert_eq!(record.record_id(), rumor.record_id()); + assert_eq!( + commerce::replacement_commitment_rumor( + &f.command, + &f.base, + &f.proposal, + &f.authorization, + f.head, + time(453) + ) + .unwrap() + .protected_wire(), + rumor.protected_wire() + ); + } +} + +#[test] +fn changed_base_sources_digest_sequence_authority_and_known_author_heads_refuse() { + let f = fixture(false); + let original: Value = serde_json::from_slice(f.command.protected_wire()).unwrap(); + for (path, value) in [ + ("/context/expected/agreement", json!("71".repeat(32))), + ("/context/expected/agreement", Value::Null), + ("/context/expected/seller_sequence", json!("2")), + ("/context/expected/buyer_head", Value::Null), + ( + "/context/expected/buyer_head", + json!(f.proposal.record_id()), + ), + ("/context/authority/generation", json!("2")), + ("/input/proposal", json!("72".repeat(32))), + ("/input/authorization", json!("73".repeat(32))), + ("/input/terms_digest", json!("74".repeat(32))), + ] { + let mut changed = original.clone(); + *changed.pointer_mut(path).unwrap() = value; + let command = + CapturedTermsInstallation::parse(&serde_json::to_vec(&changed).unwrap()).unwrap(); + assert!( + commerce::replacement_commitment_rumor( + &command, + &f.base, + &f.proposal, + &f.authorization, + f.head, + time(453) + ) + .is_err(), + "{path}" + ); + } + for head in [ + (f.base.record_id(), Sequence::new(2).unwrap()), + (f.authorization.record_id(), Sequence::new(2).unwrap()), + (f.head.0, Sequence::new(1).unwrap()), + ] { + assert!( + commerce::replacement_commitment_rumor( + &f.command, + &f.base, + &f.proposal, + &f.authorization, + head, + time(453) + ) + .is_err() + ); + } + assert!( + commerce::replacement_commitment_rumor( + &f.command, + &f.base, + &f.authorization, + &f.proposal, + f.head, + time(453) + ) + .is_err() + ); +} + +#[test] +fn no_deadline_or_future_author_claim_is_replaced_with_ambient_time() { + let f = fixture(true); + for at in [0, 451, 600, 650, 700] { + assert!( + commerce::replacement_commitment_rumor( + &f.command, + &f.base, + &f.proposal, + &f.authorization, + f.head, + time(at) + ) + .is_err(), + "{at}" + ); + } + assert!( + commerce::replacement_commitment_rumor( + &f.command, + &f.base, + &f.proposal, + &f.authorization, + f.head, + time(599) + ) + .is_ok() + ); +} diff --git a/crates/radroots/src/native_commerce_tests.rs b/crates/radroots/src/native_commerce_tests.rs @@ -926,6 +926,8 @@ mod rewrap; #[path = "native_stock_deficit_tests.rs"] mod deficit; +#[path = "native_stock_terms_tests.rs"] +mod terms; #[tokio::test] async fn peer_installation_survives_self_refusal_and_resume_uses_original_exact_recovery() { diff --git a/crates/radroots/src/native_stock_terms_tests.rs b/crates/radroots/src/native_stock_terms_tests.rs @@ -0,0 +1,270 @@ +//! Ordinary client ownership of an actual complete replacement installation. +use super::*; +use nostr::JsonUtil; +use radroots_domain::{ + AgreedFixedPrice, AgreementLine, AgreementPrice, CommerceContent, CommerceHeader, + CommercePayload, RecordId, Sequence, SourceId, Terms, TermsAuthorization, TermsProposal, +}; +use radroots_protocol::{ + command::CapturedTermsInstallation, + commerce::{DecodedRecord, EncodedCommerceRumor, EncodedRecord}, + terms::EncodedTerms, +}; +use radroots_signing::request::CancellationSignal; + +async fn incoming(r: &Rig, content: &CommerceContent, scalar: u8) -> DecodedRecord { + let encoded = EncodedRecord::capture(content).unwrap(); + let decoded = radroots_protocol::commerce::decode(encoded.protected_wire()).unwrap(); + let rumor = EncodedCommerceRumor::capture(content).unwrap(); + let keys = nostr::Keys::new(nostr::SecretKey::from_hex(&format!("{scalar:064x}")).unwrap()); + let receiver = + nostr::PublicKey::from_hex(&r.enrollment.input().participant().to_hex()).unwrap(); + let wrap = nostr::EventBuilder::gift_wrap( + &keys, + &receiver, + nostr::UnsignedEvent::from_json(rumor.protected_wire()).unwrap(), + Vec::<nostr::Tag>::new(), + ) + .await + .unwrap(); + let provider = + LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { + Ok(150000) + }) + .unwrap(); + let opening = radroots_nostr::commerce::open( + &provider, + ProviderCall::new( + provider.public_key(), + NonZeroU64::new(230000).unwrap(), + CancellationSignal::new(), + ), + &wrap.as_json(), + ) + .await + .unwrap(); + let capture = radroots_storage_sqlite::workspace::StockSourceCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + &opening, + ) + .unwrap(); + let (sources, _, _) = r.minima().await; + r.native + .retain_stock_source( + r.scope.binding().clone(), + sources, + &capture, + r.enrollment.proof(), + ) + .await + .unwrap(); + decoded +} + +async fn exercise(quantity: &str, remaining: u64, available: u64) { + let r = Rig::new().await; + let request = r.request().await; + let old = request.terms(); + let line = &old.lines()[0]; + let AgreementPrice::Fixed(old_price) = line.price() else { + panic!("fixed fixture") + }; + let price = AgreedFixedPrice::new( + old_price.rate(), + old_price.basis(), + old_price.discount_bps(), + None, + ); + let quantity = quantity.parse().unwrap(); + let total = price.total(quantity).unwrap(); + let line = AgreementLine::new( + line.id(), + line.source(), + line.option_id(), + line.product().clone(), + line.option().clone(), + quantity, + line.fulfillment_group(), + line.source_lot_label(), + AgreementPrice::Fixed(price), + total, + ) + .unwrap(); + let terms = Terms::new( + old.buyer(), + old.seller(), + vec![line], + old.fulfillment().to_vec(), + old.fulfillment_charge(), + old.fulfillment_charge().checked_add(total).unwrap(), + old.supply().clone(), + ) + .unwrap(); + let (_, initial) = r.accept().await; + assert!(initial.installation().is_some()); + let scope = request.scope(); + let make = |author, previous, sequence, payload, extra: &[RecordId]| { + let mut parents: Vec<_> = terms + .lines() + .iter() + .map(|line| SourceId::from_bytes(line.source().event_id().into_bytes())) + .collect(); + parents.extend( + [initial.record_id(), previous] + .into_iter() + .chain(extra.iter().copied()) + .map(|id| SourceId::from_bytes(id.into_bytes())), + ); + parents.sort(); + parents.dedup(); + CommerceContent::new( + CommerceHeader::new( + scope.thread_id(), + Some(scope.order_id()), + author, + scope.buyer(), + scope.seller(), + UnixSeconds::new(150).unwrap(), + Sequence::new(sequence).unwrap(), + Some(previous), + parents, + ) + .unwrap(), + payload, + ) + .unwrap() + }; + let proposal = make( + scope.seller(), + initial.record_id(), + 2, + CommercePayload::TermsProposed( + TermsProposal::new( + Some(initial.record_id()), + terms.clone(), + UnixSeconds::new(230).unwrap(), + "complete replacement", + ) + .unwrap(), + ), + &[], + ); + let proposal = incoming(&r, &proposal, 3).await; + let authorization = make( + scope.buyer(), + request.request(), + 2, + CommercePayload::TermsAuthorized(TermsAuthorization::new( + proposal.record_id(), + EncodedTerms::capture(&terms).unwrap().digest(), + UnixSeconds::new(230).unwrap(), + )), + &[proposal.record_id()], + ); + let authorization = incoming(&r, &authorization, 2).await; + let (sources, listings, minimum) = r.minima().await; + let history = r + .native + .stock_order_history( + r.scope.binding().clone(), + minimum, + sources, + listings, + scope, + r.enrollment.proof(), + ) + .await + .unwrap(); + let mut wire = serde_json::json!({"type":"orders.install_terms","context":r.context(110),"input":{"proposal":proposal.record_id(),"authorization":authorization.record_id(),"terms_digest":EncodedTerms::capture(&terms).unwrap().digest(),"allocation":{"type":"automatic"}}}); + wire["context"]["expected"] = serde_json::json!({"agreement":initial.record_id(),"buyer_head":history.analysis().buyer_head(),"checkpoint":history.checkpoint().unwrap(),"order_id":scope.order_id(),"seller_sequence":"1"}); + let command = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + wire["context"]["approval"] = serde_json::json!({"intent_digest":command.approval_intent_digest(),"scope":"orders.install_terms","expires_at":"230"}); + let command = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + let context = r + .scope + .command_context( + command.context().operation_id(), + command.context().expected().cloned(), + command.context().approval().cloned(), + UnixSeconds::new(230).unwrap(), + ) + .unwrap(); + let consent = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + r.enrollment.input().grant_id(), + StockConsentMode::ExecuteAndRecover, + StockResources::all_pools(), + UnixSeconds::new(230).unwrap(), + CapturedTermsInstallation::parse(command.protected_wire()).unwrap(), + ) + .unwrap(); + let (_, _, minimum) = r.minima().await; + r.native + .issue_stock_consent( + r.scope.binding().clone(), + minimum, + &consent, + r.enrollment.proof(), + ) + .await + .unwrap(); + let (sources, listings, minimum) = r.minima().await; + let input = crate::orders::InstallTermsInput::new( + proposal.record_id(), + authorization.record_id(), + command.input().terms_digest(), + AllocationSelection::automatic(), + ); + let installed = r + .client + .orders(&r.scope) + .install_terms(context, minimum, sources, listings, input) + .await + .unwrap(); + assert!(installed.installation().is_some()); + assert_eq!(installed.attempt().command_digest(), command.digest()); + assert_ne!(installed.record_id(), initial.record_id()); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 4); + assert_eq!(r.io.sent.lock().unwrap().len(), 4); + let (_, _, minimum) = r.minima().await; + let current = r + .client + .stock(&r.scope) + .inspect(minimum, PoolId::from_bytes([80; 32])) + .await + .unwrap() + .unwrap(); + assert_eq!(current.installed_obligations().remaining().get(), remaining); + assert_eq!( + current + .pool() + .snapshot() + .balances() + .physical() + .available + .get(), + available + ); + let resumed = r + .client + .orders(&r.scope) + .resume_acceptance(minimum, command.context().operation_id(), command.digest()) + .await + .unwrap(); + assert_eq!(resumed.record_id(), installed.record_id()); + assert_eq!(r.control.signs.load(Ordering::SeqCst), 4); + let (_, _, after) = r.minima().await; + assert_eq!(after, minimum); + r.client.close().await.unwrap(); +} + +#[tokio::test] +async fn ordinary_install_terms_uses_the_same_owner_and_resumes_without_extra_signatures_or_stock() +{ + exercise("5", 5, 5).await; +} + +#[tokio::test] +async fn ordinary_negative_install_terms_finishes_self_copy_after_original_release() { + exercise("1", 1, 9).await; +} diff --git a/crates/radroots/src/orders.rs b/crates/radroots/src/orders.rs @@ -5,7 +5,7 @@ pub use radroots_execution::session::commerce::{ AcceptanceRecipient, AcceptanceRewrapStatus, AcceptanceStatus, AcceptanceUnissuedReceipt, InstalledAcceptance, }; -pub use radroots_protocol::command::AcceptOrderInput; +pub use radroots_protocol::command::{AcceptOrderInput, InstallTermsInput}; use radroots_storage::{ inventory::InventoryCheckpointRef, workspace::seller_stock::{StockListingCheckpointRef, StockSourceCheckpointRef}, @@ -46,6 +46,31 @@ impl<'a> Orders<'a> { ) .await } + /// Owns mutually authorized complete replacement installation through the + /// same executor as acceptance. Positive holds precede issuance; old + /// obligations remain pending and negative deltas release only at T2. + pub async fn install_terms( + &self, + context: CommandContext, + minimum: InventoryCheckpointRef, + sources: StockSourceCheckpointRef, + listings: StockListingCheckpointRef, + input: InstallTermsInput, + ) -> crate::ExecutionResult<AcceptanceStatus> { + self.client + .session + .install_stock_terms( + self.client.inventory()?, + self.client.acceptance_store()?, + &self.scope, + context, + minimum, + sources, + listings, + input, + ) + .await + } /// Explicitly resumes captured original work. Existing non-replayable /// claims never sign again; qualified replay uses the original host permit. pub async fn resume_acceptance( diff --git a/crates/storage_sqlite/src/workspace/crypto.rs b/crates/storage_sqlite/src/workspace/crypto.rs @@ -709,7 +709,7 @@ fn stock_root_context( input: &super::AttachmentInput, version: i64, ) -> Result<EnvelopeContext, WorkspaceError> { - if matches!(version, 4..=19) { + if matches!(version, 4..=20) { use sha2::{Digest, Sha256}; let namespace = radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment( @@ -752,8 +752,10 @@ fn stock_root_context( b"radroots.seller_stock.authority_context.v17\0".as_slice() } else if version == 18 { b"radroots.seller_stock.authority_context.v18\0".as_slice() - } else { + } else if version == 19 { b"radroots.seller_stock.authority_context.v19\0".as_slice() + } else { + b"radroots.seller_stock.authority_context.v20\0".as_slice() }); hash.update(wire.as_slice()); let subject = radroots_domain::CommandDigest::from_bytes(hash.finalize().into()); @@ -792,8 +794,10 @@ fn stock_root_context( "radroots.seller_stock.authority.v17" } else if version == 18 { "radroots.seller_stock.authority.v18" - } else { + } else if version == 19 { "radroots.seller_stock.authority.v19" + } else { + "radroots.seller_stock.authority.v20" }) .map_err(|_| WorkspaceError::InvalidInput)?, )); @@ -874,6 +878,10 @@ fn stock_record_context( "radroots.seller_stock.grant", "radroots.seller_stock.grant.v2", ), + "replacement_movement" => ( + "radroots.seller_stock.installation_movement", + "radroots.seller_stock.installation_movement.v2", + ), "pool" => ( "radroots.seller_stock.pool", "radroots.seller_stock.pool.v1", @@ -911,12 +919,12 @@ fn stock_record_context_for_catalog( ) -> Result<EnvelopeContext, WorkspaceError> { let original = stock_record_context(input, kind, id)?; let schema = match (catalog, kind) { - (2, _) | (3..=19, "pool") => return Ok(original), + (2, _) | (3..=20, "pool") => return Ok(original), (3, "operation") => "radroots.seller_stock.operation.v2", (4, "operation") => "radroots.seller_stock.operation.v3", (5 | 6, "operation") => "radroots.seller_stock.operation.v4", - (7..=19, "operation") => "radroots.seller_stock.operation.v5", - (3..=19, "movement") => "radroots.seller_stock.movement.v2", + (7..=20, "operation") => "radroots.seller_stock.operation.v5", + (3..=20, "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 @@ -357,6 +357,11 @@ fn required_nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( ) -> Result<Option<T>, D::Error> { Option::deserialize(d) } +fn optional_present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>( + d: D, +) -> Result<Option<T>, D::Error> { + T::deserialize(d).map(Some) +} #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] struct AuthorityV1 { @@ -445,10 +450,10 @@ struct AuthorityV8 { } impl Authority { fn encode(&self) -> Result<zeroize::Zeroizing<Vec<u8>>, WorkspaceError> { - if !matches!(self.catalog, 8..=19) && self.public_sources.is_some() { + if !matches!(self.catalog, 8..=20) && self.public_sources.is_some() { return Err(WorkspaceError::RecoveryRequired); } - if matches!(self.catalog, 8..=19) { + if matches!(self.catalog, 8..=20) { let public_sources = self .public_sources .ok_or(WorkspaceError::RecoveryRequired)?; @@ -700,7 +705,7 @@ impl Authority { public_sources: None, } } - 8..=19 => { + 8..=20 => { let value: AuthorityV8 = closed_record(bytes)?; value.public_sources.validate()?; if i64::from(value.version) != catalog @@ -831,7 +836,7 @@ pub(super) async fn initialize( .await .map_err(|_| WorkspaceError::StorageFailure)?; } - sqlx::query("PRAGMA user_version=19") + sqlx::query("PRAGMA user_version=20") .execute(&mut *tx) .await .map_err(|_| WorkspaceError::StorageFailure)?; diff --git a/crates/storage_sqlite/src/workspace/stock/consent.rs b/crates/storage_sqlite/src/workspace/stock/consent.rs @@ -353,7 +353,12 @@ pub(super) async fn read( if header.family != ledger::Family::Consent || header.actor.grant_id() != Some(administrator) || body.version != 1 - || command.proposal().is_some() + || (command.proposal().is_some() + && sqlx::query_scalar::<_, i64>("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)? + < 20) || !namespace.matches_attachment(&body.selection) || body.selection.grant_id() != administrator || header.subject_grant != Some(body.subject) @@ -426,7 +431,9 @@ pub(in crate::workspace) async fn issue( proof: AttachmentProof, ) -> Result<StockConsentOutcome, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=19) || capture.command.proposal().is_some() { + if !matches!(access.authority.catalog, 7..=20) + || (capture.command.proposal().is_some() && access.authority.catalog < 20) + { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() @@ -687,7 +694,7 @@ pub(in crate::workspace) async fn query( proof: AttachmentProof, ) -> Result<Option<StockConsentReceipt>, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=19) { + if !matches!(access.authority.catalog, 7..=20) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() && access.current.input().grant_id() != subject { diff --git a/crates/storage_sqlite/src/workspace/stock/consent/tests.rs b/crates/storage_sqlite/src/workspace/stock/consent/tests.rs @@ -166,7 +166,7 @@ fn committed(outcome: StockConsentOutcome) -> StockConsentReceipt { #[tokio::test] async fn retained_catalog_cannot_mint_initial_consent_for_captured_replacement_terms() { for catalog in [9, 19] { - let r = Rig::with_catalog((catalog != 19).then_some(catalog)).await; + let r = Rig::with_catalog(Some(catalog)).await; let initial = r.command(&r.binding, 0x31); let mut wire: serde_json::Value = serde_json::from_slice(initial.protected_wire()).unwrap(); wire["type"] = serde_json::json!("orders.install_terms"); diff --git a/crates/storage_sqlite/src/workspace/stock/delivery.rs b/crates/storage_sqlite/src/workspace/stock/delivery.rs @@ -182,7 +182,7 @@ impl Prepared { append: Append, body: &[u8], ) -> Result<Self, OperationError> { - if !matches!(authority.catalog, 17..=19) { + if !matches!(authority.catalog, 17..=20) { return Err(OperationError::UnsupportedOperation); } let before = authority diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/observation_operations.rs b/crates/storage_sqlite/src/workspace/stock/delivery/observation_operations.rs @@ -18,7 +18,7 @@ pub(in crate::workspace) async fn capture_observation( } let (authority, credential, root, grant) = super::super::read(turn.connection, input, turn.crypto).await?; - if !matches!(authority.catalog, 17..=19) { + if !matches!(authority.catalog, 17..=20) { return Err(OperationError::UnsupportedOperation); } credential.authenticate_retained_capture(input, &proof)?; diff --git a/crates/storage_sqlite/src/workspace/stock/delivery/operations.rs b/crates/storage_sqlite/src/workspace/stock/delivery/operations.rs @@ -11,7 +11,7 @@ async fn authorized( .fetch_one(&mut *turn.connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - if !matches!(catalog, 17..=19) { + if !matches!(catalog, 17..=20) { return Err(OperationError::UnsupportedOperation); } let loading = signing_plan::load( @@ -23,7 +23,7 @@ async fn authorized( proof, ); let auth = Box::pin(loading).await?; - if !matches!(auth.access.authority.catalog, 17..=19) { + if !matches!(auth.access.authority.catalog, 17..=20) { return Err(OperationError::UnsupportedOperation); } if !auth diff --git a/crates/storage_sqlite/src/workspace/stock/envelope.rs b/crates/storage_sqlite/src/workspace/stock/envelope.rs @@ -188,7 +188,7 @@ pub(in crate::workspace) async fn capture( return Err(OperationError::Unauthorized); } let (authority, record, root, grant) = super::read(turn.connection, input, turn.crypto).await?; - if !matches!(authority.catalog, 16..=19) { + if !matches!(authority.catalog, 16..=20) { return Err(OperationError::UnsupportedOperation); } record.authenticate_retained_capture(input, &proof)?; @@ -368,7 +368,7 @@ pub(in crate::workspace) async fn read( .fetch_one(&mut *turn.connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - if !matches!(catalog, 16..=19) { + if !matches!(catalog, 16..=20) { return Err(OperationError::UnsupportedOperation); } let auth = Box::pin(super::signing_plan::load( @@ -380,7 +380,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 16..=19) { + if !matches!(auth.access.authority.catalog, 16..=20) { return Err(OperationError::UnsupportedOperation); } let witness = Box::pin(full_proof(turn, &request, &auth.access.authority)).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/grants.rs b/crates/storage_sqlite/src/workspace/stock/grants.rs @@ -324,7 +324,7 @@ pub(in crate::workspace) async fn change( } let (mut authority, record, old_root, old_grant) = super::read(turn.connection, change.caller.input(), turn.crypto).await?; - if !(4..=19).contains(&authority.catalog) { + if !(4..=20).contains(&authority.catalog) { return Err(WorkspaceError::Unauthorized); } let catalog = authority.catalog; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory.rs b/crates/storage_sqlite/src/workspace/stock/inventory.rs @@ -3,6 +3,7 @@ pub(in crate::workspace) mod abort; pub(in crate::workspace) mod acceptance; mod allocations; pub(in crate::workspace::stock) mod backing; +mod changes; pub(super) mod checkpoint; mod codec; pub(in crate::workspace::stock) mod deficit; @@ -47,13 +48,19 @@ pub(super) async fn check_head( .fetch_one(&mut *connection) .await .map_err(|_| WorkspaceError::RecoveryRequired)?; - if catalog == 19 { + if catalog >= 19 { let invalid: i64 = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM stock_deficits d LEFT JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.operation_id WHERE o.family IS NULL OR o.family!=0) OR EXISTS(SELECT 1 FROM pragma_foreign_key_check('stock_deficits'))") .fetch_one(&mut *connection).await.map_err(|_| WorkspaceError::RecoveryRequired)?; if invalid != 0 { return Err(WorkspaceError::RecoveryRequired); } } + if catalog >= 20 { + let invalid: i64 = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM stock_obligation_changes d LEFT JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.operation_id WHERE o.family IS NULL OR o.family!=6) OR EXISTS(SELECT 1 FROM pragma_foreign_key_check('stock_obligation_changes'))").fetch_one(&mut *connection).await.map_err(|_|WorkspaceError::RecoveryRequired)?; + if invalid != 0 { + return Err(WorkspaceError::RecoveryRequired); + } + } if let Some(expected) = checkpoint.orders { let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_orders") .fetch_one(&mut *connection) @@ -213,7 +220,7 @@ impl Turn<'_> { )) .await?; self.namespace.validate()?; - if authority.catalog == 19 && minimum.revision().get() != 0 { + if authority.catalog >= 19 && minimum.revision().get() != 0 { let genesis = radroots_storage::inventory::InventoryCheckpointRef::from_host_metadata( self.selected.authority(), Sequence::new(0).map_err(|_| OperationError::RecoveryRequired)?, @@ -349,7 +356,7 @@ impl Turn<'_> { ) .await?, ); - let losses = if catalog == 19 { + let losses = if catalog >= 19 { Box::pin(deficit::plan( self.connection, self.selected, @@ -506,7 +513,7 @@ impl Turn<'_> { mapping.as_ref().map(|value| value.effect), &losses, )?; - let framed = if matches!(catalog, 7..=19) { + let framed = if matches!(catalog, 7..=20) { Some( super::ledger::prepare( self.crypto, @@ -629,7 +636,7 @@ impl Turn<'_> { sqlx::query("INSERT INTO stock_operations(actor,grant_id,operation_id,command_digest,transaction_id,pool_id,revision,chain_head,protected) VALUES(?,?,?,?,?,?,?,?,?)") .bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(digest.as_bytes().as_slice()).bind(transaction.as_bytes().as_slice()).bind(pool.id().as_bytes().as_slice()).bind(revision.get() as i64).bind(head.as_bytes().as_slice()).bind(protected_operation).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; if let Some(framed)=&framed {framed.insert_parts(&mut tx,request.binding().actor(),operation).await?;} - if catalog == 19 { deficit::insert(&mut tx, request.binding().actor().participant(), operation, pool.id(), &losses).await?; } + if catalog >= 19 { deficit::insert(&mut tx, request.binding().actor().participant(), operation, pool.id(), &losses).await?; } if let (Some(id),Some(protected))=(movement,protected_movement) { sqlx::query("INSERT INTO stock_movements(movement_id,actor,grant_id,operation_id,pool_id,protected) VALUES(?,?,?,?,?,?)").bind(id.as_slice()).bind(request.binding().actor().participant().as_bytes().as_slice()).bind(request.binding().input().grant_id().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).bind(pool.id().as_bytes().as_slice()).bind(protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; } @@ -922,7 +929,7 @@ pub(super) async fn read_operation( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - let (frame, request, decoded) = if matches!(catalog, 7..=19) { + let (frame, request, decoded) = if matches!(catalog, 7..=20) { let retained = super::ledger::read(connection, input, crypto, operation) .await? .ok_or(OperationError::RecoveryRequired)?; @@ -969,7 +976,7 @@ pub(super) async fn read_operation( if original_grant != request.binding().input().grant_id().as_bytes() { return Err(OperationError::RecoveryRequired); } - let deficit_projection = if catalog == 19 { + let deficit_projection = if catalog >= 19 { let expected = Box::pin(deficit::plan( connection, input, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort.rs @@ -160,7 +160,7 @@ async fn abort_authorized( proof: AttachmentProof, auth: signing_plan::Authorized, ) -> Result<StockAbortOutcome, OperationError> { - if !matches!(auth.access.authority.catalog, 13..=19) { + if !matches!(auth.access.authority.catalog, 13..=20) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; @@ -381,7 +381,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 13..=19) { + if !matches!(auth.access.authority.catalog, 13..=20) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth.access, request.operation_id())).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/abort/proof.rs b/crates/storage_sqlite/src/workspace/stock/inventory/abort/proof.rs @@ -150,7 +150,7 @@ pub(super) async fn prepare( recipient: *recipient, }), Some(original) => { - if !matches!(auth.access.authority.catalog, 15..=19) { + if !matches!(auth.access.authority.catalog, 15..=20) { return Err(OperationError::RecoveryRequired); } if at < original.report.claimed_at() { @@ -180,7 +180,7 @@ pub(super) async fn prepare( } } } - let payload = if matches!(auth.access.authority.catalog, 15..=19) { + let payload = if matches!(auth.access.authority.catalog, 15..=20) { Payload::Current(Box::new( encoded .try_into() @@ -217,7 +217,7 @@ pub(super) async fn read( .fetch_one(&mut *connection) .await .map_err(|_| OperationError::RecoveryRequired)?; - if !matches!(catalog, 15..=19) { + if !matches!(catalog, 15..=20) { return Err(OperationError::RecoveryRequired); } for (proof, expected) in proofs.iter().zip(recipients) { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs @@ -11,6 +11,7 @@ use radroots_storage::workspace::seller_stock::{ use std::collections::{BTreeMap, BTreeSet}; pub(in crate::workspace::stock) mod codec; mod plan; +pub(super) mod replacement; #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -20,10 +21,17 @@ struct Body<'a> { command: &'a RawValue, #[serde(borrow)] terms: &'a RawValue, - #[serde(borrow)] - original_request: &'a RawValue, + #[serde(default, borrow, skip_serializing_if = "Option::is_none")] + original_request: Option<&'a RawValue>, #[serde(borrow, deserialize_with = "super::super::required_nullable")] original_quote: Option<&'a RawValue>, + #[serde( + default, + borrow, + skip_serializing_if = "Option::is_none", + deserialize_with = "super::super::optional_present" + )] + replacement: Option<replacement::Basis<'a>>, #[serde(deserialize_with = "super::super::required_nullable")] seller_author_head: Option<RecordId>, seller_author_sequence: Sequence, @@ -236,13 +244,13 @@ pub(in crate::workspace) async fn admit( let access = turn .access(request.binding(), request.minimum_checkpoint(), &proof) .await?; - if !matches!(access.authority.catalog, 9..=19) { + if !matches!(access.authority.catalog, 9..=20) { return Err(OperationError::UnsupportedOperation); } let command = request.command(); // This retained preparation format describes an initial acceptance only. // Capturing a replacement never grants the initial request path authority. - if command.proposal().is_some() { + if command.proposal().is_some() && access.authority.catalog < 20 { return Err(OperationError::UnsupportedOperation); } let operation = command.context().operation_id(); @@ -336,27 +344,51 @@ pub(in crate::workspace) async fn admit( source::checkpoint::Target::Minimum(request.source_checkpoint()), ) .await?; - let admitted = source::request::prepare( - turn.connection, - turn.selected, - turn.crypto, - source::history::InventoryRead { - binding: &access.current, - authority: &access.authority, - minimum: request.minimum_checkpoint(), - }, - command.authorization(), - request.listing_checkpoint(), - access.current.observed_at(), - ) - .await?; + let base = if command.proposal().is_some() { + Some(Box::pin(replacement::load(turn, &access, command)).await?) + } else { + None + }; + let inventory_read = source::history::InventoryRead { + binding: &access.current, + authority: &access.authority, + minimum: request.minimum_checkpoint(), + }; + let admitted = if let (CapturedStockCommitment::TermsInstallation(command), Some(base)) = + (command, base.as_ref()) + { + Box::pin(source::request::prepare_terms( + turn.connection, + turn.selected, + turn.crypto, + inventory_read, + source::request::ReplacementSource { + command, + base: &base.record, + }, + request.listing_checkpoint(), + access.current.observed_at(), + )) + .await? + } else { + source::request::prepare( + turn.connection, + turn.selected, + turn.crypto, + inventory_read, + command.authorization(), + request.listing_checkpoint(), + access.current.observed_at(), + ) + .await? + }; let expected = command .context() .expected() .ok_or(OperationError::InvalidCommand)?; if expected.order_id() != admitted.scope.order_id() - || expected.agreement().is_some() - || expected.seller_sequence().get() != 0 + || (base.is_none() + && (expected.agreement().is_some() || expected.seller_sequence().get() != 0)) || expected.buyer_head() != admitted.history.analysis.buyer_head() || Some(expected.checkpoint()) != admitted.history.checkpoint.as_ref() || command.terms_digest() != admitted.digest @@ -376,11 +408,17 @@ pub(in crate::workspace) async fn admit( expected.order_id(), )) .await?; - if checked - .witness - .expected - .is_some_and(|value| value.phase != super::super::order_state::Phase::Aborted) - { + let stale = match (&base, checked.witness.expected) { + (None, Some(value)) => value.phase != super::super::order_state::Phase::Aborted, + (Some(base), Some(value)) => { + value.phase == super::super::order_state::Phase::Prepared + || (value.phase == super::super::order_state::Phase::Installed + && (value.operation != base.operation || value.entry != base.installation)) + } + (Some(_), None) => true, + (None, None) => false, + }; + if stale { return Err(OperationError::StaleState); } Some(checked) @@ -405,11 +443,42 @@ pub(in crate::workspace) async fn admit( let mut mappings = Vec::new(); let mut mapping_reads = Vec::new(); let mut pool_ids = BTreeSet::new(); + let old_terms = base + .as_ref() + .map(|base| base.preparation.terms()) + .transpose()?; + let old_mappings = base + .as_ref() + .map(|base| base.preparation.mappings()) + .transpose()? + .unwrap_or_default(); + if let Some(base) = &base { + pool_ids.extend(base.originals.iter().map(|draw| draw.allocation.pool_id())); + } if matches!( admitted.terms()?.supply(), radroots_domain::SupplyCommitment::StockBacked ) { for line in admitted.terms()?.lines() { + if let Some(old) = old_terms + .as_ref() + .and_then(|terms| terms.lines().iter().find(|old| old.id() == line.id())) + { + if old.source().coordinate() != line.source().coordinate() + || old.option_id() != line.option_id() + { + return Err(OperationError::UnsupportedOperation); + } + let key = radroots_domain::stock::OptionMappingKey::new( + old.source().coordinate(), + old.option_id(), + ); + if let Some(mapping) = old_mappings.iter().find(|mapping| mapping.key() == key) { + pool_ids.insert(mapping.pool_id()); + mappings.push(*mapping); + continue; + } + } let key = radroots_domain::stock::OptionMappingKey::new( line.source().coordinate(), line.option_id(), @@ -462,8 +531,29 @@ pub(in crate::workspace) async fn admit( before_pools.push(retained.pool); pool_reads.insert(id, retained); } - let (allocations, effects) = - plan::resolve(admitted.terms()?, command, &mappings, &before_pools)?; + let replacement::Resolution { + allocations, + effects, + desired, + releases, + } = if let Some(base) = &base { + replacement::resolve( + admitted.terms()?, + command, + &mappings, + &before_pools, + &base.originals, + )? + } else { + let (allocations, effects) = + plan::resolve(admitted.terms()?, command, &mappings, &before_pools)?; + replacement::Resolution { + allocations, + effects, + desired: Vec::new(), + releases: Vec::new(), + } + }; let before = access .authority .inventory @@ -505,15 +595,24 @@ pub(in crate::workspace) async fn admit( } let terms = radroots_protocol::terms::EncodedTerms::capture(admitted.terms()?) .map_err(|_| OperationError::InvalidEvidence)?; - let original_request = radroots_protocol::commerce::EncodedRecord::capture( - admitted - .history - .records - .get(&admitted.request) - .ok_or(OperationError::RecoveryRequired)? - .content(), - ) - .map_err(|_| OperationError::RecoveryRequired)?; + let original_request = if base.is_none() { + Some(replacement::encoded( + &admitted.history.records, + admitted.authorization, + )?) + } else { + None + }; + let replacement_records = admitted + .replacement + .map(|selected| { + Ok::<_, OperationError>([ + replacement::encoded(&admitted.history.records, selected.base_agreement())?, + replacement::encoded(&admitted.history.records, selected.proposal())?, + replacement::encoded(&admitted.history.records, selected.authorization())?, + ]) + }) + .transpose()?; let original_quote = admitted .quote .map(|id| { @@ -541,13 +640,18 @@ pub(in crate::workspace) async fn admit( .transpose()? .unwrap_or(Sequence::new(0).map_err(|_| OperationError::RecoveryRequired)?); let body = Body { - version: 1, + version: if base.is_some() { 2 } else { 1 }, command: serde_json::from_slice(command.protected_wire()) .map_err(|_| OperationError::InvalidCommand)?, terms: serde_json::from_slice(terms.protected_wire()) .map_err(|_| OperationError::InvalidEvidence)?, - original_request: serde_json::from_slice(original_request.protected_wire()) - .map_err(|_| OperationError::RecoveryRequired)?, + original_request: original_request + .as_ref() + .map(|record| { + serde_json::from_slice(record.protected_wire()) + .map_err(|_| OperationError::RecoveryRequired) + }) + .transpose()?, original_quote: original_quote .as_ref() .map(|quote| { @@ -555,6 +659,23 @@ pub(in crate::workspace) async fn admit( .map_err(|_| OperationError::RecoveryRequired) }) .transpose()?, + replacement: match (base, replacement_records.as_ref()) { + (Some(base), Some(records)) => Some(replacement::Basis { + base_operation: base.operation, + base_installation: base.installation, + base: serde_json::from_slice(records[0].protected_wire()) + .map_err(|_| OperationError::RecoveryRequired)?, + proposal: serde_json::from_slice(records[1].protected_wire()) + .map_err(|_| OperationError::RecoveryRequired)?, + authorization: serde_json::from_slice(records[2].protected_wire()) + .map_err(|_| OperationError::RecoveryRequired)?, + originals: base.originals, + desired, + releases, + }), + (None, None) => None, + _ => return Err(OperationError::RecoveryRequired), + }, seller_author_head, seller_author_sequence, minimum_revision: request.minimum_checkpoint().revision(), diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs @@ -18,6 +18,80 @@ pub(in crate::workspace::stock) struct Retained { operation_keyed: bool, } impl Retained { + pub(in crate::workspace::stock) async fn plan_releases( + &self, + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + before_revision: u64, + ) -> Result<Vec<super::super::changes::Release>, OperationError> { + let body: Body = super::super::super::closed_record(&self.frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + replacement::releases(&body, connection, input, crypto, before_revision).await + } + pub(in crate::workspace::stock) async fn confirm_replacement_residual( + &self, + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + before_revision: u64, + ) -> Result<(), OperationError> { + let body: Body = super::super::super::closed_record(&self.frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + replacement::confirm_residual(&body, connection, input, crypto, before_revision).await + } + pub(in crate::workspace::stock) fn terms( + &self, + ) -> Result<radroots_domain::Terms, OperationError> { + let body: Body = super::super::super::closed_record(&self.frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + radroots_protocol::terms::decode(body.terms.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired) + } + pub(in crate::workspace::stock) fn mappings( + &self, + ) -> Result<Vec<radroots_domain::stock::OptionPoolMapping>, OperationError> { + let body: Body = super::super::super::closed_record(&self.frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + Ok(body.mappings) + } + pub(in crate::workspace::stock) fn affected_pools( + &self, + ) -> Result<Vec<PoolId>, OperationError> { + let body: Body = super::super::super::closed_record(&self.frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + Ok(if body.replacement.is_some() { + body.pools.into_iter().map(|pool| pool.id()).collect() + } else { + self.receipt + .held_pools() + .iter() + .map(|pool| pool.id()) + .collect() + }) + } + pub(in crate::workspace::stock) fn affected_pool_snapshots( + &self, + ) -> Result<Vec<PoolSnapshot>, OperationError> { + let body: Body = super::super::super::closed_record(&self.frame.body) + .map_err(|_| OperationError::RecoveryRequired)?; + Ok(if body.replacement.is_some() { + body.pools + } else { + self.receipt.held_pools().to_vec() + }) + } + pub(in crate::workspace::stock) fn commitment_sequence( + &self, + ) -> Result<Sequence, OperationError> { + let record = replacement::record(&self.receipt)?; + let radroots_domain::CommercePayload::AgreementCommitted(commitment) = + record.content().payload() + else { + return Err(OperationError::RecoveryRequired); + }; + Ok(commitment.seller_sequence()) + } pub(in crate::workspace::stock) fn held_allocations( &self, ) -> Result<Vec<(PoolId, radroots_domain::stock::StockTicks)>, OperationError> { @@ -175,22 +249,50 @@ pub(super) fn receipt( body: &Body, command: &CapturedStockCommitment, ) -> Result<StockAcceptanceReceipt, OperationError> { - let request = radroots_protocol::commerce::decode(body.original_request.get().as_bytes()) - .map_err(|_| OperationError::RecoveryRequired)?; if body.seller_author_head.is_none() != (body.seller_author_sequence.get() == 0) { return Err(OperationError::RecoveryRequired); } - let CapturedStockCommitment::Acceptance(initial) = command else { - return Err(OperationError::RecoveryRequired); + let rumor = match command { + CapturedStockCommitment::Acceptance(initial) => { + let request = radroots_protocol::commerce::decode( + body.original_request + .ok_or(OperationError::RecoveryRequired)? + .get() + .as_bytes(), + ) + .map_err(|_| OperationError::RecoveryRequired)?; + radroots_protocol::commerce::initial_commitment_rumor( + initial, + &request, + body.seller_author_head + .map(|head| (head, body.seller_author_sequence)), + body.observed_at, + ) + } + CapturedStockCommitment::TermsInstallation(command) => { + let basis = body + .replacement + .as_ref() + .ok_or(OperationError::RecoveryRequired)?; + let decode = |raw: &RawValue| { + radroots_protocol::commerce::decode(raw.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired) + }; + radroots_protocol::commerce::replacement_commitment_rumor( + command, + &decode(basis.base)?, + &decode(basis.proposal)?, + &decode(basis.authorization)?, + ( + body.seller_author_head + .ok_or(OperationError::RecoveryRequired)?, + body.seller_author_sequence, + ), + body.observed_at, + ) + } }; - let rumor = radroots_protocol::commerce::initial_commitment_rumor( - initial, - &request, - body.seller_author_head - .map(|head| (head, body.seller_author_sequence)), - body.observed_at, - ) - .map_err(|_| OperationError::RecoveryRequired)?; + let rumor = rumor.map_err(|_| OperationError::RecoveryRequired)?; StockAcceptanceReceipt::from_committed_store( input, CommitAttempt::new( @@ -235,46 +337,59 @@ pub(in crate::workspace::stock) async fn read( .map_err(|_| OperationError::RecoveryRequired)?; let encoded = radroots_protocol::terms::EncodedTerms::capture(&terms) .map_err(|_| OperationError::RecoveryRequired)?; - let original = radroots_protocol::commerce::decode(body.original_request.get().as_bytes()) + if body.version == 1 { + if body.replacement.is_some() || command.proposal().is_some() { + return Err(OperationError::RecoveryRequired); + } + let original = radroots_protocol::commerce::decode( + body.original_request + .ok_or(OperationError::RecoveryRequired)? + .get() + .as_bytes(), + ) .map_err(|_| OperationError::RecoveryRequired)?; - let radroots_domain::CommercePayload::Request(original_request) = original.content().payload() - else { - return Err(OperationError::RecoveryRequired); - }; - if original.record_id() != command.authorization() - || original_request.terms() != &terms - || original.content().header().order_id() - != command.context().expected().map(|value| value.order_id()) - || original.content().header().author() != terms.buyer() - || original.content().header().created_at() > body.observed_at - || body.expires > original_request.expires_at() - || original_request.quote().is_some() != body.original_quote.is_some() - { - return Err(OperationError::RecoveryRequired); - } - if let Some(raw) = body.original_quote { - let quoted = radroots_protocol::commerce::decode(raw.get().as_bytes()) - .map_err(|_| OperationError::RecoveryRequired)?; - let radroots_domain::CommercePayload::Quote(quote) = quoted.content().payload() else { + let radroots_domain::CommercePayload::Request(original_request) = + original.content().payload() + else { return Err(OperationError::RecoveryRequired); }; - if Some(quoted.record_id()) != original_request.quote() - || quote.terms() != &terms - || body.expires > quote.expires_at() - || quoted.content().header().thread_id() != original.content().header().thread_id() - || quoted.content().header().buyer() != terms.buyer() - || quoted.content().header().seller() != terms.seller() - || quoted.content().header().created_at() > body.observed_at + if original.record_id() != command.authorization() + || original_request.terms() != &terms + || original.content().header().order_id() + != command.context().expected().map(|value| value.order_id()) + || original.content().header().author() != terms.buyer() + || original.content().header().created_at() > body.observed_at + || body.expires > original_request.expires_at() + || original_request.quote().is_some() != body.original_quote.is_some() { return Err(OperationError::RecoveryRequired); } + if let Some(raw) = body.original_quote { + let quoted = radroots_protocol::commerce::decode(raw.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired)?; + let radroots_domain::CommercePayload::Quote(quote) = quoted.content().payload() else { + return Err(OperationError::RecoveryRequired); + }; + if Some(quoted.record_id()) != original_request.quote() + || quote.terms() != &terms + || body.expires > quote.expires_at() + || quoted.content().header().thread_id() != original.content().header().thread_id() + || quoted.content().header().buyer() != terms.buyer() + || quoted.content().header().seller() != terms.seller() + || quoted.content().header().created_at() > body.observed_at + { + return Err(OperationError::RecoveryRequired); + } + } + } else { + replacement::validate(&body, &command)?; } let expected = command .context() .expected() .ok_or(OperationError::RecoveryRequired)?; let header = &frame.header; - if body.version != 1 + if !matches!(body.version, 1 | 2) || (body.seller_author_sequence.get() == 0) != body.seller_author_head.is_none() || body.minimum_revision >= header.revision || (body.minimum_revision.get() == 0) != body.minimum_head.is_none() @@ -285,8 +400,8 @@ pub(in crate::workspace::stock) async fn read( || command.context().authority() != input.authority() || command.context().route_digest() != input.route_digest() || header.order != Some(expected.order_id()) - || expected.agreement().is_some() - || expected.seller_sequence().get() != 0 + || (body.version == 1 + && (expected.agreement().is_some() || expected.seller_sequence().get() != 0)) || expected.checkpoint() != &body.coverage || expected.buyer_head() != body.buyer_head || encoded.digest() != command.terms_digest() @@ -298,7 +413,7 @@ pub(in crate::workspace::stock) async fn read( || body.issue_before.get() - body.observed_at.get() > 120 || body.expires > command.context().not_after() || command.context().approval().is_none_or(|approval| { - approval.scope() != "orders.accept" + approval.scope() != command.command_name() || approval.intent_digest() != command.approval_intent_digest() || body.expires > approval.expires_at() }) @@ -324,10 +439,12 @@ pub(in crate::workspace::stock) async fn read( { return Err(OperationError::RecoveryRequired); } - let (allocations, effects) = plan::resolve(&terms, &command, &body.mappings, &body.pools) - .map_err(|_| OperationError::RecoveryRequired)?; - if allocations != body.allocations || effects != body.effects { - return Err(OperationError::RecoveryRequired); + if body.version == 1 { + let (allocations, effects) = plan::resolve(&terms, &command, &body.mappings, &body.pools) + .map_err(|_| OperationError::RecoveryRequired)?; + if allocations != body.allocations || effects != body.effects { + return Err(OperationError::RecoveryRequired); + } } let expected_fence = fence(header, &command)?; let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") @@ -336,9 +453,12 @@ pub(in crate::workspace::stock) async fn read( .map_err(|_| OperationError::RecoveryRequired)?; let operation_keyed = match catalog { 1..=12 => false, - 13..=19 => true, + 13..=20 => true, _ => return Err(OperationError::RecoveryRequired), }; + if body.version == 2 && catalog < 20 { + return Err(OperationError::RecoveryRequired); + } let actor = header.actor.participant(); let query = if operation_keyed { sqlx::query("SELECT revision,protected FROM stock_orders WHERE actor=? AND operation_id=? AND order_id=? AND length(protected) BETWEEN 1 AND 262144") diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/plan.rs @@ -9,8 +9,15 @@ pub(super) fn resolve( mappings: &[radroots_domain::stock::OptionPoolMapping], pools: &[PoolSnapshot], ) -> Result<(Vec<Allocation>, Vec<Effect>), OperationError> { - use radroots_domain::stock::{AllocationClaim, AllocationPlanError}; - let explicit = command + let explicit = claims(command)?; + radroots_domain::stock::plan_allocations(terms, mappings, pools, explicit.as_deref()) + .map_err(error) +} +pub(super) fn claims( + command: &CapturedStockCommitment, +) -> Result<Option<Vec<radroots_domain::stock::AllocationClaim>>, OperationError> { + use radroots_domain::stock::AllocationClaim; + command .allocation() .explicit_allocations() .map(|values| { @@ -27,14 +34,15 @@ pub(super) fn resolve( .collect::<Result<Vec<_>, _>>() }) .transpose() - .map_err(|_| OperationError::InvalidCommand)?; - radroots_domain::stock::plan_allocations(terms, mappings, pools, explicit.as_deref()).map_err( - |error| match error { - AllocationPlanError::InvalidInput => OperationError::InvalidCommand, - AllocationPlanError::StaleState => OperationError::StaleState, - AllocationPlanError::Unsupported => OperationError::UnsupportedOperation, - AllocationPlanError::Capacity => WorkspaceError::Capacity.into(), - _ => OperationError::RecoveryRequired, - }, - ) + .map_err(|_| OperationError::InvalidCommand) +} +pub(super) fn error(error: radroots_domain::stock::AllocationPlanError) -> OperationError { + use radroots_domain::stock::AllocationPlanError; + match error { + AllocationPlanError::InvalidInput => OperationError::InvalidCommand, + AllocationPlanError::StaleState => OperationError::StaleState, + AllocationPlanError::Unsupported => OperationError::UnsupportedOperation, + AllocationPlanError::Capacity => WorkspaceError::Capacity.into(), + _ => OperationError::RecoveryRequired, + } } diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/replacement.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/replacement.rs @@ -0,0 +1,399 @@ +//! Original installed draws and frozen complete replacement preparation data. +use super::*; +use radroots_domain::stock::{ObligationBacking, StockAllocation, StockTicks}; +use radroots_protocol::commerce::{DecodedRecord, EncodedRecord}; + +#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(in crate::workspace::stock) struct Draw { + pub acceptance: OperationId, + pub installation: OperationId, + pub allocation: StockAllocation, + pub current: ObligationBacking, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Basis<'a> { + pub base_operation: OperationId, + pub base_installation: OperationId, + #[serde(borrow)] + pub base: &'a RawValue, + #[serde(borrow)] + pub proposal: &'a RawValue, + #[serde(borrow)] + pub authorization: &'a RawValue, + pub originals: Vec<Draw>, + pub desired: Vec<StockAllocation>, + pub releases: Vec<StockAllocation>, +} +pub(super) struct Base { + pub operation: OperationId, + pub installation: OperationId, + pub preparation: codec::Retained, + pub record: DecodedRecord, + pub originals: Vec<Draw>, +} +pub(super) fn record(receipt: &StockAcceptanceReceipt) -> Result<DecodedRecord, OperationError> { + let rumor = radroots_protocol::private_rumor::DecodedRumor::decode( + receipt.rumor().protected_wire().as_bytes(), + ) + .map_err(|_| OperationError::RecoveryRequired)?; + radroots_protocol::commerce::decode(rumor.protected_content().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired) +} +pub(super) async fn load( + turn: &mut Turn<'_>, + access: &Access, + command: &CapturedStockCommitment, +) -> Result<Base, OperationError> { + let expected = command + .context() + .expected() + .ok_or(OperationError::InvalidCommand)?; + let row=sqlx::query("SELECT operation_id,entry_id,commit_sequence FROM stock_agreements WHERE actor=? AND order_id=? ORDER BY commit_sequence DESC LIMIT 1") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(expected.order_id().as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::StaleState)?; + let id = |index| -> Result<OperationId, OperationError> { + Ok(OperationId::from_bytes( + row.try_get::<Vec<u8>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) + }; + let operation = id(0)?; + let installation = id(1)?; + let sequence: i64 = row + .try_get(2) + .map_err(|_| OperationError::RecoveryRequired)?; + let installed = Box::pin(super::super::installation::read_entry( + turn.connection, + turn.selected, + turn.crypto, + installation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let preparation = Box::pin(codec::read( + turn.connection, + turn.selected, + turn.crypto, + operation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let record = record(&preparation.receipt)?; + if sequence <= 0 + || sequence as u64 != expected.seller_sequence().get() + || expected.agreement() != Some(record.record_id()) + || installed.receipt.record_id() != record.record_id() + || installed.receipt.order_id() != expected.order_id() + { + return Err(OperationError::StaleState); + } + let before_revision = access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)? + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?; + let mut originals = Vec::new(); + let mut cursor = 0_i64; + loop { + let row=sqlx::query("SELECT operation_id,entry_id,commit_sequence FROM stock_agreements WHERE actor=? AND order_id=? AND commit_sequence>? ORDER BY commit_sequence LIMIT 1") + .bind(turn.selected.participant().as_bytes().as_slice()).bind(expected.order_id().as_bytes().as_slice()).bind(cursor).fetch_optional(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(row) = row else { + break; + }; + let id = |index| -> Result<OperationId, OperationError> { + Ok(OperationId::from_bytes( + row.try_get::<Vec<u8>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + )) + }; + let acceptance = id(0)?; + let installation = id(1)?; + let sequence: i64 = row + .try_get(2) + .map_err(|_| OperationError::RecoveryRequired)?; + if sequence != cursor + 1 || sequence as usize > radroots_domain::causal::MAX_CAUSAL_RECORDS + { + return Err(OperationError::RecoveryRequired); + } + cursor = sequence; + let installed = Box::pin(super::super::installation::read_entry( + turn.connection, + turn.selected, + turn.crypto, + installation, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + let prepared = Box::pin(codec::read( + turn.connection, + turn.selected, + turn.crypto, + acceptance, + )) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if installed.receipt.order_id() != expected.order_id() + || prepared.receipt.order_id() != expected.order_id() + || installed.frame.header.related_operation != Some(acceptance) + { + return Err(OperationError::RecoveryRequired); + } + for allocation in prepared.original_allocations()? { + let original = super::super::allocations::InstalledAllocation { + acceptance, + installation, + allocation, + }; + let current = original + .backing(turn.connection, turn.selected, turn.crypto, before_revision) + .await?; + if current.remaining() != StockTicks::ZERO { + originals.push(Draw { + acceptance, + installation, + allocation, + current, + }); + } + if originals.len() > 64 { + return Err(WorkspaceError::Capacity.into()); + } + } + } + if cursor != sequence { + return Err(OperationError::RecoveryRequired); + } + Ok(Base { + operation, + installation, + preparation, + record, + originals, + }) +} +pub(super) fn aggregate(originals: &[Draw]) -> Result<Vec<StockAllocation>, OperationError> { + if originals.len() > 64 { + return Err(WorkspaceError::Capacity.into()); + } + let mut pairs = BTreeSet::new(); + let mut quantities = BTreeMap::new(); + for draw in originals { + if draw.current.remaining() == StockTicks::ZERO + || draw.current.remaining() > draw.allocation.ticks() + || !pairs.insert(( + draw.acceptance, + draw.allocation.line_id(), + draw.allocation.pool_id(), + )) + { + return Err(OperationError::RecoveryRequired); + } + let quantity = quantities + .entry((draw.allocation.pool_id(), draw.allocation.line_id())) + .or_insert(StockTicks::ZERO); + *quantity = quantity + .checked_add(draw.current.remaining()) + .map_err(|_| WorkspaceError::Capacity)?; + } + quantities + .into_iter() + .map(|((pool, line), quantity)| { + StockAllocation::new(line, pool, quantity).map_err(|_| OperationError::RecoveryRequired) + }) + .collect() +} +pub(super) struct Resolution { + pub allocations: Vec<plan::Allocation>, + pub effects: Vec<plan::Effect>, + pub desired: Vec<StockAllocation>, + pub releases: Vec<StockAllocation>, +} +pub(super) fn resolve( + terms: &radroots_domain::Terms, + command: &CapturedStockCommitment, + mappings: &[radroots_domain::stock::OptionPoolMapping], + pools: &[PoolSnapshot], + originals: &[Draw], +) -> Result<Resolution, OperationError> { + let current = aggregate(originals)?; + let explicit = plan::claims(command)?; + let desired = radroots_domain::stock::resolve_replacement_allocations( + terms, + mappings, + pools, + explicit.as_deref(), + ¤t, + ) + .map_err(plan::error)?; + let delta = radroots_domain::stock::plan_replacement_allocations(¤t, &desired, pools) + .map_err(plan::error)?; + Ok(Resolution { + allocations: delta.additional_allocations().to_vec(), + effects: delta.preparatory_holds().to_vec(), + desired, + releases: delta.pending_releases().to_vec(), + }) +} +pub(super) fn validate( + body: &Body, + command: &CapturedStockCommitment, +) -> Result<(), OperationError> { + let basis = body + .replacement + .as_ref() + .ok_or(OperationError::RecoveryRequired)?; + if body.version != 2 + || body.original_request.is_some() + || body.original_quote.is_some() + || basis.base_operation == command.context().operation_id() + || basis.base_installation == command.context().operation_id() + { + return Err(OperationError::RecoveryRequired); + } + let terms = radroots_protocol::terms::decode(body.terms.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired)?; + let proposal = radroots_protocol::commerce::decode(basis.proposal.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired)?; + let authorization = radroots_protocol::commerce::decode(basis.authorization.get().as_bytes()) + .map_err(|_| OperationError::RecoveryRequired)?; + let radroots_domain::CommercePayload::TermsProposed(proposed) = proposal.content().payload() + else { + return Err(OperationError::RecoveryRequired); + }; + let radroots_domain::CommercePayload::TermsAuthorized(authorized) = + authorization.content().payload() + else { + return Err(OperationError::RecoveryRequired); + }; + if proposed.terms() != &terms + || body.expires > proposed.expires_at() + || body.expires > authorized.expires_at() + { + return Err(OperationError::RecoveryRequired); + } + let planned = resolve( + &terms, + command, + &body.mappings, + &body.pools, + &basis.originals, + )?; + if planned.allocations != body.allocations + || planned.effects != body.effects + || planned.desired != basis.desired + || planned.releases != basis.releases + { + return Err(OperationError::RecoveryRequired); + } + Ok(()) +} +pub(super) fn encoded( + records: &BTreeMap<RecordId, DecodedRecord>, + id: RecordId, +) -> Result<EncodedRecord, OperationError> { + EncodedRecord::capture( + records + .get(&id) + .ok_or(OperationError::RecoveryRequired)? + .content(), + ) + .map_err(|_| OperationError::RecoveryRequired) +} +pub(super) async fn confirm_residual( + body: &Body<'_>, + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + before_revision: u64, +) -> Result<(), OperationError> { + if let Some(basis) = &body.replacement { + for draw in &basis.originals { + let original = super::super::allocations::InstalledAllocation { + acceptance: draw.acceptance, + installation: draw.installation, + allocation: draw.allocation, + }; + if original + .backing(connection, input, crypto, before_revision) + .await? + != draw.current + { + return Err(OperationError::StaleState); + } + } + } + Ok(()) +} +pub(super) async fn releases( + body: &Body<'_>, + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + before_revision: u64, +) -> Result<Vec<super::super::changes::Release>, OperationError> { + let Some(basis) = &body.replacement else { + return Ok(Vec::new()); + }; + let mut needed: BTreeMap<_, _> = basis + .releases + .iter() + .map(|value| ((value.pool_id(), value.line_id()), value.ticks())) + .collect(); + if needed.len() != basis.releases.len() { + return Err(OperationError::RecoveryRequired); + } + let mut changes = Vec::new(); + for draw in &basis.originals { + let Some(needed) = needed.get_mut(&(draw.allocation.pool_id(), draw.allocation.line_id())) + else { + continue; + }; + if *needed == StockTicks::ZERO { + continue; + } + let original = super::super::allocations::InstalledAllocation { + acceptance: draw.acceptance, + installation: draw.installation, + allocation: draw.allocation, + }; + let before = original + .backing(connection, input, crypto, before_revision) + .await?; + if before.remaining() != draw.current.remaining() { + return Err(OperationError::StaleState); + } + let quantity = (*needed).min(before.remaining()); + let deficit = quantity.min(before.deficit()); + let backed = quantity + .checked_sub(deficit) + .map_err(|_| OperationError::RecoveryRequired)?; + let after = before + .release_residual(backed, deficit) + .map_err(|_| OperationError::RecoveryRequired)?; + changes.push(super::super::changes::Release { + acceptance: draw.acceptance, + installation: draw.installation, + line: draw.allocation.line_id(), + pool: draw.allocation.pool_id(), + before, + after, + backed, + deficit, + }); + *needed = needed + .checked_sub(quantity) + .map_err(|_| OperationError::RecoveryRequired)?; + } + if needed.values().any(|value| *value != StockTicks::ZERO) { + return Err(OperationError::RecoveryRequired); + } + Ok(changes) +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/allocations.rs b/crates/storage_sqlite/src/workspace/stock/inventory/allocations.rs @@ -16,6 +16,13 @@ impl InstalledAllocation { crypto: &WorkspaceCrypto, before_revision: u64, ) -> Result<ObligationBacking, OperationError> { + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + if catalog >= 20 { + return super::changes::current(connection, input, crypto, self, before_revision).await; + } let prior = super::deficit::prior_quantity( connection, input, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/changes.rs b/crates/storage_sqlite/src/workspace/stock/inventory/changes.rs @@ -0,0 +1,204 @@ +//! Original-allocation residual transitions; the SQL projection has identities +//! only. Quantities stay in the authenticated installation journal body. +use super::*; +use radroots_domain::{ + AgreementLineId, PublicKey, + stock::{ObligationBacking, StockTicks}, +}; + +#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(in crate::workspace::stock) struct Release { + pub acceptance: OperationId, + pub installation: OperationId, + pub line: AgreementLineId, + pub pool: PoolId, + pub before: ObligationBacking, + pub after: ObligationBacking, + pub backed: StockTicks, + pub deficit: StockTicks, +} +impl Release { + pub fn validate(&self) -> Result<StockTicks, OperationError> { + let quantity = self + .backed + .checked_add(self.deficit) + .map_err(|_| OperationError::RecoveryRequired)?; + if self.before.release_residual(self.backed, self.deficit).ok() != Some(self.after) { + return Err(OperationError::RecoveryRequired); + } + Ok(quantity) + } + fn key(&self) -> ChangeIdentity { + ChangeIdentity { + acceptance: self.acceptance, + line: self.line, + pool: self.pool, + installation: self.installation, + } + } +} +#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +struct ChangeIdentity { + acceptance: OperationId, + line: AgreementLineId, + pool: PoolId, + installation: OperationId, +} +fn index_digest(values: &mut [ChangeIdentity]) -> Result<[u8; 32], OperationError> { + if values.len() > 64 { + return Err(OperationError::RecoveryRequired); + } + values.sort(); + if values.windows(2).any(|pair| { + pair[0].acceptance == pair[1].acceptance + && pair[0].line == pair[1].line + && pair[0].pool == pair[1].pool + }) { + return Err(OperationError::RecoveryRequired); + } + let mut hash = Sha256::new(); + hash.update(b"radroots.seller_stock.obligation_changes_projection.v1\0"); + hash.update((values.len() as u64).to_be_bytes()); + for value in values { + hash.update(value.acceptance.as_bytes()); + hash.update(value.line.as_bytes()); + hash.update(value.pool.as_bytes()); + hash.update(value.installation.as_bytes()); + } + Ok(hash.finalize().into()) +} +pub(super) fn digest(changes: &[Release]) -> Result<[u8; 32], OperationError> { + for change in changes { + change.validate()?; + } + index_digest(&mut changes.iter().map(Release::key).collect::<Vec<_>>()) +} +pub(super) async fn raw_digest( + connection: &mut SqliteConnection, + actor: PublicKey, + entry: OperationId, +) -> Result<[u8; 32], OperationError> { + let rows=sqlx::query("SELECT acceptance_id,line_id,pool_id,installation_id FROM stock_obligation_changes WHERE actor=? AND operation_id=? ORDER BY acceptance_id,line_id,pool_id LIMIT 65") + .bind(actor.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).fetch_all(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let mut values = Vec::with_capacity(rows.len()); + for row in rows { + let field = |index| -> Result<[u8; 32], OperationError> { + row.try_get::<Vec<u8>, _>(index) + .map_err(|_| OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired) + }; + values.push(ChangeIdentity { + acceptance: OperationId::from_bytes(field(0)?), + line: AgreementLineId::from_bytes(field(1)?), + pool: PoolId::from_bytes(field(2)?), + installation: OperationId::from_bytes(field(3)?), + }); + } + index_digest(&mut values) +} +pub(super) async fn insert( + connection: &mut SqliteConnection, + actor: PublicKey, + entry: OperationId, + changes: &[Release], +) -> Result<(), OperationError> { + digest(changes)?; + for change in changes { + sqlx::query("INSERT INTO stock_obligation_changes(actor,operation_id,acceptance_id,installation_id,line_id,pool_id) VALUES(?,?,?,?,?,?)") + .bind(actor.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(change.acceptance.as_bytes().as_slice()) + .bind(change.installation.as_bytes().as_slice()).bind(change.line.as_bytes().as_slice()).bind(change.pool.as_bytes().as_slice()) + .execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + } + Ok(()) +} + +/// Replays each protected loss/release in original revision order. Summing +/// historical losses alone would resurrect released obligations or deficits. +pub(super) async fn current( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + original: &super::allocations::InstalledAllocation, + before_revision: u64, +) -> Result<ObligationBacking, OperationError> { + let mut state = ObligationBacking::new( + original.allocation.ticks(), + original.allocation.ticks(), + StockTicks::ZERO, + ) + .map_err(|_| OperationError::RecoveryRequired)?; + let mut cursor = 0_u64; + loop { + let row=sqlx::query("WITH c AS (SELECT actor,operation_id,acceptance_id,installation_id,line_id,pool_id,0 AS kind FROM stock_deficits UNION ALL SELECT actor,operation_id,acceptance_id,installation_id,line_id,pool_id,1 AS kind FROM stock_obligation_changes) SELECT o.revision,o.operation_id,c.kind FROM c JOIN stock_operations o ON o.actor=c.actor AND o.operation_id=c.operation_id WHERE c.actor=? AND c.acceptance_id=? AND c.installation_id=? AND c.line_id=? AND c.pool_id=? AND o.revision>? AND o.revision<? ORDER BY o.revision LIMIT 1") + .bind(input.participant().as_bytes().as_slice()).bind(original.acceptance.as_bytes().as_slice()).bind(original.installation.as_bytes().as_slice()) + .bind(original.allocation.line_id().as_bytes().as_slice()).bind(original.allocation.pool_id().as_bytes().as_slice()) + .bind(cursor as i64).bind(before_revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?; + let Some(row) = row else { + return Ok(state); + }; + let revision: i64 = row + .try_get(0) + .map_err(|_| OperationError::RecoveryRequired)?; + let operation = OperationId::from_bytes( + row.try_get::<Vec<u8>, _>(1) + .map_err(|_| OperationError::RecoveryRequired)? + .try_into() + .map_err(|_| OperationError::RecoveryRequired)?, + ); + let kind: i64 = row + .try_get(2) + .map_err(|_| OperationError::RecoveryRequired)?; + if revision <= 0 { + return Err(OperationError::RecoveryRequired); + } + cursor = revision as u64; + let frame = super::super::ledger::read(connection, input, crypto, operation) + .await? + .ok_or(OperationError::RecoveryRequired)?; + if frame.header.revision.get() != cursor + || frame.header.actor.participant() != input.participant() + { + return Err(OperationError::RecoveryRequired); + } + if kind == 0 { + let (request, data) = decode_operation(&frame.body, 20)?; + if frame.header.family != super::super::ledger::Family::Inventory + || request.command().digest() != frame.header.digest + || data.revision != frame.header.revision + || data.head != frame.header.head + || data.pool.id() != original.allocation.pool_id() + { + return Err(OperationError::RecoveryRequired); + } + let mut matches = data.losses.iter().filter(|loss| { + loss.acceptance == original.acceptance + && loss.installation == original.installation + && loss.line == original.allocation.line_id() + }); + let change = matches.next().ok_or(OperationError::RecoveryRequired)?; + if matches.next().is_some() || change.before != state { + return Err(OperationError::RecoveryRequired); + } + change.quantity()?; + state = change.after; + } else if kind == 1 { + let changes = super::installation::read_changes(&frame)?; + let mut matches = changes.iter().filter(|change| { + change.acceptance == original.acceptance + && change.installation == original.installation + && change.line == original.allocation.line_id() + && change.pool == original.allocation.pool_id() + }); + let change = matches.next().ok_or(OperationError::RecoveryRequired)?; + if matches.next().is_some() || change.before != state { + return Err(OperationError::RecoveryRequired); + } + change.validate()?; + state = change.after; + } else { + return Err(OperationError::RecoveryRequired); + } + } +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs b/crates/storage_sqlite/src/workspace/stock/inventory/checkpoint.rs @@ -96,7 +96,7 @@ impl MinimumProof { super::super::ledger::raw_parts_witness(connection, &actor, &operation).await?; hash.update([parts]); hash.update(witness); - if catalog == 19 && family == 0 { + if catalog >= 19 && family == 0 { hash.update(b"D19"); hash.update( super::deficit::raw_projection(connection, &actor, &operation).await?, @@ -193,7 +193,7 @@ pub(in crate::workspace::stock) async fn authenticate_order_state( authority: &Authority, order: radroots_domain::OrderId, ) -> Result<super::super::order_state::Checked, OperationError> { - if !matches!(authority.catalog, 13..=19) { + if !matches!(authority.catalog, 13..=20) { return Err(OperationError::UnsupportedOperation); } let current = authority @@ -201,7 +201,7 @@ pub(in crate::workspace::stock) async fn authenticate_order_state( .ok_or(OperationError::RecoveryRequired)?; let mut previous = current.head; let mut hash = history_hash(true); - let mut chain = super::super::order_state::Chain::new(); + let mut chain = super::super::order_state::Chain::new(authority.catalog); for revision in (1..=current.revision.get()).rev() { let id: Vec<u8> = sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32") .bind(revision as i64).fetch_optional(&mut *connection).await @@ -262,7 +262,7 @@ pub(super) async fn authenticate_order_absence( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - if !matches!(authority.catalog, 9..=19) { + if !matches!(authority.catalog, 9..=20) { return Err(OperationError::UnsupportedOperation); } let upper = current.revision.get(); @@ -344,7 +344,7 @@ pub(in crate::workspace::stock) async fn authenticate_identity( let current = authority .inventory .ok_or(OperationError::UnsupportedOperation)?; - let multipart = matches!(authority.catalog, 7..=19); + let multipart = matches!(authority.catalog, 7..=20); let upper = current.revision.get(); let mut previous = current.head; let mut hash = history_hash(multipart); @@ -521,7 +521,7 @@ pub(in crate::workspace::stock) async fn authenticate_minimum_with_local( minimum.revision().get().max(1) }; let upper = current.revision.get(); - let multipart = matches!(authority.catalog, 7..=19); + let multipart = matches!(authority.catalog, 7..=20); let mut hash = history_hash(multipart); let mut expected = current.head; for revision in (lower..=upper).rev() { @@ -785,7 +785,7 @@ async fn authenticate_projected( .ok_or(OperationError::UnsupportedOperation)?; let upper = current.revision.get(); let mut expected = current.head; - let multipart = matches!(authority.catalog, 7..=19); + let multipart = matches!(authority.catalog, 7..=20); let mut hash = history_hash(multipart); for revision in (1..=upper).rev() { let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32").bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/codec.rs @@ -132,7 +132,7 @@ pub(super) fn encode_operation( String::from_utf8(clear.to_vec()).map_err(|_| OperationError::StorageFailure)?, ) .map_err(|_| OperationError::StorageFailure)?; - if catalog == 19 { + if catalog >= 19 { return super::encode(&OperationV5 { version: 5, authorization: authorization.ok_or(OperationError::RecoveryRequired)?, @@ -183,7 +183,7 @@ fn decode_inner( catalog: i64, allow_mapping: bool, ) -> Result<(InventoryRequest, OperationData), OperationError> { - if catalog == 19 { + if catalog >= 19 { let decoded: OperationV5<'_> = super::closed_record(bytes).map_err(|_| OperationError::RecoveryRequired)?; if decoded.version != 5 || decoded.losses.len() > super::deficit::MAX_LOSSES { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/deficit.rs b/crates/storage_sqlite/src/workspace/stock/inventory/deficit.rs @@ -12,14 +12,14 @@ pub(super) const MAX_LOSSES: usize = 32; #[derive(Clone, Eq, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct Loss { - acceptance: OperationId, - installation: OperationId, - line: AgreementLineId, - before: ObligationBacking, - after: ObligationBacking, + pub(super) acceptance: OperationId, + pub(super) installation: OperationId, + pub(super) line: AgreementLineId, + pub(super) before: ObligationBacking, + pub(super) after: ObligationBacking, } impl Loss { - fn quantity(&self) -> Result<StockTicks, OperationError> { + pub(super) fn quantity(&self) -> Result<StockTicks, OperationError> { let quantity = self .before .backed() diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/inspection.rs b/crates/storage_sqlite/src/workspace/stock/inventory/inspection.rs @@ -12,7 +12,7 @@ impl Turn<'_> { proof: AttachmentProof, ) -> Result<Option<StockSnapshot>, OperationError> { let mut access = self.access(&binding, minimum, &proof).await?; - if access.authority.catalog != 19 { + if access.authority.catalog < 19 { return Err(OperationError::UnsupportedOperation); } access.record.require(StockAction::ReadPools, id)?; @@ -60,8 +60,8 @@ impl Turn<'_> { .checked_add(value.deficit()) .map_err(|_| OperationError::RecoveryRequired)?; } - // Catalog19 has no quarantine/consumption/release producer. A - // current report must match its actual installed physical backing. + // Current original-draw transitions must reconcile to actual + // physical committed backing, independently of historical receipts. if backed != pool.pool.balances().physical().committed_hold || pool.pool.balances().physical().physical_quarantine != StockTicks::ZERO { diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation.rs @@ -1,10 +1,13 @@ -//! Initial T2 installation. Original preparation and issuance remain immutable. +//! T2 commitment installation. Original preparation and issuance remain immutable. use super::super::{issuance::evidence::selection, ledger, signing_plan}; use super::*; use checkpoint::{EntryIdentity, IdentityTarget}; use radroots_domain::{OrderId, PublicKey, RecordId, stock::StockTicks}; +use std::collections::BTreeMap; mod codec; mod projection; +#[cfg(test)] +mod wire_tests; pub(in crate::workspace::stock) use codec::{Retained, read_entry}; pub(in crate::workspace::stock) use projection::{Projection, raw_projection}; @@ -69,7 +72,7 @@ impl std::fmt::Debug for StockPublicationWork { } } -/// Confirmed initial agreement and exact per-recipient work. This is business +/// Confirmed installed commitment and exact per-recipient work. This is business /// installation evidence, independent of signing dispatch and delivery status. #[derive(Clone)] pub struct StockInstallationReceipt { @@ -137,13 +140,33 @@ struct Effect { before: PoolSnapshot, after: PoolSnapshot, quantity: StockTicks, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "super::super::optional_present" + )] + released: Option<StockTicks>, movement: [u8; 32], } -fn after(before: PoolSnapshot, quantity: StockTicks) -> Result<PoolSnapshot, OperationError> { - let balances = before - .balances() - .install_preparatory(quantity) - .map_err(|_| OperationError::RecoveryRequired)?; +fn after( + before: PoolSnapshot, + quantity: StockTicks, + released: StockTicks, +) -> Result<PoolSnapshot, OperationError> { + if quantity == StockTicks::ZERO && released == StockTicks::ZERO { + return Err(OperationError::RecoveryRequired); + } + let mut balances = before.balances(); + if quantity != StockTicks::ZERO { + balances = balances + .install_preparatory(quantity) + .map_err(|_| OperationError::RecoveryRequired)?; + } + if released != StockTicks::ZERO { + balances = balances + .release_committed(released) + .map_err(|_| OperationError::RecoveryRequired)?; + } let version = Sequence::new( before .version() @@ -163,6 +186,18 @@ fn after(before: PoolSnapshot, quantity: StockTicks) -> Result<PoolSnapshot, Ope #[serde(deny_unknown_fields)] struct Body { version: u8, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "super::super::optional_present" + )] + commit_sequence: Option<Sequence>, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "super::super::optional_present" + )] + changes: Option<Vec<super::changes::Release>>, operation: OperationId, plan_entry: OperationId, plan_head: CheckpointDigest, @@ -172,6 +207,20 @@ struct Body { effects: Vec<Effect>, work: [Work; 2], } +pub(super) fn read_changes( + frame: &ledger::Retained, +) -> Result<Vec<super::changes::Release>, OperationError> { + let body: Body = + super::super::closed_record(&frame.body).map_err(|_| OperationError::RecoveryRequired)?; + if body.version != 2 + || frame.header.family != ledger::Family::Installation + || frame.header.related_operation != Some(body.operation) + || codec::head(&frame.header, &frame.body) != frame.header.head + { + return Err(OperationError::RecoveryRequired); + } + body.changes.ok_or(OperationError::RecoveryRequired) +} pub(in crate::workspace::stock) async fn existing( turn: &mut Turn<'_>, auth: &signing_plan::Authorized, @@ -222,7 +271,7 @@ pub(in crate::workspace) async fn install( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12..=19) { + if !matches!(auth.access.authority.catalog, 12..=20) { return Err(OperationError::UnsupportedOperation); } let (old, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; @@ -301,20 +350,55 @@ pub(in crate::workspace) async fn install( let backing = Box::pin(super::backing::read( turn, &auth.access, - auth.original.receipt.held_pools(), + &auth.original.affected_pool_snapshots()?, )) .await?; - let allocations = auth.original.held_allocations()?; - let mut originals = Vec::with_capacity(allocations.len()); - let mut effects = Vec::with_capacity(allocations.len()); - for (pool, quantity) in allocations { + let before_revision = auth + .access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)? + .revision + .get() + .checked_add(1) + .ok_or(WorkspaceError::Capacity)?; + let changes = auth + .original + .plan_releases(turn.connection, turn.selected, turn.crypto, before_revision) + .await?; + let mut quantities: BTreeMap<_, _> = auth + .original + .held_allocations()? + .into_iter() + .map(|(pool, quantity)| (pool, (quantity, StockTicks::ZERO))) + .collect(); + for change in &changes { + change.validate()?; + if change.backed != StockTicks::ZERO { + let quantities = quantities + .entry(change.pool) + .or_insert((StockTicks::ZERO, StockTicks::ZERO)); + quantities.1 = quantities + .1 + .checked_add(change.backed) + .map_err(|_| WorkspaceError::Capacity)?; + } + } + let mut originals = Vec::with_capacity(quantities.len()); + let mut effects = Vec::with_capacity(quantities.len()); + for (pool, (quantity, released)) in quantities { let original = read_pool(turn.connection, turn.selected, turn.crypto, pool) .await? .ok_or(OperationError::RecoveryRequired)?; effects.push(Effect { before: original.pool, - after: after(original.pool, quantity)?, + after: after(original.pool, quantity, released)?, quantity, + released: if released == StockTicks::ZERO { + None + } else { + Some(released) + }, movement: super::super::super::random()?, }); originals.push(original); @@ -334,8 +418,15 @@ pub(in crate::workspace) async fn install( .map_err(|_| WorkspaceError::Capacity)?; let transaction = TransactionId::from_bytes(super::super::super::random()?); let entry = OperationId::from_bytes(super::super::super::random()?); + let replacement = auth.command.proposal().is_some(); let body = Body { - version: 1, + version: if replacement { 2 } else { 1 }, + commit_sequence: if replacement { + Some(auth.original.commitment_sequence()?) + } else { + None + }, + changes: if replacement { Some(changes) } else { None }, operation: request.operation, plan_entry: plan.frame.header.operation, plan_head: plan.frame.header.head, @@ -397,10 +488,14 @@ pub(in crate::workspace) async fn install( turn.crypto .seal_stock_record( turn.selected, - "installation_movement", + if body.version == 2 { + "replacement_movement" + } else { + "installation_movement" + }, &effect.movement, &encode(&codec::Movement { - version: 1, + version: body.version, operation: entry, digest: request.digest, record: body.record, @@ -442,6 +537,7 @@ pub(in crate::workspace) async fn install( for backing in &backing {backing.confirm(&mut tx).await?;} for (recipient,summary) in &selections {summary.confirm(&mut tx,turn.selected.participant(),request.operation,*recipient).await?;} framed.insert_record(&mut tx).await?; + if let Some(changes)=&body.changes {super::changes::insert(&mut tx,turn.selected.participant(),entry,changes).await?;} projection.insert(&mut tx,turn.selected.participant(),entry).await?; for (index,(effect,original)) in body.effects.iter().zip(&originals).enumerate() { let changed=sqlx::query("UPDATE stock_pools SET revision=?,protected=? WHERE pool_id=? AND revision=? AND protected=?").bind(effect.after.version().get() as i64).bind(&pool_bytes[index]).bind(effect.before.id().as_bytes().as_slice()).bind(effect.before.version().get() as i64).bind(&original.protected).execute(&mut *tx).await.map_err(|_|OperationError::StorageFailure)?; @@ -481,7 +577,7 @@ pub(in crate::workspace) async fn read( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 12..=19) { + if !matches!(auth.access.authority.catalog, 12..=20) { return Err(OperationError::UnsupportedOperation); } let (retained, identity) = Box::pin(existing(turn, &auth, request.operation)).await?; diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation/codec.rs @@ -106,7 +106,12 @@ async fn read_frame( } let body: Body = super::super::super::closed_record(&frame.body) .map_err(|_| OperationError::RecoveryRequired)?; - if body.version != 1 + if !matches!(body.version, 1 | 2) + || (body.version == 1 + && (body.commit_sequence.is_some() + || body.changes.is_some() + || body.effects.iter().any(|effect| effect.released.is_some()))) + || (body.version == 2 && (body.commit_sequence.is_none() || body.changes.is_none())) || body.effects.len() > 64 || body .effects @@ -146,15 +151,46 @@ async fn read_frame( { return Err(OperationError::RecoveryRequired); } - let allocations = original.held_allocations()?; + let sequence = original.commitment_sequence()?; + if body + .commit_sequence + .unwrap_or(Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?) + != sequence + || (body.version == 2 && sequence.get() < 2) + { + return Err(OperationError::RecoveryRequired); + } + let changes = original + .plan_releases(connection, input, crypto, header.revision.get()) + .await?; + if body.changes.as_deref().unwrap_or(&[]) != changes { + return Err(OperationError::RecoveryRequired); + } + let mut allocations: std::collections::BTreeMap<_, _> = original + .held_allocations()? + .into_iter() + .map(|(pool, quantity)| (pool, (quantity, StockTicks::ZERO))) + .collect(); + for change in &changes { + if change.backed != StockTicks::ZERO { + let quantities = allocations + .entry(change.pool) + .or_insert((StockTicks::ZERO, StockTicks::ZERO)); + quantities.1 = quantities + .1 + .checked_add(change.backed) + .map_err(|_| OperationError::RecoveryRequired)?; + } + } if allocations.len() != body.effects.len() { return Err(OperationError::RecoveryRequired); } - for ((pool, quantity), effect) in allocations.into_iter().zip(&body.effects) { + for ((pool, (quantity, released)), effect) in allocations.into_iter().zip(&body.effects) { if pool != effect.before.id() || quantity != effect.quantity + || released != effect.released.unwrap_or(StockTicks::ZERO) || effect.before.version().get() == 0 - || after(effect.before, quantity)? != effect.after + || after(effect.before, quantity, released)? != effect.after { return Err(OperationError::RecoveryRequired); } @@ -219,14 +255,23 @@ async fn read_frame( .map_err(|_| OperationError::RecoveryRequired)? .ok_or(OperationError::RecoveryRequired)?; let clear = crypto - .open_stock_record(input, "installation_movement", &effect.movement, &protected) + .open_stock_record( + input, + if body.version == 2 { + "replacement_movement" + } else { + "installation_movement" + }, + &effect.movement, + &protected, + ) .await?; let movement: Movement = clear .expose_secret(|bytes| super::super::super::closed_record(bytes)) .map_err(|_| OperationError::RecoveryRequired)?; if movement != (Movement { - version: 1, + version: body.version, operation: header.operation, digest: header.digest, record: body.record, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation/projection.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation/projection.rs @@ -6,6 +6,8 @@ pub(in crate::workspace::stock) struct Projection { order: OrderId, record: RecordId, recipients: [PublicKey; 2], + sequence: Sequence, + changes: Option<[u8; 32]>, } impl Projection { pub(super) fn new(header: &ledger::Header, body: &Body) -> Result<Self, OperationError> { @@ -14,6 +16,14 @@ impl Projection { order: header.order.ok_or(OperationError::RecoveryRequired)?, record: body.record, recipients: body.work.map(|value| value.recipient), + sequence: body + .commit_sequence + .unwrap_or(Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?), + changes: body + .changes + .as_deref() + .map(super::super::changes::digest) + .transpose()?, }) } pub(in crate::workspace::stock) fn digest( @@ -27,11 +37,15 @@ impl Projection { h.update(entry.as_bytes()); h.update(self.operation.as_bytes()); h.update(self.order.as_bytes()); - h.update(1_u64.to_be_bytes()); + h.update(self.sequence.get().to_be_bytes()); h.update(self.record.as_bytes()); for recipient in self.recipients { h.update(recipient.as_bytes()); } + if let Some(changes) = self.changes { + h.update(b"obligation_changes.v1\0"); + h.update(changes); + } h.finalize().into() } pub(super) async fn confirm( @@ -53,7 +67,7 @@ impl Projection { actor: PublicKey, entry: OperationId, ) -> Result<(), OperationError> { - sqlx::query("INSERT INTO stock_agreements(order_id,commit_sequence,actor,operation_id,entry_id,record_id) VALUES(?,1,?,?,?,?)").bind(self.order.as_bytes().as_slice()).bind(actor.as_bytes().as_slice()).bind(self.operation.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(self.record.as_bytes().as_slice()).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; + sqlx::query("INSERT INTO stock_agreements(order_id,commit_sequence,actor,operation_id,entry_id,record_id) VALUES(?,?,?,?,?,?)").bind(self.order.as_bytes().as_slice()).bind(self.sequence.get() as i64).bind(actor.as_bytes().as_slice()).bind(self.operation.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).bind(self.record.as_bytes().as_slice()).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; for recipient in self.recipients { sqlx::query("INSERT INTO stock_publication_work(actor,operation_id,recipient,installation_entry) VALUES(?,?,?,?)").bind(actor.as_bytes().as_slice()).bind(self.operation.as_bytes().as_slice()).bind(recipient.as_bytes().as_slice()).bind(entry.as_bytes().as_slice()).execute(&mut *connection).await.map_err(|_|OperationError::StorageFailure)?; } @@ -77,7 +91,7 @@ pub(in crate::workspace::stock) async fn raw_projection( let sequence: i64 = row .try_get(1) .map_err(|_| OperationError::RecoveryRequired)?; - if sequence != 1 { + if sequence <= 0 { return Err(OperationError::RecoveryRequired); } let operation = OperationId::from_bytes(field(2)?); @@ -105,6 +119,22 @@ pub(in crate::workspace::stock) async fn raw_projection( .map_err(|_| OperationError::RecoveryRequired)?, ); } + let actor_key = PublicKey::from_bytes(*actor).map_err(|_| OperationError::RecoveryRequired)?; + let entry_key = OperationId::from_bytes(*entry); + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; + let changes = if catalog >= 20 { + let raw = super::super::changes::raw_digest(connection, actor_key, entry_key).await?; + if sequence != 1 || raw != super::super::changes::digest(&[])? { + Some(raw) + } else { + None + } + } else { + None + }; let projection = Projection { operation, order: OrderId::from_bytes(field(0)?), @@ -112,6 +142,8 @@ pub(in crate::workspace::stock) async fn raw_projection( recipients: recipients .try_into() .map_err(|_| OperationError::RecoveryRequired)?, + sequence: Sequence::new(sequence as u64).map_err(|_| OperationError::RecoveryRequired)?, + changes, }; Ok(projection.digest( PublicKey::from_bytes(*actor).map_err(|_| OperationError::RecoveryRequired)?, diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/installation/wire_tests.rs b/crates/storage_sqlite/src/workspace/stock/inventory/installation/wire_tests.rs @@ -0,0 +1,83 @@ +//! Retained T2 wire shapes must distinguish absent extensions from null. +use super::*; +use radroots_domain::{ + PoolId, + listing::MeasurementUnit, + stock::{PhysicalBalances, PoolBalances, PoolUnit}, +}; + +#[test] +fn initial_installation_wire_rejects_null_extensions_and_keeps_its_exact_shape() { + let before = PoolSnapshot::new( + PoolId::from_bytes([1; 32]), + PoolUnit::new(MeasurementUnit::Each, 0).unwrap(), + PoolBalances::new( + StockTicks::new(1).unwrap(), + PhysicalBalances { + preparatory_hold: StockTicks::new(1).unwrap(), + ..PhysicalBalances::ZERO + }, + ) + .unwrap(), + Sequence::new(1).unwrap(), + ); + let work = Work { + recipient: PublicKey::from_bytes([2; 32]).unwrap(), + intent: [3; 32], + seal: [4; 32], + evidence: None, + }; + let body = Body { + version: 1, + commit_sequence: None, + changes: None, + operation: OperationId::from_bytes([5; 32]), + plan_entry: OperationId::from_bytes([6; 32]), + plan_head: CheckpointDigest::from_bytes([7; 32]), + record: RecordId::from_bytes([8; 32]), + installed_at: UnixSeconds::new(100).unwrap(), + authorization: StockAuthorizationRef::from_host_metadata( + Sequence::new(1).unwrap(), + CheckpointDigest::from_bytes([9; 32]), + ) + .unwrap(), + effects: vec![Effect { + before, + after: after(before, StockTicks::new(1).unwrap(), StockTicks::ZERO).unwrap(), + quantity: StockTicks::new(1).unwrap(), + released: None, + movement: [10; 32], + }], + work: [work; 2], + }; + let bytes = serde_json::to_vec(&body).unwrap(); + let retained: Body = crate::workspace::stock::closed_record(&bytes).unwrap(); + assert_eq!(serde_json::to_vec(&retained).unwrap(), bytes); + let original = serde_json::to_value(&body).unwrap(); + assert!(original.get("commit_sequence").is_none()); + assert!(original.get("changes").is_none()); + assert!(original["effects"][0].get("released").is_none()); + for field in ["commit_sequence", "changes"] { + let mut damaged = original.clone(); + damaged[field] = serde_json::Value::Null; + assert!( + crate::workspace::stock::closed_record::<Body>(&serde_json::to_vec(&damaged).unwrap()) + .is_err() + ); + } + let mut damaged = original; + damaged["effects"][0]["released"] = serde_json::Value::Null; + assert!( + crate::workspace::stock::closed_record::<Body>(&serde_json::to_vec(&damaged).unwrap()) + .is_err() + ); + let replacement = Body { + version: 2, + commit_sequence: Some(Sequence::new(2).unwrap()), + changes: Some(Vec::new()), + ..body + }; + let bytes = serde_json::to_vec(&replacement).unwrap(); + let retained: Body = crate::workspace::stock::closed_record(&bytes).unwrap(); + assert_eq!(serde_json::to_vec(&retained).unwrap(), bytes); +} diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs b/crates/storage_sqlite/src/workspace/stock/inventory/mapping.rs @@ -58,7 +58,7 @@ impl MappingRead { } } pub(super) fn require(access: &Access, key: OptionMappingKey) -> Result<(), OperationError> { - if !(5..=19).contains(&access.authority.catalog) { + if !(5..=20).contains(&access.authority.catalog) { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/plan.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn record_version(catalog: i64) -> Result<u8, OperationError> { match catalog { 2 => Ok(1), - 3..=19 => Ok(2), + 3..=20 => Ok(2), _ => Err(OperationError::RecoveryRequired), } } diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs b/crates/storage_sqlite/src/workspace/stock/issuance/claim.rs @@ -283,6 +283,29 @@ pub(in crate::workspace) async fn claim( true, )) .await?; + // A later self copy may finish an installed original, but new issuance + // from a pending amendment must retain its approved original residual. + let installed = current_order + .as_ref() + .and_then(|state| state.witness.expected) + .is_some_and(|state| state.phase == super::super::order_state::Phase::Installed); + if !installed { + auth.original + .confirm_replacement_residual( + turn.connection, + turn.selected, + turn.crypto, + auth.access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)? + .revision + .get() + .checked_add(1) + .ok_or(OperationError::RecoveryRequired)?, + ) + .await?; + } let at = auth.access.current.observed_at(); acceptance::check_consent(&auth.access, &auth.consent, &auth.command, true, at)?; if at < plan.bound.bound_at() || at >= plan.bound.preparation().first_issue_deadline() { @@ -291,7 +314,7 @@ pub(in crate::workspace) async fn claim( let backing = Box::pin(super::super::inventory::backing::read( turn, &auth.access, - auth.original.receipt.held_pools(), + &auth.original.affected_pool_snapshots()?, )) .await?; let entry = OperationId::from_bytes(super::super::super::random()?); diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs b/crates/storage_sqlite/src/workspace/stock/issuance/recovery.rs @@ -81,7 +81,7 @@ pub(in crate::workspace) async fn authorize( &proof, )) .await?; - if !matches!(auth.access.authority.catalog, 13..=19) { + if !matches!(auth.access.authority.catalog, 13..=20) { return Err(OperationError::UnsupportedOperation); } let plan = auth.plan.as_ref().ok_or(OperationError::StaleState)?; diff --git a/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs b/crates/storage_sqlite/src/workspace/stock/issuance/unissued.rs @@ -340,7 +340,7 @@ pub(in crate::workspace) async fn capture( } let (authority, record, root, grant) = super::super::read(turn.connection, input, turn.crypto).await?; - if !matches!(authority.catalog, 14..=19) { + if !matches!(authority.catalog, 14..=20) { return Err(OperationError::UnsupportedOperation); } record.authenticate_retained_capture(input, &proof)?; @@ -494,7 +494,7 @@ pub(in crate::workspace) async fn read( &proof, ) .await?; - if !matches!(auth.access.authority.catalog, 14..=19) { + if !matches!(auth.access.authority.catalog, 14..=20) { return Err(OperationError::UnsupportedOperation); } let witness = Box::pin(checkpoint::authenticate_minimum( diff --git a/crates/storage_sqlite/src/workspace/stock/ledger.rs b/crates/storage_sqlite/src/workspace/stock/ledger.rs @@ -510,14 +510,14 @@ pub(super) async fn history( )) .await } - Some(2) if matches!(authority.catalog, 9..=19) => { + Some(2) if matches!(authority.catalog, 9..=20) => { Box::pin(history_family_2( connection, input, crypto, binding, authority, operation, )) .await } Some(2) => Err(OperationError::UnsupportedOperation), - Some(3) if matches!(authority.catalog, 10..=19) => { + Some(3) if matches!(authority.catalog, 10..=20) => { Box::pin(history_family_3( connection, input, crypto, binding, authority, operation, )) @@ -535,7 +535,7 @@ pub(super) async fn history( )) .await } - Some(6) if matches!(authority.catalog, 12..=19) => { + Some(6) if matches!(authority.catalog, 12..=20) => { Box::pin(history_family_6( connection, input, crypto, binding, authority, operation, )) diff --git a/crates/storage_sqlite/src/workspace/stock/order_state.rs b/crates/storage_sqlite/src/workspace/stock/order_state.rs @@ -128,6 +128,10 @@ impl Witness { { return Err(OperationError::RecoveryRequired); } + let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") + .fetch_one(&mut *connection) + .await + .map_err(|_| OperationError::RecoveryRequired)?; let legal = match self.expected { None => next.phase == Phase::Prepared, Some(old) if old.actor == next.actor => match (old.phase, next.phase) { @@ -135,6 +139,9 @@ impl Witness { old.operation == next.operation } (Phase::Aborted, Phase::Prepared) => old.operation != next.operation, + (Phase::Installed, Phase::Prepared) if catalog >= 20 => { + old.operation != next.operation + } _ => false, }, Some(_) => false, @@ -164,11 +171,12 @@ impl Witness { } } -/// Constant-memory backward validation of initial decision transitions. Each +/// Constant-memory backward validation of retained decision transitions. Each /// original preparation remains independently recoverable after a later abort. pub(super) struct Chain { pub latest: Option<Marker>, previous: Previous, + replacements: bool, } enum Previous { Latest, @@ -176,10 +184,11 @@ enum Previous { AbortOrGenesis(OperationId), } impl Chain { - pub const fn new() -> Self { + pub const fn new(catalog: i64) -> Self { Self { latest: None, previous: Previous::Latest, + replacements: catalog >= 20, } } pub fn observe(&mut self, marker: Marker) -> Result<(), OperationError> { @@ -191,7 +200,9 @@ impl Chain { Previous::Preparation(operation) if marker.phase == Phase::Prepared && marker.operation == operation => {} Previous::AbortOrGenesis(operation) - if marker.phase == Phase::Aborted && marker.operation != operation => {} + if (marker.phase == Phase::Aborted + || (self.replacements && marker.phase == Phase::Installed)) + && marker.operation != operation => {} _ => return Err(OperationError::RecoveryRequired), } self.previous = match marker.phase { diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/amendment_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/amendment_tests.rs @@ -0,0 +1,530 @@ +//! Actual authenticated replacement sources and native T0/T1/S/T2 effects. +use super::*; +use nostr::JsonUtil; + +fn proof(r: &Rig) -> AttachmentProof { + r.enrollment + .proof() + .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) + .unwrap() +} +use radroots_domain::{ + AgreementLine, CommerceContent, CommerceHeader, CommercePayload, RecordId, Sequence, SourceId, + Terms, TermsAuthorization, TermsProposal, +}; +use radroots_protocol::{ + command::CapturedTermsInstallation, + commerce::{DecodedRecord, EncodedCommerceRumor, EncodedRecord}, + terms::EncodedTerms, +}; + +fn record(receipt: &StockAcceptanceReceipt) -> DecodedRecord { + let rumor: serde_json::Value = serde_json::from_str(receipt.rumor().protected_wire()).unwrap(); + radroots_protocol::commerce::decode(rumor["content"].as_str().unwrap().as_bytes()).unwrap() +} +fn amount(original: &Terms, quantity: &str) -> Terms { + assert_eq!(original.lines().len(), 1); + let line = &original.lines()[0]; + let amount = quantity.parse().unwrap(); + let radroots_domain::AgreementPrice::Fixed(price) = line.price() else { + panic!("fixed-price fixture") + }; + let price = radroots_domain::AgreedFixedPrice::new( + price.rate(), + price.basis(), + price.discount_bps(), + None, + ); + let total = price.total(amount).unwrap(); + let line = AgreementLine::new( + line.id(), + line.source(), + line.option_id(), + line.product().clone(), + line.option().clone(), + amount, + line.fulfillment_group(), + line.source_lot_label(), + radroots_domain::AgreementPrice::Fixed(price), + total, + ) + .unwrap(); + Terms::new( + original.buyer(), + original.seller(), + vec![line], + original.fulfillment().to_vec(), + original.fulfillment_charge(), + original.fulfillment_charge().checked_add(total).unwrap(), + original.supply().clone(), + ) + .unwrap() +} +async fn retain_content(r: &Rig, content: &CommerceContent, scalar: u8) -> DecodedRecord { + let encoded = EncodedRecord::capture(content).unwrap(); + let decoded = radroots_protocol::commerce::decode(encoded.protected_wire()).unwrap(); + let rumor = EncodedCommerceRumor::capture(content).unwrap(); + let keys = nostr::Keys::new(nostr::SecretKey::from_hex(&format!("{scalar:064x}")).unwrap()); + assert_eq!( + keys.public_key().to_hex(), + content.header().author().to_hex() + ); + let receiver = + nostr::PublicKey::from_hex(&r.enrollment.input().participant().to_hex()).unwrap(); + let unsigned = nostr::UnsignedEvent::from_json(rumor.protected_wire()).unwrap(); + let wrap = nostr::EventBuilder::gift_wrap(&keys, &receiver, unsigned, Vec::<nostr::Tag>::new()) + .await + .unwrap(); + let provider = + LocalSigner::with_clock(SecretKey::parse(&format!("{:064x}", 3)).unwrap(), || { + Ok(150000) + }) + .unwrap(); + let opening = radroots_nostr::commerce::open( + &provider, + ProviderCall::new( + provider.public_key(), + NonZeroU64::new(230000).unwrap(), + CancellationSignal::new(), + ), + &wrap.as_json(), + ) + .await + .unwrap(); + let capture = StockSourceCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + &opening, + ) + .unwrap(); + assert_eq!(capture.profile(), StockSourceProfile::Known); + let (minimum, _, _) = minima(r).await; + r.store + .retain_stock_source(r.binding.clone(), minimum, &capture, r.enrollment.proof()) + .await + .unwrap(); + decoded +} +async fn proposal( + r: &Rig, + base: &StockAcceptanceReceipt, + terms: Terms, + buyer_proposes: bool, +) -> CapturedTermsInstallation { + let base = record(base); + let scope = scope(); + let snapshot = history(r).await; + let proposer = if buyer_proposes { + scope.buyer() + } else { + scope.seller() + }; + let authorizer = if buyer_proposes { + scope.seller() + } else { + scope.buyer() + }; + let proposer_head = if buyer_proposes { + snapshot.analysis().buyer_head() + } else { + snapshot.analysis().seller_head() + } + .unwrap(); + let authorizer_head = if buyer_proposes { + snapshot.analysis().seller_head() + } else { + snapshot.analysis().buyer_head() + } + .unwrap(); + let make = |author, previous, sequence, payload, extra: &[RecordId]| { + let mut parents: Vec<_> = terms + .lines() + .iter() + .map(|line| SourceId::from_bytes(line.source().event_id().into_bytes())) + .collect(); + parents.extend( + [base.record_id(), previous] + .into_iter() + .chain(extra.iter().copied()) + .map(|id| SourceId::from_bytes(id.into_bytes())), + ); + parents.sort(); + parents.dedup(); + CommerceContent::new( + CommerceHeader::new( + scope.thread_id(), + Some(scope.order_id()), + author, + scope.buyer(), + scope.seller(), + UnixSeconds::new(150).unwrap(), + Sequence::new(sequence).unwrap(), + Some(previous), + parents, + ) + .unwrap(), + payload, + ) + .unwrap() + }; + // These cases start from an initial agreement: both scoped author chains + // have one record. The null-order quote remains a separate chain. + let proposed = make( + proposer, + proposer_head, + 2, + CommercePayload::TermsProposed( + TermsProposal::new( + Some(base.record_id()), + terms.clone(), + UnixSeconds::new(230).unwrap(), + "complete updated amount", + ) + .unwrap(), + ), + &[], + ); + let proposed = retain_content(r, &proposed, if buyer_proposes { 2 } else { 3 }).await; + let authorized = make( + authorizer, + authorizer_head, + 2, + CommercePayload::TermsAuthorized(TermsAuthorization::new( + proposed.record_id(), + EncodedTerms::capture(&terms).unwrap().digest(), + UnixSeconds::new(230).unwrap(), + )), + &[proposed.record_id()], + ); + let authorized = retain_content(r, &authorized, if buyer_proposes { 3 } else { 2 }).await; + let snapshot = history(r).await; + let mut wire = serde_json::json!({"type":"orders.install_terms","context":context(r,110),"input":{"proposal":proposed.record_id(),"authorization":authorized.record_id(),"terms_digest":EncodedTerms::capture(&terms).unwrap().digest(),"allocation":{"type":"automatic"}}}); + wire["context"]["expected"] = serde_json::json!({"agreement":base.record_id(),"buyer_head":snapshot.analysis().buyer_head(),"checkpoint":snapshot.checkpoint().unwrap(),"order_id":scope.order_id(),"seller_sequence":"1"}); + let capture = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + wire["context"]["approval"] = serde_json::json!({"intent_digest":capture.approval_intent_digest(),"scope":"orders.install_terms","expires_at":"230"}); + CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap() +} +async fn prepare_terms( + r: &Rig, + command: &CapturedTermsInstallation, +) -> Result<StockAcceptanceReceipt, OperationError> { + let capture = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(r.enrollment.input()), + r.enrollment.input().grant_id(), + StockConsentMode::ExecuteAndRecover, + StockResources::all_pools(), + UnixSeconds::new(230).unwrap(), + CapturedTermsInstallation::parse(command.protected_wire()).unwrap(), + ) + .unwrap(); + r.store + .issue_stock_consent( + r.binding.clone(), + inventory_minimum(r).await, + &capture, + r.enrollment.proof(), + ) + .await?; + let (sources, listings, minimum) = minima(r).await; + let request = StockAcceptanceRequest::capture_terms( + r.binding.clone(), + minimum, + sources, + listings, + command, + ) + .unwrap(); + match r + .store + .prepare_stock_acceptance(request, r.enrollment.proof()) + .await? + { + StockAcceptanceOutcome::Prepared(value) => Ok(*value), + _ => panic!("preparation must confirm"), + } +} + +#[tokio::test] +async fn positive_replacement_holds_only_the_delta_then_installs_through_original_signing_owner() { + let r = Rig::new().await; + seed(&r, "10").await; + let original_terms = inspect(&r).await.terms().clone(); + let command = command(&r, 90, false).await; + consent(&r, &command).await; + let initial = prepare(&r, &command).await.unwrap(); + bound(bind(&r, &initial, 42).await.unwrap()); + let recipient = peer(&r, &initial); + retain(&r, &initial, recipient).await; + installed(install(&r, &initial).await.unwrap()); + balances(&r, 80, 7, 0, 3, 3).await; + let line = &original_terms.lines()[0]; + physical(&r,serde_json::json!({"type":"stock.map_option","context":context(&r,91),"input":{"listing":line.source().coordinate(),"option_id":line.option_id(),"pool_id":pool(81),"expected_mapping_version":"1","per_sale_unit":{"amount":"1","unit":"each"}}})).await; + let command = proposal(&r, &initial, amount(&original_terms, "5"), false).await; + let amended = prepare_terms(&r, &command).await.unwrap(); + assert_eq!(amended.allocation_count(), 1); + balances(&r, 80, 5, 2, 3, 4).await; + bound(bind(&r, &amended, 43).await.unwrap()); + retain(&r, &amended, recipient).await; + let replacement = installed(install(&r, &amended).await.unwrap()); + assert_ne!(replacement.record_id(), initial.rumor().record_id()); + balances(&r, 80, 5, 0, 5, 5).await; + balances(&r, 81, 10, 0, 0, 1).await; + let view = r + .store + .inspect_stock( + r.binding.clone(), + inventory_minimum(&r).await, + pool(80), + proof(&r), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(view.installed_obligations().remaining().get(), 5); + assert_eq!(view.installed_obligations().backed().get(), 5); + let revision = inventory_minimum(&r).await; + assert_eq!( + installed(install(&r, &amended).await.unwrap()).record_id(), + replacement.record_id() + ); + assert_eq!(inventory_minimum(&r).await, revision); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn negative_replacement_keeps_old_obligations_while_pending_and_releases_only_at_t2() { + let mut r = Rig::new().await; + seed(&r, "10").await; + let original_terms = inspect(&r).await.terms().clone(); + let command = command(&r, 90, false).await; + consent(&r, &command).await; + let initial = prepare(&r, &command).await.unwrap(); + bound(bind(&r, &initial, 42).await.unwrap()); + let recipient = peer(&r, &initial); + retain(&r, &initial, recipient).await; + installed(install(&r, &initial).await.unwrap()); + let command = proposal(&r, &initial, amount(&original_terms, "1"), true).await; + let amended = prepare_terms(&r, &command).await.unwrap(); + assert_eq!(amended.allocation_count(), 0); + balances(&r, 80, 7, 0, 3, 3).await; + bound(bind(&r, &amended, 43).await.unwrap()); + retain(&r, &amended, recipient).await; + installed(install(&r, &amended).await.unwrap()); + balances(&r, 80, 9, 0, 1, 4).await; + let view = r + .store + .inspect_stock( + r.binding.clone(), + inventory_minimum(&r).await, + pool(80), + proof(&r), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(view.installed_obligations().remaining().get(), 1); + assert_eq!(view.installed_obligations().backed().get(), 1); + assert_eq!(view.installed_obligations().deficit().get(), 0); + r.store.close().await.unwrap(); + r.store = NativeWorkspace::open_seller_stock( + &r.path, + r.enrollment.input().clone(), + r.fixture.crypto(), + r.clock.clone(), + ) + .await + .unwrap(); + r.binding = r + .store + .authenticate(r.enrollment.input().clone(), r.enrollment.proof()) + .await + .unwrap(); + balances(&r, 80, 9, 0, 1, 4).await; + let reopened = r + .store + .inspect_stock( + r.binding.clone(), + inventory_minimum(&r).await, + pool(80), + proof(&r), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(reopened.installed_obligations().remaining().get(), 1); + let mut raw = database(&r).await; + sqlx::query("DELETE FROM stock_obligation_changes") + .execute(&mut raw) + .await + .unwrap(); + assert_eq!( + r.store + .inspect_stock( + r.binding.clone(), + inventory_minimum(&r).await, + pool(80), + proof(&r) + ) + .await + .unwrap_err(), + OperationError::RecoveryRequired + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn authorized_reduction_of_a_known_deficit_does_not_manufacture_available_stock() { + let r = Rig::new().await; + seed(&r, "10").await; + let terms = inspect(&r).await.terms().clone(); + let command = command(&r, 90, false).await; + consent(&r, &command).await; + let initial = prepare(&r, &command).await.unwrap(); + bound(bind(&r, &initial, 42).await.unwrap()); + let recipient = peer(&r, &initial); + retain(&r, &initial, recipient).await; + installed(install(&r, &initial).await.unwrap()); + physical(&r,serde_json::json!({"type":"stock.spoil","context":context(&r,91),"input":{"pool_id":pool(80),"expected_version":"3","amount":"9","reason":"known loss before mutually authorized reduction"}})).await; + balances(&r, 80, 0, 0, 1, 4).await; + let command = proposal(&r, &initial, amount(&terms, "1"), false).await; + let amended = prepare_terms(&r, &command).await.unwrap(); + bound(bind(&r, &amended, 43).await.unwrap()); + retain(&r, &amended, recipient).await; + installed(install(&r, &amended).await.unwrap()); + balances(&r, 80, 0, 0, 1, 4).await; + let view = r + .store + .inspect_stock( + r.binding.clone(), + inventory_minimum(&r).await, + pool(80), + proof(&r), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(view.installed_obligations().remaining().get(), 1); + assert_eq!(view.installed_obligations().backed().get(), 1); + assert_eq!(view.installed_obligations().deficit().get(), 0); + let mut raw = database(&r).await; + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_deficits") + .fetch_one(&mut raw) + .await + .unwrap(), + 1 + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_obligation_changes") + .fetch_one(&mut raw) + .await + .unwrap(), + 1 + ); + raw.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn changed_original_backing_before_first_signing_refuses_without_releasing_pending_claims() { + let r = Rig::new().await; + seed(&r, "10").await; + let terms = inspect(&r).await.terms().clone(); + let command = command(&r, 90, false).await; + consent(&r, &command).await; + let initial = prepare(&r, &command).await.unwrap(); + bound(bind(&r, &initial, 42).await.unwrap()); + let recipient = peer(&r, &initial); + retain(&r, &initial, recipient).await; + installed(install(&r, &initial).await.unwrap()); + let command = proposal(&r, &initial, amount(&terms, "5"), false).await; + let amended = prepare_terms(&r, &command).await.unwrap(); + physical(&r,serde_json::json!({"type":"stock.spoil","context":context(&r,91),"input":{"pool_id":pool(80),"expected_version":"4","amount":"6","reason":"loss while replacement remains unissued"}})).await; + assert_eq!( + bind(&r, &amended, 43).await.unwrap_err(), + OperationError::StaleState + ); + balances(&r, 80, 0, 2, 2, 5).await; + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn failed_negative_installation_rolls_back_all_changes_and_retains_original_issued_evidence() +{ + let r = Rig::new().await; + seed(&r, "10").await; + let terms = inspect(&r).await.terms().clone(); + let command = command(&r, 90, false).await; + consent(&r, &command).await; + let initial = prepare(&r, &command).await.unwrap(); + bound(bind(&r, &initial, 42).await.unwrap()); + let recipient = peer(&r, &initial); + retain(&r, &initial, recipient).await; + installed(install(&r, &initial).await.unwrap()); + let command = proposal(&r, &initial, amount(&terms, "1"), false).await; + let amended = prepare_terms(&r, &command).await.unwrap(); + bound(bind(&r, &amended, 43).await.unwrap()); + let evidence = retain(&r, &amended, recipient).await; + let minimum = inventory_minimum(&r).await; + let mut raw = database(&r).await; + sqlx::raw_sql("CREATE TRIGGER fault BEFORE INSERT ON stock_obligation_changes BEGIN SELECT RAISE(ABORT,'synthetic fault'); END").execute(&mut raw).await.unwrap(); + assert_eq!( + install(&r, &amended).await.unwrap_err(), + OperationError::StorageFailure + ); + assert_eq!(inventory_minimum(&r).await, minimum); + balances(&r, 80, 7, 0, 3, 3).await; + sqlx::raw_sql("DROP TRIGGER fault") + .execute(&mut raw) + .await + .unwrap(); + let result = installed(install(&r, &amended).await.unwrap()); + assert_eq!( + result + .publication_work() + .iter() + .find(|work| work.recipient() == recipient) + .unwrap() + .evidence_digest(), + Some(evidence.digest()) + ); + balances(&r, 80, 9, 0, 1, 4).await; + raw.close().await.unwrap(); + r.store.close().await.unwrap(); +} + +#[tokio::test] +async fn changing_an_original_multi_pool_split_requires_explicit_complete_allocation() { + let r = Rig::new().await; + seed(&r, "10").await; + let terms = inspect(&r).await.terms().clone(); + let initial = ready(&r).await; + let recipient = peer(&r, &initial); + retain(&r, &initial, recipient).await; + installed(install(&r, &initial).await.unwrap()); + let command = proposal(&r, &initial, amount(&terms, "5"), false).await; + assert_eq!( + prepare_terms(&r, &command).await.unwrap_err(), + OperationError::UnsupportedOperation + ); + balances(&r, 80, 9, 0, 1, 3).await; + balances(&r, 81, 8, 0, 2, 3).await; + let mut wire: serde_json::Value = serde_json::from_slice(command.protected_wire()).unwrap(); + wire["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([111; 32])); + wire["context"]["approval"] = serde_json::Value::Null; + let line = terms.lines()[0].id(); + wire["input"]["allocation"] = serde_json::json!({"type":"explicit","allocations":[{"line_id":line,"pool_id":pool(80),"quantity":{"amount":"2","unit":"each"},"expected_pool_version":"3"},{"line_id":line,"pool_id":pool(81),"quantity":{"amount":"3","unit":"each"},"expected_pool_version":"3"}]}); + let command = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + wire["context"]["approval"] = serde_json::json!({"intent_digest":command.approval_intent_digest(),"scope":"orders.install_terms","expires_at":"230"}); + let command = CapturedTermsInstallation::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + let amended = prepare_terms(&r, &command).await.unwrap(); + assert_eq!(amended.allocation_count(), 2); + balances(&r, 80, 8, 1, 1, 4).await; + balances(&r, 81, 7, 1, 2, 4).await; + bound(bind(&r, &amended, 43).await.unwrap()); + retain(&r, &amended, recipient).await; + installed(install(&r, &amended).await.unwrap()); + balances(&r, 80, 8, 0, 2, 5).await; + balances(&r, 81, 7, 0, 3, 5).await; + r.store.close().await.unwrap(); +} diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/installation_tests.rs @@ -9,6 +9,8 @@ mod local_history; #[path = "process_death_tests.rs"] mod process_death; use super::*; +#[path = "amendment_tests.rs"] +mod amendments; use crate::workspace::{ StockInstallationOutcome, StockInstallationReceipt, StockInstallationRequest, StockSnapshotRequest, diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/rewrap_tests.rs b/crates/storage_sqlite/src/workspace/stock/public_source/rewrap_tests.rs @@ -34,7 +34,7 @@ async fn additional( proof(r), ) .await; - let admission = if matches!(r.catalog, 18 | 19) { + let admission = if matches!(r.catalog, 18..=20) { let StockRewrapOutcome::Claimed(admission) = admitted.unwrap() else { panic!("fresh confirmed admission required before wrapping") }; diff --git a/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/public_source/transaction.rs @@ -31,7 +31,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !matches!(authority.catalog, 8..=19) || authority.public_sources.is_none() { + if !matches!(authority.catalog, 8..=20) || authority.public_sources.is_none() { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; diff --git a/crates/storage_sqlite/src/workspace/stock/schema.rs b/crates/storage_sqlite/src/workspace/stock/schema.rs @@ -1,7 +1,7 @@ //! Exact stock catalogs. Enrollment-only version1 is retained without upgrade. use super::WorkspaceError; use sqlx::SqliteConnection; -pub(super) const CURRENT: i64 = 19; +pub(super) const CURRENT: i64 = 20; 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"; @@ -32,7 +32,7 @@ pub(super) fn objects( ]; match version { 1 => {} - 2..=19 => objects.extend([ + 2..=20 => objects.extend([ ("table", "stock_pools", "stock_pools", POOLS), ( "table", @@ -97,7 +97,7 @@ pub(super) fn objects( if version >= 5 { objects.push(("table","stock_mappings","stock_mappings","CREATE TABLE stock_mappings (listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), option_id BLOB NOT NULL CHECK(length(option_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144), PRIMARY KEY(listing_author,listing_d,option_id)) STRICT, WITHOUT ROWID")); } - if (6..=19).contains(&version) { + if (6..=20).contains(&version) { objects.push(("table","stock_source_records","stock_source_records","CREATE TABLE stock_source_records (record_id BLOB PRIMARY KEY CHECK(length(record_id)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("table","stock_source_evidence","stock_source_evidence","CREATE TABLE stock_source_evidence (envelope_id BLOB PRIMARY KEY CHECK(length(envelope_id)=32), record_id BLOB REFERENCES stock_source_records(record_id), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_source_transaction_identity","stock_source_evidence","CREATE UNIQUE INDEX stock_source_transaction_identity ON stock_source_evidence(transaction_id)")); @@ -133,7 +133,7 @@ pub(super) fn objects( objects.push(("table","stock_orders","stock_orders","CREATE TABLE stock_orders (order_id BLOB PRIMARY KEY CHECK(length(order_id)=32), revision INTEGER NOT NULL CHECK(revision>0), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); } } - if matches!(version, 8..=19) { + if matches!(version, 8..=20) { objects.push(("table","stock_public_events","stock_public_events","CREATE TABLE stock_public_events (event_id BLOB PRIMARY KEY CHECK(length(event_id)=32), listing_author BLOB NOT NULL CHECK(length(listing_author)=32), listing_d BLOB NOT NULL CHECK(length(listing_d)=16), created_at BLOB NOT NULL CHECK(length(created_at)=8), transaction_id BLOB NOT NULL CHECK(length(transaction_id)=32), revision INTEGER NOT NULL CHECK(revision>0), chain_head BLOB NOT NULL CHECK(length(chain_head)=32), protected BLOB NOT NULL CHECK(length(protected)>0 AND length(protected)<=262144)) STRICT, WITHOUT ROWID")); objects.push(("index","stock_public_transaction_identity","stock_public_events","CREATE UNIQUE INDEX stock_public_transaction_identity ON stock_public_events(transaction_id)")); objects.push(( @@ -226,6 +226,9 @@ pub(super) fn objects( if version >= 19 { objects.push(("table", "stock_deficits", "stock_deficits", "CREATE TABLE stock_deficits (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), acceptance_id BLOB NOT NULL CHECK(length(acceptance_id)=32), installation_id BLOB NOT NULL CHECK(length(installation_id)=32), line_id BLOB NOT NULL CHECK(length(line_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), PRIMARY KEY(actor,operation_id,acceptance_id,line_id), FOREIGN KEY(actor,operation_id) REFERENCES stock_operations(actor,operation_id), FOREIGN KEY(actor,acceptance_id) REFERENCES stock_orders(actor,operation_id), FOREIGN KEY(actor,installation_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); } + if version >= 20 { + objects.push(("table", "stock_obligation_changes", "stock_obligation_changes", "CREATE TABLE stock_obligation_changes (actor BLOB NOT NULL CHECK(length(actor)=32), operation_id BLOB NOT NULL CHECK(length(operation_id)=32), acceptance_id BLOB NOT NULL CHECK(length(acceptance_id)=32), installation_id BLOB NOT NULL CHECK(length(installation_id)=32), line_id BLOB NOT NULL CHECK(length(line_id)=32), pool_id BLOB NOT NULL REFERENCES stock_pools(pool_id), PRIMARY KEY(actor,operation_id,acceptance_id,line_id,pool_id), FOREIGN KEY(actor,operation_id) REFERENCES stock_operations(actor,operation_id), FOREIGN KEY(actor,acceptance_id) REFERENCES stock_orders(actor,operation_id), FOREIGN KEY(actor,installation_id) REFERENCES stock_operations(actor,operation_id)) STRICT, WITHOUT ROWID")); + } Ok(objects) } pub(super) async fn admit(connection: &mut SqliteConnection) -> Result<i64, WorkspaceError> { diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan.rs @@ -148,7 +148,7 @@ pub(in crate::workspace::stock) async fn load( proof: &AttachmentProof, ) -> Result<Authorized, OperationError> { let access = Box::pin(turn.access(binding, minimum, proof)).await?; - if !matches!(access.authority.catalog, 10..=19) { + if !matches!(access.authority.catalog, 10..=20) { return Err(OperationError::UnsupportedOperation); } let original = Box::pin(acceptance::codec::read( @@ -181,13 +181,11 @@ pub(in crate::workspace::stock) async fn load( false, access.current.observed_at(), )?; - for pool in original.receipt.held_pools() { - if !consent.resources.contains(pool.id()) { + for pool in original.affected_pools()? { + if !consent.resources.contains(pool) { return Err(OperationError::Unauthorized); } - access - .record - .require(StockAction::ReadOperations, pool.id())?; + access.record.require(StockAction::ReadOperations, pool)?; } let id: Option<Vec<u8>> = sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE actor=? AND related_operation=? AND family=3 AND length(operation_id)=32") .bind(turn.selected.participant().as_bytes().as_slice()).bind(operation.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_| OperationError::RecoveryRequired)?; @@ -283,6 +281,21 @@ pub(in crate::workspace) async fn bind( auth.plan.ok_or(OperationError::RecoveryRequired)?.bound, ))); } + auth.original + .confirm_replacement_residual( + turn.connection, + turn.selected, + turn.crypto, + auth.access + .authority + .inventory + .ok_or(OperationError::RecoveryRequired)? + .revision + .get() + .checked_add(1) + .ok_or(OperationError::RecoveryRequired)?, + ) + .await?; let current_order = Box::pin(super::order_state::signing_state( turn, &auth.access, @@ -294,7 +307,7 @@ pub(in crate::workspace) async fn bind( let backing = Box::pin(inventory::backing::read( turn, &auth.access, - auth.original.receipt.held_pools(), + &auth.original.affected_pool_snapshots()?, )) .await?; let before = auth diff --git a/crates/storage_sqlite/src/workspace/stock/snapshot.rs b/crates/storage_sqlite/src/workspace/stock/snapshot.rs @@ -338,7 +338,7 @@ async fn read_authorized( .authority .inventory .ok_or(OperationError::RecoveryRequired)?; - let delivery = if matches!(auth.access.authority.catalog, 17..=19) { + let delivery = if matches!(auth.access.authority.catalog, 17..=20) { Some(Box::new( Box::pin(super::delivery::snapshot( turn, diff --git a/crates/storage_sqlite/src/workspace/stock/source/request.rs b/crates/storage_sqlite/src/workspace/stock/source/request.rs @@ -7,6 +7,10 @@ use radroots_domain::{ }; use radroots_storage::workspace::seller_stock::StockListingCheckpointRef; use std::collections::BTreeMap; +mod replacement; +pub(in crate::workspace::stock) use replacement::{ + Selected as ReplacementSource, prepare as prepare_terms, +}; /// Explicit private request/source data under current administrative read access. /// This does not authorize execution or promise a physical hold/agreement. @@ -78,12 +82,13 @@ impl std::fmt::Debug for StockRequestSnapshot { } pub(in crate::workspace::stock) struct Prepared { pub scope: CausalScope, - pub request: RecordId, + pub authorization: RecordId, pub digest: TermsDigest, pub expires: UnixSeconds, pub quote: Option<RecordId>, + pub replacement: Option<radroots_domain::causal::ReplacementTermsSelection>, pub history: history::Prepared, - lookup: checkpoint::Proof, + lookup: Option<checkpoint::Proof>, views: BTreeMap<EnvelopeEventId, super::super::public_source::admission::ListingView>, } fn claim_error(error: RequestClaimError) -> OperationError { @@ -105,10 +110,24 @@ impl Prepared { match self .history .records - .get(&self.request) + .get( + &self + .replacement + .map(|value| value.proposal()) + .unwrap_or(self.authorization), + ) .map(|record| record.content().payload()) { - Some(radroots_domain::CommercePayload::Request(request)) => Ok(request.terms()), + Some(radroots_domain::CommercePayload::Request(request)) + if self.replacement.is_none() => + { + Ok(request.terms()) + } + Some(radroots_domain::CommercePayload::TermsProposed(proposal)) + if self.replacement.is_some() => + { + Ok(proposal.terms()) + } _ => Err(OperationError::RecoveryRequired), } } @@ -120,12 +139,14 @@ impl Prepared { self.views .get(&line.source().event_id()) .ok_or(OperationError::RecoveryRequired)? - .validate(line, self.quote.is_some(), at)?; + .validate(line, self.quote.is_some() || self.replacement.is_some(), at)?; } Ok(()) } pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { - self.lookup.confirm(connection).await?; + if let Some(lookup) = &self.lookup { + lookup.confirm(connection).await?; + } self.history.confirm(connection).await?; for view in self.views.values() { view.confirm(connection).await?; @@ -219,12 +240,13 @@ pub(in crate::workspace::stock) async fn prepare( } Ok(Prepared { scope, - request, + authorization: request, digest, expires, quote, + replacement: None, history, - lookup, + lookup: Some(lookup), views, }) } diff --git a/crates/storage_sqlite/src/workspace/stock/source/request/replacement.rs b/crates/storage_sqlite/src/workspace/stock/source/request/replacement.rs @@ -0,0 +1,126 @@ +//! Complete current local source admission for the selected replacement. +use super::*; +use radroots_domain::causal::{ReplacementTermsError, ReplacementTermsSelection}; +use radroots_protocol::{command::CapturedTermsInstallation, commerce::DecodedRecord}; + +fn error(value: ReplacementTermsError) -> OperationError { + match value { + ReplacementTermsError::MissingHistory => OperationError::MissingHistory, + ReplacementTermsError::Uninterpreted => OperationError::UnsupportedOperation, + ReplacementTermsError::Expired => OperationError::DeadlineExceeded, + ReplacementTermsError::ClockAhead => WorkspaceError::Unavailable.into(), + ReplacementTermsError::Conflicted + | ReplacementTermsError::Withdrawn + | ReplacementTermsError::Rejected + | ReplacementTermsError::ConflictingAuthorizations => OperationError::StaleState, + _ => OperationError::InvalidEvidence, + } +} +pub(in crate::workspace::stock) struct Selected<'a> { + pub command: &'a CapturedTermsInstallation, + pub base: &'a DecodedRecord, +} +pub(in crate::workspace::stock) async fn prepare( + connection: &mut SqliteConnection, + input: &AttachmentInput, + crypto: &WorkspaceCrypto, + inventory_read: history::InventoryRead<'_>, + selected: Selected<'_>, + listing_minimum: StockListingCheckpointRef, + observed_at: UnixSeconds, +) -> Result<Prepared, OperationError> { + let Selected { command, base } = selected; + let expected = command + .context() + .expected() + .ok_or(OperationError::InvalidCommand)?; + let original = base.content().header(); + if expected.agreement() != Some(base.record_id()) + || original.order_id() != Some(expected.order_id()) + { + return Err(OperationError::StaleState); + } + let scope = CausalScope::new( + original.thread_id(), + expected.order_id(), + original.buyer(), + original.seller(), + ) + .map_err(|_| OperationError::InvalidEvidence)?; + let authority = inventory_read.authority; + let history = Box::pin(history::prepare( + connection, + input, + crypto, + inventory_read, + scope, + listing_minimum, + )) + .await?; + let nodes: Vec<_> = history + .records + .iter() + .map(|(id, record)| CausalRecord::new(*id, record.content())) + .collect(); + let selected = ReplacementTermsSelection::new( + base.record_id(), + command.input().proposal(), + command.input().authorization(), + command.input().terms_digest(), + ); + let claim = radroots_domain::causal::prepare_replacement_terms( + scope, + selected, + &nodes, + &history.external, + &history.uninterpreted, + observed_at, + ) + .map_err(error)?; + if history + .records + .get(&base.record_id()) + .is_none_or(|record| record.content() != base.content()) + || claim.base_commitment().seller_sequence() != expected.seller_sequence() + || expected.buyer_head() != history.analysis.buyer_head() + || Some(expected.checkpoint()) != history.checkpoint.as_ref() + { + return Err(OperationError::StaleState); + } + let digest = radroots_protocol::terms::EncodedTerms::capture(claim.terms()) + .map_err(|_| OperationError::InvalidEvidence)? + .digest(); + if digest != selected.terms_digest() { + return Err(OperationError::InvalidEvidence); + } + let expires = claim.expires_at(); + let mut views = BTreeMap::new(); + for line in claim.terms().lines() { + if let std::collections::btree_map::Entry::Vacant(entry) = + views.entry(line.source().event_id()) + { + let view = super::super::super::public_source::admission::prepare( + connection, + input, + crypto, + authority, + line.source(), + observed_at, + ) + .await?; + entry.insert(view); + } + views[&line.source().event_id()].validate(line, true, observed_at)?; + } + Ok(Prepared { + scope, + authorization: selected.authorization(), + digest, + expires, + quote: None, + replacement: Some(selected), + history, + lookup: None, + views, + }) +} diff --git a/crates/storage_sqlite/src/workspace/stock/source/transaction.rs b/crates/storage_sqlite/src/workspace/stock/source/transaction.rs @@ -28,7 +28,7 @@ async fn access( } let (authority, record, root, grant) = super::super::read(turn.connection, binding.input(), turn.crypto).await?; - if !(6..=19).contains(&authority.catalog) { + if !(6..=20).contains(&authority.catalog) { return Err(OperationError::UnsupportedOperation); } let current = record.authenticate(binding.input(), proof, turn.clock.now()?)?; @@ -114,7 +114,7 @@ pub(in crate::workspace) async fn history( proof: AttachmentProof, ) -> Result<StockHistorySnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=19) { + if !matches!(access.authority.catalog, 8..=20) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::history::prepare( @@ -175,7 +175,7 @@ pub(in crate::workspace) async fn inspect_request( proof: AttachmentProof, ) -> Result<StockRequestSnapshot, OperationError> { let access = access(turn, &binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 8..=19) { + if !matches!(access.authority.catalog, 8..=20) { return Err(OperationError::UnsupportedOperation); } let prepared = Box::pin(super::request::prepare( @@ -230,7 +230,7 @@ pub(in crate::workspace) async fn inspect_request( .ok_or(OperationError::RecoveryRequired)?; Ok(StockRequestSnapshot { inventory: prepared.history.inventory, - scope:prepared.scope,request:prepared.request,terms:Box::new(prepared.terms()?.clone()),digest:prepared.digest, + scope:prepared.scope,request:prepared.authorization,terms:Box::new(prepared.terms()?.clone()),digest:prepared.digest, expires:prepared.expires,quote:prepared.quote,checkpoint:prepared.history.checkpoint.clone().ok_or(OperationError::RecoveryRequired)?,observed_at, sources:StockSourceCheckpointRef::from_host_metadata(turn.selected.authority(),private.revision,private.head)?.with_optional_authorization(access.authority.authorization), listings:radroots_storage::workspace::seller_stock::StockListingCheckpointRef::from_host_metadata(turn.selected.authority(),public.revision,public.head)?.with_optional_authorization(access.authority.authorization), diff --git a/crates/storage_sqlite/src/workspace/stock/tests.rs b/crates/storage_sqlite/src/workspace/stock/tests.rs @@ -20,6 +20,7 @@ pub(in crate::workspace::stock) fn catalog_authority_schema(catalog: i64) -> &'s 17 => "radroots.seller_stock.authority.v17", 18 => "radroots.seller_stock.authority.v18", 19 => "radroots.seller_stock.authority.v19", + 20 => "radroots.seller_stock.authority.v20", _ => panic!("unsupported private stock fixture catalog"), } } @@ -301,7 +302,7 @@ async fn retained_v10_preserves_prior_families_and_signing_plan_retention() { } #[tokio::test] async fn retained_v11_preserves_prior_families_and_adds_claims_and_obtained_evidence() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(11).await; } // Exact catalog fixtures exercise retained/successor codecs; they are not @@ -346,7 +347,7 @@ pub(in crate::workspace::stock) async fn literal_enrollment_catalog( catalog: i64, enrollment: &StockEnrollment, ) { - assert!(matches!(catalog, 13..=18)); + assert!(matches!(catalog, 13..=19)); let record = enrollment.record.lock().unwrap().take().unwrap(); literal_catalog_contents( fixture, @@ -405,7 +406,7 @@ async fn literal_catalog_contents( if catalog >= 7 { value["inventory"]["orders"] = serde_json::json!("0"); } - if matches!(catalog, 8..=18) { + if matches!(catalog, 8..=19) { value["public_sources"] = serde_json::json!({"revision":"0","events":"0","heads":"0","parts":"0","head":null}); } @@ -456,6 +457,7 @@ async fn literal_catalog_contents( 16 => "PRAGMA user_version=16", 17 => "PRAGMA user_version=17", 18 => "PRAGMA user_version=18", + 19 => "PRAGMA user_version=19", _ => unreachable!(), }) .execute(&mut *tx) @@ -999,42 +1001,80 @@ async fn retained_enrollment_v1_authenticates_but_never_auto_creates_inventory() #[tokio::test] async fn retained_v12_preserves_initial_installation_catalog_without_upgrade() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(12).await; } #[tokio::test] async fn retained_v13_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(13).await; } #[tokio::test] async fn retained_v14_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(14).await; } #[tokio::test] async fn retained_v15_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(15).await; } #[tokio::test] async fn retained_v16_authenticates_literal_catalog_and_original_inventory_records() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(16).await; } #[tokio::test] async fn retained_v17_authenticates_original_delivery_catalog_without_upgrade() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(17).await; } #[tokio::test] async fn retained_v18_authenticates_original_rewrap_catalog_without_upgrade() { - assert_eq!(schema::CURRENT, 19); + assert_eq!(schema::CURRENT, 20); retained_inventory_catalog(18).await; } + +#[tokio::test] +async fn retained_v19_preserves_deficit_catalog_without_obligation_transition_table_or_upgrade() { + assert_eq!(schema::CURRENT, 20); + let fixture = CryptoFixture::new(); + let path = fixture.root().join("retained19"); + let (input, proof) = literal_catalog(&fixture, &path, 19).await; + let store = + NativeWorkspace::open_seller_stock(&path, input.clone(), fixture.crypto(), Arc::new(Clock)) + .await + .unwrap(); + let binding = store.authenticate(input.clone(), &proof).await.unwrap(); + assert_eq!(binding.actor().participant(), input.participant()); + store.close().await.unwrap(); + let mut raw = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new().filename(path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + assert_eq!( + sqlx::query_scalar::<_, i64>("PRAGMA user_version") + .fetch_one(&mut raw) + .await + .unwrap(), + 19 + ); + assert_eq!( + sqlx::query_scalar::<_, i64>( + "SELECT count(*) FROM sqlite_schema WHERE type='table' AND name='stock_deficits'" + ) + .fetch_one(&mut raw) + .await + .unwrap(), + 1 + ); + assert_eq!(sqlx::query_scalar::<_,i64>("SELECT count(*) FROM sqlite_schema WHERE type='table' AND name='stock_obligation_changes'").fetch_one(&mut raw).await.unwrap(),0); + raw.close().await.unwrap(); +} diff --git a/tools/xtask/src/architecture/decision_package.rs b/tools/xtask/src/architecture/decision_package.rs @@ -44,6 +44,7 @@ struct Policy { #[serde(deny_unknown_fields)] struct StockAccounting { replacement_terms_admission: ReplacementTermsAdmission, + native_terms_installation: NativeTermsInstallation, native_inspection: NativeInspection, value_owner: String, scope: String, @@ -73,6 +74,31 @@ struct ReplacementTermsAdmission { #[derive(Deserialize)] #[serde(deny_unknown_fields)] +struct NativeTermsInstallation { + catalog: u8, + facade_method: String, + execution_method: String, + source_owner: String, + allocation_owner: String, + delta_owner: String, + current_installed_base_required: bool, + original_allocations_required: bool, + positive_hold_phase: String, + negative_release_phase: String, + pending_negatives_finance_holds: bool, + old_commitment_retained_while_pending: bool, + changed_residual_requires_new_admission: bool, + release_composition: String, + quantity_storage: String, + index_plaintext_quantities: bool, + automatic_changed_multi_pool_split: String, + same_signing_and_recovery_owner: bool, + unknown_issuance_releases_stock: bool, + retained_catalog_auto_upgrade: bool, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] struct NativeCorrection { catalog: u8, selection: String, @@ -791,12 +817,36 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && !replacement.claim_creates_stock_effects, "replacement claim/native authority boundary policy drift", )?; + let terms = &accounting.native_terms_installation; + require( + terms.catalog == 20 + && terms.facade_method == "Orders.install_terms" + && terms.execution_method == "ClientSession.install_stock_terms" + && terms.source_owner == "radroots_domain.causal.prepare_replacement_terms" + && terms.allocation_owner == "radroots_domain.stock.resolve_replacement_allocations" + && terms.delta_owner == "radroots_domain.stock.plan_replacement_allocations" + && terms.current_installed_base_required + && terms.original_allocations_required + && terms.positive_hold_phase == "T0" + && terms.negative_release_phase == "T2" + && !terms.pending_negatives_finance_holds + && terms.old_commitment_retained_while_pending + && terms.changed_residual_requires_new_admission + && terms.release_composition == "original_installation_order_deficit_then_backed" + && terms.quantity_storage == "protected_installation_body" + && !terms.index_plaintext_quantities + && terms.automatic_changed_multi_pool_split == "requires_explicit_complete_allocation" + && terms.same_signing_and_recovery_owner + && !terms.unknown_issuance_releases_stock + && !terms.retained_catalog_auto_upgrade, + "native replacement ownership, residual or stock phase policy drift", + )?; let inspection = &accounting.native_inspection; require( inspection.model_owner == "radroots_storage.inventory.StockSnapshot" && inspection.facade_method == "Stock.inspect" && inspection.storage_port == "InventoryStore.inspect_stock" - && inspection.supported_catalogs == [19] + && inspection.supported_catalogs == [19, 20] && inspection.worker_charge_bytes == 1048576 && inspection.same_checkpoint_required && inspection.original_allocation_required @@ -808,7 +858,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { )?; let correction = &accounting.native_correction; require( - correction.catalog == 19 + correction.catalog == 20 && correction.selection == "available_then_original_installation_and_allocation_order" && correction.max_affected_allocations == 32 && correction.protected_original_allocation_required @@ -859,7 +909,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { envelope.journal_family == 10 && envelope.payload_version == 1 && envelope.payload_prefix_bytes == 213 - && envelope.supported_catalogs == [16, 17, 18, 19] + && envelope.supported_catalogs == [16, 17, 18, 19, 20] && envelope.retained_unsupported_catalogs == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] && envelope.raw_max_bytes == 65536 @@ -907,7 +957,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && !rewrap.ordinary_status_is_atomic_absence_proof && rewrap.payload_version == 1 && rewrap.payload_prefix_bytes == 117 - && rewrap.supported_catalogs == [18, 19] + && rewrap.supported_catalogs == [18, 19, 20] && rewrap.retained_unsupported_catalogs == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] && rewrap.raw_max_bytes == 65536 @@ -935,7 +985,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { )?; let delivery = &stock.delivery; require( - delivery.supported_catalogs == [17, 18, 19] + delivery.supported_catalogs == [17, 18, 19, 20] && delivery.retained_unsupported_catalogs == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] && delivery.attempt_journal_family == 11 @@ -995,11 +1045,13 @@ 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 == 19 + && stock.schema_version == 20 && stock.retained_enrollment_versions == [1] && stock.retained_inventory_versions - == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] - && stock.authority_payload_schema == "radroots.seller_stock.authority.v19" + == [ + 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + ] + && stock.authority_payload_schema == "radroots.seller_stock.authority.v20" && stock.public_source_payload_schemas == [ "radroots.seller_stock.public_source_event.v1", @@ -1278,7 +1330,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.qualified_local_recovery.native_authorizer == "NativeWorkspace.authorize_stock_exact_replay" && stock.qualified_local_recovery.captured_replay == "local_replay_safe" - && stock.qualified_local_recovery.native_catalog == 19 + && stock.qualified_local_recovery.native_catalog == 20 && stock.qualified_local_recovery.worker_charge_bytes == 1048576 && stock .qualified_local_recovery @@ -1341,7 +1393,7 @@ fn validate_bytes(raw: &[u8]) -> Result<(), String> { && stock.preparation_abort.unsupported_hosts_return == "capability_unavailable" && stock.preparation_abort.retained_payload_versions == [1] && stock.preparation_abort.retained_v1_requires_absent_claims - && stock.preparation_abort.claimed_cleanup_catalogs == [15, 16, 17, 18, 19] + && stock.preparation_abort.claimed_cleanup_catalogs == [15, 16, 17, 18, 19, 20] && stock.preparation_abort.untracked_claimed_catalogs == [13, 14] && stock.preparation_abort.per_recipient_proof_count == 2 && stock @@ -1925,6 +1977,39 @@ mod tests { } #[test] + fn native_terms_require_original_state_and_separate_stock_effect_phases() { + for (field, value) in [ + ("catalog", json!(19)), + ("facade_method", json!("another_executor")), + ("source_owner", json!("captured_metadata")), + ("current_installed_base_required", json!(false)), + ("original_allocations_required", json!(false)), + ("positive_hold_phase", json!("T2")), + ("negative_release_phase", json!("T0")), + ("pending_negatives_finance_holds", json!(true)), + ("old_commitment_retained_while_pending", json!(false)), + ("changed_residual_requires_new_admission", json!(false)), + ("quantity_storage", json!("plaintext_index")), + ("index_plaintext_quantities", json!(true)), + ( + "automatic_changed_multi_pool_split", + json!("current_mapping"), + ), + ("same_signing_and_recovery_owner", json!(false)), + ("unknown_issuance_releases_stock", json!(true)), + ("retained_catalog_auto_upgrade", json!(true)), + ] { + assert!( + validate_bytes(&changed( + &format!("/stock_accounting/native_terms_installation/{field}"), + value + )) + .is_err(), + "{field}" + ); + } + } + #[test] fn native_corrections_require_original_allocations_and_atomic_deficits() { for (field, value) in [ ("catalog", json!(18)),