lib

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

commit 7845f46c23bcfc4ebc4d3b8e705fe456308f7ce1
parent f6c67bf981dd183b81c57e8b3a048af126ffaa95
Author: triesap <tyson@radroots.org>
Date:   Thu, 22 Oct 2026 22:49:48 +0000

domain: Validate complete causal commerce record values

- Model nineteen carrier-independent families with private bounded payloads.
- Check declared parties, roles, order scope, chains and required source references.
- Preserve the separate wire, hash, authentication and business-effect boundaries.
- Verify every family and reference, portable features, additive API and coverage.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 275+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/README.md | 36++++++++++++++++++++++++++++++++++++
Acrates/domain/src/commerce.rs | 478+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/domain/src/commerce/payload.rs | 465+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/domain/src/commerce/value.rs | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/identifier.rs | 4++++
Mcrates/domain/src/lib.rs | 10+++++++++-
Mcrates/domain/tests/identifier.rs | 1+
Mcrates/domain/tests/listing.rs | 3+++
Mcrates/domain/tests/support/agreement.rs | 14+++++++-------
Acrates/domain/tests/support/commerce.rs | 804+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 2299 insertions(+), 8 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -186,6 +186,68 @@ pub radroots_domain::ChatRelation::Reply pub radroots_domain::ChatRelation::Reply::parent: radroots_domain::MessageId impl core::fmt::Debug for radroots_domain::ChatRelation pub fn radroots_domain::ChatRelation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::CommerceError +pub radroots_domain::CommerceError::InvalidAuthor +pub radroots_domain::CommerceError::InvalidLines +pub radroots_domain::CommerceError::InvalidMeasurements +pub radroots_domain::CommerceError::InvalidOrder +pub radroots_domain::CommerceError::InvalidParents +pub radroots_domain::CommerceError::InvalidPrevious +pub radroots_domain::CommerceError::InvalidReferences +pub radroots_domain::CommerceError::InvalidSequence +pub radroots_domain::CommerceError::InvalidText +pub radroots_domain::CommerceError::MissingParent +pub radroots_domain::CommerceError::PartiesCoincide +pub radroots_domain::CommerceError::TermsPartiesMismatch +impl core::error::Error for radroots_domain::CommerceError +impl core::fmt::Display for radroots_domain::CommerceError +pub fn radroots_domain::CommerceError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::CommercePayload +pub radroots_domain::CommercePayload::AgreementCommitted(radroots_domain::AgreementCommitment) +pub radroots_domain::CommercePayload::CancellationAuthorized(radroots_domain::ProposalAuthorization) +pub radroots_domain::CommercePayload::CancellationProposed(radroots_domain::CancellationProposal) +pub radroots_domain::CommercePayload::Decline(radroots_domain::RecordReason) +pub radroots_domain::CommercePayload::Handover(radroots_domain::HandoverClaim) +pub radroots_domain::CommercePayload::Issue(radroots_domain::IssueReport) +pub radroots_domain::CommercePayload::Quote(radroots_domain::TermsQuote) +pub radroots_domain::CommercePayload::Ready(radroots_domain::ReadinessClaim) +pub radroots_domain::CommercePayload::Receipt(radroots_domain::ReceiptObservation) +pub radroots_domain::CommercePayload::Request(radroots_domain::TermsRequest) +pub radroots_domain::CommercePayload::ResidualReleased(radroots_domain::ResidualRelease) +pub radroots_domain::CommercePayload::ResolutionAuthorized(radroots_domain::ProposalAuthorization) +pub radroots_domain::CommercePayload::ResolutionCommitted(radroots_domain::ResolutionCommitment) +pub radroots_domain::CommercePayload::ResolutionProposed(radroots_domain::ResolutionProposal) +pub radroots_domain::CommercePayload::TermsAuthorized(radroots_domain::TermsAuthorization) +pub radroots_domain::CommercePayload::TermsProposed(radroots_domain::TermsProposal) +pub radroots_domain::CommercePayload::TermsRejected(radroots_domain::RecordReason) +pub radroots_domain::CommercePayload::WithdrawalAcknowledged(radroots_domain::WithdrawalAcknowledgement) +pub radroots_domain::CommercePayload::WithdrawalRequested(radroots_domain::RecordReason) +impl radroots_domain::CommercePayload +pub const fn radroots_domain::CommercePayload::record_type(&self) -> radroots_domain::CommerceType +impl core::fmt::Debug for radroots_domain::CommercePayload +pub fn radroots_domain::CommercePayload::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::CommerceType +pub radroots_domain::CommerceType::AgreementCommitted +pub radroots_domain::CommerceType::CancellationAuthorized +pub radroots_domain::CommerceType::CancellationProposed +pub radroots_domain::CommerceType::Decline +pub radroots_domain::CommerceType::Handover +pub radroots_domain::CommerceType::Issue +pub radroots_domain::CommerceType::Quote +pub radroots_domain::CommerceType::Ready +pub radroots_domain::CommerceType::Receipt +pub radroots_domain::CommerceType::Request +pub radroots_domain::CommerceType::ResidualReleased +pub radroots_domain::CommerceType::ResolutionAuthorized +pub radroots_domain::CommerceType::ResolutionCommitted +pub radroots_domain::CommerceType::ResolutionProposed +pub radroots_domain::CommerceType::TermsAuthorized +pub radroots_domain::CommerceType::TermsProposed +pub radroots_domain::CommerceType::TermsRejected +pub radroots_domain::CommerceType::WithdrawalAcknowledged +pub radroots_domain::CommerceType::WithdrawalRequested +impl radroots_domain::CommerceType +pub const fn radroots_domain::CommerceType::as_str(self) -> &'static str pub enum radroots_domain::ContentMeasure pub radroots_domain::ContentMeasure::Estimated pub radroots_domain::ContentMeasure::Estimated::quantity: radroots_domain::Quantity @@ -227,6 +289,15 @@ pub radroots_domain::IdentifierError::InvalidLength impl core::error::Error for radroots_domain::IdentifierError impl core::fmt::Display for radroots_domain::IdentifierError pub fn radroots_domain::IdentifierError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::IssueCode +pub radroots_domain::IssueCode::Collection +pub radroots_domain::IssueCode::Excess +pub radroots_domain::IssueCode::Other +pub radroots_domain::IssueCode::Quality +pub radroots_domain::IssueCode::Shortage +pub radroots_domain::IssueCode::Substitution +impl radroots_domain::IssueCode +pub const fn radroots_domain::IssueCode::as_str(self) -> &'static str pub enum radroots_domain::MessageError pub radroots_domain::MessageError::LimitExceeded impl core::error::Error for radroots_domain::MessageError @@ -329,6 +400,16 @@ pub const fn radroots_domain::AgreedFixedPrice::selected_tier_from(self) -> core pub fn radroots_domain::AgreedFixedPrice::total(self, radroots_domain::PositiveDecimal) -> core::result::Result<radroots_domain::Money, radroots_domain::TermsError> impl core::fmt::Debug for radroots_domain::AgreedFixedPrice pub fn radroots_domain::AgreedFixedPrice::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::AgreementCommitment +impl radroots_domain::AgreementCommitment +pub const fn radroots_domain::AgreementCommitment::authority(&self) -> radroots_domain::AuthorityRef +pub const fn radroots_domain::AgreementCommitment::authorization(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::AgreementCommitment::base_agreement(&self) -> core::option::Option<radroots_domain::RecordId> +pub fn radroots_domain::AgreementCommitment::new(core::option::Option<radroots_domain::RecordId>, radroots_domain::RecordId, radroots_domain::TermsDigest, radroots_domain::AuthorityRef, radroots_domain::Sequence) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::AgreementCommitment::seller_sequence(&self) -> radroots_domain::Sequence +pub const fn radroots_domain::AgreementCommitment::terms_digest(&self) -> radroots_domain::TermsDigest +impl core::fmt::Debug for radroots_domain::AgreementCommitment +pub fn radroots_domain::AgreementCommitment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::AgreementLine impl radroots_domain::AgreementLine pub const fn radroots_domain::AgreementLine::amount(&self) -> radroots_domain::PositiveDecimal @@ -387,6 +468,15 @@ impl radroots_domain::AuthorityRef pub const fn radroots_domain::AuthorityRef::executor_id(self) -> radroots_domain::ExecutorId pub const fn radroots_domain::AuthorityRef::generation(self) -> radroots_domain::Generation pub const fn radroots_domain::AuthorityRef::new(radroots_domain::ExecutorId, radroots_domain::Generation) -> Self +pub struct radroots_domain::CancellationProposal +impl radroots_domain::CancellationProposal +pub const fn radroots_domain::CancellationProposal::agreement(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::CancellationProposal::expires_at(&self) -> radroots_domain::UnixSeconds +pub fn radroots_domain::CancellationProposal::new(radroots_domain::RecordId, alloc::vec::Vec<radroots_domain::LineQuantity>, &str, radroots_domain::UnixSeconds) -> core::result::Result<Self, radroots_domain::CommerceError> +pub fn radroots_domain::CancellationProposal::reason(&self) -> &str +pub fn radroots_domain::CancellationProposal::residual(&self) -> &[radroots_domain::LineQuantity] +impl core::fmt::Debug for radroots_domain::CancellationProposal +pub fn radroots_domain::CancellationProposal::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::ChatMessage impl radroots_domain::ChatMessage pub const fn radroots_domain::ChatMessage::author(&self) -> radroots_identity::key::PublicKey @@ -452,6 +542,31 @@ impl serde_core::ser::Serialize for radroots_domain::CommandDigest pub fn radroots_domain::CommandDigest::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::CommandDigest pub fn radroots_domain::CommandDigest::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::CommerceContent +impl radroots_domain::CommerceContent +pub const fn radroots_domain::CommerceContent::header(&self) -> &radroots_domain::CommerceHeader +pub fn radroots_domain::CommerceContent::new(radroots_domain::CommerceHeader, radroots_domain::CommercePayload) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::CommerceContent::payload(&self) -> &radroots_domain::CommercePayload +pub const fn radroots_domain::CommerceContent::profile(&self) -> &'static str +pub const fn radroots_domain::CommerceContent::record_type(&self) -> radroots_domain::CommerceType +pub const fn radroots_domain::CommerceContent::version(&self) -> u32 +impl core::fmt::Debug for radroots_domain::CommerceContent +pub fn radroots_domain::CommerceContent::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::CommerceHeader +impl radroots_domain::CommerceHeader +pub const radroots_domain::CommerceHeader::MAX_PARENTS: usize +pub const fn radroots_domain::CommerceHeader::author(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::CommerceHeader::author_previous(&self) -> core::option::Option<radroots_domain::RecordId> +pub const fn radroots_domain::CommerceHeader::author_sequence(&self) -> radroots_domain::Sequence +pub const fn radroots_domain::CommerceHeader::buyer(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::CommerceHeader::created_at(&self) -> radroots_domain::UnixSeconds +pub fn radroots_domain::CommerceHeader::new(radroots_domain::ThreadId, core::option::Option<radroots_domain::OrderId>, radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, radroots_domain::UnixSeconds, radroots_domain::Sequence, core::option::Option<radroots_domain::RecordId>, alloc::vec::Vec<radroots_domain::SourceId>) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::CommerceHeader::order_id(&self) -> core::option::Option<radroots_domain::OrderId> +pub fn radroots_domain::CommerceHeader::parents(&self) -> &[radroots_domain::SourceId] +pub const fn radroots_domain::CommerceHeader::seller(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::CommerceHeader::thread_id(&self) -> radroots_domain::ThreadId +impl core::fmt::Debug for radroots_domain::CommerceHeader +pub fn radroots_domain::CommerceHeader::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::CorrelationId(_) impl radroots_domain::CorrelationId pub fn radroots_domain::CorrelationId::as_str(&self) -> &str @@ -555,6 +670,14 @@ pub const fn radroots_domain::ExpectedOrder::order_id(&self) -> radroots_domain: pub const fn radroots_domain::ExpectedOrder::seller_sequence(&self) -> radroots_domain::Sequence impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ExpectedOrder pub fn radroots_domain::ExpectedOrder::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::FinalMeasurement +impl radroots_domain::FinalMeasurement +pub const fn radroots_domain::FinalMeasurement::line_id(self) -> radroots_domain::AgreementLineId +pub const fn radroots_domain::FinalMeasurement::line_total(self) -> radroots_domain::Money +pub const fn radroots_domain::FinalMeasurement::new(radroots_domain::AgreementLineId, radroots_domain::Quantity, radroots_domain::Money) -> Self +pub const fn radroots_domain::FinalMeasurement::quantity(self) -> radroots_domain::Quantity +impl core::fmt::Debug for radroots_domain::FinalMeasurement +pub fn radroots_domain::FinalMeasurement::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::FixedPrice impl radroots_domain::FixedPrice pub const radroots_domain::FixedPrice::MAX_TIERS: usize @@ -621,12 +744,33 @@ impl serde_core::ser::Serialize for radroots_domain::GrantId pub fn radroots_domain::GrantId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::GrantId pub fn radroots_domain::GrantId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::HandoverClaim +impl radroots_domain::HandoverClaim +pub const fn radroots_domain::HandoverClaim::agreement(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::HandoverClaim::authority(&self) -> radroots_domain::AuthorityRef +pub const fn radroots_domain::HandoverClaim::fulfillment_group(&self) -> radroots_domain::FulfillmentGroupId +pub fn radroots_domain::HandoverClaim::lines(&self) -> &[radroots_domain::LineQuantity] +pub fn radroots_domain::HandoverClaim::measurements(&self) -> &[radroots_domain::FinalMeasurement] +pub fn radroots_domain::HandoverClaim::new(radroots_domain::RecordId, radroots_domain::FulfillmentGroupId, alloc::vec::Vec<radroots_domain::LineQuantity>, alloc::vec::Vec<radroots_domain::FinalMeasurement>, radroots_domain::UnixSeconds, radroots_domain::AuthorityRef, radroots_domain::Sequence) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::HandoverClaim::occurred_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::HandoverClaim::seller_sequence(&self) -> radroots_domain::Sequence +impl core::fmt::Debug for radroots_domain::HandoverClaim +pub fn radroots_domain::HandoverClaim::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::IssuanceWindow impl radroots_domain::IssuanceWindow pub fn radroots_domain::IssuanceWindow::capture(radroots_domain::UnixSeconds, radroots_domain::UnixSeconds) -> core::result::Result<Self, radroots_domain::ContextError> pub const fn radroots_domain::IssuanceWindow::first_issue_not_after(self) -> radroots_domain::UnixSeconds pub fn radroots_domain::IssuanceWindow::new(radroots_domain::UnixSeconds, radroots_domain::UnixSeconds) -> core::result::Result<Self, radroots_domain::ContextError> pub const fn radroots_domain::IssuanceWindow::prepared_at(self) -> radroots_domain::UnixSeconds +pub struct radroots_domain::IssueReport +impl radroots_domain::IssueReport +pub const fn radroots_domain::IssueReport::code(&self) -> radroots_domain::IssueCode +pub fn radroots_domain::IssueReport::description(&self) -> &str +pub fn radroots_domain::IssueReport::lines(&self) -> &[radroots_domain::LineQuantity] +pub fn radroots_domain::IssueReport::new(radroots_domain::IssueCode, &str, alloc::vec::Vec<radroots_domain::LineQuantity>, alloc::vec::Vec<radroots_domain::RecordId>) -> core::result::Result<Self, radroots_domain::CommerceError> +pub fn radroots_domain::IssueReport::source_records(&self) -> &[radroots_domain::RecordId] +impl core::fmt::Debug for radroots_domain::IssueReport +pub fn radroots_domain::IssueReport::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::LinePrice impl radroots_domain::LinePrice pub const fn radroots_domain::LinePrice::basis(self) -> radroots_domain::PositiveDecimal @@ -636,6 +780,13 @@ pub const fn radroots_domain::LinePrice::selected_tier_from(self) -> core::optio pub const fn radroots_domain::LinePrice::total(self) -> radroots_domain::Money impl core::fmt::Debug for radroots_domain::LinePrice pub fn radroots_domain::LinePrice::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::LineQuantity +impl radroots_domain::LineQuantity +pub const fn radroots_domain::LineQuantity::amount(self) -> radroots_domain::Decimal +pub const fn radroots_domain::LineQuantity::line_id(self) -> radroots_domain::AgreementLineId +pub const fn radroots_domain::LineQuantity::new(radroots_domain::AgreementLineId, radroots_domain::Decimal) -> Self +impl core::fmt::Debug for radroots_domain::LineQuantity +pub fn radroots_domain::LineQuantity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::ListingOptionId(_) impl radroots_domain::ListingOptionId pub const fn radroots_domain::ListingOptionId::as_bytes(&self) -> &[u8; 32] @@ -763,6 +914,13 @@ pub fn radroots_domain::PrivateFulfillment::new(radroots_domain::listing::Fulfil pub const fn radroots_domain::PrivateFulfillment::window(&self) -> radroots_domain::Window impl core::fmt::Debug for radroots_domain::PrivateFulfillment pub fn radroots_domain::PrivateFulfillment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::ProposalAuthorization +impl radroots_domain::ProposalAuthorization +pub const fn radroots_domain::ProposalAuthorization::expires_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::ProposalAuthorization::new(radroots_domain::RecordId, radroots_domain::UnixSeconds) -> Self +pub const fn radroots_domain::ProposalAuthorization::proposal(&self) -> radroots_domain::RecordId +impl core::fmt::Debug for radroots_domain::ProposalAuthorization +pub fn radroots_domain::ProposalAuthorization::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::Quantity impl radroots_domain::Quantity pub const fn radroots_domain::Quantity::amount(self) -> radroots_domain::Decimal @@ -773,6 +931,25 @@ pub fn radroots_domain::Quantity::new(radroots_domain::Decimal, radroots_domain: pub const fn radroots_domain::Quantity::unit(self) -> radroots_domain::listing::MeasurementUnit impl core::fmt::Debug for radroots_domain::Quantity pub fn radroots_domain::Quantity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::ReadinessClaim +impl radroots_domain::ReadinessClaim +pub const fn radroots_domain::ReadinessClaim::agreement(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::ReadinessClaim::fulfillment_group(&self) -> radroots_domain::FulfillmentGroupId +pub fn radroots_domain::ReadinessClaim::lines(&self) -> &[radroots_domain::LineQuantity] +pub fn radroots_domain::ReadinessClaim::new(radroots_domain::RecordId, radroots_domain::FulfillmentGroupId, alloc::vec::Vec<radroots_domain::LineQuantity>, radroots_domain::Window) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::ReadinessClaim::window(&self) -> radroots_domain::Window +impl core::fmt::Debug for radroots_domain::ReadinessClaim +pub fn radroots_domain::ReadinessClaim::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::ReceiptObservation +impl radroots_domain::ReceiptObservation +pub const fn radroots_domain::ReceiptObservation::handover(&self) -> radroots_domain::RecordId +pub fn radroots_domain::ReceiptObservation::lines(&self) -> &[radroots_domain::LineQuantity] +pub fn radroots_domain::ReceiptObservation::new(radroots_domain::RecordId, alloc::vec::Vec<radroots_domain::LineQuantity>, core::option::Option<radroots_domain::RecordId>, radroots_domain::UnixSeconds, &str) -> core::result::Result<Self, radroots_domain::CommerceError> +pub fn radroots_domain::ReceiptObservation::note(&self) -> &str +pub const fn radroots_domain::ReceiptObservation::occurred_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::ReceiptObservation::supersedes(&self) -> core::option::Option<radroots_domain::RecordId> +impl core::fmt::Debug for radroots_domain::ReceiptObservation +pub fn radroots_domain::ReceiptObservation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::RecordId(_) impl radroots_domain::RecordId pub const fn radroots_domain::RecordId::as_bytes(&self) -> &[u8; 32] @@ -787,6 +964,50 @@ impl serde_core::ser::Serialize for radroots_domain::RecordId pub fn radroots_domain::RecordId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::RecordId pub fn radroots_domain::RecordId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::RecordReason +impl radroots_domain::RecordReason +pub fn radroots_domain::RecordReason::new(radroots_domain::RecordId, &str) -> core::result::Result<Self, radroots_domain::CommerceError> +pub fn radroots_domain::RecordReason::reason(&self) -> &str +pub const fn radroots_domain::RecordReason::target(&self) -> radroots_domain::RecordId +impl core::fmt::Debug for radroots_domain::RecordReason +pub fn radroots_domain::RecordReason::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::ResidualRelease +impl radroots_domain::ResidualRelease +pub const fn radroots_domain::ResidualRelease::agreement(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::ResidualRelease::authority(&self) -> radroots_domain::AuthorityRef +pub const fn radroots_domain::ResidualRelease::authorization(&self) -> radroots_domain::RecordId +pub fn radroots_domain::ResidualRelease::new(radroots_domain::RecordId, radroots_domain::RecordId, radroots_domain::RecordId, alloc::vec::Vec<radroots_domain::LineQuantity>, radroots_domain::AuthorityRef, radroots_domain::Sequence) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::ResidualRelease::proposal(&self) -> radroots_domain::RecordId +pub fn radroots_domain::ResidualRelease::residual(&self) -> &[radroots_domain::LineQuantity] +pub const fn radroots_domain::ResidualRelease::seller_sequence(&self) -> radroots_domain::Sequence +impl core::fmt::Debug for radroots_domain::ResidualRelease +pub fn radroots_domain::ResidualRelease::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::Resolution +impl radroots_domain::Resolution +pub fn radroots_domain::Resolution::accepted_receipts(&self) -> &[radroots_domain::RecordId] +pub fn radroots_domain::Resolution::issues(&self) -> &[radroots_domain::RecordId] +pub fn radroots_domain::Resolution::new(alloc::vec::Vec<radroots_domain::RecordId>, alloc::vec::Vec<radroots_domain::RecordId>, alloc::vec::Vec<radroots_domain::LineQuantity>, &str) -> core::result::Result<Self, radroots_domain::CommerceError> +pub fn radroots_domain::Resolution::release_residual(&self) -> &[radroots_domain::LineQuantity] +pub fn radroots_domain::Resolution::summary(&self) -> &str +impl core::fmt::Debug for radroots_domain::Resolution +pub fn radroots_domain::Resolution::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::ResolutionCommitment +impl radroots_domain::ResolutionCommitment +pub const fn radroots_domain::ResolutionCommitment::authority(&self) -> radroots_domain::AuthorityRef +pub const fn radroots_domain::ResolutionCommitment::authorization(&self) -> radroots_domain::RecordId +pub fn radroots_domain::ResolutionCommitment::new(radroots_domain::RecordId, radroots_domain::RecordId, radroots_domain::AuthorityRef, radroots_domain::Sequence) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::ResolutionCommitment::proposal(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::ResolutionCommitment::seller_sequence(&self) -> radroots_domain::Sequence +impl core::fmt::Debug for radroots_domain::ResolutionCommitment +pub fn radroots_domain::ResolutionCommitment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::ResolutionProposal +impl radroots_domain::ResolutionProposal +pub const fn radroots_domain::ResolutionProposal::agreement(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::ResolutionProposal::expires_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::ResolutionProposal::new(radroots_domain::RecordId, radroots_domain::Resolution, radroots_domain::UnixSeconds) -> Self +pub const fn radroots_domain::ResolutionProposal::resolution(&self) -> &radroots_domain::Resolution +impl core::fmt::Debug for radroots_domain::ResolutionProposal +pub fn radroots_domain::ResolutionProposal::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::RouteDigest(_) impl radroots_domain::RouteDigest pub const fn radroots_domain::RouteDigest::as_bytes(&self) -> &[u8; 32] @@ -857,6 +1078,53 @@ pub const fn radroots_domain::Terms::seller(&self) -> radroots_identity::key::Pu pub const fn radroots_domain::Terms::supply(&self) -> &radroots_domain::SupplyCommitment impl core::fmt::Debug for radroots_domain::Terms pub fn radroots_domain::Terms::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::TermsAuthorization +impl radroots_domain::TermsAuthorization +pub const fn radroots_domain::TermsAuthorization::expires_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::TermsAuthorization::new(radroots_domain::RecordId, radroots_domain::TermsDigest, radroots_domain::UnixSeconds) -> Self +pub const fn radroots_domain::TermsAuthorization::proposal(&self) -> radroots_domain::RecordId +pub const fn radroots_domain::TermsAuthorization::terms_digest(&self) -> radroots_domain::TermsDigest +impl core::fmt::Debug for radroots_domain::TermsAuthorization +pub fn radroots_domain::TermsAuthorization::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::TermsDigest(_) +impl radroots_domain::TermsDigest +pub const fn radroots_domain::TermsDigest::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::TermsDigest::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::TermsDigest::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::TermsDigest +pub fn radroots_domain::TermsDigest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::TermsDigest +pub type radroots_domain::TermsDigest::Err = radroots_domain::IdentifierError +pub fn radroots_domain::TermsDigest::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::TermsDigest +pub fn radroots_domain::TermsDigest::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::TermsDigest +pub fn radroots_domain::TermsDigest::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::TermsProposal +impl radroots_domain::TermsProposal +pub const fn radroots_domain::TermsProposal::base_agreement(&self) -> core::option::Option<radroots_domain::RecordId> +pub const fn radroots_domain::TermsProposal::expires_at(&self) -> radroots_domain::UnixSeconds +pub fn radroots_domain::TermsProposal::new(core::option::Option<radroots_domain::RecordId>, radroots_domain::Terms, radroots_domain::UnixSeconds, &str) -> core::result::Result<Self, radroots_domain::CommerceError> +pub fn radroots_domain::TermsProposal::reason(&self) -> &str +pub const fn radroots_domain::TermsProposal::terms(&self) -> &radroots_domain::Terms +impl core::fmt::Debug for radroots_domain::TermsProposal +pub fn radroots_domain::TermsProposal::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::TermsQuote +impl radroots_domain::TermsQuote +pub const fn radroots_domain::TermsQuote::expires_at(&self) -> radroots_domain::UnixSeconds +pub const fn radroots_domain::TermsQuote::in_reply_to(&self) -> core::option::Option<radroots_domain::SourceId> +pub fn radroots_domain::TermsQuote::new(radroots_domain::Terms, radroots_domain::UnixSeconds, core::option::Option<radroots_domain::SourceId>) -> Self +pub const fn radroots_domain::TermsQuote::terms(&self) -> &radroots_domain::Terms +impl core::fmt::Debug for radroots_domain::TermsQuote +pub fn radroots_domain::TermsQuote::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::TermsRequest +impl radroots_domain::TermsRequest +pub const fn radroots_domain::TermsRequest::expires_at(&self) -> radroots_domain::UnixSeconds +pub fn radroots_domain::TermsRequest::new(radroots_domain::Terms, radroots_domain::UnixSeconds, core::option::Option<radroots_domain::RecordId>) -> Self +pub const fn radroots_domain::TermsRequest::quote(&self) -> core::option::Option<radroots_domain::RecordId> +pub const fn radroots_domain::TermsRequest::terms(&self) -> &radroots_domain::Terms +impl core::fmt::Debug for radroots_domain::TermsRequest +pub fn radroots_domain::TermsRequest::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::ThreadId(_) impl radroots_domain::ThreadId pub const fn radroots_domain::ThreadId::as_bytes(&self) -> &[u8; 32] @@ -924,6 +1192,13 @@ pub const fn radroots_domain::Window::start(self) -> radroots_domain::UnixSecond pub const fn radroots_domain::Window::timezone(self) -> radroots_domain::TimeZoneId impl core::fmt::Debug for radroots_domain::Window pub fn radroots_domain::Window::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::WithdrawalAcknowledgement +impl radroots_domain::WithdrawalAcknowledgement +pub fn radroots_domain::WithdrawalAcknowledgement::new(radroots_domain::RecordId, radroots_domain::Sequence) -> core::result::Result<Self, radroots_domain::CommerceError> +pub const fn radroots_domain::WithdrawalAcknowledgement::seller_sequence(&self) -> radroots_domain::Sequence +pub const fn radroots_domain::WithdrawalAcknowledgement::withdrawal(&self) -> radroots_domain::RecordId +impl core::fmt::Debug for radroots_domain::WithdrawalAcknowledgement +pub fn radroots_domain::WithdrawalAcknowledgement::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::WorkspaceId(_) impl radroots_domain::WorkspaceId pub const fn radroots_domain::WorkspaceId::as_bytes(&self) -> &[u8; 32] diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -128,6 +128,42 @@ fn encode(terms: &radroots_domain::Terms) { } ``` +`CommerceContent` retains the19 supported logical record families as immutable +private data before protocol-owned canonical record-ID computation. Its header +requires distinct participants, a participant author, a positive sequence with +the explicit first/later previous-link shape, and at most8 strictly sorted +unique full parent digests. Fixed seller/buyer record roles are checked; all +non-quote families require an order ID. Terms-bearing records match header +participants and declare their exact listing sources. Each payload's required +source references and the author's previous record must appear in the parent +set. Source-array, line, text and parent bounds apply jointly; construction +refuses missing references and never silently omits them to fit a limit. + +Complete payloads preserve typed terms digests, positive seller sequences, +explicit authority claims, bounded line/measurement assertions, issue data and +resolution proposals. Measurements cannot repeat or name a line outside their +handover claim. Private text is zeroizing and diagnostics are redacted. There is +no automatic serialization/deserialization, numeric Nostr rumor kind, ambient +clock, signature or installed effect. An exact zero observation remains data; +it never grants a movement, release or trusted measurement. + +Declared parent membership is not authenticated coverage. Actual parent +author/thread/order/type/sequence continuity, counterparty consent, source and +terms hashes, deadline readiness, measurement economics and cumulative business +state remain separate admission/execution requirements. Record and terms +digests remain distinct from unsigned chat rumors and signed carrier IDs. + +```compile_fail +use radroots_domain::{RecordId, TermsDigest}; +let _: TermsDigest = RecordId::from_bytes([0; 32]); +``` + +```compile_fail +fn encode(content: &radroots_domain::CommerceContent) { + let _ = serde_json::to_string(content); +} +``` + Namespaces remain separate across native calls: ```compile_fail diff --git a/crates/domain/src/commerce.rs b/crates/domain/src/commerce.rs @@ -0,0 +1,478 @@ +//! Carrier-independent private record claims. These values provide no content +//! hash, signature, authenticated parent coverage, consent or installed effects. +use crate::{OrderId, PublicKey, RecordId, Sequence, SourceId, Terms, ThreadId, UnixSeconds}; +use alloc::{boxed::Box, vec::Vec}; +use core::fmt; + +mod value; +pub use value::{FinalMeasurement, IssueCode, IssueReport, LineQuantity, Resolution}; +mod payload; +pub use payload::{ + AgreementCommitment, CancellationProposal, HandoverClaim, ProposalAuthorization, + ReadinessClaim, ReceiptObservation, RecordReason, ResidualRelease, ResolutionCommitment, + ResolutionProposal, TermsAuthorization, TermsProposal, TermsQuote, TermsRequest, + WithdrawalAcknowledgement, +}; + +/// Exact declared common record data; construction authenticates no participant. +#[derive(Clone, Eq, PartialEq)] +pub struct CommerceHeader { + thread_id: ThreadId, + order_id: Option<OrderId>, + author: PublicKey, + buyer: PublicKey, + seller: PublicKey, + created_at: UnixSeconds, + author_sequence: Sequence, + author_previous: Option<RecordId>, + parents: Box<[SourceId]>, +} +impl CommerceHeader { + /// Largest supported direct causal-parent set. Payload/source limits apply + /// jointly; referenced data must never be silently omitted to fit this cap. + pub const MAX_PARENTS: usize = 8; + /// Validates declared participants, positive sequence/previous shape and a + /// sorted unique parent set before capture. Previous author/thread/order, + /// source signatures, sequence continuity and actual coverage need admission. + #[allow(clippy::too_many_arguments)] + pub fn new( + thread_id: ThreadId, + order_id: Option<OrderId>, + author: PublicKey, + buyer: PublicKey, + seller: PublicKey, + created_at: UnixSeconds, + author_sequence: Sequence, + author_previous: Option<RecordId>, + parents: Vec<SourceId>, + ) -> Result<Self, CommerceError> { + if buyer == seller { + return Err(CommerceError::PartiesCoincide); + } + if author != buyer && author != seller { + return Err(CommerceError::InvalidAuthor); + } + if author_sequence.get() == 0 { + return Err(CommerceError::InvalidSequence); + } + if (author_sequence.get() == 1) != author_previous.is_none() { + return Err(CommerceError::InvalidPrevious); + } + if parents.len() > Self::MAX_PARENTS || parents.windows(2).any(|pair| pair[0] >= pair[1]) { + return Err(CommerceError::InvalidParents); + } + if let Some(previous) = author_previous + && !parents.contains(&source(previous)) + { + return Err(CommerceError::MissingParent); + } + Ok(Self { + thread_id, + order_id, + author, + buyer, + seller, + created_at, + author_sequence, + author_previous, + parents: parents.into_boxed_slice(), + }) + } + /// Returns the exact application thread claim. + pub const fn thread_id(&self) -> ThreadId { + self.thread_id + } + /// Returns the explicit order claim; only quotes may omit it in content. + pub const fn order_id(&self) -> Option<OrderId> { + self.order_id + } + /// Returns the claimed author, without signer or delegation proof. + pub const fn author(&self) -> PublicKey { + self.author + } + /// Returns the distinct buyer claim. + pub const fn buyer(&self) -> PublicKey { + self.buyer + } + /// Returns the distinct seller claim. + pub const fn seller(&self) -> PublicKey { + self.seller + } + /// Returns the claimed exact author time, without observing a clock. + pub const fn created_at(&self) -> UnixSeconds { + self.created_at + } + /// Returns the positive declared author sequence, not verified continuity. + pub const fn author_sequence(&self) -> Sequence { + self.author_sequence + } + /// Returns the explicit previous-record claim; sequence1 requires None. + pub const fn author_previous(&self) -> Option<RecordId> { + self.author_previous + } + /// Borrows sorted unique full digests. Generic source identity does not + /// convert a chat rumor, structured record or signed carrier into another. + pub fn parents(&self) -> &[SourceId] { + &self.parents + } + fn require(&self, parent: SourceId) -> Result<(), CommerceError> { + if self.parents.contains(&parent) { + Ok(()) + } else { + Err(CommerceError::MissingParent) + } + } + fn require_record(&self, parent: RecordId) -> Result<(), CommerceError> { + self.require(source(parent)) + } + fn require_optional(&self, parent: Option<RecordId>) -> Result<(), CommerceError> { + match parent { + Some(parent) => self.require_record(parent), + None => Ok(()), + } + } + fn terms(&self, terms: &Terms) -> Result<(), CommerceError> { + if terms.buyer() != self.buyer || terms.seller() != self.seller { + return Err(CommerceError::TermsPartiesMismatch); + } + for line in terms.lines() { + self.require(SourceId::from_bytes(line.source().event_id().into_bytes()))?; + } + Ok(()) + } +} + +/// Closed logical record-family vocabulary; this is not a Nostr numeric kind. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum CommerceType { + /// Complete seller quote. + Quote, + /// Complete buyer request. + Request, + /// Seller refusal of a request. + Decline, + /// Complete initial/replacement terms proposal. + TermsProposed, + /// Counterparty terms authorization claim. + TermsAuthorized, + /// Counterparty proposal rejection claim. + TermsRejected, + /// Seller agreement commitment claim. + AgreementCommitted, + /// Buyer request to withdraw an authorization. + WithdrawalRequested, + /// Seller withdrawal-decision acknowledgement. + WithdrawalAcknowledged, + /// Bilateral residual-cancellation proposal. + CancellationProposed, + /// Counterparty cancellation authorization claim. + CancellationAuthorized, + /// Seller residual-release claim. + ResidualReleased, + /// Seller readiness assertion. + Ready, + /// Seller handover assertion. + Handover, + /// Independent buyer observation. + Receipt, + /// Participant issue report. + Issue, + /// Complete issue-resolution proposal. + ResolutionProposed, + /// Counterparty resolution authorization claim. + ResolutionAuthorized, + /// Seller resolution-commitment claim. + ResolutionCommitted, +} +impl CommerceType { + /// Returns the exact closed content token, never a placeholder rumor kind. + pub const fn as_str(self) -> &'static str { + match self { + Self::Quote => "quote", + Self::Request => "request", + Self::Decline => "decline", + Self::TermsProposed => "terms_proposed", + Self::TermsAuthorized => "terms_authorized", + Self::TermsRejected => "terms_rejected", + Self::AgreementCommitted => "agreement_committed", + Self::WithdrawalRequested => "withdrawal_requested", + Self::WithdrawalAcknowledged => "withdrawal_acknowledged", + Self::CancellationProposed => "cancellation_proposed", + Self::CancellationAuthorized => "cancellation_authorized", + Self::ResidualReleased => "residual_released", + Self::Ready => "ready", + Self::Handover => "handover", + Self::Receipt => "receipt", + Self::Issue => "issue", + Self::ResolutionProposed => "resolution_proposed", + Self::ResolutionAuthorized => "resolution_authorized", + Self::ResolutionCommitted => "resolution_committed", + } + } + fn author(self, header: &CommerceHeader) -> Result<(), CommerceError> { + let valid = match self { + Self::Quote + | Self::Decline + | Self::AgreementCommitted + | Self::WithdrawalAcknowledged + | Self::ResidualReleased + | Self::Ready + | Self::Handover + | Self::ResolutionCommitted => header.author == header.seller, + Self::Request | Self::WithdrawalRequested | Self::Receipt => { + header.author == header.buyer + } + // The exact consenting/rejecting counterparty is determined from + // authenticated parent proposals, never just these declarations. + Self::TermsProposed + | Self::TermsAuthorized + | Self::TermsRejected + | Self::CancellationProposed + | Self::CancellationAuthorized + | Self::Issue + | Self::ResolutionProposed + | Self::ResolutionAuthorized => true, + }; + if valid { + Ok(()) + } else { + Err(CommerceError::InvalidAuthor) + } + } +} + +/// Complete typed private payload alternatives. Each nested value is bounded; +/// its asserted sources, authority and physical facts still need admission. +#[derive(Clone, Eq, PartialEq)] +#[non_exhaustive] +pub enum CommercePayload { + /// Complete seller quote with an optional generic inquiry/source reference. + Quote(TermsQuote), + /// Complete buyer request and optional exact structured quote. + Request(TermsRequest), + /// Request target and private refusal reason. + Decline(RecordReason), + /// Complete proposed terms and explicit optional base agreement. + TermsProposed(TermsProposal), + /// Exact proposal and complete-terms commitment claim. + TermsAuthorized(TermsAuthorization), + /// Exact proposal and private rejection reason. + TermsRejected(RecordReason), + /// Complete seller commitment metadata. + AgreementCommitted(AgreementCommitment), + /// Exact authorization and private withdrawal reason. + WithdrawalRequested(RecordReason), + /// Seller's explicit withdrawal-decision metadata. + WithdrawalAcknowledged(WithdrawalAcknowledgement), + /// Complete proposed residual release. + CancellationProposed(CancellationProposal), + /// Exact cancellation-proposal authorization claim. + CancellationAuthorized(ProposalAuthorization), + /// Complete seller residual-release metadata. + ResidualReleased(ResidualRelease), + /// Complete seller readiness assertion. + Ready(ReadinessClaim), + /// Complete seller handover/measurement assertion. + Handover(HandoverClaim), + /// Independent buyer receipt assertion. + Receipt(ReceiptObservation), + /// Complete bounded participant issue report. + Issue(IssueReport), + /// Complete proposed issue resolution. + ResolutionProposed(ResolutionProposal), + /// Exact resolution-proposal authorization claim. + ResolutionAuthorized(ProposalAuthorization), + /// Seller's complete resolution-commitment metadata. + ResolutionCommitted(ResolutionCommitment), +} +impl CommercePayload { + /// Returns the logical content family, without assigning a Nostr carrier kind. + pub const fn record_type(&self) -> CommerceType { + match self { + Self::Quote(_) => CommerceType::Quote, + Self::Request(_) => CommerceType::Request, + Self::Decline(_) => CommerceType::Decline, + Self::TermsProposed(_) => CommerceType::TermsProposed, + Self::TermsAuthorized(_) => CommerceType::TermsAuthorized, + Self::TermsRejected(_) => CommerceType::TermsRejected, + Self::AgreementCommitted(_) => CommerceType::AgreementCommitted, + Self::WithdrawalRequested(_) => CommerceType::WithdrawalRequested, + Self::WithdrawalAcknowledged(_) => CommerceType::WithdrawalAcknowledged, + Self::CancellationProposed(_) => CommerceType::CancellationProposed, + Self::CancellationAuthorized(_) => CommerceType::CancellationAuthorized, + Self::ResidualReleased(_) => CommerceType::ResidualReleased, + Self::Ready(_) => CommerceType::Ready, + Self::Handover(_) => CommerceType::Handover, + Self::Receipt(_) => CommerceType::Receipt, + Self::Issue(_) => CommerceType::Issue, + Self::ResolutionProposed(_) => CommerceType::ResolutionProposed, + Self::ResolutionAuthorized(_) => CommerceType::ResolutionAuthorized, + Self::ResolutionCommitted(_) => CommerceType::ResolutionCommitted, + } + } + fn references(&self, header: &CommerceHeader) -> Result<(), CommerceError> { + match self { + Self::Quote(value) => { + header.terms(value.terms())?; + if let Some(parent) = value.in_reply_to() { + header.require(parent)?; + } + } + Self::Request(value) => { + header.terms(value.terms())?; + header.require_optional(value.quote())?; + } + Self::Decline(value) + | Self::TermsRejected(value) + | Self::WithdrawalRequested(value) => header.require_record(value.target())?, + Self::TermsProposed(value) => { + header.terms(value.terms())?; + header.require_optional(value.base_agreement())?; + } + Self::TermsAuthorized(value) => header.require_record(value.proposal())?, + Self::AgreementCommitted(value) => { + header.require_optional(value.base_agreement())?; + header.require_record(value.authorization())?; + } + Self::WithdrawalAcknowledged(value) => header.require_record(value.withdrawal())?, + Self::CancellationProposed(value) => header.require_record(value.agreement())?, + Self::CancellationAuthorized(value) | Self::ResolutionAuthorized(value) => { + header.require_record(value.proposal())? + } + Self::ResidualReleased(value) => { + header.require_record(value.proposal())?; + header.require_record(value.authorization())?; + header.require_record(value.agreement())?; + } + Self::Ready(value) => header.require_record(value.agreement())?, + Self::Handover(value) => header.require_record(value.agreement())?, + Self::Receipt(value) => { + header.require_record(value.handover())?; + header.require_optional(value.supersedes())?; + } + Self::Issue(value) => { + for parent in value.source_records() { + header.require_record(*parent)?; + } + } + Self::ResolutionProposed(value) => { + header.require_record(value.agreement())?; + for parent in value + .resolution() + .issues() + .iter() + .chain(value.resolution().accepted_receipts()) + { + header.require_record(*parent)?; + } + } + Self::ResolutionCommitted(value) => { + header.require_record(value.proposal())?; + header.require_record(value.authorization())?; + } + } + Ok(()) + } +} + +/// Complete version1 logical content before protocol-owned canonical record-ID +/// computation. No automatic serialization, authentication or effect is exposed. +#[derive(Clone, Eq, PartialEq)] +pub struct CommerceContent { + header: CommerceHeader, + payload: CommercePayload, +} +impl CommerceContent { + /// Checks self-contained declared role/order/terms/reference consistency. + /// Parent authentication, exact cross-record scope/roles/coverage, deadline + /// actionability, terms digests and agreement-relative economic/state checks + /// remain mandatory before any consent, reduction, signing or stock effects. + pub fn new(header: CommerceHeader, payload: CommercePayload) -> Result<Self, CommerceError> { + let record_type = payload.record_type(); + if record_type != CommerceType::Quote && header.order_id.is_none() { + return Err(CommerceError::InvalidOrder); + } + record_type.author(&header)?; + payload.references(&header)?; + Ok(Self { header, payload }) + } + /// Returns the exact fixed supported content profile identity. + pub const fn profile(&self) -> &'static str { + "radroots.commerce" + } + /// Returns the exact fixed supported content version. + pub const fn version(&self) -> u32 { + 1 + } + /// Explicitly borrows the original declared causal/scope metadata. + pub const fn header(&self) -> &CommerceHeader { + &self.header + } + /// Explicitly borrows complete private payload data. + pub const fn payload(&self) -> &CommercePayload { + &self.payload + } + /// Returns the closed logical family; no numeric rumor kind is assigned. + pub const fn record_type(&self) -> CommerceType { + self.payload.record_type() + } +} +fn source(record: RecordId) -> SourceId { + SourceId::from_bytes(record.into_bytes()) +} + +/// Input-free record-value validation failure; no private text is retained. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum CommerceError { + /// The declared buyer and seller are the same participant. + PartiesCoincide, + /// The declared author is not a participant or has the wrong fixed role. + InvalidAuthor, + /// A stateful order record lacks an order identity. + InvalidOrder, + /// A declared author/seller sequence is zero. + InvalidSequence, + /// First/later author sequence has the wrong explicit previous-link shape. + InvalidPrevious, + /// Parent references exceed8 or are not strictly sorted and unique. + InvalidParents, + /// A declared source required by this value is absent from the parent set. + MissingParent, + /// Complete terms name different participants from their common header. + TermsPartiesMismatch, + /// Bounded private text exceeds its declared character/UTF-8 limits. + InvalidText, + /// A line set has invalid count or duplicate line identities. + InvalidLines, + /// Measurements exceed bounds, repeat a line or name a line outside the claim. + InvalidMeasurements, + /// A source/reference set has invalid count or duplicate identities. + InvalidReferences, +} +impl fmt::Display for CommerceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::PartiesCoincide => "commerce participants must be distinct", + Self::InvalidAuthor => "invalid declared commerce author", + Self::InvalidOrder => "commerce order identity required", + Self::InvalidSequence => "commerce sequence must be positive", + Self::InvalidPrevious => "invalid previous commerce record", + Self::InvalidParents => "invalid commerce parent set", + Self::MissingParent => "required commerce parent not declared", + Self::TermsPartiesMismatch => "commerce terms participants differ", + Self::InvalidText => "commerce text exceeds bound", + Self::InvalidLines => "invalid commerce line set", + Self::InvalidMeasurements => "invalid commerce measurements", + Self::InvalidReferences => "invalid commerce references", + }) + } +} +impl core::error::Error for CommerceError {} +macro_rules! redacted { + ($($name:ident),+)=> { $(impl fmt::Debug for $name { + fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { f.write_str(concat!(stringify!($name),"(<redacted>)")) } + })+ }; +} +redacted!(CommerceHeader, CommercePayload, CommerceContent); diff --git a/crates/domain/src/commerce/payload.rs b/crates/domain/src/commerce/payload.rs @@ -0,0 +1,465 @@ +use super::{ + CommerceError, + value::{check_lines, check_text}, +}; +use super::{FinalMeasurement, LineQuantity, Resolution}; +use crate::{ + AuthorityRef, FulfillmentGroupId, RecordId, Sequence, SourceId, Terms, TermsDigest, + UnixSeconds, Window, +}; +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::fmt; +use zeroize::Zeroizing; + +macro_rules! copy_getters { + ($($field:ident:$ty:ty),+ $(,)?)=> { $( + #[doc=concat!("Returns the explicit `",stringify!($field),"` claim without authenticating it.")] + pub const fn $field(&self)->$ty { self.$field } + )+ }; +} +macro_rules! simple { + ($name:ident,$doc:literal,{$($field:ident:$ty:ty),+ $(,)?})=> { + #[doc=$doc] + #[derive(Clone,Copy,Eq,PartialEq)] + pub struct $name { $($field:$ty),+ } + impl $name { + /// Captures already validated representations; references remain claims. + pub const fn new($($field:$ty),+)->Self { Self { $($field),+ } } + copy_getters!($($field:$ty),+); + } + }; +} + +/// Complete seller quote data, without a hold, signature or buyer consent. +#[derive(Clone, Eq, PartialEq)] +pub struct TermsQuote { + terms: Box<Terms>, + expires_at: UnixSeconds, + in_reply_to: Option<SourceId>, +} +impl TermsQuote { + /// Captures complete values. Expiry actionability and any referenced chat or + /// record require independent source/time admission; no clock is observed. + pub fn new(terms: Terms, expires_at: UnixSeconds, in_reply_to: Option<SourceId>) -> Self { + Self { + terms: Box::new(terms), + expires_at, + in_reply_to, + } + } + /// Explicitly borrows the complete private terms claim. + pub const fn terms(&self) -> &Terms { + &self.terms + } + copy_getters!(expires_at:UnixSeconds,in_reply_to:Option<SourceId>); +} +/// Complete buyer request data, without authentication or stock effects. +#[derive(Clone, Eq, PartialEq)] +pub struct TermsRequest { + terms: Box<Terms>, + expires_at: UnixSeconds, + quote: Option<RecordId>, +} +impl TermsRequest { + /// Captures complete terms and an explicit optional quote reference. + pub fn new(terms: Terms, expires_at: UnixSeconds, quote: Option<RecordId>) -> Self { + Self { + terms: Box::new(terms), + expires_at, + quote, + } + } + /// Explicitly borrows the complete private terms claim. + pub const fn terms(&self) -> &Terms { + &self.terms + } + copy_getters!(expires_at:UnixSeconds,quote:Option<RecordId>); +} +/// A typed record target and bounded private reason. Its enclosing variant +/// identifies whether the target is a request, proposal or authorization. +#[derive(Clone, Eq, PartialEq)] +pub struct RecordReason { + target: RecordId, + reason: Zeroizing<String>, +} +impl RecordReason { + /// Bounds exact reason text before copying; target family needs admission. + pub fn new(target: RecordId, reason: &str) -> Result<Self, CommerceError> { + check_text(reason, 1024)?; + Ok(Self { + target, + reason: Zeroizing::new(reason.into()), + }) + } + copy_getters!(target:RecordId); + /// Explicitly borrows the private reason, without terminal/display escaping. + pub fn reason(&self) -> &str { + &self.reason + } +} +/// Complete proposed replacement terms, preserving the declared base reference. +#[derive(Clone, Eq, PartialEq)] +pub struct TermsProposal { + base_agreement: Option<RecordId>, + terms: Box<Terms>, + expires_at: UnixSeconds, + reason: Zeroizing<String>, +} +impl TermsProposal { + /// Bounds private text before capture. Consent and base-head admission are separate. + pub fn new( + base_agreement: Option<RecordId>, + terms: Terms, + expires_at: UnixSeconds, + reason: &str, + ) -> Result<Self, CommerceError> { + check_text(reason, 1024)?; + Ok(Self { + base_agreement, + terms: Box::new(terms), + expires_at, + reason: Zeroizing::new(reason.into()), + }) + } + copy_getters!(base_agreement:Option<RecordId>,expires_at:UnixSeconds); + /// Explicitly borrows complete private replacement terms. + pub const fn terms(&self) -> &Terms { + &self.terms + } + /// Explicitly borrows private proposal text. + pub fn reason(&self) -> &str { + &self.reason + } +} +simple!(TermsAuthorization,"A proposal/terms commitment claim, not participant consent.",{ + proposal:RecordId,terms_digest:TermsDigest,expires_at:UnixSeconds +}); +simple!(ProposalAuthorization,"A proposal/expiry claim whose counterparty must be independently verified.",{ + proposal:RecordId,expires_at:UnixSeconds +}); + +/// Seller commitment data, without authenticated authority or installation. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct AgreementCommitment { + base_agreement: Option<RecordId>, + authorization: RecordId, + terms_digest: TermsDigest, + authority: AuthorityRef, + seller_sequence: Sequence, +} +impl AgreementCommitment { + /// Requires a positive seller sequence; all source/authority evidence is separate. + pub fn new( + base_agreement: Option<RecordId>, + authorization: RecordId, + terms_digest: TermsDigest, + authority: AuthorityRef, + seller_sequence: Sequence, + ) -> Result<Self, CommerceError> { + positive(seller_sequence)?; + Ok(Self { + base_agreement, + authorization, + terms_digest, + authority, + seller_sequence, + }) + } + copy_getters!(base_agreement:Option<RecordId>,authorization:RecordId,terms_digest:TermsDigest, + authority:AuthorityRef,seller_sequence:Sequence); +} +/// Serialized seller withdrawal-decision claim, without final race resolution. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct WithdrawalAcknowledgement { + withdrawal: RecordId, + seller_sequence: Sequence, +} +impl WithdrawalAcknowledgement { + /// Requires a positive explicit seller decision sequence. + pub fn new(withdrawal: RecordId, seller_sequence: Sequence) -> Result<Self, CommerceError> { + positive(seller_sequence)?; + Ok(Self { + withdrawal, + seller_sequence, + }) + } + copy_getters!(withdrawal:RecordId,seller_sequence:Sequence); +} +/// Bounded residual-cancellation proposal, without releasing any stock. +#[derive(Clone, Eq, PartialEq)] +pub struct CancellationProposal { + agreement: RecordId, + residual: Box<[LineQuantity]>, + reason: Zeroizing<String>, + expires_at: UnixSeconds, +} +impl CancellationProposal { + /// Requires one through32 distinct line assertions and bounded private text. + pub fn new( + agreement: RecordId, + residual: Vec<LineQuantity>, + reason: &str, + expires_at: UnixSeconds, + ) -> Result<Self, CommerceError> { + check_lines(&residual, 1)?; + check_text(reason, 1024)?; + Ok(Self { + agreement, + residual: residual.into_boxed_slice(), + reason: Zeroizing::new(reason.into()), + expires_at, + }) + } + copy_getters!(agreement:RecordId,expires_at:UnixSeconds); + /// Borrows exact proposed residual assertions, without assuming current residual. + pub fn residual(&self) -> &[LineQuantity] { + &self.residual + } + /// Explicitly borrows the private cancellation reason. + pub fn reason(&self) -> &str { + &self.reason + } +} +/// Complete seller residual-release claim; construction does not move stock. +#[derive(Clone, Eq, PartialEq)] +pub struct ResidualRelease { + proposal: RecordId, + authorization: RecordId, + agreement: RecordId, + residual: Box<[LineQuantity]>, + authority: AuthorityRef, + seller_sequence: Sequence, +} +impl ResidualRelease { + /// Bounds line data and requires a positive seller decision sequence. + pub fn new( + proposal: RecordId, + authorization: RecordId, + agreement: RecordId, + residual: Vec<LineQuantity>, + authority: AuthorityRef, + seller_sequence: Sequence, + ) -> Result<Self, CommerceError> { + check_lines(&residual, 1)?; + positive(seller_sequence)?; + Ok(Self { + proposal, + authorization, + agreement, + residual: residual.into_boxed_slice(), + authority, + seller_sequence, + }) + } + copy_getters!(proposal:RecordId,authorization:RecordId,agreement:RecordId,authority:AuthorityRef,seller_sequence:Sequence); + /// Borrows the complete declared release quantities, pending state/consent checks. + pub fn residual(&self) -> &[LineQuantity] { + &self.residual + } +} +/// A seller readiness assertion, without physical handover or buyer receipt. +#[derive(Clone, Eq, PartialEq)] +pub struct ReadinessClaim { + agreement: RecordId, + fulfillment_group: FulfillmentGroupId, + lines: Box<[LineQuantity]>, + window: Window, +} +impl ReadinessClaim { + /// Bounds exact declared lines; agreement/group membership needs admission. + pub fn new( + agreement: RecordId, + fulfillment_group: FulfillmentGroupId, + lines: Vec<LineQuantity>, + window: Window, + ) -> Result<Self, CommerceError> { + check_lines(&lines, 1)?; + Ok(Self { + agreement, + fulfillment_group, + lines: lines.into_boxed_slice(), + window, + }) + } + copy_getters!(agreement:RecordId,fulfillment_group:FulfillmentGroupId,window:Window); + /// Borrows complete asserted ready quantities. + pub fn lines(&self) -> &[LineQuantity] { + &self.lines + } +} +/// A seller handover/measurement assertion; it is not physical truth or consumption. +#[derive(Clone, Eq, PartialEq)] +pub struct HandoverClaim { + agreement: RecordId, + fulfillment_group: FulfillmentGroupId, + lines: Box<[LineQuantity]>, + measurements: Box<[FinalMeasurement]>, + occurred_at: UnixSeconds, + authority: AuthorityRef, + seller_sequence: Sequence, +} +impl HandoverClaim { + /// Bounds line/measurement data, rejects duplicate or unrelated measurement + /// line IDs and requires a positive seller decision sequence. Agreement + /// unit/range/economic/cumulative admission remains mandatory and separate. + pub fn new( + agreement: RecordId, + fulfillment_group: FulfillmentGroupId, + lines: Vec<LineQuantity>, + measurements: Vec<FinalMeasurement>, + occurred_at: UnixSeconds, + authority: AuthorityRef, + seller_sequence: Sequence, + ) -> Result<Self, CommerceError> { + check_lines(&lines, 1)?; + positive(seller_sequence)?; + if measurements.len() > 32 { + return Err(CommerceError::InvalidMeasurements); + } + for (index, measurement) in measurements.iter().enumerate() { + if !lines + .iter() + .any(|line| line.line_id() == measurement.line_id()) + || measurements[..index] + .iter() + .any(|prior| prior.line_id() == measurement.line_id()) + { + return Err(CommerceError::InvalidMeasurements); + } + } + Ok(Self { + agreement, + fulfillment_group, + lines: lines.into_boxed_slice(), + measurements: measurements.into_boxed_slice(), + occurred_at, + authority, + seller_sequence, + }) + } + copy_getters!(agreement:RecordId,fulfillment_group:FulfillmentGroupId,occurred_at:UnixSeconds, + authority:AuthorityRef,seller_sequence:Sequence); + /// Borrows complete seller quantity assertions. + pub fn lines(&self) -> &[LineQuantity] { + &self.lines + } + /// Borrows bounded final measurements, still requiring independent price/range checks. + pub fn measurements(&self) -> &[FinalMeasurement] { + &self.measurements + } +} +/// A buyer's independent observation, without seller stock consumption. +#[derive(Clone, Eq, PartialEq)] +pub struct ReceiptObservation { + handover: RecordId, + lines: Box<[LineQuantity]>, + supersedes: Option<RecordId>, + occurred_at: UnixSeconds, + note: Zeroizing<String>, +} +impl ReceiptObservation { + /// Bounds exact observations and private text. Zero observation remains + /// representable; it never becomes a positive movement or inferred release. + pub fn new( + handover: RecordId, + lines: Vec<LineQuantity>, + supersedes: Option<RecordId>, + occurred_at: UnixSeconds, + note: &str, + ) -> Result<Self, CommerceError> { + check_lines(&lines, 1)?; + check_text(note, 1024)?; + Ok(Self { + handover, + lines: lines.into_boxed_slice(), + supersedes, + occurred_at, + note: Zeroizing::new(note.into()), + }) + } + copy_getters!(handover:RecordId,supersedes:Option<RecordId>,occurred_at:UnixSeconds); + /// Borrows complete asserted observations; supersession is not accumulation. + pub fn lines(&self) -> &[LineQuantity] { + &self.lines + } + /// Explicitly borrows private receipt text. + pub fn note(&self) -> &str { + &self.note + } +} +/// A complete proposed issue resolution, not mutual authorization or installation. +#[derive(Clone, Eq, PartialEq)] +pub struct ResolutionProposal { + agreement: RecordId, + resolution: Resolution, + expires_at: UnixSeconds, +} +impl ResolutionProposal { + /// Captures bounded resolution data and explicit source/time claims. + pub const fn new(agreement: RecordId, resolution: Resolution, expires_at: UnixSeconds) -> Self { + Self { + agreement, + resolution, + expires_at, + } + } + copy_getters!(agreement:RecordId,expires_at:UnixSeconds); + /// Explicitly borrows complete private resolution data. + pub const fn resolution(&self) -> &Resolution { + &self.resolution + } +} +/// A seller resolution-commitment claim, without installed effects. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct ResolutionCommitment { + proposal: RecordId, + authorization: RecordId, + authority: AuthorityRef, + seller_sequence: Sequence, +} +impl ResolutionCommitment { + /// Requires a positive seller decision sequence; consent/authority need admission. + pub fn new( + proposal: RecordId, + authorization: RecordId, + authority: AuthorityRef, + seller_sequence: Sequence, + ) -> Result<Self, CommerceError> { + positive(seller_sequence)?; + Ok(Self { + proposal, + authorization, + authority, + seller_sequence, + }) + } + copy_getters!(proposal:RecordId,authorization:RecordId,authority:AuthorityRef,seller_sequence:Sequence); +} +fn positive(sequence: Sequence) -> Result<(), CommerceError> { + if sequence.get() == 0 { + return Err(CommerceError::InvalidSequence); + } + Ok(()) +} +macro_rules! redacted { + ($($name:ident),+)=> { $(impl fmt::Debug for $name { + fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { f.write_str(concat!(stringify!($name),"(<redacted>)")) } + })+ }; +} +redacted!( + TermsQuote, + TermsRequest, + RecordReason, + TermsProposal, + TermsAuthorization, + ProposalAuthorization, + AgreementCommitment, + WithdrawalAcknowledgement, + CancellationProposal, + ResidualRelease, + ReadinessClaim, + HandoverClaim, + ReceiptObservation, + ResolutionProposal, + ResolutionCommitment +); diff --git a/crates/domain/src/commerce/value.rs b/crates/domain/src/commerce/value.rs @@ -0,0 +1,217 @@ +use super::CommerceError; +use crate::{AgreementLineId, Decimal, Money, Quantity, RecordId}; +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::fmt; +use zeroize::Zeroizing; + +/// An exact nonnegative line assertion, not a physical movement or authorization. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct LineQuantity { + line_id: AgreementLineId, + amount: Decimal, +} +impl LineQuantity { + /// Captures exact data. Operation policy must separately admit a positive + /// movement where required; a zero observation is not a stock release. + pub const fn new(line_id: AgreementLineId, amount: Decimal) -> Self { + Self { line_id, amount } + } + /// Returns the exact line identity claim. + pub const fn line_id(self) -> AgreementLineId { + self.line_id + } + /// Returns the exact asserted amount, without conversion or stock effect. + pub const fn amount(self) -> Decimal { + self.amount + } +} + +/// A measurement/price assertion pending agreement-relative verification. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct FinalMeasurement { + line_id: AgreementLineId, + quantity: Quantity, + line_total: Money, +} +impl FinalMeasurement { + /// Captures validated representations. The admitting executor must check + /// unit, range, price and cumulative quantities against the exact agreement. + pub const fn new(line_id: AgreementLineId, quantity: Quantity, line_total: Money) -> Self { + Self { + line_id, + quantity, + line_total, + } + } + /// Returns the line identity claim. + pub const fn line_id(self) -> AgreementLineId { + self.line_id + } + /// Returns the exact measured quantity claim. + pub const fn quantity(self) -> Quantity { + self.quantity + } + /// Returns the claimed price; it is never a trusted total override. + pub const fn line_total(self) -> Money { + self.line_total + } +} + +/// Closed issue vocabulary, without a unilateral change to agreement terms. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum IssueCode { + /// A participant reports a shortage. + Shortage, + /// A participant reports a quality concern. + Quality, + /// A participant reports a substitution concern. + Substitution, + /// A participant reports a collection concern. + Collection, + /// A participant reports an excess. + Excess, + /// Another explicitly described issue. + Other, +} +impl IssueCode { + /// Returns the exact supported profile token. + pub const fn as_str(self) -> &'static str { + match self { + Self::Shortage => "shortage", + Self::Quality => "quality", + Self::Substitution => "substitution", + Self::Collection => "collection", + Self::Excess => "excess", + Self::Other => "other", + } + } +} + +/// Complete bounded issue data; it establishes neither physical truth nor consent. +#[derive(Clone, Eq, PartialEq)] +pub struct IssueReport { + code: IssueCode, + description: Zeroizing<String>, + lines: Box<[LineQuantity]>, + source_records: Box<[RecordId]>, +} +impl IssueReport { + /// Validates bounds and duplicate identities before owned text capture. + pub fn new( + code: IssueCode, + description: &str, + lines: Vec<LineQuantity>, + source_records: Vec<RecordId>, + ) -> Result<Self, CommerceError> { + check_text(description, 2048)?; + check_lines(&lines, 0)?; + check_records(&source_records, 0)?; + Ok(Self { + code, + description: Zeroizing::new(description.into()), + lines: lines.into_boxed_slice(), + source_records: source_records.into_boxed_slice(), + }) + } + /// Returns the explicit issue vocabulary value. + pub const fn code(&self) -> IssueCode { + self.code + } + /// Explicitly borrows private issue text. + pub fn description(&self) -> &str { + &self.description + } + /// Borrows the complete ordered line assertions. + pub fn lines(&self) -> &[LineQuantity] { + &self.lines + } + /// Borrows exact structured-record references; they remain unauthenticated. + pub fn source_records(&self) -> &[RecordId] { + &self.source_records + } +} + +/// Complete proposed resolution, without agreement installation or release. +#[derive(Clone, Eq, PartialEq)] +pub struct Resolution { + issues: Box<[RecordId]>, + accepted_receipts: Box<[RecordId]>, + release_residual: Box<[LineQuantity]>, + summary: Zeroizing<String>, +} +impl Resolution { + /// Bounds the complete proposal and rejects duplicate references/line IDs. + pub fn new( + issues: Vec<RecordId>, + accepted_receipts: Vec<RecordId>, + release_residual: Vec<LineQuantity>, + summary: &str, + ) -> Result<Self, CommerceError> { + check_records(&issues, 1)?; + check_records(&accepted_receipts, 0)?; + check_lines(&release_residual, 0)?; + check_text(summary, 2048)?; + Ok(Self { + issues: issues.into_boxed_slice(), + accepted_receipts: accepted_receipts.into_boxed_slice(), + release_residual: release_residual.into_boxed_slice(), + summary: Zeroizing::new(summary.into()), + }) + } + /// Borrows the nonempty exact issue-reference list. + pub fn issues(&self) -> &[RecordId] { + &self.issues + } + /// Borrows explicitly accepted receipt references, without inferred truth. + pub fn accepted_receipts(&self) -> &[RecordId] { + &self.accepted_receipts + } + /// Borrows proposed residual quantities; nothing is released by construction. + pub fn release_residual(&self) -> &[LineQuantity] { + &self.release_residual + } + /// Explicitly borrows private resolution text. + pub fn summary(&self) -> &str { + &self.summary + } +} + +pub(super) fn check_text(value: &str, maximum: usize) -> Result<(), CommerceError> { + if value.len() > maximum * 4 || value.chars().count() > maximum { + return Err(CommerceError::InvalidText); + } + Ok(()) +} +pub(super) fn check_lines(lines: &[LineQuantity], minimum: usize) -> Result<(), CommerceError> { + if lines.len() < minimum || lines.len() > 32 { + return Err(CommerceError::InvalidLines); + } + for (index, line) in lines.iter().enumerate() { + if lines[..index] + .iter() + .any(|previous| previous.line_id == line.line_id) + { + return Err(CommerceError::InvalidLines); + } + } + Ok(()) +} +pub(super) fn check_records(records: &[RecordId], minimum: usize) -> Result<(), CommerceError> { + if records.len() < minimum || records.len() > 32 { + return Err(CommerceError::InvalidReferences); + } + for (index, record) in records.iter().enumerate() { + if records[..index].contains(record) { + return Err(CommerceError::InvalidReferences); + } + } + Ok(()) +} + +macro_rules! redacted { + ($($name:ident),+)=> { $(impl fmt::Debug for $name { + fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { f.write_str(concat!(stringify!($name),"(<redacted>)")) } + })+ }; +} +redacted!(LineQuantity, FinalMeasurement, IssueReport, Resolution); diff --git a/crates/domain/src/identifier.rs b/crates/domain/src/identifier.rs @@ -124,6 +124,10 @@ identifier!( FulfillmentGroupId, "An exact 256-bit private fulfillment-group identity." ); +identifier!( + TermsDigest, + "A canonical complete-terms commitment; bytes alone convey no consent." +); identifier!(ThreadId, "An exact 256-bit private thread identifier."); identifier!( WorkspaceId, diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -7,6 +7,7 @@ extern crate alloc; mod agreement; mod amount; +mod commerce; mod context; mod currency; mod fulfillment; @@ -29,6 +30,13 @@ pub use agreement::{ SupplyCommitment, Terms, TermsError, }; pub use amount::{AmountError, Decimal, PositiveDecimal}; +pub use commerce::{ + AgreementCommitment, CancellationProposal, CommerceContent, CommerceError, CommerceHeader, + CommercePayload, CommerceType, FinalMeasurement, HandoverClaim, IssueCode, IssueReport, + LineQuantity, ProposalAuthorization, ReadinessClaim, ReceiptObservation, RecordReason, + ResidualRelease, Resolution, ResolutionCommitment, ResolutionProposal, TermsAuthorization, + TermsProposal, TermsQuote, TermsRequest, WithdrawalAcknowledgement, +}; pub use context::{ ActorRef, ActorRole, Approval, AuthorityRef, CheckpointRef, CommandContextData, ContextError, CorrelationId, Coverage, ExpectedOrder, Generation, Sequence, UnixSeconds, @@ -41,7 +49,7 @@ pub use fulfillment::{FulfillmentError, PrivateFulfillment}; pub use identifier::{ AgreementLineId, ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, ExecutorId, FulfillmentGroupId, GrantId, IdentifierError, ListingOptionId, MessageId, - OperationId, OrderId, RecordId, RouteDigest, SigningAttemptId, SourceId, ThreadId, + OperationId, OrderId, RecordId, RouteDigest, SigningAttemptId, SourceId, TermsDigest, ThreadId, TransactionId, WorkspaceId, }; pub use issuance::{FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow}; diff --git a/crates/domain/tests/identifier.rs b/crates/domain/tests/identifier.rs @@ -31,6 +31,7 @@ fn captured_context_identities_preserve_full_width_and_canonical_encoding() { check!(radroots_domain::SigningAttemptId); check!(radroots_domain::AgreementLineId); check!(radroots_domain::FulfillmentGroupId); + check!(radroots_domain::TermsDigest); check!(radroots_domain::GrantId); check!(radroots_domain::RecordId); check!(radroots_domain::SourceId); diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -9,6 +9,9 @@ mod time; #[path = "support/agreement.rs"] mod agreement; +#[path = "support/commerce.rs"] +mod commerce; + #[test] fn public_text_has_shared_unicode_bounds_and_revision_data_rejects_inverted_time() { use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds}; diff --git a/crates/domain/tests/support/agreement.rs b/crates/domain/tests/support/agreement.rs @@ -6,13 +6,13 @@ use radroots_domain::{ listing::*, }; -fn seller() -> PublicKey { +pub(super) fn seller() -> PublicKey { PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() } -fn buyer() -> PublicKey { +pub(super) fn buyer() -> PublicKey { PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5").unwrap() } -fn money(minor: &str) -> Money { +pub(super) fn money(minor: &str) -> Money { Money::from_parts("CAD", minor, 2).unwrap() } fn source(author: PublicKey) -> ListingRevision { @@ -21,7 +21,7 @@ fn source(author: PublicKey) -> ListingRevision { EnvelopeEventId::from_bytes([3; 32]), ) } -fn window() -> Window { +pub(super) fn window() -> Window { Window::new( UnixSeconds::new(100).unwrap(), UnixSeconds::new(200).unwrap(), @@ -29,7 +29,7 @@ fn window() -> Window { ) .unwrap() } -fn group(id: u8) -> FulfillmentGroup { +pub(super) fn group(id: u8) -> FulfillmentGroup { FulfillmentGroup::new( FulfillmentGroupId::from_bytes([id; 32]), PrivateFulfillment::new( @@ -90,7 +90,7 @@ fn line_with( total, ) } -fn line(id: u8, group: u8) -> AgreementLine { +pub(super) fn line(id: u8, group: u8) -> AgreementLine { line_with( id, source(seller()), @@ -104,7 +104,7 @@ fn line(id: u8, group: u8) -> AgreementLine { ) .unwrap() } -fn terms( +pub(super) fn terms( lines: Vec<AgreementLine>, groups: Vec<FulfillmentGroup>, fee: Money, diff --git a/crates/domain/tests/support/commerce.rs b/crates/domain/tests/support/commerce.rs @@ -0,0 +1,804 @@ +use super::agreement::{buyer, group, line, money, seller, terms, window}; +use radroots_domain::*; + +fn record(id: u8) -> RecordId { + RecordId::from_bytes([id; 32]) +} +fn source(id: u8) -> SourceId { + SourceId::from_bytes([id; 32]) +} +fn time(value: u64) -> UnixSeconds { + UnixSeconds::new(value).unwrap() +} +fn seq(value: u64) -> Sequence { + Sequence::new(value).unwrap() +} +fn authority() -> AuthorityRef { + AuthorityRef::new( + ExecutorId::from_bytes([20; 32]), + Generation::new(2).unwrap(), + ) +} +fn digest() -> TermsDigest { + TermsDigest::from_bytes([21; 32]) +} +fn private_terms() -> Terms { + terms(vec![line(7, 9)], vec![group(9)], money("50"), money("700")).unwrap() +} +fn quantities() -> Vec<LineQuantity> { + vec![LineQuantity::new( + AgreementLineId::from_bytes([7; 32]), + "2".parse().unwrap(), + )] +} +fn measurement() -> FinalMeasurement { + FinalMeasurement::new( + AgreementLineId::from_bytes([7; 32]), + Quantity::new("1".parse().unwrap(), listing::MeasurementUnit::Kilogram).unwrap(), + money("325"), + ) +} +fn parents() -> Vec<SourceId> { + [3, 10, 11, 12, 13, 14, 15, 16].map(source).to_vec() +} +fn header(author: PublicKey, order: Option<OrderId>, parents: Vec<SourceId>) -> CommerceHeader { + CommerceHeader::new( + ThreadId::from_bytes([1; 32]), + order, + author, + buyer(), + seller(), + time(100), + seq(1), + None, + parents, + ) + .unwrap() +} +fn order() -> Option<OrderId> { + Some(OrderId::from_bytes([2; 32])) +} +fn issue() -> IssueReport { + IssueReport::new( + IssueCode::Shortage, + "Private issue", + quantities(), + vec![record(10)], + ) + .unwrap() +} +fn resolution() -> Resolution { + Resolution::new( + vec![record(11)], + vec![record(12)], + quantities(), + "Private resolution", + ) + .unwrap() +} + +// Expected roles come from the operation contract, independently of the +// production role matcher: bit1 seller, bit2 buyer, both requires later +// authenticated parent-relative counterparty checks. +fn cases() -> Vec<(CommercePayload, &'static str, u8)> { + let quote = TermsQuote::new(private_terms(), time(200), Some(source(10))); + assert_eq!(quote.terms(), &private_terms()); + assert_eq!(quote.expires_at(), time(200)); + assert_eq!(quote.in_reply_to(), Some(source(10))); + let request = TermsRequest::new(private_terms(), time(201), Some(record(10))); + assert_eq!(request.terms(), &private_terms()); + assert_eq!(request.expires_at(), time(201)); + assert_eq!(request.quote(), Some(record(10))); + let reason = RecordReason::new(record(10), "Private reason 🥕").unwrap(); + assert_eq!(reason.target(), record(10)); + assert_eq!(reason.reason(), "Private reason 🥕"); + let proposal = TermsProposal::new( + Some(record(11)), + private_terms(), + time(202), + "Private proposal", + ) + .unwrap(); + assert_eq!(proposal.base_agreement(), Some(record(11))); + assert_eq!(proposal.terms(), &private_terms()); + assert_eq!(proposal.expires_at(), time(202)); + assert_eq!(proposal.reason(), "Private proposal"); + let authorized = TermsAuthorization::new(record(10), digest(), time(203)); + assert_eq!(authorized.proposal(), record(10)); + assert_eq!(authorized.terms_digest(), digest()); + assert_eq!(authorized.expires_at(), time(203)); + let committed = + AgreementCommitment::new(Some(record(11)), record(10), digest(), authority(), seq(7)) + .unwrap(); + assert_eq!(committed.base_agreement(), Some(record(11))); + assert_eq!(committed.authorization(), record(10)); + assert_eq!(committed.terms_digest(), digest()); + assert_eq!(committed.authority(), authority()); + assert_eq!(committed.seller_sequence(), seq(7)); + let acknowledged = WithdrawalAcknowledgement::new(record(10), seq(8)).unwrap(); + assert_eq!(acknowledged.withdrawal(), record(10)); + assert_eq!(acknowledged.seller_sequence(), seq(8)); + let cancellation = + CancellationProposal::new(record(11), quantities(), "Private cancellation", time(204)) + .unwrap(); + assert_eq!(cancellation.agreement(), record(11)); + assert_eq!(cancellation.residual(), quantities()); + assert_eq!(cancellation.reason(), "Private cancellation"); + assert_eq!(cancellation.expires_at(), time(204)); + let authorization = ProposalAuthorization::new(record(10), time(205)); + assert_eq!(authorization.proposal(), record(10)); + assert_eq!(authorization.expires_at(), time(205)); + let released = ResidualRelease::new( + record(10), + record(11), + record(12), + quantities(), + authority(), + seq(9), + ) + .unwrap(); + assert_eq!(released.proposal(), record(10)); + assert_eq!(released.authorization(), record(11)); + assert_eq!(released.agreement(), record(12)); + assert_eq!(released.residual(), quantities()); + assert_eq!(released.authority(), authority()); + assert_eq!(released.seller_sequence(), seq(9)); + let ready = ReadinessClaim::new( + record(10), + FulfillmentGroupId::from_bytes([9; 32]), + quantities(), + window(), + ) + .unwrap(); + assert_eq!(ready.agreement(), record(10)); + assert_eq!( + ready.fulfillment_group(), + FulfillmentGroupId::from_bytes([9; 32]) + ); + assert_eq!(ready.lines(), quantities()); + assert_eq!(ready.window(), window()); + let handover = HandoverClaim::new( + record(10), + FulfillmentGroupId::from_bytes([9; 32]), + quantities(), + vec![measurement()], + time(90), + authority(), + seq(10), + ) + .unwrap(); + assert_eq!(handover.agreement(), record(10)); + assert_eq!( + handover.fulfillment_group(), + FulfillmentGroupId::from_bytes([9; 32]) + ); + assert_eq!(handover.lines(), quantities()); + assert_eq!(handover.measurements(), [measurement()]); + assert_eq!(handover.occurred_at(), time(90)); + assert_eq!(handover.authority(), authority()); + assert_eq!(handover.seller_sequence(), seq(10)); + let receipt = ReceiptObservation::new( + record(10), + quantities(), + Some(record(11)), + time(91), + "Private receipt", + ) + .unwrap(); + assert_eq!(receipt.handover(), record(10)); + assert_eq!(receipt.lines(), quantities()); + assert_eq!(receipt.supersedes(), Some(record(11))); + assert_eq!(receipt.occurred_at(), time(91)); + assert_eq!(receipt.note(), "Private receipt"); + let issue = issue(); + assert_eq!(issue.code(), IssueCode::Shortage); + assert_eq!(issue.description(), "Private issue"); + assert_eq!(issue.lines(), quantities()); + assert_eq!(issue.source_records(), [record(10)]); + let resolution = resolution(); + assert_eq!(resolution.issues(), [record(11)]); + assert_eq!(resolution.accepted_receipts(), [record(12)]); + assert_eq!(resolution.release_residual(), quantities()); + assert_eq!(resolution.summary(), "Private resolution"); + let resolution_proposal = ResolutionProposal::new(record(10), resolution.clone(), time(206)); + assert_eq!(resolution_proposal.agreement(), record(10)); + assert_eq!(resolution_proposal.resolution(), &resolution); + assert_eq!(resolution_proposal.expires_at(), time(206)); + let resolved = ResolutionCommitment::new(record(10), record(11), authority(), seq(11)).unwrap(); + assert_eq!(resolved.proposal(), record(10)); + assert_eq!(resolved.authorization(), record(11)); + assert_eq!(resolved.authority(), authority()); + assert_eq!(resolved.seller_sequence(), seq(11)); + vec![ + (CommercePayload::Quote(quote), "quote", 1), + (CommercePayload::Request(request), "request", 2), + (CommercePayload::Decline(reason.clone()), "decline", 1), + ( + CommercePayload::TermsProposed(proposal), + "terms_proposed", + 3, + ), + ( + CommercePayload::TermsAuthorized(authorized), + "terms_authorized", + 3, + ), + ( + CommercePayload::TermsRejected(reason.clone()), + "terms_rejected", + 3, + ), + ( + CommercePayload::AgreementCommitted(committed), + "agreement_committed", + 1, + ), + ( + CommercePayload::WithdrawalRequested(reason), + "withdrawal_requested", + 2, + ), + ( + CommercePayload::WithdrawalAcknowledged(acknowledged), + "withdrawal_acknowledged", + 1, + ), + ( + CommercePayload::CancellationProposed(cancellation), + "cancellation_proposed", + 3, + ), + ( + CommercePayload::CancellationAuthorized(authorization), + "cancellation_authorized", + 3, + ), + ( + CommercePayload::ResidualReleased(released), + "residual_released", + 1, + ), + (CommercePayload::Ready(ready), "ready", 1), + (CommercePayload::Handover(handover), "handover", 1), + (CommercePayload::Receipt(receipt), "receipt", 2), + (CommercePayload::Issue(issue), "issue", 3), + ( + CommercePayload::ResolutionProposed(resolution_proposal), + "resolution_proposed", + 3, + ), + ( + CommercePayload::ResolutionAuthorized(authorization), + "resolution_authorized", + 3, + ), + ( + CommercePayload::ResolutionCommitted(resolved), + "resolution_committed", + 1, + ), + ] +} + +#[test] +fn all_nineteen_complete_families_preserve_exact_data_and_declared_role_order_reference_rules() { + let cases = cases(); + assert_eq!(cases.len(), 19); + for (payload, token, roles) in cases { + assert_eq!(payload.record_type().as_str(), token); + assert_eq!(format!("{payload:?}"), "CommercePayload(<redacted>)"); + for (author, bit) in [(seller(), 1), (buyer(), 2)] { + let original = header(author, order(), parents()); + let result = CommerceContent::new(original.clone(), payload.clone()); + if roles & bit == 0 { + assert_eq!(result.unwrap_err(), CommerceError::InvalidAuthor, "{token}"); + continue; + } + let value = result.unwrap(); + assert_eq!(value.profile(), "radroots.commerce"); + assert_eq!(value.version(), 1); + assert_eq!(value.record_type().as_str(), token); + assert_eq!(value.header(), &original); + assert_eq!(value.payload(), &payload); + assert_eq!(value, value.clone()); + assert_eq!(format!("{value:?}"), "CommerceContent(<redacted>)"); + let no_order = CommerceContent::new(header(author, None, parents()), payload.clone()); + if token == "quote" { + assert!(no_order.is_ok()); + } else { + assert_eq!( + no_order.unwrap_err(), + CommerceError::InvalidOrder, + "{token}" + ); + } + assert_eq!( + CommerceContent::new(header(author, order(), vec![]), payload.clone()).unwrap_err(), + CommerceError::MissingParent, + "{token}" + ); + let required: &[u8] = match token { + "quote" | "request" => &[3, 10], + "terms_proposed" => &[3, 11], + "agreement_committed" | "receipt" | "resolution_committed" => &[10, 11], + "residual_released" | "resolution_proposed" => &[10, 11, 12], + "cancellation_proposed" => &[11], + "decline" + | "terms_authorized" + | "terms_rejected" + | "withdrawal_requested" + | "withdrawal_acknowledged" + | "cancellation_authorized" + | "ready" + | "handover" + | "issue" + | "resolution_authorized" => &[10], + _ => panic!("unknown fixture family"), + }; + for missing in required { + let mut remaining = parents(); + remaining.retain(|parent| *parent != source(*missing)); + assert_eq!( + CommerceContent::new(header(author, order(), remaining), payload.clone()) + .unwrap_err(), + CommerceError::MissingParent, + "{token}: missing source{missing}" + ); + } + } + } +} + +#[test] +fn common_scope_claims_are_exact_bounded_and_have_no_implicit_genesis_or_source_coverage() { + let thread = ThreadId::from_bytes([1; 32]); + let make = |author, buyer, seller, sequence, previous, parents| { + CommerceHeader::new( + thread, + order(), + author, + buyer, + seller, + time(100), + sequence, + previous, + parents, + ) + }; + let outsider = + PublicKey::from_hex("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9") + .unwrap(); + assert_eq!( + make(seller(), seller(), seller(), seq(1), None, vec![]).unwrap_err(), + CommerceError::PartiesCoincide + ); + assert_eq!( + make(outsider, buyer(), seller(), seq(1), None, vec![]).unwrap_err(), + CommerceError::InvalidAuthor + ); + assert_eq!( + make(seller(), buyer(), seller(), seq(0), None, vec![]).unwrap_err(), + CommerceError::InvalidSequence + ); + assert_eq!( + make( + seller(), + buyer(), + seller(), + seq(1), + Some(record(16)), + parents() + ) + .unwrap_err(), + CommerceError::InvalidPrevious + ); + assert_eq!( + make(seller(), buyer(), seller(), seq(2), None, parents()).unwrap_err(), + CommerceError::InvalidPrevious + ); + assert_eq!( + make( + seller(), + buyer(), + seller(), + seq(2), + Some(record(16)), + vec![] + ) + .unwrap_err(), + CommerceError::MissingParent + ); + for invalid in [ + vec![source(2), source(1)], + vec![source(1); 2], + (0..9).map(source).collect(), + ] { + assert_eq!( + make(seller(), buyer(), seller(), seq(1), None, invalid).unwrap_err(), + CommerceError::InvalidParents + ); + } + let mut spacious = Vec::with_capacity(4096); + spacious.extend(parents()); + let value = make( + seller(), + buyer(), + seller(), + seq(i64::MAX as u64), + Some(record(16)), + spacious, + ) + .unwrap(); + assert_eq!(value.thread_id(), thread); + assert_eq!(value.order_id(), order()); + assert_eq!(value.author(), seller()); + assert_eq!(value.buyer(), buyer()); + assert_eq!(value.seller(), seller()); + assert_eq!(value.created_at(), time(100)); + assert_eq!(value.author_sequence(), seq(i64::MAX as u64)); + assert_eq!(value.author_previous(), Some(record(16))); + assert_eq!(value.parents(), parents()); + assert_eq!(value, value.clone()); + assert_eq!(format!("{value:?}"), "CommerceHeader(<redacted>)"); +} + +#[test] +fn complete_terms_sources_and_participants_are_required_without_conflating_references_with_proof() { + let outsider = + PublicKey::from_hex("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9") + .unwrap(); + for payload in [ + CommercePayload::Quote(TermsQuote::new(private_terms(), time(200), None)), + CommercePayload::Request(TermsRequest::new(private_terms(), time(200), None)), + CommercePayload::TermsProposed( + TermsProposal::new(None, private_terms(), time(200), "").unwrap(), + ), + ] { + let author = if payload.record_type() == CommerceType::Request { + outsider + } else { + seller() + }; + let different = CommerceHeader::new( + ThreadId::from_bytes([1; 32]), + order(), + author, + outsider, + seller(), + time(100), + seq(1), + None, + parents(), + ) + .unwrap(); + assert_eq!( + CommerceContent::new(different, payload.clone()).unwrap_err(), + CommerceError::TermsPartiesMismatch + ); + let author = if payload.record_type() == CommerceType::Request { + buyer() + } else { + outsider + }; + let different_seller = CommerceHeader::new( + ThreadId::from_bytes([1; 32]), + order(), + author, + buyer(), + outsider, + time(100), + seq(1), + None, + parents(), + ) + .unwrap(); + assert_eq!( + CommerceContent::new(different_seller, payload.clone()).unwrap_err(), + CommerceError::TermsPartiesMismatch + ); + let author = if payload.record_type() == CommerceType::Request { + buyer() + } else { + seller() + }; + assert!( + CommerceContent::new(header(author, order(), vec![source(3)]), payload.clone()).is_ok() + ); + assert_eq!( + CommerceContent::new(header(author, order(), vec![source(10)]), payload).unwrap_err(), + CommerceError::MissingParent + ); + } + let committed = + AgreementCommitment::new(None, record(10), digest(), authority(), seq(1)).unwrap(); + assert!( + CommerceContent::new( + header(seller(), order(), vec![source(10)]), + CommercePayload::AgreementCommitted(committed) + ) + .is_ok() + ); + let receipt = ReceiptObservation::new(record(10), quantities(), None, time(90), "").unwrap(); + assert!( + CommerceContent::new( + header(buyer(), order(), vec![source(10)]), + CommercePayload::Receipt(receipt) + ) + .is_ok() + ); + // Payload reference maxima and the eight-parent envelope apply jointly. + // References are refused rather than silently omitted or claimed covered. + let issue = + IssueReport::new(IssueCode::Other, "", vec![], (0..9).map(record).collect()).unwrap(); + assert_eq!( + CommerceContent::new( + header(seller(), order(), (0..8).map(source).collect()), + CommercePayload::Issue(issue) + ) + .unwrap_err(), + CommerceError::MissingParent + ); +} + +#[test] +fn bounded_private_text_preserves_unicode_and_optional_empty_claims_without_diagnostic_disclosure() +{ + let maximum = "🥕".repeat(1024); + assert_eq!( + RecordReason::new(record(10), &maximum).unwrap().reason(), + maximum + ); + assert_eq!(RecordReason::new(record(10), "").unwrap().reason(), ""); + for invalid in ["x".repeat(1025), "🥕".repeat(1025), "x".repeat(4097)] { + assert_eq!( + RecordReason::new(record(10), &invalid).unwrap_err(), + CommerceError::InvalidText + ); + assert_eq!( + TermsProposal::new(None, private_terms(), time(200), &invalid).unwrap_err(), + CommerceError::InvalidText + ); + assert_eq!( + CancellationProposal::new(record(10), quantities(), &invalid, time(200)).unwrap_err(), + CommerceError::InvalidText + ); + assert_eq!( + ReceiptObservation::new(record(10), quantities(), None, time(90), &invalid) + .unwrap_err(), + CommerceError::InvalidText + ); + } + let maximum = "🥕".repeat(2048); + assert_eq!( + IssueReport::new(IssueCode::Other, &maximum, vec![], vec![]) + .unwrap() + .description(), + maximum + ); + assert_eq!( + Resolution::new(vec![record(10)], vec![], vec![], &maximum) + .unwrap() + .summary(), + maximum + ); + for invalid in ["x".repeat(2049), "🥕".repeat(2049), "x".repeat(8193)] { + assert_eq!( + IssueReport::new(IssueCode::Other, &invalid, vec![], vec![]).unwrap_err(), + CommerceError::InvalidText + ); + assert_eq!( + Resolution::new(vec![record(10)], vec![], vec![], &invalid).unwrap_err(), + CommerceError::InvalidText + ); + } + for (code, token) in [ + (IssueCode::Shortage, "shortage"), + (IssueCode::Quality, "quality"), + (IssueCode::Substitution, "substitution"), + (IssueCode::Collection, "collection"), + (IssueCode::Excess, "excess"), + (IssueCode::Other, "other"), + ] { + assert_eq!(code.as_str(), token); + } + assert_eq!( + format!( + "{:?}", + RecordReason::new(record(10), "Private reason").unwrap() + ), + "RecordReason(<redacted>)" + ); + assert_eq!(format!("{:?}", issue()), "IssueReport(<redacted>)"); + assert_eq!(format!("{:?}", resolution()), "Resolution(<redacted>)"); +} + +#[test] +fn quantity_reference_and_measurement_collections_reject_ambiguity_and_preserve_zero_observations() +{ + let maximum_lines: Vec<_> = (0..32) + .map(|id| LineQuantity::new(AgreementLineId::from_bytes([id; 32]), "1".parse().unwrap())) + .collect(); + let value = IssueReport::new( + IssueCode::Other, + "", + maximum_lines.clone(), + (0..32).map(record).collect(), + ) + .unwrap(); + assert_eq!(value.lines(), maximum_lines); + assert_eq!(value.source_records().len(), 32); + assert!( + Resolution::new( + (0..32).map(record).collect(), + (32..64).map(record).collect(), + maximum_lines.clone(), + "" + ) + .is_ok() + ); + for invalid in [vec![maximum_lines[0]; 2], vec![maximum_lines[0]; 33]] { + assert_eq!( + IssueReport::new(IssueCode::Other, "", invalid.clone(), vec![]).unwrap_err(), + CommerceError::InvalidLines + ); + assert_eq!( + ReadinessClaim::new( + record(10), + FulfillmentGroupId::from_bytes([9; 32]), + invalid, + window() + ) + .unwrap_err(), + CommerceError::InvalidLines + ); + } + for invalid in [vec![record(1); 2], vec![record(1); 33]] { + assert_eq!( + IssueReport::new(IssueCode::Other, "", vec![], invalid.clone()).unwrap_err(), + CommerceError::InvalidReferences + ); + assert_eq!( + Resolution::new(invalid, vec![], vec![], "").unwrap_err(), + CommerceError::InvalidReferences + ); + } + assert_eq!( + Resolution::new(vec![], vec![], vec![], "").unwrap_err(), + CommerceError::InvalidReferences + ); + assert_eq!( + ReadinessClaim::new( + record(10), + FulfillmentGroupId::from_bytes([9; 32]), + vec![], + window() + ) + .unwrap_err(), + CommerceError::InvalidLines + ); + assert_eq!( + CancellationProposal::new(record(10), vec![], "", time(200)).unwrap_err(), + CommerceError::InvalidLines + ); + assert_eq!( + ReceiptObservation::new(record(10), vec![], None, time(90), "").unwrap_err(), + CommerceError::InvalidLines + ); + let zero = LineQuantity::new(AgreementLineId::from_bytes([7; 32]), Decimal::ZERO); + assert_eq!(zero.line_id(), AgreementLineId::from_bytes([7; 32])); + assert_eq!(zero.amount(), Decimal::ZERO); + assert_eq!(format!("{zero:?}"), "LineQuantity(<redacted>)"); + let observed = + ReceiptObservation::new(record(10), vec![zero], None, time(90), "Nothing observed") + .unwrap(); + assert_eq!(observed.lines(), [zero]); + assert!( + CommerceContent::new( + header(buyer(), order(), vec![source(10)]), + CommercePayload::Receipt(observed) + ) + .is_ok() + ); + let measured = measurement(); + assert_eq!(measured.line_id(), AgreementLineId::from_bytes([7; 32])); + assert_eq!( + measured.quantity(), + Quantity::new("1".parse().unwrap(), listing::MeasurementUnit::Kilogram).unwrap() + ); + assert_eq!(measured.line_total(), money("325")); + assert_eq!(format!("{measured:?}"), "FinalMeasurement(<redacted>)"); + let unrelated = FinalMeasurement::new( + AgreementLineId::from_bytes([8; 32]), + measured.quantity(), + money("325"), + ); + for invalid in [vec![measured; 2], vec![measured; 33], vec![unrelated]] { + assert_eq!( + HandoverClaim::new( + record(10), + FulfillmentGroupId::from_bytes([9; 32]), + quantities(), + invalid, + time(90), + authority(), + seq(1) + ) + .unwrap_err(), + CommerceError::InvalidMeasurements + ); + } + let no_measurements = HandoverClaim::new( + record(10), + FulfillmentGroupId::from_bytes([9; 32]), + quantities(), + vec![], + time(90), + authority(), + seq(1), + ) + .unwrap(); + assert!(no_measurements.measurements().is_empty()); +} + +#[test] +fn every_seller_decision_requires_positive_sequence_without_minting_authority() { + assert_eq!( + AgreementCommitment::new(None, record(10), digest(), authority(), seq(0)).unwrap_err(), + CommerceError::InvalidSequence + ); + assert_eq!( + WithdrawalAcknowledgement::new(record(10), seq(0)).unwrap_err(), + CommerceError::InvalidSequence + ); + assert_eq!( + ResidualRelease::new( + record(10), + record(11), + record(12), + quantities(), + authority(), + seq(0) + ) + .unwrap_err(), + CommerceError::InvalidSequence + ); + assert_eq!( + HandoverClaim::new( + record(10), + FulfillmentGroupId::from_bytes([9; 32]), + quantities(), + vec![], + time(90), + authority(), + seq(0) + ) + .unwrap_err(), + CommerceError::InvalidSequence + ); + assert_eq!( + ResolutionCommitment::new(record(10), record(11), authority(), seq(0)).unwrap_err(), + CommerceError::InvalidSequence + ); +} + +#[test] +fn record_errors_are_input_free_and_bounded() { + for error in [ + CommerceError::PartiesCoincide, + CommerceError::InvalidAuthor, + CommerceError::InvalidOrder, + CommerceError::InvalidSequence, + CommerceError::InvalidPrevious, + CommerceError::InvalidParents, + CommerceError::MissingParent, + CommerceError::TermsPartiesMismatch, + CommerceError::InvalidText, + CommerceError::InvalidLines, + CommerceError::InvalidMeasurements, + CommerceError::InvalidReferences, + ] { + assert!(error.to_string().len() < 96); + assert!(core::error::Error::source(&error).is_none()); + assert!(!format!("{error:?}").contains("Private reason")); + } +}