commit ffb204d4797d5403b90dd42a84dcc7274f2e0edd parent 7d3683c0c6da11feb7153c241a6a793e1c7227f0 Author: triesap <tyson@radroots.org> Date: Fri, 30 Oct 2026 02:17:14 +0000 protocol: capture exact replacement commitment commands - Bind proposal, authorization, complete terms and allocation to displayed intent - Share the closed commitment capture through the existing stock pipeline - Refuse replacement effects and consent in retained initial-only formats - Verify independent vectors, native refusal and installation, portability and APIs Diffstat:
17 files changed, 941 insertions(+), 46 deletions(-)
diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -175,6 +175,26 @@ impl core::convert::From<radroots_protocol::command::CapturedPoolCreation> for r pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedPoolCreation) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedInventoryCommand pub fn radroots_protocol::command::CapturedInventoryCommand::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_protocol::command::CapturedStockCommitment +pub radroots_protocol::command::CapturedStockCommitment::Acceptance(radroots_protocol::command::CapturedOrderAcceptance) +pub radroots_protocol::command::CapturedStockCommitment::TermsInstallation(radroots_protocol::command::CapturedTermsInstallation) +impl radroots_protocol::command::CapturedStockCommitment +pub const fn radroots_protocol::command::CapturedStockCommitment::allocation(&self) -> &radroots_protocol::command::AllocationSelection +pub const fn radroots_protocol::command::CapturedStockCommitment::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub const fn radroots_protocol::command::CapturedStockCommitment::authorization(&self) -> radroots_domain::identifier::RecordId +pub const fn radroots_protocol::command::CapturedStockCommitment::command_name(&self) -> &'static str +pub const fn radroots_protocol::command::CapturedStockCommitment::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedStockCommitment::digest(&self) -> radroots_domain::identifier::CommandDigest +pub fn radroots_protocol::command::CapturedStockCommitment::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::CapturedStockCommitment::proposal(&self) -> core::option::Option<radroots_domain::identifier::RecordId> +pub fn radroots_protocol::command::CapturedStockCommitment::protected_wire(&self) -> &[u8] +pub const fn radroots_protocol::command::CapturedStockCommitment::terms_digest(&self) -> radroots_domain::identifier::TermsDigest +impl core::convert::From<radroots_protocol::command::CapturedOrderAcceptance> for radroots_protocol::command::CapturedStockCommitment +pub fn radroots_protocol::command::CapturedStockCommitment::from(radroots_protocol::command::CapturedOrderAcceptance) -> Self +impl core::convert::From<radroots_protocol::command::CapturedTermsInstallation> for radroots_protocol::command::CapturedStockCommitment +pub fn radroots_protocol::command::CapturedStockCommitment::from(radroots_protocol::command::CapturedTermsInstallation) -> Self +impl core::fmt::Debug for radroots_protocol::command::CapturedStockCommitment +pub fn radroots_protocol::command::CapturedStockCommitment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub enum radroots_protocol::command::ChatKind pub radroots_protocol::command::ChatKind::Inquire pub radroots_protocol::command::ChatKind::Reply @@ -269,6 +289,8 @@ pub const fn radroots_protocol::command::CapturedOrderAcceptance::input(&self) - pub fn radroots_protocol::command::CapturedOrderAcceptance::new(radroots_domain::context::CommandContextData, radroots_protocol::command::AcceptOrderInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> pub fn radroots_protocol::command::CapturedOrderAcceptance::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> pub fn radroots_protocol::command::CapturedOrderAcceptance::protected_wire(&self) -> &[u8] +impl core::convert::From<radroots_protocol::command::CapturedOrderAcceptance> for radroots_protocol::command::CapturedStockCommitment +pub fn radroots_protocol::command::CapturedStockCommitment::from(radroots_protocol::command::CapturedOrderAcceptance) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedOrderAcceptance pub fn radroots_protocol::command::CapturedOrderAcceptance::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::CapturedPoolCorrection @@ -297,6 +319,19 @@ impl core::convert::From<radroots_protocol::command::CapturedPoolCreation> for r pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedPoolCreation) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedPoolCreation pub fn radroots_protocol::command::CapturedPoolCreation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::command::CapturedTermsInstallation +impl radroots_protocol::command::CapturedTermsInstallation +pub const fn radroots_protocol::command::CapturedTermsInstallation::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub const fn radroots_protocol::command::CapturedTermsInstallation::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedTermsInstallation::digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::command::CapturedTermsInstallation::input(&self) -> &radroots_protocol::command::InstallTermsInput +pub fn radroots_protocol::command::CapturedTermsInstallation::new(radroots_domain::context::CommandContextData, radroots_protocol::command::InstallTermsInput) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::CapturedTermsInstallation::parse(&[u8]) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::CapturedTermsInstallation::protected_wire(&self) -> &[u8] +impl core::convert::From<radroots_protocol::command::CapturedTermsInstallation> for radroots_protocol::command::CapturedStockCommitment +pub fn radroots_protocol::command::CapturedStockCommitment::from(radroots_protocol::command::CapturedTermsInstallation) -> Self +impl core::fmt::Debug for radroots_protocol::command::CapturedTermsInstallation +pub fn radroots_protocol::command::CapturedTermsInstallation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::CreatePoolInput impl radroots_protocol::command::CreatePoolInput pub const fn radroots_protocol::command::CreatePoolInput::id(&self) -> radroots_domain::identifier::PoolId @@ -316,6 +351,15 @@ pub fn radroots_protocol::command::InquireInput::text(&self) -> &str pub const fn radroots_protocol::command::InquireInput::thread_id(&self) -> radroots_domain::identifier::ThreadId impl core::fmt::Debug for radroots_protocol::command::InquireInput pub fn radroots_protocol::command::InquireInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::command::InstallTermsInput +impl radroots_protocol::command::InstallTermsInput +pub const fn radroots_protocol::command::InstallTermsInput::allocation(&self) -> &radroots_protocol::command::AllocationSelection +pub const fn radroots_protocol::command::InstallTermsInput::authorization(&self) -> radroots_domain::identifier::RecordId +pub const fn radroots_protocol::command::InstallTermsInput::new(radroots_domain::identifier::RecordId, radroots_domain::identifier::RecordId, radroots_domain::identifier::TermsDigest, radroots_protocol::command::AllocationSelection) -> Self +pub const fn radroots_protocol::command::InstallTermsInput::proposal(&self) -> radroots_domain::identifier::RecordId +pub const fn radroots_protocol::command::InstallTermsInput::terms_digest(&self) -> radroots_domain::identifier::TermsDigest +impl core::fmt::Debug for radroots_protocol::command::InstallTermsInput +pub fn radroots_protocol::command::InstallTermsInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_protocol::command::ListingRevisionRef impl radroots_protocol::command::ListingRevisionRef pub const fn radroots_protocol::command::ListingRevisionRef::author(&self) -> radroots_identity::key::PublicKey diff --git a/contracts/api_baselines/radroots_storage.txt b/contracts/api_baselines/radroots_storage.txt @@ -1471,6 +1471,7 @@ pub struct radroots_storage::inventory::StockAcceptanceReceipt impl radroots_storage::inventory::StockAcceptanceReceipt pub const fn radroots_storage::inventory::StockAcceptanceReceipt::allocation_count(&self) -> usize pub const fn radroots_storage::inventory::StockAcceptanceReceipt::attempt(&self) -> radroots_storage::command::CommitAttempt +pub const fn radroots_storage::inventory::StockAcceptanceReceipt::authorization(&self) -> radroots_domain::identifier::RecordId pub const fn radroots_storage::inventory::StockAcceptanceReceipt::checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef pub const fn radroots_storage::inventory::StockAcceptanceReceipt::first_issue_deadline(&self) -> radroots_domain::context::UnixSeconds pub fn radroots_storage::inventory::StockAcceptanceReceipt::from_committed_store(&radroots_storage::workspace::AttachmentInput, radroots_storage::command::CommitAttempt, radroots_domain::identifier::OrderId, radroots_domain::identifier::RecordId, radroots_domain::identifier::TermsDigest, radroots_storage::inventory::InventoryCheckpointRef, alloc::vec::Vec<radroots_domain::stock::PoolSnapshot>, usize, radroots_domain::issuance::IssuanceWindow, radroots_protocol::commerce::rumor::EncodedCommerceRumor) -> core::result::Result<Self, radroots_storage::command::OperationError> @@ -1478,7 +1479,6 @@ pub fn radroots_storage::inventory::StockAcceptanceReceipt::held_pools(&self) -> pub fn radroots_storage::inventory::StockAcceptanceReceipt::into_held_pools(self) -> alloc::vec::Vec<radroots_domain::stock::PoolSnapshot> pub const fn radroots_storage::inventory::StockAcceptanceReceipt::order_id(&self) -> radroots_domain::identifier::OrderId pub const fn radroots_storage::inventory::StockAcceptanceReceipt::prepared_at(&self) -> radroots_domain::context::UnixSeconds -pub const fn radroots_storage::inventory::StockAcceptanceReceipt::request(&self) -> radroots_domain::identifier::RecordId pub fn radroots_storage::inventory::StockAcceptanceReceipt::rumor(&self) -> &radroots_protocol::commerce::rumor::EncodedCommerceRumor pub const fn radroots_storage::inventory::StockAcceptanceReceipt::terms_digest(&self) -> radroots_domain::identifier::TermsDigest impl core::fmt::Debug for radroots_storage::inventory::StockAcceptanceReceipt @@ -1488,7 +1488,8 @@ impl radroots_storage::inventory::StockAcceptanceRequest pub fn radroots_storage::inventory::StockAcceptanceRequest::attempt(&self) -> radroots_storage::command::CommitAttempt pub const fn radroots_storage::inventory::StockAcceptanceRequest::binding(&self) -> &radroots_storage::workspace::WorkspaceBinding pub fn radroots_storage::inventory::StockAcceptanceRequest::capture(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::StockListingCheckpointRef, &radroots_protocol::command::order_acceptance::CapturedOrderAcceptance) -> core::result::Result<Self, radroots_storage::command::OperationError> -pub const fn radroots_storage::inventory::StockAcceptanceRequest::command(&self) -> &radroots_protocol::command::order_acceptance::CapturedOrderAcceptance +pub fn radroots_storage::inventory::StockAcceptanceRequest::capture_terms(radroots_storage::workspace::WorkspaceBinding, radroots_storage::inventory::InventoryCheckpointRef, radroots_storage::workspace::seller_stock::StockSourceCheckpointRef, radroots_storage::workspace::seller_stock::StockListingCheckpointRef, &radroots_protocol::command::order_terms::CapturedTermsInstallation) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub const fn radroots_storage::inventory::StockAcceptanceRequest::command(&self) -> &radroots_protocol::command::stock_commitment::CapturedStockCommitment pub const fn radroots_storage::inventory::StockAcceptanceRequest::listing_checkpoint(&self) -> radroots_storage::workspace::seller_stock::StockListingCheckpointRef pub const fn radroots_storage::inventory::StockAcceptanceRequest::minimum_checkpoint(&self) -> radroots_storage::inventory::InventoryCheckpointRef pub const fn radroots_storage::inventory::StockAcceptanceRequest::source_checkpoint(&self) -> radroots_storage::workspace::seller_stock::StockSourceCheckpointRef diff --git a/contracts/api_baselines/radroots_storage_sqlite.txt b/contracts/api_baselines/radroots_storage_sqlite.txt @@ -561,11 +561,11 @@ impl core::fmt::Debug for radroots_storage_sqlite::workspace::StockClaimRequest pub fn radroots_storage_sqlite::workspace::StockClaimRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_storage_sqlite::workspace::StockConsentCapture impl radroots_storage_sqlite::workspace::StockConsentCapture -pub fn radroots_storage_sqlite::workspace::StockConsentCapture::command(&self) -> &radroots_protocol::command::order_acceptance::CapturedOrderAcceptance +pub fn radroots_storage_sqlite::workspace::StockConsentCapture::command(&self) -> &radroots_protocol::command::stock_commitment::CapturedStockCommitment pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::control_operation_id(&self) -> radroots_domain::identifier::OperationId pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::expires_at(&self) -> radroots_domain::context::UnixSeconds pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::mode(&self) -> radroots_storage_sqlite::workspace::StockConsentMode -pub fn radroots_storage_sqlite::workspace::StockConsentCapture::prepare(radroots_storage::workspace::seller_stock::selection::SellerAuthoritySelection, radroots_domain::identifier::GrantId, radroots_storage_sqlite::workspace::StockConsentMode, radroots_storage::workspace::seller_stock::permissions::StockResources, radroots_domain::context::UnixSeconds, radroots_protocol::command::order_acceptance::CapturedOrderAcceptance) -> core::result::Result<Self, radroots_storage::command::OperationError> +pub fn radroots_storage_sqlite::workspace::StockConsentCapture::prepare(radroots_storage::workspace::seller_stock::selection::SellerAuthoritySelection, radroots_domain::identifier::GrantId, radroots_storage_sqlite::workspace::StockConsentMode, radroots_storage::workspace::seller_stock::permissions::StockResources, radroots_domain::context::UnixSeconds, impl core::convert::Into<radroots_protocol::command::stock_commitment::CapturedStockCommitment>) -> core::result::Result<Self, radroots_storage::command::OperationError> pub fn radroots_storage_sqlite::workspace::StockConsentCapture::resources(&self) -> &radroots_storage::workspace::seller_stock::permissions::StockResources pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::subject_grant(&self) -> radroots_domain::identifier::GrantId pub const fn radroots_storage_sqlite::workspace::StockConsentCapture::transaction_id(&self) -> radroots_domain::identifier::TransactionId diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs @@ -59,7 +59,11 @@ pub use inventory::{CapturedInventoryCommand, InventoryCommandKind}; pub use order_acceptance::{ AcceptOrderInput, AllocationInput, AllocationSelection, CapturedOrderAcceptance, }; +mod order_terms; +pub use order_terms::{CapturedTermsInstallation, InstallTermsInput}; +mod stock_commitment; pub use stock::{CapturedPoolCreation, CreatePoolInput}; +pub use stock_commitment::CapturedStockCommitment; pub use stock_correction::{CapturedPoolCorrection, PoolCorrectionInput}; pub use stock_mapping::{CapturedOptionMapping, MapOptionInput}; diff --git a/crates/protocol/src/command/order_acceptance.rs b/crates/protocol/src/command/order_acceptance.rs @@ -242,7 +242,7 @@ struct AllocationWire { quantity: Quantity, expected_pool_version: Sequence, } -fn parse_selection(raw: &[u8]) -> Result<AllocationSelection, CommandError> { +pub(super) fn parse_selection(raw: &[u8]) -> Result<AllocationSelection, CommandError> { #[derive(Deserialize)] struct Probe { #[serde(rename = "type")] diff --git a/crates/protocol/src/command/order_terms.rs b/crates/protocol/src/command/order_terms.rs @@ -0,0 +1,201 @@ +//! Exact `orders.install_terms` capture. Data capture supplies no source, +//! consent, current agreement/residual, stock effect or signing permission. +use super::{ + AllocationSelection, COMMAND_MAX_BYTES, CommandError, Context, check_frame, hash, + order_acceptance::parse_selection, parse_object, +}; +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::fmt; +use radroots_domain::{ + ActorRole, ApprovalIntentDigest, CommandContextData, CommandDigest, RecordId, TermsDigest, +}; +use serde::{Deserialize, Serialize, ser::SerializeStruct}; +use serde_json::value::RawValue; +use zeroize::Zeroizing; + +/// Complete proposal/authorization selectors and allocation claims. The +/// executor independently authenticates their terms, base and current state. +pub struct InstallTermsInput { + proposal: RecordId, + authorization: RecordId, + terms: TermsDigest, + allocation: AllocationSelection, +} +impl InstallTermsInput { + /// Captures data only; both records and the actual digest remain unverified. + pub const fn new( + proposal: RecordId, + authorization: RecordId, + terms: TermsDigest, + allocation: AllocationSelection, + ) -> Self { + Self { + proposal, + authorization, + terms, + allocation, + } + } + /// Exact selected complete proposal. + pub const fn proposal(&self) -> RecordId { + self.proposal + } + /// Exact selected counterparty authorization. + pub const fn authorization(&self) -> RecordId { + self.authorization + } + /// Expected complete canonical terms digest, not a hash proof. + pub const fn terms_digest(&self) -> TermsDigest { + self.terms + } + /// Automatic resolution or explicit bounded allocation claims. + pub const fn allocation(&self) -> &AllocationSelection { + &self.allocation + } +} +impl fmt::Debug for InstallTermsInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("InstallTermsInput(<redacted>)") + } +} + +/// Closed normalized `orders.install_terms` data and separately domain-bound +/// command/approval digests. Construction grants no execution or stock right. +pub struct CapturedTermsInstallation { + context: CommandContextData, + input: InstallTermsInput, + wire: Zeroizing<Box<[u8]>>, + digest: CommandDigest, + approval: ApprovalIntentDigest, +} +impl CapturedTermsInstallation { + /// Requires seller and explicit order descriptors. Approval may be absent + /// while obtaining consent; actual approval verification belongs to T0. + pub fn new( + context: CommandContextData, + input: InstallTermsInput, + ) -> Result<Self, CommandError> { + if context.actor().role() != ActorRole::Seller || context.expected().is_none() { + return Err(CommandError::InvalidInput); + } + let encode = |approval, correlation| -> Result<Zeroizing<Vec<u8>>, CommandError> { + let bytes = Zeroizing::new( + serde_json::to_vec(&Wire { + context: &context, + input: &input, + approval, + correlation, + }) + .map_err(|_| CommandError::InvalidInput)?, + ); + if bytes.len() > COMMAND_MAX_BYTES { + return Err(CommandError::LimitExceeded); + } + Ok(bytes) + }; + let wire = Zeroizing::new(encode(true, true)?.to_vec().into_boxed_slice()); + let digest = + CommandDigest::from_bytes(hash(b"radroots.command.v1\0", &encode(true, false)?)); + let approval = ApprovalIntentDigest::from_bytes(hash( + b"radroots.approval.v1\0", + &encode(false, false)?, + )); + Ok(Self { + context, + input, + wire, + digest, + approval, + }) + } + /// Parses only the bounded exact command/context/input shape, without IO. + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Root<'a> { + #[serde(rename = "type")] + kind: String, + context: CommandContextData, + #[serde(borrow)] + input: &'a RawValue, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Input<'a> { + proposal: RecordId, + authorization: RecordId, + terms_digest: TermsDigest, + #[serde(borrow)] + allocation: &'a RawValue, + } + let root: Root<'_> = parse_object(raw)?; + if root.kind != "orders.install_terms" { + return Err(CommandError::UnsupportedCommand); + } + let input: Input<'_> = parse_object(root.input.get().as_bytes())?; + Self::new( + root.context, + InstallTermsInput::new( + input.proposal, + input.authorization, + input.terms_digest, + parse_selection(input.allocation.get().as_bytes())?, + ), + ) + } + /// Captured context descriptors, not current native authority. + pub const fn context(&self) -> &CommandContextData { + &self.context + } + /// Exact selected source and allocation claims. + pub const fn input(&self) -> &InstallTermsInput { + &self.input + } + /// Bounded protected normalized command bytes, including correlation. + pub fn protected_wire(&self) -> &[u8] { + &self.wire + } + /// Command digest includes approval and excludes observer correlation. + pub const fn digest(&self) -> CommandDigest { + self.digest + } + /// Intent digest excludes approval and observer correlation. + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + self.approval + } +} +impl fmt::Debug for CapturedTermsInstallation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedTermsInstallation(<redacted>)") + } +} +struct Wire<'a> { + context: &'a CommandContextData, + input: &'a InstallTermsInput, + approval: bool, + correlation: bool, +} +impl Serialize for Wire<'_> { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut out = serializer.serialize_struct("TermsInstallation", 3)?; + out.serialize_field( + "context", + &Context(self.context, self.approval, self.correlation), + )?; + out.serialize_field("input", &InputWire(self.input))?; + out.serialize_field("type", "orders.install_terms")?; + out.end() + } +} +struct InputWire<'a>(&'a InstallTermsInput); +impl Serialize for InputWire<'_> { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + let mut out = serializer.serialize_struct("InstallTermsInput", 4)?; + out.serialize_field("allocation", &self.0.allocation)?; + out.serialize_field("authorization", &self.0.authorization)?; + out.serialize_field("proposal", &self.0.proposal)?; + out.serialize_field("terms_digest", &self.0.terms)?; + out.end() + } +} diff --git a/crates/protocol/src/command/stock_commitment.rs b/crates/protocol/src/command/stock_commitment.rs @@ -0,0 +1,117 @@ +//! Closed common capture for the one stock commitment execution pipeline. +use super::{ + AllocationSelection, CapturedOrderAcceptance, CapturedTermsInstallation, CommandError, + check_frame, parse_object, +}; +use alloc::string::String; +use core::fmt; +use radroots_domain::{ + ApprovalIntentDigest, CommandContextData, CommandDigest, RecordId, TermsDigest, +}; +use serde::Deserialize; + +/// Exact known stock commitment commands. These are captured data, never +/// execution, signing, consent, installed-state or allocation capabilities. +pub enum CapturedStockCommitment { + /// Initial buyer-request acceptance. + Acceptance(CapturedOrderAcceptance), + /// Installation of exact mutually authorized complete proposed terms. + TermsInstallation(CapturedTermsInstallation), +} +impl From<CapturedOrderAcceptance> for CapturedStockCommitment { + fn from(value: CapturedOrderAcceptance) -> Self { + Self::Acceptance(value) + } +} +impl From<CapturedTermsInstallation> for CapturedStockCommitment { + fn from(value: CapturedTermsInstallation) -> Self { + Self::TermsInstallation(value) + } +} +impl CapturedStockCommitment { + /// Dispatches only to the corresponding exact bounded closed parser. + pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { + check_frame(raw)?; + #[derive(Deserialize)] + struct Probe { + #[serde(rename = "type")] + kind: String, + } + let probe: Probe = parse_object(raw)?; + match probe.kind.as_str() { + "orders.accept" => CapturedOrderAcceptance::parse(raw).map(Self::Acceptance), + "orders.install_terms" => { + CapturedTermsInstallation::parse(raw).map(Self::TermsInstallation) + } + _ => Err(CommandError::UnsupportedCommand), + } + } + /// Exact command scope; not proof that its approval is genuine/current. + pub const fn command_name(&self) -> &'static str { + match self { + Self::Acceptance(_) => "orders.accept", + Self::TermsInstallation(_) => "orders.install_terms", + } + } + /// Captured context data; current authority must be independently checked. + pub const fn context(&self) -> &CommandContextData { + match self { + Self::Acceptance(value) => value.context(), + Self::TermsInstallation(value) => value.context(), + } + } + /// Exact normalized protected command bytes. + pub fn protected_wire(&self) -> &[u8] { + match self { + Self::Acceptance(value) => value.protected_wire(), + Self::TermsInstallation(value) => value.protected_wire(), + } + } + /// Command identity bound to its exact semantic input and approval. + pub const fn digest(&self) -> CommandDigest { + match self { + Self::Acceptance(value) => value.digest(), + Self::TermsInstallation(value) => value.digest(), + } + } + /// Displayed intent identity before approval and observer correlation. + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + match self { + Self::Acceptance(value) => value.approval_intent_digest(), + Self::TermsInstallation(value) => value.approval_intent_digest(), + } + } + /// Exact buyer request or terms authorization selected by this command. + pub const fn authorization(&self) -> RecordId { + match self { + Self::Acceptance(value) => value.input().request(), + Self::TermsInstallation(value) => value.input().authorization(), + } + } + /// Exact proposal when the command installs mutually authorized terms. + pub const fn proposal(&self) -> Option<RecordId> { + match self { + Self::Acceptance(_) => None, + Self::TermsInstallation(value) => Some(value.input().proposal()), + } + } + /// Expected complete terms digest; source recomputation belongs to execution. + pub const fn terms_digest(&self) -> TermsDigest { + match self { + Self::Acceptance(value) => value.input().terms_digest(), + Self::TermsInstallation(value) => value.input().terms_digest(), + } + } + /// Bounded allocation selection data for native planning. + pub const fn allocation(&self) -> &AllocationSelection { + match self { + Self::Acceptance(value) => value.input().allocation(), + Self::TermsInstallation(value) => value.input().allocation(), + } + } +} +impl fmt::Debug for CapturedStockCommitment { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedStockCommitment(<redacted>)") + } +} diff --git a/crates/protocol/tests/fixtures/terms_installation.v1.json b/crates/protocol/tests/fixtures/terms_installation.v1.json @@ -0,0 +1,128 @@ +{ + "schema": "radroots.terms_installation_commands.v1", + "provenance": "Synthetic command inputs; independent ECMAScript ASCII-key canonicalization and Node SHA-256. No Rust writer or actual authority is used.", + "producer": "Node.js 26.10.0", + "source_context_fixture_sha256": "29b768ebc164016ef34da0024f9391c090e93ba704c993a170de1d1f15c9cef8", + "cases": [ + { + "name": "automatic_without_approval", + "wire": { + "type": "orders.install_terms", + "context": { + "actor": { + "grant_id": "0303030303030303030303030303030303030303030303030303030303030303", + "organization": null, + "participant": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "role": "seller" + }, + "approval": null, + "authority": { + "executor_id": "0202020202020202020202020202020202020202020202020202020202020202", + "generation": "1" + }, + "correlation_id": null, + "expected": { + "agreement": "4040404040404040404040404040404040404040404040404040404040404040", + "buyer_head": "3232323232323232323232323232323232323232323232323232323232323232", + "checkpoint": { + "coverage": "scope_satisfied", + "digest": "2222222222222222222222222222222222222222222222222222222222222222", + "missing": [], + "sequence": "1" + }, + "order_id": "2323232323232323232323232323232323232323232323232323232323232323", + "seller_sequence": "1" + }, + "not_after": "200", + "operation_id": "5151515151515151515151515151515151515151515151515151515151515151", + "route_digest": "0606060606060606060606060606060606060606060606060606060606060606", + "workspace_id": "0101010101010101010101010101010101010101010101010101010101010101" + }, + "input": { + "proposal": "3131313131313131313131313131313131313131313131313131313131313131", + "authorization": "3232323232323232323232323232323232323232323232323232323232323232", + "terms_digest": "2424242424242424242424242424242424242424242424242424242424242424", + "allocation": { + "type": "automatic" + } + } + }, + "protected_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":null,\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"correlation_id\":null,\"expected\":{\"agreement\":\"4040404040404040404040404040404040404040404040404040404040404040\",\"buyer_head\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"checkpoint\":{\"coverage\":\"scope_satisfied\",\"digest\":\"2222222222222222222222222222222222222222222222222222222222222222\",\"missing\":[],\"sequence\":\"1\"},\"order_id\":\"2323232323232323232323232323232323232323232323232323232323232323\",\"seller_sequence\":\"1\"},\"not_after\":\"200\",\"operation_id\":\"5151515151515151515151515151515151515151515151515151515151515151\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"allocation\":{\"type\":\"automatic\"},\"authorization\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"proposal\":\"3131313131313131313131313131313131313131313131313131313131313131\",\"terms_digest\":\"2424242424242424242424242424242424242424242424242424242424242424\"},\"type\":\"orders.install_terms\"}", + "semantic_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":null,\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"expected\":{\"agreement\":\"4040404040404040404040404040404040404040404040404040404040404040\",\"buyer_head\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"checkpoint\":{\"coverage\":\"scope_satisfied\",\"digest\":\"2222222222222222222222222222222222222222222222222222222222222222\",\"missing\":[],\"sequence\":\"1\"},\"order_id\":\"2323232323232323232323232323232323232323232323232323232323232323\",\"seller_sequence\":\"1\"},\"not_after\":\"200\",\"operation_id\":\"5151515151515151515151515151515151515151515151515151515151515151\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"allocation\":{\"type\":\"automatic\"},\"authorization\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"proposal\":\"3131313131313131313131313131313131313131313131313131313131313131\",\"terms_digest\":\"2424242424242424242424242424242424242424242424242424242424242424\"},\"type\":\"orders.install_terms\"}", + "command_digest": "5de9d5fc537cdcf2ab8bf4b103e3e0a6ad5014c84a6fc803d89fcf87a2de45c9", + "approval_intent_digest": "c341ab703f9f5dd014c3f09e5b7a7e98becbdd81c4b13a97b64f8b45de4ff059" + }, + { + "name": "explicit_with_approval", + "wire": { + "type": "orders.install_terms", + "context": { + "actor": { + "grant_id": "0303030303030303030303030303030303030303030303030303030303030303", + "organization": null, + "participant": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "role": "seller" + }, + "approval": { + "intent_digest": "32e72a66a024f3590a470a1ffbdff19169ea2280129aac1c11fd223040a2bc3f", + "scope": "orders.install_terms", + "expires_at": "190" + }, + "authority": { + "executor_id": "0202020202020202020202020202020202020202020202020202020202020202", + "generation": "1" + }, + "correlation_id": "replacement 🥬 observer", + "expected": { + "agreement": "4040404040404040404040404040404040404040404040404040404040404040", + "buyer_head": "3232323232323232323232323232323232323232323232323232323232323232", + "checkpoint": { + "coverage": "scope_satisfied", + "digest": "2222222222222222222222222222222222222222222222222222222222222222", + "missing": [], + "sequence": "1" + }, + "order_id": "2323232323232323232323232323232323232323232323232323232323232323", + "seller_sequence": "1" + }, + "not_after": "200", + "operation_id": "5252525252525252525252525252525252525252525252525252525252525252", + "route_digest": "0606060606060606060606060606060606060606060606060606060606060606", + "workspace_id": "0101010101010101010101010101010101010101010101010101010101010101" + }, + "input": { + "proposal": "3131313131313131313131313131313131313131313131313131313131313131", + "authorization": "3232323232323232323232323232323232323232323232323232323232323232", + "terms_digest": "2424242424242424242424242424242424242424242424242424242424242424", + "allocation": { + "type": "explicit", + "allocations": [ + { + "line_id": "2525252525252525252525252525252525252525252525252525252525252525", + "pool_id": "2626262626262626262626262626262626262626262626262626262626262626", + "quantity": { + "amount": "250", + "unit": "g" + }, + "expected_pool_version": "1" + }, + { + "line_id": "2525252525252525252525252525252525252525252525252525252525252525", + "pool_id": "2727272727272727272727272727272727272727272727272727272727272727", + "quantity": { + "amount": "0.5", + "unit": "kg" + }, + "expected_pool_version": "4" + } + ] + } + } + }, + "protected_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":{\"expires_at\":\"190\",\"intent_digest\":\"32e72a66a024f3590a470a1ffbdff19169ea2280129aac1c11fd223040a2bc3f\",\"scope\":\"orders.install_terms\"},\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"correlation_id\":\"replacement 🥬 observer\",\"expected\":{\"agreement\":\"4040404040404040404040404040404040404040404040404040404040404040\",\"buyer_head\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"checkpoint\":{\"coverage\":\"scope_satisfied\",\"digest\":\"2222222222222222222222222222222222222222222222222222222222222222\",\"missing\":[],\"sequence\":\"1\"},\"order_id\":\"2323232323232323232323232323232323232323232323232323232323232323\",\"seller_sequence\":\"1\"},\"not_after\":\"200\",\"operation_id\":\"5252525252525252525252525252525252525252525252525252525252525252\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"allocation\":{\"allocations\":[{\"expected_pool_version\":\"1\",\"line_id\":\"2525252525252525252525252525252525252525252525252525252525252525\",\"pool_id\":\"2626262626262626262626262626262626262626262626262626262626262626\",\"quantity\":{\"amount\":\"250\",\"unit\":\"g\"}},{\"expected_pool_version\":\"4\",\"line_id\":\"2525252525252525252525252525252525252525252525252525252525252525\",\"pool_id\":\"2727272727272727272727272727272727272727272727272727272727272727\",\"quantity\":{\"amount\":\"0.5\",\"unit\":\"kg\"}}],\"type\":\"explicit\"},\"authorization\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"proposal\":\"3131313131313131313131313131313131313131313131313131313131313131\",\"terms_digest\":\"2424242424242424242424242424242424242424242424242424242424242424\"},\"type\":\"orders.install_terms\"}", + "semantic_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":{\"expires_at\":\"190\",\"intent_digest\":\"32e72a66a024f3590a470a1ffbdff19169ea2280129aac1c11fd223040a2bc3f\",\"scope\":\"orders.install_terms\"},\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"expected\":{\"agreement\":\"4040404040404040404040404040404040404040404040404040404040404040\",\"buyer_head\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"checkpoint\":{\"coverage\":\"scope_satisfied\",\"digest\":\"2222222222222222222222222222222222222222222222222222222222222222\",\"missing\":[],\"sequence\":\"1\"},\"order_id\":\"2323232323232323232323232323232323232323232323232323232323232323\",\"seller_sequence\":\"1\"},\"not_after\":\"200\",\"operation_id\":\"5252525252525252525252525252525252525252525252525252525252525252\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"allocation\":{\"allocations\":[{\"expected_pool_version\":\"1\",\"line_id\":\"2525252525252525252525252525252525252525252525252525252525252525\",\"pool_id\":\"2626262626262626262626262626262626262626262626262626262626262626\",\"quantity\":{\"amount\":\"250\",\"unit\":\"g\"}},{\"expected_pool_version\":\"4\",\"line_id\":\"2525252525252525252525252525252525252525252525252525252525252525\",\"pool_id\":\"2727272727272727272727272727272727272727272727272727272727272727\",\"quantity\":{\"amount\":\"0.5\",\"unit\":\"kg\"}}],\"type\":\"explicit\"},\"authorization\":\"3232323232323232323232323232323232323232323232323232323232323232\",\"proposal\":\"3131313131313131313131313131313131313131313131313131313131313131\",\"terms_digest\":\"2424242424242424242424242424242424242424242424242424242424242424\"},\"type\":\"orders.install_terms\"}", + "command_digest": "35ea8104865455ef6b39c25f4bb1743d9aef37c1ca4e9f138acac2d18a96269f", + "approval_intent_digest": "32e72a66a024f3590a470a1ffbdff19169ea2280129aac1c11fd223040a2bc3f" + } + ] +} diff --git a/crates/protocol/tests/order_terms.rs b/crates/protocol/tests/order_terms.rs @@ -0,0 +1,236 @@ +#![cfg(feature = "commands")] +use radroots_protocol::command::{ + COMMAND_MAX_BYTES, CapturedCommand, CapturedInventoryCommand, CapturedOrderAcceptance, + CapturedStockCommitment, CapturedTermsInstallation, CommandError, +}; +use serde_json::{Value, json}; + +fn vectors() -> Value { + serde_json::from_str(include_str!("fixtures/terms_installation.v1.json")).unwrap() +} +fn parse(value: &Value) -> Result<CapturedTermsInstallation, CommandError> { + CapturedTermsInstallation::parse(&serde_json::to_vec(value).unwrap()) +} + +#[test] +fn automatic_and_explicit_capture_match_independent_ecmascript_bytes_and_digests() { + for case in vectors()["cases"].as_array().unwrap() { + let captured = parse(&case["wire"]).unwrap(); + assert_eq!( + captured.protected_wire(), + case["protected_canonical_utf8"] + .as_str() + .unwrap() + .as_bytes() + ); + assert_eq!( + captured.digest().to_string(), + case["command_digest"].as_str().unwrap() + ); + assert_eq!( + captured.approval_intent_digest().to_string(), + case["approval_intent_digest"].as_str().unwrap() + ); + assert_eq!( + CapturedTermsInstallation::parse(captured.protected_wire()) + .unwrap() + .digest(), + captured.digest() + ); + assert_eq!(captured.input().proposal().to_string(), "31".repeat(32)); + assert_eq!( + captured.input().authorization().to_string(), + "32".repeat(32) + ); + assert_eq!( + captured.input().terms_digest().to_string(), + case["wire"]["input"]["terms_digest"].as_str().unwrap() + ); + assert_eq!( + format!("{captured:?}"), + "CapturedTermsInstallation(<redacted>)" + ); + assert_eq!( + format!("{:?}", captured.input()), + "InstallTermsInput(<redacted>)" + ); + assert!(CapturedCommand::parse(captured.protected_wire()).is_err()); + assert!(CapturedInventoryCommand::parse(captured.protected_wire()).is_err()); + assert!(CapturedOrderAcceptance::parse(captured.protected_wire()).is_err()); + } + let values = vectors(); + assert!( + parse(&values["cases"][0]["wire"]) + .unwrap() + .input() + .allocation() + .is_automatic() + ); + assert_eq!( + parse(&values["cases"][1]["wire"]) + .unwrap() + .input() + .allocation() + .explicit_allocations() + .unwrap() + .len(), + 2 + ); +} + +#[test] +fn proposal_authorization_digest_base_and_allocation_each_bind_the_displayed_intent() { + let data = vectors(); + let original = &data["cases"][0]["wire"]; + let expected = parse(original).unwrap(); + for (path, value) in [ + ("/input/proposal", json!("61".repeat(32))), + ("/input/authorization", json!("62".repeat(32))), + ("/input/terms_digest", json!("63".repeat(32))), + ("/context/expected/agreement", json!("64".repeat(32))), + ("/context/expected/seller_sequence", json!("2")), + ( + "/input/allocation", + data["cases"][1]["wire"]["input"]["allocation"].clone(), + ), + ] { + let mut changed = original.clone(); + *changed.pointer_mut(path).unwrap() = value; + let changed = parse(&changed).unwrap(); + assert_ne!(changed.digest(), expected.digest()); + assert_ne!( + changed.approval_intent_digest(), + expected.approval_intent_digest() + ); + } + let mut correlated = original.clone(); + correlated["context"]["correlation_id"] = json!("different observer"); + let correlated = parse(&correlated).unwrap(); + assert_eq!(correlated.digest(), expected.digest()); + assert_eq!( + correlated.approval_intent_digest(), + expected.approval_intent_digest() + ); + assert_ne!(correlated.protected_wire(), expected.protected_wire()); + let mut approved = original.clone(); + approved["context"]["approval"] = json!({"intent_digest":expected.approval_intent_digest(),"scope":"orders.install_terms","expires_at":"190"}); + let approved = parse(&approved).unwrap(); + assert_ne!(approved.digest(), expected.digest()); + assert_eq!( + approved.approval_intent_digest(), + expected.approval_intent_digest() + ); +} + +#[test] +fn closed_shapes_and_seller_order_descriptors_cannot_turn_capture_into_a_fallback_command() { + let data = vectors(); + let original = &data["cases"][0]["wire"]; + for (path, value) in [ + ("/type", json!("orders.accept")), + ("/context/actor/role", json!("buyer")), + ("/context/expected", Value::Null), + ("/input/proposal", json!("2A".repeat(32))), + ("/input/authorization", json!("2A".repeat(32))), + ("/input/terms_digest", json!("2A".repeat(32))), + ( + "/input/allocation", + json!({"type":"automatic","allocations":[]}), + ), + ( + "/input/allocation", + json!({"type":"explicit","allocations":[]}), + ), + ("/input/allocation", json!({"type":"unknown"})), + ] { + let mut changed = original.clone(); + *changed.pointer_mut(path).unwrap() = value; + assert!(parse(&changed).is_err(), "{path}"); + } + for field in ["proposal", "authorization", "terms_digest", "allocation"] { + let mut changed = original.clone(); + changed["input"].as_object_mut().unwrap().remove(field); + assert!(parse(&changed).is_err(), "{field}"); + } + let mut extra = original.clone(); + extra["input"]["stock_free"] = json!(true); + assert!(parse(&extra).is_err()); + let mut extra = original.clone(); + extra["unrecognized"] = json!(true); + assert!(parse(&extra).is_err()); +} + +#[test] +fn duplicate_members_and_allocation_or_frame_overflow_refuse_before_any_execution() { + let data = vectors(); + let original = &data["cases"][0]["wire"]; + let raw = serde_json::to_string(original).unwrap(); + let member = format!("\"proposal\":\"{}\"", "31".repeat(32)); + let duplicate = raw.replacen(&member, &format!("{member},{member}"), 1); + assert!(CapturedTermsInstallation::parse(duplicate.as_bytes()).is_err()); + let mut excess = data["cases"][1]["wire"].clone(); + let allocation = excess["input"]["allocation"]["allocations"][0].clone(); + excess["input"]["allocation"]["allocations"] = json!(vec![allocation; 65]); + assert!(parse(&excess).is_err()); + let mut oversized = raw.into_bytes(); + oversized.resize(COMMAND_MAX_BYTES + 1, b' '); + assert!(matches!( + CapturedTermsInstallation::parse(&oversized), + Err(CommandError::LimitExceeded) + )); +} + +#[test] +fn shared_commitment_dispatch_preserves_exact_bytes_and_rejects_ambiguous_roots() { + let data = vectors(); + let acceptance: Value = + serde_json::from_str(include_str!("fixtures/order_acceptance.v1.json")).unwrap(); + for (cases, name) in [ + (&data["cases"], "orders.install_terms"), + (&acceptance["cases"], "orders.accept"), + ] { + for case in cases.as_array().unwrap() { + let raw = serde_json::to_vec(&case["wire"]).unwrap(); + let captured = CapturedStockCommitment::parse(&raw).unwrap(); + assert_eq!(captured.command_name(), name); + assert_eq!( + captured.proposal().is_some(), + name == "orders.install_terms" + ); + assert_eq!( + CapturedStockCommitment::parse(captured.protected_wire()) + .unwrap() + .digest(), + captured.digest() + ); + match &captured { + CapturedStockCommitment::Acceptance(value) => { + assert_eq!(value.protected_wire(), captured.protected_wire()); + assert_eq!(value.input().request(), captured.authorization()); + assert_eq!( + value.approval_intent_digest(), + captured.approval_intent_digest() + ); + } + CapturedStockCommitment::TermsInstallation(value) => { + assert_eq!(value.protected_wire(), captured.protected_wire()); + assert_eq!(value.input().authorization(), captured.authorization()); + assert_eq!( + value.approval_intent_digest(), + captured.approval_intent_digest() + ); + } + } + } + } + let raw = serde_json::to_string(&data["cases"][0]["wire"]).unwrap(); + let duplicate = raw.replacen( + "\"type\":\"orders.install_terms\"", + "\"type\":\"orders.install_terms\",\"type\":\"orders.accept\"", + 1, + ); + assert!(CapturedStockCommitment::parse(duplicate.as_bytes()).is_err()); + let mut unknown = data["cases"][0]["wire"].clone(); + unknown["type"] = json!("orders.handover"); + assert!(CapturedStockCommitment::parse(&serde_json::to_vec(&unknown).unwrap()).is_err()); +} diff --git a/crates/protocol/tests/support/order_terms_oracle.mjs b/crates/protocol/tests/support/order_terms_oracle.mjs @@ -0,0 +1,44 @@ +// Independent ECMAScript canonicalization/SHA-256 oracle for the closed +// ASCII-key command profile. This consumes synthetic fixture inputs only, +// never Rust writer output, source authority or product data. +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; + +const source = readFileSync(new URL("../fixtures/order_acceptance.v1.json", import.meta.url)); +const inputs = JSON.parse(source).cases; +const canonical = value => { + if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; + if (value !== null && typeof value === "object") { + return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`; + } + return JSON.stringify(value); +}; +const hash = (domain, value) => createHash("sha256").update(domain, "utf8").update(canonical(value), "utf8").digest("hex"); +const cases = inputs.map((original, index) => { + const context = structuredClone(original.wire.context); + context.operation_id = (index ? "52" : "51").repeat(32); + context.expected.agreement = "40".repeat(32); + context.expected.seller_sequence = "1"; + context.expected.buyer_head = "32".repeat(32); + context.correlation_id = index ? "replacement 🥬 observer" : null; + context.approval = null; + const wire = { type: "orders.install_terms", context, input: { + proposal: "31".repeat(32), authorization: "32".repeat(32), + terms_digest: original.wire.input.terms_digest, + allocation: structuredClone(original.wire.input.allocation), + }}; + const intent = structuredClone(wire); + delete intent.context.approval; + delete intent.context.correlation_id; + const approval = hash("radroots.approval.v1\0", intent); + if (index) wire.context.approval = { intent_digest: approval, scope: "orders.install_terms", expires_at: "190" }; + const semantic = structuredClone(wire); + delete semantic.context.correlation_id; + return { name: index ? "explicit_with_approval" : "automatic_without_approval", wire, + protected_canonical_utf8: canonical(wire), semantic_canonical_utf8: canonical(semantic), + command_digest: hash("radroots.command.v1\0", semantic), approval_intent_digest: approval }; +}); +process.stdout.write(JSON.stringify({ schema: "radroots.terms_installation_commands.v1", + provenance: "Synthetic command inputs; independent ECMAScript ASCII-key canonicalization and Node SHA-256. No Rust writer or actual authority is used.", + producer: `Node.js ${process.versions.node}`, + source_context_fixture_sha256: createHash("sha256").update(source).digest("hex"), cases }, null, 2) + "\n"); diff --git a/crates/storage/src/inventory/acceptance.rs b/crates/storage/src/inventory/acceptance.rs @@ -7,7 +7,10 @@ use crate::workspace::{ use radroots_domain::{ IssuanceWindow, OrderId, RecordId, TermsDigest, UnixSeconds, stock::PoolSnapshot, }; -use radroots_protocol::{command::CapturedOrderAcceptance, commerce::EncodedCommerceRumor}; +use radroots_protocol::{ + command::{CapturedOrderAcceptance, CapturedStockCommitment, CapturedTermsInstallation}, + commerce::EncodedCommerceRumor, +}; use std::sync::Arc; /// Captured inputs and independently retained minima, never authority evidence. @@ -16,7 +19,7 @@ pub struct StockAcceptanceRequest { minimum: InventoryCheckpointRef, sources: StockSourceCheckpointRef, listings: StockListingCheckpointRef, - command: CapturedOrderAcceptance, + command: CapturedStockCommitment, } impl StockAcceptanceRequest { /// Copies bounded protected command bytes. Current consent, source policy, @@ -28,8 +31,40 @@ impl StockAcceptanceRequest { listings: StockListingCheckpointRef, command: &CapturedOrderAcceptance, ) -> Result<Self, OperationError> { - let command = CapturedOrderAcceptance::parse(command.protected_wire()) - .map_err(|_| OperationError::InvalidCommand)?; + Self::capture_wire( + binding, + minimum, + sources, + listings, + command.protected_wire(), + ) + } + /// Copies exact terms-installation data into the same native commitment + /// request. This performs no admission, allocation, signing or stock effect. + pub fn capture_terms( + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + sources: StockSourceCheckpointRef, + listings: StockListingCheckpointRef, + command: &CapturedTermsInstallation, + ) -> Result<Self, OperationError> { + Self::capture_wire( + binding, + minimum, + sources, + listings, + command.protected_wire(), + ) + } + fn capture_wire( + binding: WorkspaceBinding, + minimum: InventoryCheckpointRef, + sources: StockSourceCheckpointRef, + listings: StockListingCheckpointRef, + raw: &[u8], + ) -> Result<Self, OperationError> { + let command = + CapturedStockCommitment::parse(raw).map_err(|_| OperationError::InvalidCommand)?; Ok(Self { binding, minimum, @@ -50,7 +85,7 @@ impl StockAcceptanceRequest { pub const fn listing_checkpoint(&self) -> StockListingCheckpointRef { self.listings } - pub const fn command(&self) -> &CapturedOrderAcceptance { + pub const fn command(&self) -> &CapturedStockCommitment { &self.command } /// Original identity anchor; not proof of a confirmed commit. @@ -75,7 +110,7 @@ impl core::fmt::Debug for StockAcceptanceRequest { pub struct StockAcceptanceReceipt { attempt: CommitAttempt, order: OrderId, - request: RecordId, + authorization: RecordId, terms: TermsDigest, checkpoint: InventoryCheckpointRef, pools: Vec<PoolSnapshot>, @@ -91,7 +126,7 @@ impl StockAcceptanceReceipt { namespace: &AttachmentInput, attempt: CommitAttempt, order: OrderId, - request: RecordId, + authorization: RecordId, terms: TermsDigest, checkpoint: InventoryCheckpointRef, pools: Vec<PoolSnapshot>, @@ -115,7 +150,7 @@ impl StockAcceptanceReceipt { Ok(Self { attempt, order, - request, + authorization, terms, checkpoint, pools, @@ -130,8 +165,10 @@ impl StockAcceptanceReceipt { pub const fn order_id(&self) -> OrderId { self.order } - pub const fn request(&self) -> RecordId { - self.request + /// Original selected buyer request or terms authorization. This metadata + /// alone proves neither participant consent nor a confirmed preparation. + pub const fn authorization(&self) -> RecordId { + self.authorization } pub const fn terms_digest(&self) -> TermsDigest { self.terms diff --git a/crates/storage_sqlite/src/workspace/stock/consent.rs b/crates/storage_sqlite/src/workspace/stock/consent.rs @@ -4,7 +4,7 @@ mod tests; use super::*; use radroots_domain::{ActorRole, CommandDigest, OperationId, OrderId, UnixSeconds}; -use radroots_protocol::command::CapturedOrderAcceptance; +use radroots_protocol::command::CapturedStockCommitment; use radroots_storage::{ command::OperationError, inventory::InventoryCheckpointRef, workspace::seller_stock::StockResources, @@ -32,7 +32,7 @@ pub struct StockConsentCapture { mode: StockConsentMode, resources: StockResources, expires: UnixSeconds, - command: CapturedOrderAcceptance, + command: CapturedStockCommitment, digest: CommandDigest, } impl StockConsentCapture { @@ -42,8 +42,9 @@ impl StockConsentCapture { mode: StockConsentMode, resources: StockResources, expires: UnixSeconds, - command: CapturedOrderAcceptance, + command: impl Into<CapturedStockCommitment>, ) -> Result<Self, OperationError> { + let command = command.into(); validate_capture(&namespace, subject, mode, expires, &command)?; let digest = scope_digest( &namespace, @@ -84,7 +85,7 @@ impl StockConsentCapture { pub const fn expires_at(&self) -> UnixSeconds { self.expires } - pub fn command(&self) -> &CapturedOrderAcceptance { + pub fn command(&self) -> &CapturedStockCommitment { &self.command } pub fn resources(&self) -> &StockResources { @@ -99,7 +100,7 @@ impl StockConsentCapture { mode: self.mode, resources: self.resources.clone(), expires: self.expires, - command: CapturedOrderAcceptance::parse(self.command.protected_wire()) + command: CapturedStockCommitment::parse(self.command.protected_wire()) .map_err(|_| OperationError::InvalidCommand)?, digest: self.digest, }) @@ -115,7 +116,7 @@ fn validate_capture( subject: GrantId, mode: StockConsentMode, expires: UnixSeconds, - command: &CapturedOrderAcceptance, + command: &CapturedStockCommitment, ) -> Result<(), OperationError> { let context = command.context(); let approval = context @@ -130,7 +131,7 @@ fn validate_capture( || context.route_digest() != namespace.route_digest() || context.expected().is_none() || expires.get() == 0 - || approval.scope() != "orders.accept" + || approval.scope() != command.command_name() || approval.intent_digest() != command.approval_intent_digest() || (mode == StockConsentMode::ExecuteAndRecover && (context.actor().grant_id() != Some(subject) @@ -261,7 +262,7 @@ struct Body<'a> { pub(super) struct Retained { pub frame: ledger::Retained, pub observed_at: UnixSeconds, - pub command: CapturedOrderAcceptance, + pub command: CapturedStockCommitment, pub mode: StockConsentMode, pub resources: StockResources, pub subject: GrantId, @@ -343,7 +344,7 @@ pub(super) async fn read( let body: Body<'_> = super::object(&mut parser).map_err(|_| OperationError::RecoveryRequired)?; parser.end().map_err(|_| OperationError::RecoveryRequired)?; - let command = CapturedOrderAcceptance::parse(body.command.get().as_bytes()) + let command = CapturedStockCommitment::parse(body.command.get().as_bytes()) .map_err(|_| OperationError::RecoveryRequired)?; let namespace = SellerAuthoritySelection::from_attachment(input); validate_capture(&namespace, body.subject, body.mode, body.expires, &command) @@ -352,6 +353,7 @@ pub(super) async fn read( if header.family != ledger::Family::Consent || header.actor.grant_id() != Some(administrator) || body.version != 1 + || command.proposal().is_some() || !namespace.matches_attachment(&body.selection) || body.selection.grant_id() != administrator || header.subject_grant != Some(body.subject) @@ -424,7 +426,7 @@ pub(in crate::workspace) async fn issue( proof: AttachmentProof, ) -> Result<StockConsentOutcome, OperationError> { let access = turn.access(&binding, minimum, &proof).await?; - if !matches!(access.authority.catalog, 7..=19) { + if !matches!(access.authority.catalog, 7..=19) || capture.command.proposal().is_some() { return Err(OperationError::UnsupportedOperation); } if !access.record.administrator() diff --git a/crates/storage_sqlite/src/workspace/stock/consent/tests.rs b/crates/storage_sqlite/src/workspace/stock/consent/tests.rs @@ -3,6 +3,7 @@ use super::*; use crate::workspace::{tests::CryptoFixture, tests::participant}; use radroots_domain::{CommandContextData, PoolId}; +use radroots_protocol::command::CapturedOrderAcceptance; use radroots_storage::inventory::{InventoryOutcome, InventoryRequest, InventoryStore}; use std::sync::atomic::{AtomicU64, Ordering}; #[path = "test_provider.rs"] @@ -163,6 +164,79 @@ 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 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"); + wire["input"] = serde_json::json!({"proposal":"61".repeat(32),"authorization":"62".repeat(32),"terms_digest":"24".repeat(32),"allocation":{"type":"automatic"}}); + wire["context"]["expected"]["agreement"] = serde_json::json!("63".repeat(32)); + wire["context"]["expected"]["seller_sequence"] = serde_json::json!("1"); + wire["context"]["approval"] = serde_json::Value::Null; + let command = radroots_protocol::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":"150"}); + let command = radroots_protocol::command::CapturedTermsInstallation::parse( + &serde_json::to_vec(&wire).unwrap(), + ) + .unwrap(); + let capture = StockConsentCapture::prepare( + SellerAuthoritySelection::from_attachment(&r.input), + r.input.grant_id(), + StockConsentMode::ExecuteAndRecover, + StockResources::all_pools(), + UnixSeconds::new(150).unwrap(), + command, + ) + .unwrap(); + assert_eq!( + r.store + .issue_stock_consent(r.binding.clone(), r.minimum, &capture, &r.proof) + .await + .unwrap_err(), + OperationError::UnsupportedOperation + ); + let mut raw = SqliteConnection::connect_with( + &sqlx::sqlite::SqliteConnectOptions::new() + .filename(r.path.join("stock_execution_v1.sqlite")), + ) + .await + .unwrap(); + assert_eq!( + sqlx::query_scalar::<_, i64>("SELECT count(*) FROM stock_operations") + .fetch_one(&mut raw) + .await + .unwrap(), + 0 + ); + assert_eq!( + sqlx::query_scalar::<_, i64>("PRAGMA user_version") + .fetch_one(&mut raw) + .await + .unwrap(), + catalog + ); + raw.close().await.unwrap(); + let receipt = committed( + r.store + .issue_stock_consent( + r.binding.clone(), + r.minimum, + &r.capture(&r.binding, 0x32), + &r.proof, + ) + .await + .unwrap(), + ); + assert_eq!(receipt.checkpoint().revision().get(), 1); + r.store.close().await.unwrap(); + } +} + +#[tokio::test] async fn original_consent_replays_after_expiry_and_survives_physical_progress_and_reopen() { let r = Rig::new().await; let capture = r.capture(&r.binding, 0x31); diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance.rs @@ -3,7 +3,7 @@ use super::super::{consent, ledger, source}; use super::*; use radroots_domain::{CheckpointRef, OrderId, RecordId, TermsDigest}; -use radroots_protocol::command::CapturedOrderAcceptance; +use radroots_protocol::command::CapturedStockCommitment; use radroots_storage::inventory::InventoryCheckpointRef; use radroots_storage::workspace::seller_stock::{ StockListingCheckpointRef, StockSourceCheckpointRef, @@ -90,7 +90,7 @@ struct Fence { } fn fence( header: &ledger::Header, - command: &CapturedOrderAcceptance, + command: &CapturedStockCommitment, ) -> Result<Fence, OperationError> { Ok(Fence { version: 1, @@ -99,8 +99,8 @@ fn fence( digest: header.digest, transaction: header.transaction, revision: Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?, - request: command.input().request(), - terms: command.input().terms_digest(), + request: command.authorization(), + terms: command.terms_digest(), }) } fn bytes(value: &impl Serialize) -> Result<zeroize::Zeroizing<Vec<u8>>, OperationError> { @@ -151,7 +151,7 @@ fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest { pub(in crate::workspace::stock) fn check_consent( access: &Access, scope: &consent::Retained, - command: &CapturedOrderAcceptance, + command: &CapturedStockCommitment, fresh: bool, at: UnixSeconds, ) -> Result<(), OperationError> { @@ -190,7 +190,7 @@ pub(in crate::workspace::stock) fn check_consent( pub(in crate::workspace::stock) async fn current_consent( turn: &mut Turn<'_>, access: &Access, - command: &CapturedOrderAcceptance, + command: &CapturedStockCommitment, ) -> Result<(consent::Retained, MinimumProof), OperationError> { let operation = consent::natural( turn.connection, @@ -240,6 +240,11 @@ pub(in crate::workspace) async fn admit( 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() { + return Err(OperationError::UnsupportedOperation); + } let operation = command.context().operation_id(); let original = codec::read(turn.connection, turn.selected, turn.crypto, operation).await?; let identity = checkpoint::authenticate_identity( @@ -340,7 +345,7 @@ pub(in crate::workspace) async fn admit( authority: &access.authority, minimum: request.minimum_checkpoint(), }, - command.input().request(), + command.authorization(), request.listing_checkpoint(), access.current.observed_at(), ) @@ -354,7 +359,7 @@ pub(in crate::workspace) async fn admit( || expected.seller_sequence().get() != 0 || expected.buyer_head() != admitted.history.analysis.buyer_head() || Some(expected.checkpoint()) != admitted.history.checkpoint.as_ref() - || command.input().terms_digest() != admitted.digest + || command.terms_digest() != admitted.digest || command.context().workspace_id() != turn.selected.workspace_id() || command.context().authority() != turn.selected.authority() || command.context().route_digest() != turn.selected.route_digest() @@ -429,7 +434,7 @@ pub(in crate::workspace) async fn admit( proof: witness, }); } - if let Some(explicit) = command.input().allocation().explicit_allocations() { + if let Some(explicit) = command.allocation().explicit_allocations() { pool_ids.extend(explicit.iter().map(|value| value.pool_id())); } } diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/codec.rs @@ -36,10 +36,10 @@ impl Retained { .map_err(|_| OperationError::RecoveryRequired)?; Ok(body.allocations) } - pub fn command(&self) -> Result<CapturedOrderAcceptance, OperationError> { + pub fn command(&self) -> Result<CapturedStockCommitment, OperationError> { let body: Body = super::super::super::closed_record(&self.frame.body) .map_err(|_| OperationError::RecoveryRequired)?; - CapturedOrderAcceptance::parse(body.command.get().as_bytes()) + CapturedStockCommitment::parse(body.command.get().as_bytes()) .map_err(|_| OperationError::RecoveryRequired) } pub fn identity(&self) -> checkpoint::EntryIdentity { @@ -173,15 +173,18 @@ pub(super) fn receipt( input: &AttachmentInput, header: &ledger::Header, body: &Body, - command: &CapturedOrderAcceptance, + 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 = radroots_protocol::commerce::initial_commitment_rumor( - command, + initial, &request, body.seller_author_head .map(|head| (head, body.seller_author_sequence)), @@ -197,8 +200,8 @@ pub(super) fn receipt( Some(header.transaction), ), header.order.ok_or(OperationError::RecoveryRequired)?, - command.input().request(), - command.input().terms_digest(), + command.authorization(), + command.terms_digest(), InventoryCheckpointRef::from_host_metadata( input.authority(), header.revision, @@ -226,7 +229,7 @@ pub(in crate::workspace::stock) async fn read( } let body: Body = super::super::super::closed_record(&frame.body) .map_err(|_| OperationError::RecoveryRequired)?; - let command = CapturedOrderAcceptance::parse(body.command.get().as_bytes()) + let command = CapturedStockCommitment::parse(body.command.get().as_bytes()) .map_err(|_| OperationError::RecoveryRequired)?; let terms = radroots_protocol::terms::decode(body.terms.get().as_bytes()) .map_err(|_| OperationError::RecoveryRequired)?; @@ -238,7 +241,7 @@ pub(in crate::workspace::stock) async fn read( else { return Err(OperationError::RecoveryRequired); }; - if original.record_id() != command.input().request() + if original.record_id() != command.authorization() || original_request.terms() != &terms || original.content().header().order_id() != command.context().expected().map(|value| value.order_id()) @@ -286,7 +289,7 @@ pub(in crate::workspace::stock) async fn read( || expected.seller_sequence().get() != 0 || expected.checkpoint() != &body.coverage || expected.buyer_head() != body.buyer_head - || encoded.digest() != command.input().terms_digest() + || encoded.digest() != command.terms_digest() || terms.seller() != header.actor.participant() || body.observed_at.get() == 0 || body.expires <= body.observed_at diff --git a/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/plan.rs b/crates/storage_sqlite/src/workspace/stock/inventory/acceptance/plan.rs @@ -5,13 +5,12 @@ pub(super) use radroots_domain::stock::{ }; pub(super) fn resolve( terms: &radroots_domain::Terms, - command: &CapturedOrderAcceptance, + command: &CapturedStockCommitment, mappings: &[radroots_domain::stock::OptionPoolMapping], pools: &[PoolSnapshot], ) -> Result<(Vec<Allocation>, Vec<Effect>), OperationError> { use radroots_domain::stock::{AllocationClaim, AllocationPlanError}; let explicit = command - .input() .allocation() .explicit_allocations() .map(|values| { diff --git a/crates/storage_sqlite/src/workspace/stock/signing_plan.rs b/crates/storage_sqlite/src/workspace/stock/signing_plan.rs @@ -96,7 +96,7 @@ pub enum StockSigningPlanOutcome { pub(in crate::workspace::stock) struct Authorized { pub(in crate::workspace::stock) access: Access, pub(in crate::workspace::stock) original: acceptance::codec::Retained, - pub(in crate::workspace::stock) command: radroots_protocol::command::CapturedOrderAcceptance, + pub(in crate::workspace::stock) command: radroots_protocol::command::CapturedStockCommitment, pub(in crate::workspace::stock) original_proof: MinimumProof, pub(in crate::workspace::stock) consent: consent::Retained, pub(in crate::workspace::stock) consent_proof: MinimumProof,