lib

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

commit 60e7c6342fe4f420c12c77bacf711cbe79240fd7
parent 8025df736993c16f2f69069a491a295b8800bdc3
Author: triesap <tyson@radroots.org>
Date:   Thu, 22 Oct 2026 20:45:13 +0000

domain: Preserve validated supply windows and private fulfillment

- Admit exact pinned IANA identifiers and strictly ordered absolute windows.
- Carry estimated supply through canonical listings and native replay/reopen.
- Bound private fulfillment data and retain exact timezone provenance and APIs.
- Verify feature and portable builds, 78 native receipts, guards and coverage.

Diffstat:
MCargo.lock | 1+
Mcontracts/api_baselines/radroots_domain.txt | 41+++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/Cargo.toml | 1+
Mcrates/domain/README.md | 11+++++++++++
Acrates/domain/src/fulfillment.rs | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/lib.rs | 4++++
Mcrates/domain/src/listing.rs | 15+++++++++++++--
Acrates/domain/src/time.rs | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/tests/listing.rs | 3+++
Acrates/domain/tests/support/listing_time.rs | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/README.md | 15+++++++++------
Mcrates/protocol/src/command/captured.rs | 2+-
Mcrates/protocol/src/listing/input.rs | 39++++++++++++++++++++++++++++++++++++---
Mcrates/protocol/tests/public_command.rs | 129++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcrates/radroots/tests/support/receipt_listing_economics.rs | 2++
15 files changed, 610 insertions(+), 13 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3142,6 +3142,7 @@ dependencies = [ name = "radroots_domain" version = "0.1.0-alpha" dependencies = [ + "jiff-tzdb", "radroots_identity", "serde", "serde_json", diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -41,6 +41,9 @@ pub fn radroots_domain::listing::Price::serialize<S: serde_core::ser::Serializer #[non_exhaustive] pub enum radroots_domain::listing::Supply pub radroots_domain::listing::Supply::Available pub radroots_domain::listing::Supply::Available::amount: radroots_domain::Decimal +pub radroots_domain::listing::Supply::Estimated +pub radroots_domain::listing::Supply::Estimated::amount: radroots_domain::Decimal +pub radroots_domain::listing::Supply::Estimated::window: core::option::Option<radroots_domain::Window> pub radroots_domain::listing::Supply::Unknown pub struct radroots_domain::listing::LeadSeconds(_) impl radroots_domain::listing::LeadSeconds @@ -81,6 +84,7 @@ pub const fn radroots_domain::listing::ListingOption::minimum(&self) -> radroots pub fn radroots_domain::listing::ListingOption::new(radroots_domain::ListingOptionId, &str, radroots_domain::listing::SaleUnit, radroots_domain::PositiveDecimal, radroots_domain::PositiveDecimal, radroots_domain::listing::Price, radroots_domain::listing::Supply, radroots_domain::listing::LeadSeconds) -> core::result::Result<Self, radroots_domain::listing::ListingError> pub const fn radroots_domain::listing::ListingOption::price(&self) -> &radroots_domain::listing::Price pub fn radroots_domain::listing::ListingOption::quote_required(radroots_domain::ListingOptionId, &str, radroots_domain::listing::SaleUnit, radroots_domain::PositiveDecimal, radroots_domain::PositiveDecimal, radroots_domain::listing::Supply, radroots_domain::listing::LeadSeconds) -> core::result::Result<Self, radroots_domain::listing::ListingError> +pub const fn radroots_domain::listing::ListingOption::supply(&self) -> radroots_domain::listing::Supply pub const fn radroots_domain::listing::ListingOption::unit(&self) -> &radroots_domain::listing::SaleUnit pub fn radroots_domain::listing::ListingOption::validate_amount(&self, radroots_domain::PositiveDecimal) -> core::result::Result<(), radroots_domain::listing::ListingError> impl core::fmt::Debug for radroots_domain::listing::ListingOption @@ -189,6 +193,11 @@ pub fn radroots_domain::MoneyError::from(radroots_domain::CurrencyError) -> Self impl core::error::Error for radroots_domain::CurrencyError impl core::fmt::Display for radroots_domain::CurrencyError pub fn radroots_domain::CurrencyError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::FulfillmentError +pub radroots_domain::FulfillmentError::InvalidText +impl core::error::Error for radroots_domain::FulfillmentError +impl core::fmt::Display for radroots_domain::FulfillmentError +pub fn radroots_domain::FulfillmentError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_domain::IdentifierError pub radroots_domain::IdentifierError::InvalidEncoding pub radroots_domain::IdentifierError::InvalidLength @@ -247,6 +256,13 @@ impl core::error::Error for radroots_domain::QuantityError pub fn radroots_domain::QuantityError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)> impl core::fmt::Display for radroots_domain::QuantityError pub fn radroots_domain::QuantityError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::TimeError +pub radroots_domain::TimeError::InvalidTimeZone +pub radroots_domain::TimeError::InvalidWindow +pub radroots_domain::TimeError::UnsupportedDatabase +impl core::error::Error for radroots_domain::TimeError +impl core::fmt::Display for radroots_domain::TimeError +pub fn radroots_domain::TimeError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::ActorRef impl radroots_domain::ActorRef pub const fn radroots_domain::ActorRef::grant_id(self) -> core::option::Option<radroots_domain::GrantId> @@ -623,6 +639,16 @@ pub const fn radroots_domain::PriceTier::new(radroots_domain::Decimal, radroots_ pub const fn radroots_domain::PriceTier::rate(self) -> radroots_domain::Money impl core::fmt::Debug for radroots_domain::PriceTier pub fn radroots_domain::PriceTier::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::PrivateFulfillment +impl radroots_domain::PrivateFulfillment +pub fn radroots_domain::PrivateFulfillment::address(&self) -> &str +pub fn radroots_domain::PrivateFulfillment::contact(&self) -> core::option::Option<&str> +pub fn radroots_domain::PrivateFulfillment::instructions(&self) -> &str +pub const fn radroots_domain::PrivateFulfillment::mode(&self) -> radroots_domain::listing::FulfillmentMode +pub fn radroots_domain::PrivateFulfillment::new(radroots_domain::listing::FulfillmentMode, radroots_domain::Window, &str, &str, core::option::Option<&str>) -> core::result::Result<Self, radroots_domain::FulfillmentError> +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::Quantity impl radroots_domain::Quantity pub const fn radroots_domain::Quantity::amount(self) -> radroots_domain::Decimal @@ -716,6 +742,12 @@ impl serde_core::ser::Serialize for radroots_domain::ThreadId pub fn radroots_domain::ThreadId::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::ThreadId pub fn radroots_domain::ThreadId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::TimeZoneId(_) +impl radroots_domain::TimeZoneId +pub fn radroots_domain::TimeZoneId::from_name(&str) -> core::result::Result<Self, radroots_domain::TimeError> +pub const fn radroots_domain::TimeZoneId::name(self) -> &'static str +impl core::fmt::Debug for radroots_domain::TimeZoneId +pub fn radroots_domain::TimeZoneId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::TransactionId(_) impl radroots_domain::TransactionId pub const fn radroots_domain::TransactionId::as_bytes(&self) -> &[u8; 32] @@ -755,6 +787,14 @@ pub const fn radroots_domain::VariableWeight::rate(self) -> radroots_domain::Mon pub fn radroots_domain::VariableWeight::total_at(self, radroots_domain::Quantity) -> core::result::Result<radroots_domain::Money, radroots_domain::PricingError> impl core::fmt::Debug for radroots_domain::VariableWeight pub fn radroots_domain::VariableWeight::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::Window +impl radroots_domain::Window +pub const fn radroots_domain::Window::end(self) -> radroots_domain::UnixSeconds +pub fn radroots_domain::Window::new(radroots_domain::UnixSeconds, radroots_domain::UnixSeconds, radroots_domain::TimeZoneId) -> core::result::Result<Self, radroots_domain::TimeError> +pub const fn radroots_domain::Window::start(self) -> radroots_domain::UnixSeconds +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::WorkspaceId(_) impl radroots_domain::WorkspaceId pub const fn radroots_domain::WorkspaceId::as_bytes(&self) -> &[u8; 32] @@ -776,4 +816,5 @@ pub const radroots_domain::FIRST_ISSUANCE_MAX_SECONDS: u64 pub const radroots_domain::MAX_PRICED_LINES: usize pub const radroots_domain::PRICING_PROFILE: &str pub const radroots_domain::SUPPORTED_CURRENCY_COUNT: usize +pub const radroots_domain::TIME_ZONE_DATABASE_VERSION: &str pub fn radroots_domain::checked_order_total(&[radroots_domain::Money], radroots_domain::Money) -> core::result::Result<radroots_domain::Money, radroots_domain::PricingError> diff --git a/crates/domain/Cargo.toml b/crates/domain/Cargo.toml @@ -18,6 +18,7 @@ std = ["radroots_identity/std"] serde = ["dep:serde", "radroots_identity/serde"] [dependencies] +jiff-tzdb = { workspace = true } radroots_identity = { workspace = true, default-features = false } serde = { workspace = true, optional = true } zeroize = { workspace = true, features = ["alloc"] } diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -76,6 +76,17 @@ approve an endpoint, fetch a file, verify its contents or promise a decoder. references and preserved order. Empty media is explicit. Media descriptors serialize complete exact strings and have no unchecked deserialization route. +`Supply::Estimated` retains an exact nonnegative amount and an explicit nullable +`Window`. Package and `each` estimates remain integral. Estimates are neither +stock balances nor reservations, ceilings or current-availability guarantees. +`Window` requires strictly ordered absolute Unix-second instants and an exact +canonical `TimeZoneId` from the already pinned no_std `jiff-tzdb` 0.1.8 / IANA +2026c data (MIT OR Unlicense). No system zone, clock, local wall-time, offset or +fold is inferred. The timezone dependency retains its own upstream notices. +Private fulfillment data retains a required window, explicit pickup/delivery +mode and bounded zeroizing address/instructions/contact. It has no public wire +serialization and grants no agreement, destination or delivery authority. + Namespaces remain separate across native calls: ```compile_fail diff --git a/crates/domain/src/fulfillment.rs b/crates/domain/src/fulfillment.rs @@ -0,0 +1,84 @@ +use crate::{Window, listing::FulfillmentMode}; +use alloc::string::String; +use core::fmt; +use zeroize::Zeroizing; + +/// Explicit private fulfillment data, without agreement or logistics authority. +/// Address, instructions and contact are zeroizing owned text; ordinary debug +/// and errors disclose none of it. Wire encoding belongs to private protocols. +#[derive(Clone, Eq, PartialEq)] +pub struct PrivateFulfillment { + mode: FulfillmentMode, + window: Window, + address: Zeroizing<String>, + instructions: Zeroizing<String>, + contact: Option<Zeroizing<String>>, +} +impl PrivateFulfillment { + /// Bounds exact private claims before copying. Contact is explicitly absent + /// or provided; no endpoint, delivery or address-verification trust is minted. + pub fn new( + mode: FulfillmentMode, + window: Window, + address: &str, + instructions: &str, + contact: Option<&str>, + ) -> Result<Self, FulfillmentError> { + text(address, 2048)?; + text(instructions, 2048)?; + if let Some(contact) = contact { + text(contact, 256)?; + } + Ok(Self { + mode, + window, + address: Zeroizing::new(address.into()), + instructions: Zeroizing::new(instructions.into()), + contact: contact.map(|v| Zeroizing::new(v.into())), + }) + } + /// Returns the explicitly selected private mode. + pub const fn mode(&self) -> FulfillmentMode { + self.mode + } + /// Returns the exact required window without ambient time conversion. + pub const fn window(&self) -> Window { + self.window + } + /// Explicitly borrows private address text; callers own any disclosure. + pub fn address(&self) -> &str { + &self.address + } + /// Explicitly borrows private instructions. + pub fn instructions(&self) -> &str { + &self.instructions + } + /// Explicitly borrows the optional private contact claim. + pub fn contact(&self) -> Option<&str> { + self.contact.as_ref().map(|v| v.as_str()) + } +} +impl fmt::Debug for PrivateFulfillment { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PrivateFulfillment(<redacted>)") + } +} +fn text(value: &str, maximum: usize) -> Result<(), FulfillmentError> { + if value.len() > maximum * 4 || value.chars().count() > maximum { + return Err(FulfillmentError::InvalidText); + } + Ok(()) +} +/// Input-free private fulfillment construction failure. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum FulfillmentError { + /// Private text exceeds its declared limit. + InvalidText, +} +impl fmt::Display for FulfillmentError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("invalid private fulfillment text") + } +} +impl core::error::Error for FulfillmentError {} diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -8,6 +8,7 @@ extern crate alloc; mod amount; mod context; mod currency; +mod fulfillment; mod identifier; mod issuance; /// Validated public-offer values; these establish no stock or command authority. @@ -16,6 +17,7 @@ mod message; mod money; mod pricing; mod quantity; +mod time; mod variable_price; /// The identity-owned validated participant key; no second key type is defined. @@ -30,6 +32,7 @@ pub use currency::{ CURRENCY_REGISTRY_ID, CURRENCY_REGISTRY_SHA256, Currency, CurrencyError, SUPPORTED_CURRENCY_COUNT, }; +pub use fulfillment::{FulfillmentError, PrivateFulfillment}; pub use identifier::{ ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, ExecutorId, GrantId, IdentifierError, ListingOptionId, MessageId, OperationId, OrderId, RecordId, RouteDigest, @@ -43,4 +46,5 @@ pub use pricing::{ checked_order_total, }; pub use quantity::{ContentMeasure, Quantity, QuantityError}; +pub use time::{TIME_ZONE_DATABASE_VERSION, TimeError, TimeZoneId, Window}; pub use variable_price::VariableWeight; diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs @@ -3,7 +3,7 @@ use crate::{ AuthorityRef, ContentMeasure, Decimal, LinePrice, ListingOptionId, PositiveDecimal, - PricingError, PublicKey, Sequence, + PricingError, PublicKey, Sequence, Window, }; use alloc::{boxed::Box, string::String, vec::Vec}; use core::{fmt, str::FromStr}; @@ -275,6 +275,13 @@ pub enum Supply { /// Public advertised quantity, without backing authority. amount: Decimal, }, + /// An estimate and optional declared expected window, without reservation. + Estimated { + /// Exact nonnegative estimate in the selected sale unit. + amount: Decimal, + /// Explicit absent or validated absolute expected window. + window: Option<Window>, + }, } /// Validated public product description; producer data grants no agency rights. @@ -372,7 +379,7 @@ impl ListingOption { || (unit.integral() && (inc.scale() != 0 || min.scale() != 0 - || matches!(supply, Supply::Available { amount } if amount.scale() != 0))) + || matches!(supply, Supply::Available { amount } | Supply::Estimated { amount,.. } if amount.scale() != 0))) { return Err(ListingError::InvalidQuantity); } @@ -403,6 +410,10 @@ impl ListingOption { pub const fn minimum(&self) -> PositiveDecimal { self.minimum } + /// Returns the advertised supply claim without freshness or stock authority. + pub const fn supply(&self) -> Supply { + self.supply + } /// Checks minimum, increment and integral count rules without claiming stock. /// Advertised supply is an estimate, not an implicit quantity ceiling. pub fn validate_amount(&self, amount: PositiveDecimal) -> Result<(), ListingError> { diff --git a/crates/domain/src/time.rs b/crates/domain/src/time.rs @@ -0,0 +1,103 @@ +use crate::UnixSeconds; +use core::fmt; + +/// Pinned IANA data identity shared with the retained calendar source. +pub const TIME_ZONE_DATABASE_VERSION: &str = "2026c"; + +/// Exact canonical IANA identifier, without ambient clock or conversion effects. +#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(transparent))] +pub struct TimeZoneId(&'static str); +impl TimeZoneId { + /// Admits a bounded exact name from the pinned dataset. Case, whitespace and + /// unknown names are never normalized or replaced with a guessed zone. + pub fn from_name(value: &str) -> Result<Self, TimeError> { + if jiff_tzdb::VERSION != Some(TIME_ZONE_DATABASE_VERSION) { + return Err(TimeError::UnsupportedDatabase); + } + if value.is_empty() || value.len() > 80 { + return Err(TimeError::InvalidTimeZone); + } + let (canonical, _) = jiff_tzdb::get(value).ok_or(TimeError::InvalidTimeZone)?; + if canonical != value { + return Err(TimeError::InvalidTimeZone); + } + Ok(Self(canonical)) + } + /// Returns the exact validated name, not a claim about an ambient zone. + pub const fn name(self) -> &'static str { + self.0 + } +} +impl fmt::Debug for TimeZoneId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("TimeZoneId(<redacted>)") + } +} + +/// Ordered absolute instants and an explicit display zone. No local wall-time +/// ambiguity, fold or offset is guessed; civil conversion is a separate job. +#[derive(Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Window { + start: UnixSeconds, + end: UnixSeconds, + timezone: TimeZoneId, +} +impl Window { + /// Requires a strictly later end, preserving the existing calendar rule. + pub fn new( + start: UnixSeconds, + end: UnixSeconds, + timezone: TimeZoneId, + ) -> Result<Self, TimeError> { + if end <= start { + return Err(TimeError::InvalidWindow); + } + Ok(Self { + start, + end, + timezone, + }) + } + /// Returns the exact absolute start without observing current time. + pub const fn start(self) -> UnixSeconds { + self.start + } + /// Returns the exact strictly later end. + pub const fn end(self) -> UnixSeconds { + self.end + } + /// Returns the explicit validated display-zone identity. + pub const fn timezone(self) -> TimeZoneId { + self.timezone + } +} +impl fmt::Debug for Window { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Window(<redacted>)") + } +} + +/// Input-free shared time-value failure, with no ambient fallback. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum TimeError { + /// An unknown, noncanonical or excessive IANA name was supplied. + InvalidTimeZone, + /// End is not strictly after start. + InvalidWindow, + /// Compiled data does not match the explicitly pinned version. + UnsupportedDatabase, +} +impl fmt::Display for TimeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidTimeZone => "invalid time zone", + Self::InvalidWindow => "invalid absolute window", + Self::UnsupportedDatabase => "unsupported time zone database", + }) + } +} +impl core::error::Error for TimeError {} diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -3,6 +3,9 @@ use radroots_domain::{ListingOptionId, listing::*}; #[path = "support/listing_media.rs"] mod media; +#[path = "support/listing_time.rs"] +mod time; + #[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/listing_time.rs b/crates/domain/tests/support/listing_time.rs @@ -0,0 +1,173 @@ +use radroots_domain::{ + FulfillmentError, ListingOptionId, PrivateFulfillment, TIME_ZONE_DATABASE_VERSION, TimeError, + TimeZoneId, UnixSeconds, Window, listing::*, +}; + +fn window() -> Window { + Window::new( + UnixSeconds::new(100).unwrap(), + UnixSeconds::new(101).unwrap(), + TimeZoneId::from_name("America/Toronto").unwrap(), + ) + .unwrap() +} + +#[test] +fn pinned_zone_names_are_exact_and_all_dataset_entries_are_admitted() { + assert_eq!(jiff_tzdb::VERSION, Some(TIME_ZONE_DATABASE_VERSION)); + for name in jiff_tzdb::available() { + assert_eq!(TimeZoneId::from_name(name).unwrap().name(), name); + } + for name in [ + "", + "america/toronto", + " America/Toronto", + "America/Toronto ", + "Invented/Zone", + "+05:00", + "America/Toronto\0", + &"a".repeat(81), + &"🥕".repeat(21), + ] { + assert_eq!(TimeZoneId::from_name(name), Err(TimeError::InvalidTimeZone)); + } + let zone = TimeZoneId::from_name("Etc/UTC").unwrap(); + assert_eq!(zone.name(), "Etc/UTC"); + assert!(!format!("{zone:?}").contains("UTC")); +} + +#[test] +fn windows_preserve_ordered_absolute_bounds_without_civil_time_conversion() { + let zone = TimeZoneId::from_name("America/Toronto").unwrap(); + let start = UnixSeconds::new(0).unwrap(); + let end = UnixSeconds::new(253_402_300_799).unwrap(); + let value = Window::new(start, end, zone).unwrap(); + assert_eq!( + (value.start(), value.end(), value.timezone()), + (start, end, zone) + ); + for (start, end) in [(end, start), (start, start), (end, end)] { + assert_eq!(Window::new(start, end, zone), Err(TimeError::InvalidWindow)); + } + // Absolute instants remain exact; no local fold/offset is inferred. + let transition = Window::new( + UnixSeconds::new(1_793_480_400).unwrap(), + UnixSeconds::new(1_793_487_600).unwrap(), + zone, + ) + .unwrap(); + assert_eq!(transition.end().get() - transition.start().get(), 7200); + assert_eq!(format!("{transition:?}"), "Window(<redacted>)"); + assert_eq!( + TimeError::InvalidWindow.to_string(), + "invalid absolute window" + ); + assert_eq!(TimeError::InvalidTimeZone.to_string(), "invalid time zone"); + assert_eq!( + TimeError::UnsupportedDatabase.to_string(), + "unsupported time zone database" + ); + #[cfg(feature = "serde")] + assert_eq!( + serde_json::to_value(value).unwrap(), + serde_json::json!({ + "start":"0","end":"253402300799","timezone":"America/Toronto"}) + ); +} + +#[test] +fn private_fulfillment_bounds_unicode_and_redacts_without_public_terms_or_effects() { + let address = "🥕".repeat(2048); + let instructions = "é".repeat(2048); + let contact = "☎".repeat(256); + for mode in [FulfillmentMode::Pickup, FulfillmentMode::Delivery] { + let value = + PrivateFulfillment::new(mode, window(), &address, &instructions, Some(&contact)) + .unwrap(); + assert_eq!(value.mode(), mode); + assert_eq!(value.window(), window()); + assert_eq!(value.address(), address); + assert_eq!(value.instructions(), instructions); + assert_eq!(value.contact(), Some(contact.as_str())); + assert_eq!(value, value.clone()); + assert_eq!(format!("{value:?}"), "PrivateFulfillment(<redacted>)"); + let empty = PrivateFulfillment::new(mode, window(), "", "", None).unwrap(); + assert_eq!(empty.contact(), None); + assert_eq!(empty.address(), ""); + assert_eq!(empty.instructions(), ""); + assert_eq!( + PrivateFulfillment::new(mode, window(), "", "", Some("")) + .unwrap() + .contact(), + Some("") + ); + } + for (address, instructions, contact) in [ + ("a".repeat(2049), String::new(), None), + ("a".repeat(8193), String::new(), None), + (String::new(), "é".repeat(2049), None), + (String::new(), String::new(), Some("☎".repeat(257))), + (String::new(), String::new(), Some("a".repeat(1025))), + ] { + assert_eq!( + PrivateFulfillment::new( + FulfillmentMode::Pickup, + window(), + &address, + &instructions, + contact.as_deref() + ), + Err(FulfillmentError::InvalidText) + ); + } + assert_eq!( + FulfillmentError::InvalidText.to_string(), + "invalid private fulfillment text" + ); +} + +#[test] +fn estimates_allow_zero_and_measured_fractions_but_keep_count_units_integral() { + for unit in [ + SaleUnit::package_unspecified("bunch").unwrap(), + SaleUnit::measured(MeasurementUnit::Each), + SaleUnit::measured(MeasurementUnit::Kilogram), + ] { + for amount in ["0", "2", "0.5"] { + for window in [None, Some(window())] { + let result = ListingOption::quote_required( + ListingOptionId::from_bytes([9; 32]), + "expected", + unit.clone(), + "1".parse().unwrap(), + "1".parse().unwrap(), + Supply::Estimated { + amount: amount.parse().unwrap(), + window, + }, + LeadSeconds::new(0).unwrap(), + ); + if amount == "0.5" && unit.integral() { + assert_eq!(result.unwrap_err(), ListingError::InvalidQuantity); + } else { + let value = result.unwrap(); + assert_eq!( + value.supply(), + Supply::Estimated { + amount: amount.parse().unwrap(), + window + } + ); + // Advertised estimate is neither a ceiling nor reservation. + assert!(value.validate_amount("100".parse().unwrap()).is_ok()); + #[cfg(feature = "serde")] + assert_eq!( + serde_json::to_value(value.supply()).unwrap(), + serde_json::json!({ + "type":"estimated","amount":amount,"window":window}) + ); + } + } + } + } +} diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -49,7 +49,11 @@ positional arrays, and the closed typed decoder rejects duplicate, missing and unknown fields. Up to eight complete media-reference objects retain exact URL/digest/MIME/alt claims; missing, malformed or excessive references are refused. Media never activates fetching, uploading or a decoder. Estimated -supply/windows remain unsupported. +supply retains its exact nonnegative amount and a required nullable absolute +window. Windows require strictly ordered Unix-second strings and an exact known +IANA zone from the pinned dataset; missing fields, positional arrays, duplicates, +noncanonical zones and extra offset/fold/wall-time claims are refused. Estimates +do not provide stock, reservation or freshness authority. Only the fixed default contributes a three-field NIP-99 base-rate `price` tag; the monetary summary identifies its basis, unit, discount and tier conditions. Variable bounds/caps stay explicit in the profile and summary. No recurring @@ -66,7 +70,7 @@ with at most nine tags and19 fields shared by signer and storage admission. | `nip01` | no | enables pure exact NIP-01 serialization and complete byte counting | | `intent` | no | enables pure domain-separated v1 signing commitment data | | `chat` | no | enables commands, NIP-01 and the bounded known-kind chat/plan data profile | -| `listing` | no | enables portable typed quote-required listing input and exact public profile/event production | +| `listing` | no | enables portable complete listing input and exact public profile/event production | The listing producer emits one canonical `radroots.listing` version-1 profile, explicit default units and no fabricated price. Paused/withdrawn projections @@ -74,10 +78,9 @@ keep the same addressable coordinate, state non-availability in summary and content, and omit a standard status that cannot represent that state. Complete signed-event framing is bounded to 64 KiB before the canonical preimage is allocated. Canonical profile ordering remains explicit when a consumer enables -JSON insertion-order preservation. The early producer supports unspecified -package contents, unknown/available public supply and empty media. Full prices, -registered currencies and the remaining profile modes require their own -validated implementation. Pure input/preimage construction supplies no workspace +JSON insertion-order preservation. The producer retains all implemented price, +package-content and public-supply modes, including estimated supply windows, +and the explicit media list. Pure input/preimage construction supplies no workspace permission, durable preparation, signature, installed record or delivery receipt. Disabling default features leaves the catalog and structural validation APIs diff --git a/crates/protocol/src/command/captured.rs b/crates/protocol/src/command/captured.rs @@ -33,7 +33,7 @@ impl CommandKind { pub enum CapturedCommand { /// Original chat profile, retaining its exact established commitments. Chat(CapturedChatCommand), - /// Supported quote-required public profile. + /// Supported complete public listing profile. #[cfg(feature = "listing")] Listing(crate::listing::CapturedListingCommand), } diff --git a/crates/protocol/src/listing/input.rs b/crates/protocol/src/listing/input.rs @@ -5,7 +5,8 @@ use crate::command::{CommandError, check_frame, required_nullable}; use alloc::{string::String, vec::Vec}; use radroots_domain::{ AuthorityRef, ContentMeasure, Decimal, DiscountBps, FixedPrice, ListingOptionId, Money, - PositiveDecimal, PriceTier, PublicKey, Quantity, UnixSeconds, VariableWeight, listing::*, + PositiveDecimal, PriceTier, PublicKey, Quantity, TimeZoneId, UnixSeconds, VariableWeight, + Window, listing::*, }; use serde::Deserialize; @@ -183,7 +184,30 @@ impl RawPrice { #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] enum RawSupply { Unknown, - Available { amount: Decimal }, + Available { + amount: Decimal, + }, + Estimated { + amount: Decimal, + #[serde(deserialize_with = "required_nullable")] + window: Option<RawWindow>, + }, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawWindow { + start: UnixSeconds, + end: UnixSeconds, + timezone: String, +} +impl RawWindow { + fn domain(self) -> Result<Window, CommandError> { + invalid(Window::new( + self.start, + self.end, + invalid(TimeZoneId::from_name(&self.timezone))?, + )) + } } #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -244,6 +268,10 @@ impl Input { match option.supply { RawSupply::Unknown => Supply::Unknown, RawSupply::Available { amount } => Supply::Available { amount }, + RawSupply::Estimated { amount, window } => Supply::Estimated { + amount, + window: window.map(RawWindow::domain).transpose()?, + }, }, option.lead_seconds, ))?); @@ -326,7 +354,7 @@ impl PublishInput { || option .pointer("/supply/type") .and_then(serde_json::Value::as_str) - .is_some_and(|v| !matches!(v, "unknown" | "available")) + .is_some_and(|v| !matches!(v, "unknown" | "available" | "estimated")) || option .pointer("/unit/contents/type") .and_then(serde_json::Value::as_str) @@ -381,6 +409,11 @@ fn object_shapes(value: &serde_json::Value) -> Result<(), CommandError> { object(&option["unit"])?; object(&option["price"])?; object(&option["supply"])?; + if let Some(window) = option["supply"].get("window") + && !window.is_null() + { + object(window)?; + } if let Some(contents) = option["unit"].get("contents") { object(contents)?; if let Some(quantity) = contents.get("quantity") { diff --git a/crates/protocol/tests/public_command.rs b/crates/protocol/tests/public_command.rs @@ -104,6 +104,133 @@ fn fixed_price(code: &str, minor: &str, exponent: u8) -> Value { "basis":"2","discount_bps":1000,"tiers":[]}) } +fn estimated_supply(window: Value) -> Value { + json!({"type":"estimated","amount":"10","window":window}) +} +fn absolute_window() -> Value { + json!({"start":"1793480400","end":"1793487600","timezone":"America/Toronto"}) +} + +#[test] +fn estimated_supply_preserves_explicit_null_and_exact_absolute_window_in_commands_and_events() { + use radroots_protocol::listing::ListingEvent; + for window in [Value::Null, absolute_window()] { + let mut wire = input(); + wire["profile"]["options"][0]["supply"] = estimated_supply(window); + let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + assert_eq!(serde_json::to_value(&parsed).unwrap(), wire); + let event = ListingEvent::new(&parsed, key(), UnixSeconds::new(101).unwrap()).unwrap(); + let profile = event + .fields() + .tags + .iter() + .find(|tag| tag[0] == "radroots:listing") + .unwrap(); + assert_eq!( + serde_json::from_str::<Value>(&profile[1]).unwrap(), + wire["profile"] + ); + let captured = CapturedListingCommand::capture(context(), parsed).unwrap(); + let replay = CapturedListingCommand::parse(captured.protected_wire()).unwrap(); + assert_eq!(captured.digest(), replay.digest()); + assert_eq!(captured.protected_wire(), replay.protected_wire()); + } +} + +#[test] +fn estimated_supply_refuses_missing_duplicate_array_noncanonical_and_ambiguous_window_data() { + let mut original = input(); + original["profile"]["options"][0]["supply"] = estimated_supply(absolute_window()); + for (pointer, bad) in [ + ( + "/profile/options/0/supply", + json!({"type":"estimated","amount":"10"}), + ), + ("/profile/options/0/supply/amount", json!("0.5")), + ("/profile/options/0/supply/amount", json!("-1")), + ("/profile/options/0/supply/amount", json!(10)), + ( + "/profile/options/0/supply/window", + json!(["1793480400", "1793487600", "America/Toronto"]), + ), + ( + "/profile/options/0/supply/window", + json!({"start":"100","timezone":"Etc/UTC"}), + ), + ("/profile/options/0/supply/window/start", json!(1793480400)), + ( + "/profile/options/0/supply/window/start", + json!("01793480400"), + ), + ("/profile/options/0/supply/window/start", json!("-1")), + ( + "/profile/options/0/supply/window/start", + json!("253402300800"), + ), + ("/profile/options/0/supply/window/end", json!("1793480400")), + ("/profile/options/0/supply/window/end", json!("0")), + ( + "/profile/options/0/supply/window/timezone", + json!("america/toronto"), + ), + ( + "/profile/options/0/supply/window/timezone", + json!("Invented/Zone"), + ), + ( + "/profile/options/0/supply/window/timezone", + json!("America/Toronto "), + ), + ( + "/profile/options/0/supply/window/timezone", + json!("a".repeat(81)), + ), + ("/profile/options/0/supply/window/timezone", json!(null)), + ] { + let mut wire = original.clone(); + *wire.pointer_mut(pointer).unwrap() = bad; + assert_eq!( + PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap_err(), + CommandError::InvalidInput, + "{pointer}" + ); + } + for key in ["start", "end", "timezone"] { + let mut missing = original.clone(); + missing["profile"]["options"][0]["supply"]["window"] + .as_object_mut() + .unwrap() + .remove(key); + assert!(PublishInput::parse(&serde_json::to_vec(&missing).unwrap()).is_err()); + } + for (key, value) in [ + ("offset", json!("-04:00")), + ("fold", json!(1)), + ("wall_time", json!("2026-11-01T01:30:00")), + ] { + let mut extra = original.clone(); + extra["profile"]["options"][0]["supply"]["window"][key] = value; + assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err()); + } + let raw = serde_json::to_string(&original).unwrap(); + for (needle, replacement) in [ + ( + "\"start\":\"1793480400\"", + "\"start\":\"1793480400\",\"start\":\"1793480401\"", + ), + ("\"window\":{", "\"window\":null,\"window\":{"), + ] { + assert!(raw.contains(needle)); + assert!(PublishInput::parse(raw.replacen(needle, replacement, 1).as_bytes()).is_err()); + } + let mut measured = original; + measured["profile"]["options"][0]["unit"] = json!({"type":"measured","unit":"kg"}); + measured["profile"]["options"][0]["supply"]["amount"] = json!("0.5"); + assert!(PublishInput::parse(&serde_json::to_vec(&measured).unwrap()).is_ok()); + measured["profile"]["options"][0]["supply"]["amount"] = json!("0"); + assert!(PublishInput::parse(&serde_json::to_vec(&measured).unwrap()).is_ok()); +} + #[test] fn media_references_round_trip_without_upload_fetch_or_empty_profile_fallback() { use radroots_protocol::listing::ListingEvent; @@ -527,7 +654,7 @@ fn unsupported_profile_features_are_refused_without_silent_fallback() { ), ( "/profile/options/0/supply", - json!({"type":"estimated","amount":"10","window":null}), + json!({"type":"future_supply","amount":"10","window":null}), ), ( "/profile/options/0/unit/contents", diff --git a/crates/radroots/tests/support/receipt_listing_economics.rs b/crates/radroots/tests/support/receipt_listing_economics.rs @@ -30,6 +30,8 @@ async fn monetary_listings_sign_install_deliver_and_reopen_without_repricing_or_ "mime":"application/octet-stream","alt":""}]); wire["profile"]["options"][0]["price"] = price; wire["profile"]["options"][0]["unit"]["contents"] = contents; + wire["profile"]["options"][0]["supply"] = json!({"type":"estimated","amount":"10", + "window":{"start":"1793480400","end":"1793487600","timezone":"America/Toronto"}}); let captured = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); let deadline = now() + 120; let receipt = ready