lib

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

commit 22c816a10f815cc1b5b9d6b16d02986418e997b0
parent d2bbf19bdbc5c465d2a9ea5194ce57488a48c68e
Author: triesap <tyson@radroots.org>
Date:   Sun, 25 Oct 2026 01:55:51 +0000

protocol: capture exact order acceptance inputs

- Bind original order, request, terms and allocation choices.
- Validate positive bounded explicit allocations and canonical values.
- Preserve independent command and approval digest vectors.
- Verify closed data, portable checks and existing dispatcher refusal.

Diffstat:
Mcontracts/api_baselines/radroots_protocol.txt | 39+++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/src/command.rs | 4++++
Acrates/protocol/src/command/order_acceptance.rs | 380+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/fixtures/order_acceptance.v1.json | 116+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/order_acceptance.rs | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
5 files changed, 748 insertions(+), 0 deletions(-)

diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -225,6 +225,34 @@ pub radroots_protocol::command::InventoryCommandKind::CreatePool pub radroots_protocol::command::InventoryCommandKind::MapOption pub radroots_protocol::command::InventoryCommandKind::RemoveStock pub radroots_protocol::command::InventoryCommandKind::SpoilStock +pub struct radroots_protocol::command::AcceptOrderInput +impl radroots_protocol::command::AcceptOrderInput +pub const fn radroots_protocol::command::AcceptOrderInput::allocation(&self) -> &radroots_protocol::command::AllocationSelection +pub const fn radroots_protocol::command::AcceptOrderInput::new(radroots_domain::identifier::RecordId, radroots_domain::identifier::TermsDigest, radroots_protocol::command::AllocationSelection) -> Self +pub const fn radroots_protocol::command::AcceptOrderInput::request(&self) -> radroots_domain::identifier::RecordId +pub const fn radroots_protocol::command::AcceptOrderInput::terms_digest(&self) -> radroots_domain::identifier::TermsDigest +impl core::fmt::Debug for radroots_protocol::command::AcceptOrderInput +pub fn radroots_protocol::command::AcceptOrderInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::command::AllocationInput +impl radroots_protocol::command::AllocationInput +pub const fn radroots_protocol::command::AllocationInput::expected_pool_version(self) -> radroots_domain::context::Sequence +pub const fn radroots_protocol::command::AllocationInput::line_id(self) -> radroots_domain::identifier::AgreementLineId +pub fn radroots_protocol::command::AllocationInput::new(radroots_domain::identifier::AgreementLineId, radroots_domain::identifier::PoolId, radroots_domain::quantity::Quantity, radroots_domain::context::Sequence) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub const fn radroots_protocol::command::AllocationInput::pool_id(self) -> radroots_domain::identifier::PoolId +pub const fn radroots_protocol::command::AllocationInput::quantity(self) -> radroots_domain::quantity::Quantity +impl core::fmt::Debug for radroots_protocol::command::AllocationInput +pub fn radroots_protocol::command::AllocationInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::command::AllocationSelection(_) +impl radroots_protocol::command::AllocationSelection +pub const radroots_protocol::command::AllocationSelection::MAX_ALLOCATIONS: usize +pub const fn radroots_protocol::command::AllocationSelection::automatic() -> Self +pub fn radroots_protocol::command::AllocationSelection::explicit(alloc::vec::Vec<radroots_protocol::command::AllocationInput>) -> core::result::Result<Self, radroots_protocol::command::CommandError> +pub fn radroots_protocol::command::AllocationSelection::explicit_allocations(&self) -> core::option::Option<&[radroots_protocol::command::AllocationInput]> +pub const fn radroots_protocol::command::AllocationSelection::is_automatic(&self) -> bool +impl core::fmt::Debug for radroots_protocol::command::AllocationSelection +pub fn radroots_protocol::command::AllocationSelection::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_protocol::command::AllocationSelection +pub fn radroots_protocol::command::AllocationSelection::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> pub struct radroots_protocol::command::CapturedChatCommand impl radroots_protocol::command::CapturedChatCommand pub const fn radroots_protocol::command::CapturedChatCommand::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest @@ -257,6 +285,17 @@ impl core::convert::From<radroots_protocol::command::CapturedOptionMapping> for pub fn radroots_protocol::command::CapturedInventoryCommand::from(radroots_protocol::command::CapturedOptionMapping) -> Self impl core::fmt::Debug for radroots_protocol::command::CapturedOptionMapping pub fn radroots_protocol::command::CapturedOptionMapping::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::command::CapturedOrderAcceptance +impl radroots_protocol::command::CapturedOrderAcceptance +pub const fn radroots_protocol::command::CapturedOrderAcceptance::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest +pub const fn radroots_protocol::command::CapturedOrderAcceptance::context(&self) -> &radroots_domain::context::CommandContextData +pub const fn radroots_protocol::command::CapturedOrderAcceptance::digest(&self) -> radroots_domain::identifier::CommandDigest +pub const fn radroots_protocol::command::CapturedOrderAcceptance::input(&self) -> &radroots_protocol::command::AcceptOrderInput +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::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 impl radroots_protocol::command::CapturedPoolCorrection pub const fn radroots_protocol::command::CapturedPoolCorrection::approval_intent_digest(&self) -> radroots_domain::identifier::ApprovalIntentDigest diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs @@ -50,11 +50,15 @@ impl core::error::Error for CommandError {} mod captured; mod inventory; +mod order_acceptance; mod stock; mod stock_correction; mod stock_mapping; pub use captured::{CapturedCommand, CommandKind}; pub use inventory::{CapturedInventoryCommand, InventoryCommandKind}; +pub use order_acceptance::{ + AcceptOrderInput, AllocationInput, AllocationSelection, CapturedOrderAcceptance, +}; pub use stock::{CapturedPoolCreation, CreatePoolInput}; 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 @@ -0,0 +1,380 @@ +//! Exact T0 command data. Capture establishes no source, approval, grant or hold. +use super::{COMMAND_MAX_BYTES, CommandError, Context, check_frame, hash, parse_object}; +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::fmt; +use radroots_domain::{ + ActorRole, AgreementLineId, ApprovalIntentDigest, CommandContextData, CommandDigest, PoolId, + Quantity, RecordId, Sequence, TermsDigest, +}; +use serde::{ + Deserialize, Serialize, + ser::{SerializeSeq, SerializeStruct}, +}; +use serde_json::value::RawValue; +use zeroize::Zeroizing; + +/// One advanced seller allocation claim, before live validation and acquisition. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct AllocationInput { + line: AgreementLineId, + pool: PoolId, + quantity: Quantity, + expected: Sequence, +} +impl AllocationInput { + /// Requires positive quantity and an existing pool version. The executor + /// separately checks line coverage, compatible units and the actual pool. + pub fn new( + line: AgreementLineId, + pool: PoolId, + quantity: Quantity, + expected: Sequence, + ) -> Result<Self, CommandError> { + if quantity.amount().is_zero() || expected.get() == 0 { + return Err(CommandError::InvalidInput); + } + Ok(Self { + line, + pool, + quantity, + expected, + }) + } + pub const fn line_id(self) -> AgreementLineId { + self.line + } + pub const fn pool_id(self) -> PoolId { + self.pool + } + pub const fn quantity(self) -> Quantity { + self.quantity + } + pub const fn expected_pool_version(self) -> Sequence { + self.expected + } +} +impl fmt::Debug for AllocationInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AllocationInput(<redacted>)") + } +} +/// Automatic mapping resolution or an explicit, nonempty bounded seller choice. +/// Neither choice authorizes stock-free acceptance or proves physical backing. +pub struct AllocationSelection(Choice); +enum Choice { + Automatic, + Explicit(Box<[AllocationInput]>), +} +impl AllocationSelection { + pub const MAX_ALLOCATIONS: usize = 64; + pub const fn automatic() -> Self { + Self(Choice::Automatic) + } + /// Refuses empty/oversized lists and ambiguous duplicate line/pool pairs. + /// Capture preserves supplied order; acquisition order belongs to the plan. + pub fn explicit(allocations: Vec<AllocationInput>) -> Result<Self, CommandError> { + if allocations.is_empty() || allocations.len() > Self::MAX_ALLOCATIONS { + return Err(CommandError::InvalidInput); + } + for (index, value) in allocations.iter().enumerate() { + if allocations[..index] + .iter() + .any(|prior| prior.line == value.line && prior.pool == value.pool) + { + return Err(CommandError::InvalidInput); + } + } + Ok(Self(Choice::Explicit(allocations.into_boxed_slice()))) + } + pub const fn is_automatic(&self) -> bool { + matches!(self.0, Choice::Automatic) + } + pub fn explicit_allocations(&self) -> Option<&[AllocationInput]> { + match &self.0 { + Choice::Automatic => None, + Choice::Explicit(values) => Some(values), + } + } +} +impl fmt::Debug for AllocationSelection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AllocationSelection(<redacted>)") + } +} +/// Exact request and Terms identities; source lookup and authorization are IO. +pub struct AcceptOrderInput { + request: RecordId, + terms: TermsDigest, + allocation: AllocationSelection, +} +impl AcceptOrderInput { + pub const fn new( + request: RecordId, + terms: TermsDigest, + allocation: AllocationSelection, + ) -> Self { + Self { + request, + terms, + allocation, + } + } + pub const fn request(&self) -> RecordId { + self.request + } + pub const fn terms_digest(&self) -> TermsDigest { + self.terms + } + pub const fn allocation(&self) -> &AllocationSelection { + &self.allocation + } +} +impl fmt::Debug for AcceptOrderInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AcceptOrderInput(<redacted>)") + } +} +/// Closed `orders.accept` capture. A concrete authority must revalidate source, +/// approval, current access, order/mapping/pool state and commit actual holds. +pub struct CapturedOrderAcceptance { + context: CommandContextData, + input: AcceptOrderInput, + wire: Zeroizing<Box<[u8]>>, + digest: CommandDigest, + approval: ApprovalIntentDigest, +} +impl CapturedOrderAcceptance { + /// Requires seller/order descriptors as data. Approval may be absent while + /// computing an intent for consent; capture never verifies that consent. + pub fn new(context: CommandContextData, input: AcceptOrderInput) -> 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, + }) + } + 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> { + request: RecordId, + terms_digest: TermsDigest, + #[serde(borrow)] + allocation: &'a RawValue, + } + let root: Root<'_> = parse_object(raw)?; + if root.kind != "orders.accept" { + return Err(CommandError::UnsupportedCommand); + } + let input: Input<'_> = parse_object(root.input.get().as_bytes())?; + Self::new( + root.context, + AcceptOrderInput::new( + input.request, + input.terms_digest, + parse_selection(input.allocation.get().as_bytes())?, + ), + ) + } + pub const fn context(&self) -> &CommandContextData { + &self.context + } + pub const fn input(&self) -> &AcceptOrderInput { + &self.input + } + pub fn protected_wire(&self) -> &[u8] { + &self.wire + } + pub const fn digest(&self) -> CommandDigest { + self.digest + } + pub const fn approval_intent_digest(&self) -> ApprovalIntentDigest { + self.approval + } +} +impl fmt::Debug for CapturedOrderAcceptance { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("CapturedOrderAcceptance(<redacted>)") + } +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct AllocationWire { + line_id: AgreementLineId, + pool_id: PoolId, + quantity: Quantity, + expected_pool_version: Sequence, +} +fn parse_selection(raw: &[u8]) -> Result<AllocationSelection, CommandError> { + #[derive(Deserialize)] + struct Probe { + #[serde(rename = "type")] + kind: String, + } + let probe: Probe = parse_object(raw)?; + match probe.kind.as_str() { + "automatic" => { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Automatic { + #[serde(rename = "type")] + _kind: String, + } + let _: Automatic = parse_object(raw)?; + Ok(AllocationSelection::automatic()) + } + "explicit" => { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Explicit<'a> { + #[serde(rename = "type")] + _kind: String, + #[serde(borrow)] + allocations: &'a RawValue, + } + let value: Explicit<'_> = parse_object(raw)?; + let mut decoder = serde_json::Deserializer::from_str(value.allocations.get()); + struct Allocations; + impl<'de> serde::de::Visitor<'de> for Allocations { + type Value = Vec<AllocationInput>; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("one through64 closed allocation objects") + } + fn visit_seq<A: serde::de::SeqAccess<'de>>( + self, + mut seq: A, + ) -> Result<Self::Value, A::Error> { + let mut values = Vec::new(); + while let Some(raw) = seq.next_element::<&RawValue>()? { + if values.len() == AllocationSelection::MAX_ALLOCATIONS { + return Err(serde::de::Error::custom("allocation count limit")); + } + let value: AllocationWire = + parse_object(raw.get().as_bytes()).map_err(serde::de::Error::custom)?; + values.push( + AllocationInput::new( + value.line_id, + value.pool_id, + value.quantity, + value.expected_pool_version, + ) + .map_err(serde::de::Error::custom)?, + ); + } + Ok(values) + } + } + let values = serde::Deserializer::deserialize_seq(&mut decoder, Allocations) + .map_err(|_| CommandError::InvalidInput)?; + decoder.end().map_err(|_| CommandError::InvalidInput)?; + AllocationSelection::explicit(values) + } + _ => Err(CommandError::InvalidInput), + } +} +struct Wire<'a> { + context: &'a CommandContextData, + input: &'a AcceptOrderInput, + approval: bool, + correlation: bool, +} +impl Serialize for Wire<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut out = s.serialize_struct("OrderAcceptance", 3)?; + out.serialize_field( + "context", + &Context(self.context, self.approval, self.correlation), + )?; + out.serialize_field("input", &InputWire(self.input))?; + out.serialize_field("type", "orders.accept")?; + out.end() + } +} +struct InputWire<'a>(&'a AcceptOrderInput); +impl Serialize for InputWire<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut out = s.serialize_struct("AcceptOrderInput", 3)?; + out.serialize_field("allocation", &self.0.allocation)?; + out.serialize_field("request", &self.0.request)?; + out.serialize_field("terms_digest", &self.0.terms)?; + out.end() + } +} +impl Serialize for AllocationSelection { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut out = s.serialize_struct( + "AllocationSelection", + if self.is_automatic() { 1 } else { 2 }, + )?; + if let Some(values) = self.explicit_allocations() { + out.serialize_field("allocations", &AllocationsWire(values))?; + } + out.serialize_field( + "type", + if self.is_automatic() { + "automatic" + } else { + "explicit" + }, + )?; + out.end() + } +} +struct AllocationsWire<'a>(&'a [AllocationInput]); +impl Serialize for AllocationsWire<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut out = s.serialize_seq(Some(self.0.len()))?; + for value in self.0 { + out.serialize_element(&AllocationWrite(value))?; + } + out.end() + } +} +struct AllocationWrite<'a>(&'a AllocationInput); +impl Serialize for AllocationWrite<'_> { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + let mut out = s.serialize_struct("AllocationInput", 4)?; + out.serialize_field("expected_pool_version", &self.0.expected)?; + out.serialize_field("line_id", &self.0.line)?; + out.serialize_field("pool_id", &self.0.pool)?; + out.serialize_field("quantity", &self.0.quantity)?; + out.end() + } +} diff --git a/crates/protocol/tests/fixtures/order_acceptance.v1.json b/crates/protocol/tests/fixtures/order_acceptance.v1.json @@ -0,0 +1,116 @@ +{ + "provenance": "Synthetic seller order preparation cases; independent Python sorted ASCII keys and compact UTF-8 encoding implement the governed canonical subset. No Rust writer or product data is consumed.", + "oracle_python": "3.14.7", + "cases": [ + { + "wire": { + "type": "orders.accept", + "context": { + "actor": { + "grant_id": "0303030303030303030303030303030303030303030303030303030303030303", + "organization": null, + "participant": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "role": "seller" + }, + "approval": null, + "authority": { + "executor_id": "0202020202020202020202020202020202020202020202020202020202020202", + "generation": "1" + }, + "correlation_id": null, + "expected": { + "agreement": null, + "buyer_head": "2121212121212121212121212121212121212121212121212121212121212121", + "checkpoint": { + "coverage": "scope_satisfied", + "digest": "2222222222222222222222222222222222222222222222222222222222222222", + "missing": [], + "sequence": "1" + }, + "order_id": "2323232323232323232323232323232323232323232323232323232323232323", + "seller_sequence": "0" + }, + "not_after": "200", + "operation_id": "0707070707070707070707070707070707070707070707070707070707070707", + "route_digest": "0606060606060606060606060606060606060606060606060606060606060606", + "workspace_id": "0101010101010101010101010101010101010101010101010101010101010101" + }, + "input": { + "request": "2121212121212121212121212121212121212121212121212121212121212121", + "terms_digest": "2424242424242424242424242424242424242424242424242424242424242424", + "allocation": { + "type": "automatic" + } + } + }, + "semantic_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":null,\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"expected\":{\"agreement\":null,\"buyer_head\":\"2121212121212121212121212121212121212121212121212121212121212121\",\"checkpoint\":{\"coverage\":\"scope_satisfied\",\"digest\":\"2222222222222222222222222222222222222222222222222222222222222222\",\"missing\":[],\"sequence\":\"1\"},\"order_id\":\"2323232323232323232323232323232323232323232323232323232323232323\",\"seller_sequence\":\"0\"},\"not_after\":\"200\",\"operation_id\":\"0707070707070707070707070707070707070707070707070707070707070707\",\"route_digest\":\"0606060606060606060606060606060606060606060606060606060606060606\",\"workspace_id\":\"0101010101010101010101010101010101010101010101010101010101010101\"},\"input\":{\"allocation\":{\"type\":\"automatic\"},\"request\":\"2121212121212121212121212121212121212121212121212121212121212121\",\"terms_digest\":\"2424242424242424242424242424242424242424242424242424242424242424\"},\"type\":\"orders.accept\"}", + "command_digest": "d11735ec58bc026f429f6cb08808a27b460c16867356904b1312c3df2ebacfb0", + "approval_intent_digest": "0ebe2a7998b6beaaa9a1c2c0ef618748f88610e2559e6753ee5ef3fd88a8ae83" + }, + { + "wire": { + "type": "orders.accept", + "context": { + "actor": { + "grant_id": "0303030303030303030303030303030303030303030303030303030303030303", + "organization": null, + "participant": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "role": "seller" + }, + "approval": null, + "authority": { + "executor_id": "0202020202020202020202020202020202020202020202020202020202020202", + "generation": "1" + }, + "correlation_id": null, + "expected": { + "agreement": null, + "buyer_head": "2121212121212121212121212121212121212121212121212121212121212121", + "checkpoint": { + "coverage": "scope_satisfied", + "digest": "2222222222222222222222222222222222222222222222222222222222222222", + "missing": [], + "sequence": "1" + }, + "order_id": "2323232323232323232323232323232323232323232323232323232323232323", + "seller_sequence": "0" + }, + "not_after": "200", + "operation_id": "0707070707070707070707070707070707070707070707070707070707070707", + "route_digest": "0606060606060606060606060606060606060606060606060606060606060606", + "workspace_id": "0101010101010101010101010101010101010101010101010101010101010101" + }, + "input": { + "request": "2121212121212121212121212121212121212121212121212121212121212121", + "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" + } + ] + } + } + }, + "semantic_canonical_utf8": "{\"context\":{\"actor\":{\"grant_id\":\"0303030303030303030303030303030303030303030303030303030303030303\",\"organization\":null,\"participant\":\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\"role\":\"seller\"},\"approval\":null,\"authority\":{\"executor_id\":\"0202020202020202020202020202020202020202020202020202020202020202\",\"generation\":\"1\"},\"expected\":{\"agreement\":null,\"buyer_head\":\"2121212121212121212121212121212121212121212121212121212121212121\",\"checkpoint\":{\"coverage\":\"scope_satisfied\",\"digest\":\"2222222222222222222222222222222222222222222222222222222222222222\",\"missing\":[],\"sequence\":\"1\"},\"order_id\":\"2323232323232323232323232323232323232323232323232323232323232323\",\"seller_sequence\":\"0\"},\"not_after\":\"200\",\"operation_id\":\"0707070707070707070707070707070707070707070707070707070707070707\",\"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\"},\"request\":\"2121212121212121212121212121212121212121212121212121212121212121\",\"terms_digest\":\"2424242424242424242424242424242424242424242424242424242424242424\"},\"type\":\"orders.accept\"}", + "command_digest": "36e277988011df9deb17998586d99f7246062b83e0dcfc737bdbf3380529987e", + "approval_intent_digest": "01060576ece96f8180245fbde29907a9d3bc73b5bb043a6c0b3b969b92704fc5" + } + ] +} diff --git a/crates/protocol/tests/order_acceptance.rs b/crates/protocol/tests/order_acceptance.rs @@ -0,0 +1,209 @@ +#![cfg(feature = "commands")] +use radroots_protocol::command::{ + CapturedCommand, CapturedInventoryCommand, CapturedOrderAcceptance, +}; +use serde_json::{Value, json}; +fn cases() -> Value { + serde_json::from_str(include_str!("fixtures/order_acceptance.v1.json")).unwrap() +} +fn parse( + value: &Value, +) -> Result<CapturedOrderAcceptance, radroots_protocol::command::CommandError> { + CapturedOrderAcceptance::parse(&serde_json::to_vec(value).unwrap()) +} + +#[test] +fn acceptance_capture_matches_independent_automatic_and_explicit_hash_vectors() { + for case in cases()["cases"].as_array().unwrap() { + let captured = parse(&case["wire"]).unwrap(); + assert_eq!( + captured.digest().to_string(), + case["command_digest"].as_str().unwrap() + ); + assert_eq!( + captured.approval_intent_digest().to_string(), + case["approval_intent_digest"].as_str().unwrap() + ); + assert_eq!( + serde_json::from_slice::<Value>(captured.protected_wire()).unwrap(), + case["wire"] + ); + assert_eq!( + CapturedOrderAcceptance::parse(captured.protected_wire()) + .unwrap() + .digest(), + captured.digest() + ); + assert_eq!( + format!("{captured:?}"), + "CapturedOrderAcceptance(<redacted>)" + ); + } + let data = cases(); + let automatic = parse(&data["cases"][0]["wire"]).unwrap(); + assert!(automatic.input().allocation().is_automatic()); + assert!( + automatic + .input() + .allocation() + .explicit_allocations() + .is_none() + ); + let explicit = parse(&data["cases"][1]["wire"]).unwrap(); + let allocations = explicit + .input() + .allocation() + .explicit_allocations() + .unwrap(); + assert_eq!(allocations.len(), 2); + assert_eq!(allocations[0].quantity().amount().to_string(), "250"); + assert_eq!(allocations[1].expected_pool_version().get(), 4); + // Preparation cannot enter either existing outbox or inventory execution. + assert!(CapturedCommand::parse(automatic.protected_wire()).is_err()); + assert!(CapturedInventoryCommand::parse(automatic.protected_wire()).is_err()); +} + +#[test] +fn expected_order_terms_request_and_allocation_are_part_of_the_original_intent() { + let data = cases(); + let wire = &data["cases"][0]["wire"]; + let original = parse(wire).unwrap(); + for (path, value) in [ + ("/input/request", json!("31".repeat(32))), + ("/input/terms_digest", json!("32".repeat(32))), + ("/context/expected/buyer_head", json!("33".repeat(32))), + ("/context/expected/seller_sequence", json!("1")), + ( + "/input/allocation", + data["cases"][1]["wire"]["input"]["allocation"].clone(), + ), + ] { + let mut changed = wire.clone(); + *changed.pointer_mut(path).unwrap() = value; + let changed = parse(&changed).unwrap(); + assert_ne!(changed.digest(), original.digest()); + assert_ne!( + changed.approval_intent_digest(), + original.approval_intent_digest() + ); + } + let mut correlated = wire.clone(); + correlated["context"]["correlation_id"] = json!("T0 diagnostic"); + assert_eq!(parse(&correlated).unwrap().digest(), original.digest()); + let mut approved = wire.clone(); + approved["context"]["approval"] = json!({"intent_digest":original.approval_intent_digest(),"scope":"orders.accept","expires_at":"200"}); + let approved = parse(&approved).unwrap(); + assert_ne!(approved.digest(), original.digest()); + assert_eq!( + approved.approval_intent_digest(), + original.approval_intent_digest() + ); +} + +#[test] +fn capture_requires_closed_seller_order_data_and_distinguishes_allocation_choices() { + let data = cases(); + let automatic = &data["cases"][0]["wire"]; + for (path, value) in [ + ("/type", json!("orders.decline")), + ("/context/actor/role", json!("buyer")), + ("/context/expected", Value::Null), + ("/input/request", json!("2A".repeat(32))), + ("/input/terms_digest", json!("2A".repeat(32))), + ("/input/allocation", json!([])), + ( + "/input/allocation", + json!({"type":"automatic","allocations":null}), + ), + ( + "/input/allocation", + json!({"type":"automatic","allocations":[]}), + ), + ( + "/input/allocation", + json!({"type":"explicit","allocations":[]}), + ), + ("/input/allocation", json!({"type":"explicit"})), + ("/input/allocation", json!({"type":"unknown"})), + ( + "/input/allocation", + json!({"type":"automatic","stock_free":true}), + ), + ] { + let mut changed = automatic.clone(); + *changed.pointer_mut(path).unwrap() = value; + assert!(parse(&changed).is_err(), "{path}"); + } + for field in ["request", "terms_digest", "allocation"] { + let mut changed = automatic.clone(); + changed["input"].as_object_mut().unwrap().remove(field); + assert!(parse(&changed).is_err()); + } + let mut extra = automatic.clone(); + extra["input"]["terms"] = json!({}); + assert!(parse(&extra).is_err()); + let raw = serde_json::to_string(automatic).unwrap(); + let duplicate=raw.replacen("\"request\":","\"request\":\"3131313131313131313131313131313131313131313131313131313131313131\",\"request\":",1); + assert!(CapturedOrderAcceptance::parse(duplicate.as_bytes()).is_err()); +} + +#[test] +fn advanced_claims_are_positive_versioned_unique_closed_and_bounded_before_capture() { + let data = cases(); + let wire = &data["cases"][1]["wire"]; + for (path, value) in [ + ( + "/input/allocation/allocations/0/quantity/amount", + json!("0"), + ), + ( + "/input/allocation/allocations/0/quantity/amount", + json!(250), + ), + ( + "/input/allocation/allocations/0/quantity", + json!(["250", "g"]), + ), + ( + "/input/allocation/allocations/0/expected_pool_version", + json!("0"), + ), + ( + "/input/allocation/allocations/0/expected_pool_version", + json!(1), + ), + ("/input/allocation/allocations/0", json!([])), + ] { + let mut changed = wire.clone(); + *changed.pointer_mut(path).unwrap() = value; + assert!(parse(&changed).is_err(), "{path}"); + } + let mut duplicate = wire.clone(); + duplicate["input"]["allocation"]["allocations"][1] = + duplicate["input"]["allocation"]["allocations"][0].clone(); + assert!(parse(&duplicate).is_err()); + let mut extra = wire.clone(); + extra["input"]["allocation"]["allocations"][0]["allow_deficit"] = json!(true); + assert!(parse(&extra).is_err()); + let mut bounded = wire.clone(); + let values = (1..=64) + .map(|index| { + let mut value = wire["input"]["allocation"]["allocations"][0].clone(); + value["pool_id"] = json!(format!("{index:064x}")); + value + }) + .collect::<Vec<_>>(); + bounded["input"]["allocation"]["allocations"] = json!(values); + assert_eq!( + parse(&bounded) + .unwrap() + .input() + .allocation() + .explicit_allocations() + .unwrap() + .len(), + 64 + ); + bounded["input"]["allocation"]["allocations"].as_array_mut().unwrap().push(json!({"line_id":"25".repeat(32),"pool_id":format!("{:064x}",65),"quantity":{"amount":"1","unit":"g"},"expected_pool_version":"1"})); + assert!(parse(&bounded).is_err()); +}