lib

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

commit b0d26aef0af793e54d01dd2e1e78ea83ae93c60a
parent c12a2516efdea5a389a374ca09dadd512a892223
Author: triesap <tyson@radroots.org>
Date:   Tue, 20 Oct 2026 09:41:43 +0000

listing: Build bounded quote-required public offer profiles

- Validate distinct listing and option identities with exact unit increments
- Produce canonical known-kind profiles without fabricated prices or stock rights
- Preserve inactive coordinates and enforce complete signed-event byte limits
- Verify native and WASM paths, JSON map feature independence, APIs and guards

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcontracts/api_baselines/radroots_protocol.txt | 18++++++++++++++++++
Mcrates/domain/README.md | 14+++++++++++---
Mcrates/domain/src/identifier.rs | 4++++
Mcrates/domain/src/lib.rs | 6++++--
Acrates/domain/src/listing.rs | 493+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/domain/tests/listing.rs | 244+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/Cargo.toml | 1+
Mcrates/protocol/README.md | 14++++++++++++++
Mcrates/protocol/src/lib.rs | 5+++++
Acrates/protocol/src/listing.rs | 256+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/protocol/tests/listing.rs | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 1363 insertions(+), 5 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -1,5 +1,92 @@ pub mod radroots_domain pub use radroots_domain::PublicKey +pub mod radroots_domain::listing +pub enum radroots_domain::listing::FulfillmentMode +pub radroots_domain::listing::FulfillmentMode::Delivery +pub radroots_domain::listing::FulfillmentMode::Pickup +#[non_exhaustive] pub enum radroots_domain::listing::ListingError +pub radroots_domain::listing::ListingError::InvalidDuration +pub radroots_domain::listing::ListingError::InvalidFulfillment +pub radroots_domain::listing::ListingError::InvalidIdentifier +pub radroots_domain::listing::ListingError::InvalidOptions +pub radroots_domain::listing::ListingError::InvalidQuantity +pub radroots_domain::listing::ListingError::InvalidText +impl core::error::Error for radroots_domain::listing::ListingError +impl core::fmt::Display for radroots_domain::listing::ListingError +pub fn radroots_domain::listing::ListingError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub enum radroots_domain::listing::ListingState +pub radroots_domain::listing::ListingState::Active +pub radroots_domain::listing::ListingState::Paused +pub radroots_domain::listing::ListingState::Withdrawn +pub enum radroots_domain::listing::MeasurementUnit +pub radroots_domain::listing::MeasurementUnit::Each +pub radroots_domain::listing::MeasurementUnit::Gram +pub radroots_domain::listing::MeasurementUnit::Kilogram +pub radroots_domain::listing::MeasurementUnit::Litre +pub radroots_domain::listing::MeasurementUnit::Millilitre +impl radroots_domain::listing::MeasurementUnit +pub const fn radroots_domain::listing::MeasurementUnit::symbol(self) -> &'static str +#[non_exhaustive] pub enum radroots_domain::listing::Price +pub radroots_domain::listing::Price::QuoteRequired +#[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::Unknown +pub struct radroots_domain::listing::LeadSeconds(_) +impl radroots_domain::listing::LeadSeconds +pub const fn radroots_domain::listing::LeadSeconds::get(self) -> u64 +pub fn radroots_domain::listing::LeadSeconds::new(u64) -> core::result::Result<Self, radroots_domain::listing::ListingError> +pub struct radroots_domain::listing::ListingId(_) +impl radroots_domain::listing::ListingId +pub const fn radroots_domain::listing::ListingId::as_bytes(&self) -> &[u8; 16] +pub const fn radroots_domain::listing::ListingId::from_bytes([u8; 16]) -> Self +impl core::fmt::Display for radroots_domain::listing::ListingId +pub fn radroots_domain::listing::ListingId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::listing::ListingId +pub type radroots_domain::listing::ListingId::Err = radroots_domain::listing::ListingError +pub fn radroots_domain::listing::ListingId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::listing::ListingId +pub fn radroots_domain::listing::ListingId::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::listing::ListingId +pub fn radroots_domain::listing::ListingId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::listing::ListingOption +impl radroots_domain::listing::ListingOption +pub const fn radroots_domain::listing::ListingOption::id(&self) -> radroots_domain::ListingOptionId +pub fn radroots_domain::listing::ListingOption::label(&self) -> &str +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::unit(&self) -> &radroots_domain::listing::SaleUnit +impl core::fmt::Debug for radroots_domain::listing::ListingOption +pub fn radroots_domain::listing::ListingOption::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::listing::ListingTerms +impl radroots_domain::listing::ListingTerms +pub fn radroots_domain::listing::ListingTerms::default_option(&self) -> &radroots_domain::listing::ListingOption +pub const fn radroots_domain::listing::ListingTerms::fulfillment(&self) -> &radroots_domain::listing::PublicFulfillment +pub fn radroots_domain::listing::ListingTerms::new(radroots_domain::listing::ListingState, radroots_domain::listing::Product, radroots_domain::ListingOptionId, alloc::vec::Vec<radroots_domain::listing::ListingOption>, radroots_domain::listing::PublicFulfillment, core::option::Option<radroots_domain::AuthorityRef>) -> core::result::Result<Self, radroots_domain::listing::ListingError> +pub fn radroots_domain::listing::ListingTerms::options(&self) -> &[radroots_domain::listing::ListingOption] +pub const fn radroots_domain::listing::ListingTerms::state(&self) -> radroots_domain::listing::ListingState +impl core::fmt::Debug for radroots_domain::listing::ListingTerms +pub fn radroots_domain::listing::ListingTerms::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::listing::Product +impl radroots_domain::listing::Product +pub fn radroots_domain::listing::Product::name(&self) -> &str +pub fn radroots_domain::listing::Product::new(&str, &str, core::option::Option<radroots_identity::key::PublicKey>, core::option::Option<&str>) -> core::result::Result<Self, radroots_domain::listing::ListingError> +impl core::fmt::Debug for radroots_domain::listing::Product +pub fn radroots_domain::listing::Product::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::listing::PublicFulfillment +impl radroots_domain::listing::PublicFulfillment +pub fn radroots_domain::listing::PublicFulfillment::area(&self) -> &str +pub fn radroots_domain::listing::PublicFulfillment::new(alloc::vec::Vec<radroots_domain::listing::FulfillmentMode>, &str, radroots_domain::listing::LeadSeconds) -> core::result::Result<Self, radroots_domain::listing::ListingError> +impl core::fmt::Debug for radroots_domain::listing::PublicFulfillment +pub fn radroots_domain::listing::PublicFulfillment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::listing::SaleUnit(_) +impl radroots_domain::listing::SaleUnit +pub const fn radroots_domain::listing::SaleUnit::integral(&self) -> bool +pub fn radroots_domain::listing::SaleUnit::label(&self) -> &str +pub const fn radroots_domain::listing::SaleUnit::measured(radroots_domain::listing::MeasurementUnit) -> Self +pub fn radroots_domain::listing::SaleUnit::package_unspecified(&str) -> core::result::Result<Self, radroots_domain::listing::ListingError> +impl core::fmt::Debug for radroots_domain::listing::SaleUnit +pub fn radroots_domain::listing::SaleUnit::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_domain::ActorRole pub radroots_domain::ActorRole::Buyer pub radroots_domain::ActorRole::Coordinator @@ -260,6 +347,20 @@ pub fn radroots_domain::IssuanceWindow::capture(radroots_domain::UnixSeconds, ra 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::ListingOptionId(_) +impl radroots_domain::ListingOptionId +pub const fn radroots_domain::ListingOptionId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::ListingOptionId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::ListingOptionId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::ListingOptionId +pub fn radroots_domain::ListingOptionId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::ListingOptionId +pub type radroots_domain::ListingOptionId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::ListingOptionId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::ListingOptionId +pub fn radroots_domain::ListingOptionId::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::ListingOptionId +pub fn radroots_domain::ListingOptionId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::MessageId(_) impl radroots_domain::MessageId pub const fn radroots_domain::MessageId::as_bytes(&self) -> &[u8; 32] diff --git a/contracts/api_baselines/radroots_protocol.txt b/contracts/api_baselines/radroots_protocol.txt @@ -465,6 +465,24 @@ pub struct radroots_protocol::intent::InvalidIntentBinding impl core::error::Error for radroots_protocol::intent::InvalidIntentBinding impl core::fmt::Display for radroots_protocol::intent::InvalidIntentBinding pub fn radroots_protocol::intent::InvalidIntentBinding::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub mod radroots_protocol::listing +pub struct radroots_protocol::listing::ListingEvent +impl radroots_protocol::listing::ListingEvent +pub const fn radroots_protocol::listing::ListingEvent::event_id(&self) -> &[u8; 32] +pub fn radroots_protocol::listing::ListingEvent::fields(&self) -> radroots_protocol::nip01::EventFields<'_> +pub fn radroots_protocol::listing::ListingEvent::new(&radroots_protocol::listing::PublishInput, radroots_identity::key::PublicKey, radroots_domain::context::UnixSeconds) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +impl core::fmt::Debug for radroots_protocol::listing::ListingEvent +pub fn radroots_protocol::listing::ListingEvent::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_protocol::listing::PublishInput +impl radroots_protocol::listing::PublishInput +pub const fn radroots_protocol::listing::PublishInput::id(&self) -> radroots_domain::listing::ListingId +pub fn radroots_protocol::listing::PublishInput::new(radroots_domain::listing::ListingId, &str, &str, &str, radroots_domain::context::UnixSeconds, radroots_domain::listing::ListingTerms) -> core::result::Result<Self, radroots_protocol::nip01::WireError> +pub const fn radroots_protocol::listing::PublishInput::published_at(&self) -> radroots_domain::context::UnixSeconds +pub const fn radroots_protocol::listing::PublishInput::terms(&self) -> &radroots_domain::listing::ListingTerms +impl core::fmt::Debug for radroots_protocol::listing::PublishInput +pub fn radroots_protocol::listing::PublishInput::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub const radroots_protocol::listing::LISTING_EVENT_MAX_BYTES: usize +pub const radroots_protocol::listing::LISTING_KIND: u32 pub mod radroots_protocol::nip01 pub enum radroots_protocol::nip01::WireError pub radroots_protocol::nip01::WireError::InvalidInput diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -1,9 +1,8 @@ # Radroots domain Independently implemented exact values for the shared SDK successor. This -package is under construction and is not published or part of the current -public release closure. It does not yet implement listings, agreements or -command execution. +pre-release package provides validated values and public quote-required offer +terms. It does not execute commands, install agreements or establish stock. `Decimal` has a nonnegative coefficient up to 999999999999 and scale 0–6. Construction normalizes fractional trailing zeros. String admission requires @@ -21,6 +20,15 @@ Each stores 32 bytes and uses exactly 64 lowercase hexadecimal characters in strings and JSON. Byte/string construction validates representation; generation belongs to the execution owner's qualified CSPRNG boundary. +`listing::ListingId` is the distinct 128-bit stable coordinate discriminator; +`ListingOptionId` is a 256-bit sale-choice identity. Public listing terms bound +and deduplicate options, retain an exact selected default, and validate positive +increments/minimums without floating conversion. Package and `each` quantities +remain integral; measured units imply no conversion. Quote-required prices +contain no invented zero amount or currency. Optional opaque authority and +producer metadata establish no permission or endpoint trust. These immutable +terms serialize public data explicitly and redact ordinary diagnostics. + Namespaces remain separate across native calls: ```compile_fail diff --git a/crates/domain/src/identifier.rs b/crates/domain/src/identifier.rs @@ -112,6 +112,10 @@ macro_rules! identifier { } identifier!(OrderId, "An exact 256-bit bilateral order identifier."); +identifier!( + ListingOptionId, + "An exact 256-bit public sale-option identifier." +); 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 @@ -9,6 +9,8 @@ mod amount; mod context; mod identifier; mod issuance; +/// Validated public-offer values; these establish no stock or command authority. +pub mod listing; mod message; /// The identity-owned validated participant key; no second key type is defined. @@ -21,8 +23,8 @@ pub use context::{ }; pub use identifier::{ ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, ExecutorId, GrantId, - IdentifierError, MessageId, OperationId, OrderId, RecordId, RouteDigest, SigningAttemptId, - SourceId, ThreadId, TransactionId, WorkspaceId, + IdentifierError, ListingOptionId, MessageId, OperationId, OrderId, RecordId, RouteDigest, + SigningAttemptId, SourceId, ThreadId, TransactionId, WorkspaceId, }; pub use issuance::{FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow}; pub use message::{CHAT_MAX_BYTES, ChatMessage, ChatRelation, MessageError}; diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs @@ -0,0 +1,493 @@ +//! Public offer values without protocol effects or private inventory backing. +//! Quote-required choices are supported independently of monetary registries. + +use crate::{AuthorityRef, Decimal, ListingOptionId, PositiveDecimal, PublicKey, Sequence}; +use alloc::{string::String, vec::Vec}; +use core::{fmt, str::FromStr}; + +/// A fixed, input-free public-offer value failure. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum ListingError { + /// An identifier has the wrong width or noncanonical hexadecimal. + InvalidIdentifier, + /// A descriptive field is empty where required or exceeds its bound. + InvalidText, + /// An amount violates its increment, minimum or count unit. + InvalidQuantity, + /// Choices are missing, excessive, duplicated or lack the selected default. + InvalidOptions, + /// Fulfillment modes are empty, duplicated or excessive. + InvalidFulfillment, + /// A duration exceeds the cross-host exact integer bound. + InvalidDuration, +} +impl fmt::Display for ListingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidIdentifier => "invalid listing identifier", + Self::InvalidText => "invalid listing text", + Self::InvalidQuantity => "invalid listing quantity", + Self::InvalidOptions => "invalid listing options", + Self::InvalidFulfillment => "invalid public fulfillment", + Self::InvalidDuration => "invalid listing duration", + }) + } +} +impl core::error::Error for ListingError {} + +/// Stable128-bit coordinate discriminator. Generation requires host entropy; +/// parsing this descriptor never proves novelty, ownership or publication. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct ListingId([u8; 16]); +impl ListingId { + /// Captures exact bytes supplied by the execution owner's entropy boundary. + pub const fn from_bytes(bytes: [u8; 16]) -> Self { + Self(bytes) + } + /// Borrows the original bytes. + pub const fn as_bytes(&self) -> &[u8; 16] { + &self.0 + } +} +impl FromStr for ListingId { + type Err = ListingError; + fn from_str(value: &str) -> Result<Self, Self::Err> { + if value.len() != 32 { + return Err(ListingError::InvalidIdentifier); + } + let digit = |b| match b { + b'0'..=b'9' => Ok(b - b'0'), + b'a'..=b'f' => Ok(b - b'a' + 10), + _ => Err(ListingError::InvalidIdentifier), + }; + let mut bytes = [0; 16]; + let (pairs, _) = value.as_bytes().as_chunks::<2>(); + for (out, &[a, b]) in bytes.iter_mut().zip(pairs) { + *out = digit(a)? * 16 + digit(b)?; + } + Ok(Self(bytes)) + } +} +impl fmt::Display for ListingId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for byte in self.0 { + write!(f, "{byte:02x}")?; + } + Ok(()) + } +} +#[cfg(feature = "serde")] +impl serde::Serialize for ListingId { + fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { + s.collect_str(self) + } +} +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for ListingId { + fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { + struct Visitor; + impl serde::de::Visitor<'_> for Visitor { + type Value = ListingId; + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("32 lowercase hexadecimal characters") + } + fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { + value.parse().map_err(E::custom) + } + } + d.deserialize_str(Visitor) + } +} + +/// Exact lead time, serialized as a canonical decimal string. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(transparent))] +pub struct LeadSeconds(Sequence); +impl LeadSeconds { + /// Checks the shared integer range; zero means no advertised lead time. + pub fn new(value: u64) -> Result<Self, ListingError> { + Sequence::new(value) + .map(Self) + .map_err(|_| ListingError::InvalidDuration) + } + /// Returns the exact duration without conversion to a timestamp. + pub const fn get(self) -> u64 { + self.0.get() + } +} + +/// Required public listing state; inactive states retain their coordinate. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +pub enum ListingState { + /// Available for new inquiries subject to current action readiness. + Active, + /// Temporarily unavailable, without a sold or completion claim. + Paused, + /// Withdrawn from new business, without cancelling existing obligations. + Withdrawn, +} + +/// Explicit measurement identity; equal numbers do not imply conversion. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub enum MeasurementUnit { + /// Grams. + #[cfg_attr(feature = "serde", serde(rename = "g"))] + Gram, + /// Kilograms. + #[cfg_attr(feature = "serde", serde(rename = "kg"))] + Kilogram, + /// Millilitres. + #[cfg_attr(feature = "serde", serde(rename = "mL"))] + Millilitre, + /// Litres. + #[cfg_attr(feature = "serde", serde(rename = "L"))] + Litre, + /// Integral individual units. + #[cfg_attr(feature = "serde", serde(rename = "each"))] + Each, +} +impl MeasurementUnit { + /// Exact public protocol symbol, without an implicit unit conversion. + pub const fn symbol(self) -> &'static str { + match self { + Self::Gram => "g", + Self::Kilogram => "kg", + Self::Millilitre => "mL", + Self::Litre => "L", + Self::Each => "each", + } + } +} + +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] +enum UnitKind { + Measured { + unit: MeasurementUnit, + }, + Package { + label: String, + contents: UnspecifiedContents, + }, +} +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] +enum UnspecifiedContents { + Unspecified, +} + +/// Validated sale unit. An unspecified package implies no mass/volume mapping. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(transparent))] +pub struct SaleUnit(UnitKind); +impl SaleUnit { + /// Selects an explicit measurement unit. + pub const fn measured(unit: MeasurementUnit) -> Self { + Self(UnitKind::Measured { unit }) + } + /// Selects a labelled package without inventing its physical contents. + pub fn package_unspecified(label: &str) -> Result<Self, ListingError> { + text(label, 80, false)?; + Ok(Self(UnitKind::Package { + label: label.into(), + contents: UnspecifiedContents::Unspecified, + })) + } + /// Borrows the explicit display label/symbol used by public projections. + pub fn label(&self) -> &str { + match &self.0 { + UnitKind::Measured { unit } => unit.symbol(), + UnitKind::Package { label, .. } => label, + } + } + /// Whether sale quantities must be integral counts. + pub const fn integral(&self) -> bool { + matches!( + self.0, + UnitKind::Package { .. } + | UnitKind::Measured { + unit: MeasurementUnit::Each + } + ) + } +} +impl fmt::Debug for SaleUnit { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SaleUnit(<redacted>)") + } +} + +/// An advertised estimate/claim, never an authoritative stock balance. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] +pub enum Supply { + /// No quantity is advertised. + Unknown, + /// The seller advertises this nonnegative quantity in the sale unit. + Available { + /// Public advertised quantity, without backing authority. + amount: Decimal, + }, +} + +/// Supported quote-required price. Monetary modes require their validated +/// registry and exact economics before they can be represented here. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] +pub enum Price { + /// No zero-price, rate, currency, discount or hold is inferred. + QuoteRequired, +} + +/// Validated public product description; producer data grants no agency rights. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct Product { + name: String, + description: String, + producer: Option<PublicKey>, + origin_summary: Option<String>, +} +impl Product { + /// Captures explicitly public descriptive fields without hierarchy lookup. + pub fn new( + name: &str, + description: &str, + producer: Option<PublicKey>, + origin_summary: Option<&str>, + ) -> Result<Self, ListingError> { + text(name, 160, false)?; + text(description, 4096, true)?; + if let Some(origin) = origin_summary { + text(origin, 160, true)?; + } + Ok(Self { + name: name.into(), + description: description.into(), + producer, + origin_summary: origin_summary.map(String::from), + }) + } + /// Borrows the validated public product name. + pub fn name(&self) -> &str { + &self.name + } +} +impl fmt::Debug for Product { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Product(<redacted>)") + } +} + +/// A validated buyer-selectable quote choice, with no private pool/lot IDs. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ListingOption { + id: ListingOptionId, + label: String, + unit: SaleUnit, + increment: PositiveDecimal, + minimum: PositiveDecimal, + price: Price, + supply: Supply, + lead_seconds: LeadSeconds, +} +impl ListingOption { + /// Captures quote-required terms. Minimum is an exact multiple of increment; + /// count/package units and their advertised available supply are integral. + pub fn quote_required( + id: ListingOptionId, + label: &str, + unit: SaleUnit, + increment: PositiveDecimal, + minimum: PositiveDecimal, + supply: Supply, + lead_seconds: LeadSeconds, + ) -> Result<Self, ListingError> { + text(label, 120, false)?; + let inc = increment.amount(); + let min = minimum.amount(); + let scale = inc.scale().max(min.scale()); + let align = |v: Decimal| v.coefficient() * 10_u64.pow(u32::from(scale - v.scale())); + if !align(min).is_multiple_of(align(inc)) + || (unit.integral() + && (inc.scale() != 0 + || min.scale() != 0 + || matches!(supply, Supply::Available { amount } if amount.scale() != 0))) + { + return Err(ListingError::InvalidQuantity); + } + Ok(Self { + id, + label: label.into(), + unit, + increment, + minimum, + price: Price::QuoteRequired, + supply, + lead_seconds, + }) + } + /// Returns the stable sale-choice identity. + pub const fn id(&self) -> ListingOptionId { + self.id + } + /// Borrows the exact sale unit. + pub const fn unit(&self) -> &SaleUnit { + &self.unit + } + /// Returns the validated price mode, without inventing a quoted amount. + pub const fn price(&self) -> Price { + self.price + } + /// Borrows the public default-choice description. + pub fn label(&self) -> &str { + &self.label + } +} +impl fmt::Debug for ListingOption { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingOption(<redacted>)") + } +} + +/// Public fulfillment mode, without exact private destination or time window. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +pub enum FulfillmentMode { + /// Collection by the buyer. + Pickup, + /// Delivery, subject to separately agreed private terms. + Delivery, +} + +/// Bounded coarse public fulfillment; this is not an installed agreement. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct PublicFulfillment { + modes: Vec<FulfillmentMode>, + area: String, + lead_seconds: LeadSeconds, +} +impl PublicFulfillment { + /// Captures one or two distinct modes and an explicitly public coarse area. + pub fn new( + modes: Vec<FulfillmentMode>, + area: &str, + lead_seconds: LeadSeconds, + ) -> Result<Self, ListingError> { + if modes.is_empty() || modes.len() > 2 || (modes.len() == 2 && modes[0] == modes[1]) { + return Err(ListingError::InvalidFulfillment); + } + text(area, 160, true)?; + Ok(Self { + modes, + area: area.into(), + lead_seconds, + }) + } + /// Borrows the public coarse area; it grants no endpoint or address trust. + pub fn area(&self) -> &str { + &self.area + } +} +impl fmt::Debug for PublicFulfillment { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PublicFulfillment(<redacted>)") + } +} + +/// Immutable public-offer terms for the supported quote-required producer. +/// These are data, without workspace authority, signing or private backing. +#[derive(Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ListingTerms { + state: ListingState, + product: Product, + default_option: ListingOptionId, + options: Vec<ListingOption>, + fulfillment: PublicFulfillment, + authority: Option<AuthorityRef>, + #[cfg_attr(feature = "serde", serde(skip))] + default_index: usize, +} +impl ListingTerms { + /// Checks bounded unique choices and exact default membership before capture. + pub fn new( + state: ListingState, + product: Product, + default_option: ListingOptionId, + options: Vec<ListingOption>, + fulfillment: PublicFulfillment, + authority: Option<AuthorityRef>, + ) -> Result<Self, ListingError> { + if options.is_empty() + || options.len() > 16 + || options + .iter() + .enumerate() + .any(|(i, o)| options[..i].iter().any(|p| p.id == o.id)) + { + return Err(ListingError::InvalidOptions); + } + let default_index = options + .iter() + .position(|o| o.id == default_option) + .ok_or(ListingError::InvalidOptions)?; + Ok(Self { + state, + product, + default_option, + options, + fulfillment, + authority, + default_index, + }) + } + /// Returns the advertised state, without determining action readiness. + pub const fn state(&self) -> ListingState { + self.state + } + /// Borrows the bounded, unique public choices. + pub fn options(&self) -> &[ListingOption] { + &self.options + } + /// Borrows the previously validated default choice without a fallback. + pub fn default_option(&self) -> &ListingOption { + // Private immutable fields and the validating constructor ensure exact + // membership. Returning a reference introduces no reconstructed choice. + &self.options[self.default_index] + } + /// Borrows the coarse public fulfillment data. + pub const fn fulfillment(&self) -> &PublicFulfillment { + &self.fulfillment + } +} +impl fmt::Debug for ListingTerms { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingTerms(<redacted>)") + } +} + +fn text(value: &str, maximum: usize, allow_empty: bool) -> Result<(), ListingError> { + if (!allow_empty && value.is_empty()) + || value.len() > maximum.saturating_mul(4) + || value.chars().count() > maximum + { + return Err(ListingError::InvalidText); + } + Ok(()) +} diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -0,0 +1,244 @@ +use radroots_domain::{ListingOptionId, listing::*}; + +fn product() -> Product { + Product::new( + "Carrots", + "Public description", + None, + Some("Example region"), + ) + .unwrap() +} +fn fulfillment() -> PublicFulfillment { + PublicFulfillment::new( + vec![FulfillmentMode::Pickup], + "Example region", + LeadSeconds::new(0).unwrap(), + ) + .unwrap() +} +fn option( + n: u8, + unit: SaleUnit, + increment: &str, + minimum: &str, + amount: &str, +) -> Result<ListingOption, ListingError> { + ListingOption::quote_required( + ListingOptionId::from_bytes([n; 32]), + "One bunch", + unit, + increment.parse().unwrap(), + minimum.parse().unwrap(), + Supply::Available { + amount: amount.parse().unwrap(), + }, + LeadSeconds::new(0).unwrap(), + ) +} + +#[test] +fn identifiers_durations_and_public_data_preserve_exact_cross_host_values() { + let id = ListingId::from_bytes([0xAB; 16]); + assert_eq!(id.to_string(), "ab".repeat(16)); + assert_eq!( + id.to_string().parse::<ListingId>().unwrap().as_bytes(), + &[0xAB; 16] + ); + for bad in [ + "ab".repeat(15), + "ab".repeat(17), + "AB".repeat(16), + "0g".repeat(16), + "é".repeat(16), + ] { + assert_eq!( + bad.parse::<ListingId>().unwrap_err(), + ListingError::InvalidIdentifier + ); + } + assert_eq!( + LeadSeconds::new(i64::MAX as u64).unwrap().get(), + i64::MAX as u64 + ); + assert_eq!( + LeadSeconds::new(i64::MAX as u64 + 1).unwrap_err(), + ListingError::InvalidDuration + ); + let name = "🥕".repeat(160); + let value = Product::new(&name, "\u{0001}", None, None).unwrap(); + assert_eq!(value.name(), name); + assert!(!format!("{value:?}").contains('🥕')); + assert!(Product::new(&(name + "x"), "", None, None).is_err()); + assert!(Product::new("", "", None, None).is_err()); + assert!(Product::new("x", &"x".repeat(4097), None, None).is_err()); + assert!(Product::new("x", "", None, Some(&"x".repeat(161))).is_err()); + assert!(SaleUnit::package_unspecified("").is_err()); + assert!(SaleUnit::package_unspecified(&"x".repeat(81)).is_err()); + assert!(PublicFulfillment::new(vec![], "", LeadSeconds::new(0).unwrap()).is_err()); + assert!( + PublicFulfillment::new( + vec![FulfillmentMode::Pickup; 2], + "", + LeadSeconds::new(0).unwrap() + ) + .is_err() + ); + assert!( + PublicFulfillment::new( + vec![FulfillmentMode::Pickup; 3], + "", + LeadSeconds::new(0).unwrap() + ) + .is_err() + ); + assert!( + PublicFulfillment::new( + vec![FulfillmentMode::Pickup], + &"x".repeat(161), + LeadSeconds::new(0).unwrap() + ) + .is_err() + ); + assert!( + PublicFulfillment::new( + vec![FulfillmentMode::Pickup, FulfillmentMode::Delivery], + "", + LeadSeconds::new(0).unwrap() + ) + .is_ok() + ); +} + +#[test] +fn exact_increments_and_units_never_invent_fractional_packages_or_conversion() { + for unit in [ + MeasurementUnit::Gram, + MeasurementUnit::Kilogram, + MeasurementUnit::Millilitre, + MeasurementUnit::Litre, + ] { + let value = option(1, SaleUnit::measured(unit), "0.25", "0.5", "1.5").unwrap(); + assert_eq!(value.unit().label(), unit.symbol()); + assert!(!value.unit().integral()); + assert_eq!(value.price(), Price::QuoteRequired); + assert!(option(1, SaleUnit::measured(unit), "0.25", "0.3", "1.5").is_err()); + } + for unit in [ + SaleUnit::measured(MeasurementUnit::Each), + SaleUnit::package_unspecified("bunch").unwrap(), + ] { + assert!(unit.integral()); + for (inc, min, amount) in [ + ("0.5", "1", "10"), + ("1", "1.5", "10"), + ("1", "1", "0.5"), + ("2", "1", "10"), + ] { + assert_eq!( + option(1, unit.clone(), inc, min, amount).unwrap_err(), + ListingError::InvalidQuantity + ); + } + let available = option(1, unit, "1", "2", "0").unwrap(); + assert_eq!(available.id(), ListingOptionId::from_bytes([1; 32])); + } + let unknown = ListingOption::quote_required( + ListingOptionId::from_bytes([2; 32]), + "Measured", + SaleUnit::measured(MeasurementUnit::Kilogram), + "0.000001".parse().unwrap(), + "0.000002".parse().unwrap(), + Supply::Unknown, + LeadSeconds::new(0).unwrap(), + ) + .unwrap(); + assert_eq!(unknown.label(), "Measured"); +} + +#[test] +fn bounded_unique_options_preserve_exact_default_without_fallback() { + let make = |n| { + option( + n, + SaleUnit::package_unspecified("bunch").unwrap(), + "1", + "1", + "10", + ) + .unwrap() + }; + let terms = |choices, default| { + ListingTerms::new( + ListingState::Active, + product(), + ListingOptionId::from_bytes([default; 32]), + choices, + fulfillment(), + None, + ) + }; + assert!(terms(vec![], 1).is_err()); + assert!(terms(vec![make(1), make(1)], 1).is_err()); + assert!(terms(vec![make(1)], 2).is_err()); + assert!(terms((1..=17).map(make).collect(), 1).is_err()); + let valid = terms((1..=16).map(make).collect(), 16).unwrap(); + assert_eq!( + valid.default_option().id(), + ListingOptionId::from_bytes([16; 32]) + ); + assert_eq!(valid.options().len(), 16); + assert_eq!(valid.fulfillment().area(), "Example region"); + assert_eq!(valid.state(), ListingState::Active); + assert!(!format!("{valid:?}").contains("Carrots")); +} + +#[cfg(feature = "serde")] +#[test] +fn serialized_values_have_exact_string_numbers_and_no_private_or_derived_fields() { + let id = ListingId::from_bytes([0xAB; 16]); + let raw = serde_json::to_string(&id).unwrap(); + assert_eq!(serde_json::from_str::<ListingId>(&raw).unwrap(), id); + assert!(serde_json::from_str::<ListingId>("null").is_err()); + assert!(serde_json::from_str::<ListingId>(&format!("\"{}\"", "AB".repeat(16))).is_err()); + assert_eq!( + serde_json::to_string(&LeadSeconds::new(0).unwrap()).unwrap(), + "\"0\"" + ); + for bad in ["0", "\"00\"", "\"-1\"", "null"] { + assert!(serde_json::from_str::<LeadSeconds>(bad).is_err()); + } + let choice = option( + 1, + SaleUnit::package_unspecified("bunch").unwrap(), + "1", + "1", + "10", + ) + .unwrap(); + let terms = ListingTerms::new( + ListingState::Active, + product(), + choice.id(), + vec![choice], + fulfillment(), + None, + ) + .unwrap(); + let value = serde_json::to_value(terms).unwrap(); + assert_eq!( + value["options"][0]["unit"], + serde_json::json!({"type":"package","label":"bunch","contents":{"type":"unspecified"}}) + ); + assert_eq!(value["options"][0]["increment"], "1"); + assert_eq!( + value["options"][0]["price"], + serde_json::json!({"type":"quote_required"}) + ); + assert_eq!( + value["options"][0]["supply"], + serde_json::json!({"type":"available","amount":"10"}) + ); + assert!(value.get("default_index").is_none()); + assert_eq!(value.as_object().unwrap().len(), 6); +} diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml @@ -38,6 +38,7 @@ commands = ["serde", "dep:radroots_domain", "dep:serde_json", "dep:sha2", "dep:z intent = ["dep:radroots_domain", "dep:sha2"] nip01 = ["dep:radroots_identity", "dep:sha2", "dep:zeroize"] chat = ["commands", "nip01"] +listing = ["commands", "nip01"] [dependencies] radroots_identity = { workspace = true, default-features = false, optional = true } diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -34,6 +34,7 @@ numbers embedded in wire and schema contracts. | `nip01` (`nip01` feature) | exact bounded canonical preimages, IDs and complete-event sizes | | `intent` (`intent` feature) | exact v1 signing commitment data without execution authority | | `chat` (`chat` feature) | bounded kind-14/13 data, complete immutable signing-plan codec and observed DM route descriptors | +| `listing` (`listing` feature) | typed quote-required input and bounded kind-30402/profile-v1 preimages without command or publication authority | Versioned DTOs live below an explicit generation module. The command codec implements its fixed v1 profile without exposing automatic serialization of @@ -52,6 +53,19 @@ they use. | `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 | + +The listing producer emits one canonical `radroots.listing` version-1 profile, +explicit default units and no fabricated price. Paused/withdrawn projections +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 +permission, durable preparation, signature, installed record or delivery receipt. Disabling default features leaves the catalog and structural validation APIs available with `alloc` only. Enable `serde` without `std` for portable encoded diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs @@ -21,6 +21,11 @@ pub mod nip01; #[cfg(feature = "chat")] pub mod chat; +/// Assigned kind30402 quote-required listing preimages. Pure construction does +/// not authenticate a workspace, prepare a command or publish an event. +#[cfg(feature = "listing")] +pub mod listing; + #[cfg(all(test, not(feature = "std")))] extern crate std; diff --git a/crates/protocol/src/listing.rs b/crates/protocol/src/listing.rs @@ -0,0 +1,256 @@ +//! Known public listing producer. Full monetary/media admission is separate; +//! unsupported features are never reduced to an invented quote or zero price. + +use crate::nip01::{self, EventFields, WireError}; +use alloc::{ + format, + string::{String, ToString}, + vec, + vec::Vec, +}; +use core::fmt; +use radroots_domain::{ + PublicKey, UnixSeconds, + listing::{ListingId, ListingState, ListingTerms, Price}, +}; +use serde::Serialize; +use serde_json::Value; +use sha2::{Digest, Sha256}; + +/// Assigned NIP-99 addressable classified-listing kind. +pub const LISTING_KIND: u32 = 30402; +/// Complete public event cap, including NIP-01 key, ID and signature framing. +pub const LISTING_EVENT_MAX_BYTES: usize = 65_536; + +/// Explicit immutable public-offer input; no IDs, time or authority are inferred. +#[derive(Clone, Serialize)] +pub struct PublishInput { + id: ListingId, + title: String, + summary: String, + description_markdown: String, + published_at: UnixSeconds, + #[serde(rename = "profile", serialize_with = "serialize_profile")] + terms: ListingTerms, +} +impl PublishInput { + /// Captures bounded text and validated quote-required terms. The human + /// summary describes the selected default unit/basis. No price is inferred. + pub fn new( + id: ListingId, + title: &str, + summary: &str, + description_markdown: &str, + published_at: UnixSeconds, + terms: ListingTerms, + ) -> Result<Self, WireError> { + for (value, limit, empty) in [ + (title, 160, false), + (summary, 280, false), + (description_markdown, 16_384, true), + ] { + if (!empty && value.is_empty()) + || value.len() > limit * 4 + || value.chars().count() > limit + { + return Err(WireError::InvalidInput); + } + } + Ok(Self { + id, + title: title.into(), + summary: summary.into(), + description_markdown: description_markdown.into(), + published_at, + terms, + }) + } + /// Returns the independently selected stable coordinate discriminator. + pub const fn id(&self) -> ListingId { + self.id + } + /// Borrows the exact validated terms, without stock or publication claims. + pub const fn terms(&self) -> &ListingTerms { + &self.terms + } + /// Returns the captured original publication timestamp. + pub const fn published_at(&self) -> UnixSeconds { + self.published_at + } +} +impl fmt::Debug for PublishInput { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("PublishInput(<redacted>)") + } +} + +fn profile_value(terms: &ListingTerms) -> Result<Value, WireError> { + let mut value = serde_json::to_value(terms).map_err(|_| WireError::InvalidInput)?; + let object = value.as_object_mut().ok_or(WireError::InvalidInput)?; + if object.len() != 6 + || object.keys().any(|key| { + !matches!( + key.as_str(), + "authority" | "default_option" | "fulfillment" | "options" | "product" | "state" + ) + }) + || terms + .options() + .iter() + .any(|option| !matches!(option.price(), Price::QuoteRequired)) + { + return Err(WireError::InvalidInput); + } + object.insert("profile".into(), Value::String("radroots.listing".into())); + object.insert("version".into(), Value::from(1_u8)); + // This producer supports no media. It never parses and silently strips + // media supplied by another producer or coerces an unsupported price. + object.insert("media".into(), Value::Array(Vec::new())); + Ok(value) +} +fn serialize_profile<S: serde::Serializer>( + terms: &ListingTerms, + serializer: S, +) -> Result<S::Ok, S::Error> { + profile_value(terms) + .map_err(serde::ser::Error::custom)? + .serialize(serializer) +} + +/// Retained exact public event fields. This value contains no signature and +/// supplies no evidence of T0/T1, signer invocation, installation or delivery. +pub struct ListingEvent { + author: PublicKey, + created_at: UnixSeconds, + tags: Vec<Vec<String>>, + content: String, + id: [u8; 32], +} +impl ListingEvent { + /// Builds one bounded profile/projection from immutable captured input. + /// Inactive revisions retain kind30402 and the same `d`, visibly state + /// non-availability, and omit a standard status rather than asserting sold. + pub fn new( + input: &PublishInput, + author: PublicKey, + created_at: UnixSeconds, + ) -> Result<Self, WireError> { + if input.published_at > created_at { + return Err(WireError::InvalidInput); + } + let mut profile = String::new(); + canonical(&profile_value(&input.terms)?, &mut profile)?; + let inactive = match input.terms.state() { + ListingState::Active => None, + ListingState::Paused => Some("Paused: unavailable"), + ListingState::Withdrawn => Some("Withdrawn: unavailable"), + }; + let summary = match inactive { + Some(label) => format!("[{label}] {}", input.summary), + None => input.summary.clone(), + }; + let content = match inactive { + Some(label) => format!("[{label}]\n\n{}", input.description_markdown), + None => input.description_markdown.clone(), + }; + let mut tags = vec![ + vec!["d".into(), input.id.to_string()], + vec!["title".into(), input.title.clone()], + vec!["summary".into(), summary], + vec!["published_at".into(), input.published_at.to_string()], + vec!["location".into(), input.terms.fulfillment().area().into()], + vec![ + "radroots:price_unit".into(), + input.terms.default_option().unit().label().into(), + ], + ]; + if inactive.is_none() { + tags.push(vec!["status".into(), "active".into()]); + } + tags.push(vec!["radroots:listing".into(), profile]); + let fields = EventFields { + author, + created_at: created_at.get(), + kind: LISTING_KIND, + tags: &tags, + content: &content, + }; + nip01::signed_json_len(&fields, LISTING_EVENT_MAX_BYTES)?; + let id = Sha256::digest(nip01::canonical_preimage(&fields).as_bytes()).into(); + Ok(Self { + author, + created_at, + tags, + content, + id, + }) + } + /// Borrows all original fields without sorting tags or reconstructing text. + pub fn fields(&self) -> EventFields<'_> { + EventFields { + author: self.author, + created_at: self.created_at.get(), + kind: LISTING_KIND, + tags: &self.tags, + content: &self.content, + } + } + /// Exact canonical unsigned NIP-01 event ID, not a signature or store receipt. + pub const fn event_id(&self) -> &[u8; 32] { + &self.id + } +} +impl fmt::Debug for ListingEvent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingEvent(<redacted>)") + } +} + +// RFC8785 subset: field names are fixed ASCII, quantities/IDs/times are strings, +// numeric fields are exact safe unsigned integers, and Unicode is preserved. +// Explicit sorting remains correct if a downstream crate enables preserve_order. +fn canonical(value: &Value, out: &mut String) -> Result<(), WireError> { + match value { + Value::Object(fields) => { + let mut keys: Vec<_> = fields.keys().collect(); + if keys.iter().any(|key| !key.is_ascii()) { + return Err(WireError::InvalidInput); + } + keys.sort_unstable(); + out.push('{'); + for (i, key) in keys.into_iter().enumerate() { + if i != 0 { + out.push(','); + } + out.push_str(&serde_json::to_string(key).map_err(|_| WireError::InvalidInput)?); + out.push(':'); + canonical(&fields[key], out)?; + } + out.push('}'); + } + Value::Array(values) => { + out.push('['); + for (i, value) in values.iter().enumerate() { + if i != 0 { + out.push(','); + } + canonical(value, out)?; + } + out.push(']'); + } + Value::Number(number) => { + if number + .as_u64() + .is_none_or(|value| value > 9_007_199_254_740_991) + { + return Err(WireError::InvalidInput); + } + out.push_str(&number.to_string()); + } + _ => out.push_str(&serde_json::to_string(value).map_err(|_| WireError::InvalidInput)?), + } + if out.len() > LISTING_EVENT_MAX_BYTES { + return Err(WireError::LimitExceeded); + } + Ok(()) +} diff --git a/crates/protocol/tests/listing.rs b/crates/protocol/tests/listing.rs @@ -0,0 +1,212 @@ +#![cfg(feature = "listing")] +use radroots_domain::{ListingOptionId, PublicKey, UnixSeconds, listing::*}; +use radroots_protocol::{ + listing::*, + nip01::{self, WireError}, +}; + +fn key() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn input(state: ListingState, body: &str) -> PublishInput { + let option = ListingOption::quote_required( + ListingOptionId::from_bytes([2; 32]), + "One bunch", + SaleUnit::package_unspecified("bunch").unwrap(), + "1".parse().unwrap(), + "1".parse().unwrap(), + Supply::Available { + amount: "10".parse().unwrap(), + }, + LeadSeconds::new(0).unwrap(), + ) + .unwrap(); + let terms = ListingTerms::new( + state, + Product::new( + "Carrots", + "Public description", + None, + Some("Example region"), + ) + .unwrap(), + option.id(), + vec![option], + PublicFulfillment::new( + vec![FulfillmentMode::Pickup], + "Example region", + LeadSeconds::new(0).unwrap(), + ) + .unwrap(), + None, + ) + .unwrap(); + PublishInput::new( + ListingId::from_bytes([1; 16]), + "Carrot bunch", + "One bunch; quote required", + body, + UnixSeconds::new(100).unwrap(), + terms, + ) + .unwrap() +} +fn event(input: &PublishInput) -> ListingEvent { + ListingEvent::new(input, key(), UnixSeconds::new(101).unwrap()).unwrap() +} +fn tag<'a>(event: &'a ListingEvent, name: &str) -> &'a [String] { + let fields = event.fields(); + let mut selected = fields.tags.iter().filter(|t| t[0] == name); + let value = selected.next().unwrap(); + assert!(selected.next().is_none()); + value +} + +#[test] +fn assigned_listing_profile_is_canonical_and_quote_required_has_no_fabricated_price() { + let captured = input(ListingState::Active, "Ask for terms."); + let value = event(&captured); + assert_eq!(value.fields().kind, 30402); + assert_eq!(tag(&value, "d"), ["d", &"01".repeat(16)]); + assert_eq!( + tag(&value, "radroots:price_unit"), + ["radroots:price_unit", "bunch"] + ); + assert_eq!(tag(&value, "status"), ["status", "active"]); + assert_eq!(tag(&value, "published_at"), ["published_at", "100"]); + assert!(!value.fields().tags.iter().any(|t| t[0] == "price")); + // Independently written golden profile fixes ordering and exact scalar + // representation; this does not claim independent signature qualification. + let golden = concat!( + "{\"authority\":null,\"default_option\":\"", + "0202020202020202020202020202020202020202020202020202020202020202", + "\",\"fulfillment\":{\"area\":\"Example region\",\"lead_seconds\":\"0\",\"modes\":[\"pickup\"]},\"media\":[],\"options\":[{\"id\":\"", + "0202020202020202020202020202020202020202020202020202020202020202", + "\",\"increment\":\"1\",\"label\":\"One bunch\",\"lead_seconds\":\"0\",\"minimum\":\"1\",\"price\":{\"type\":\"quote_required\"},\"supply\":{\"amount\":\"10\",\"type\":\"available\"},\"unit\":{\"contents\":{\"type\":\"unspecified\"},\"label\":\"bunch\",\"type\":\"package\"}}],\"product\":{\"description\":\"Public description\",\"name\":\"Carrots\",\"origin_summary\":\"Example region\",\"producer\":null},\"profile\":\"radroots.listing\",\"state\":\"active\",\"version\":1}" + ); + assert_eq!(tag(&value, "radroots:listing")[1], golden); + let serialized = serde_json::to_value(&captured).unwrap(); + assert_eq!( + serialized["profile"], + serde_json::from_str::<serde_json::Value>(golden).unwrap() + ); + assert!(serialized.get("terms").is_none()); + assert_eq!(serialized.as_object().unwrap().len(), 6); + assert_eq!(captured.id().to_string(), "01".repeat(16)); + assert_eq!(captured.published_at().get(), 100); + assert!(!format!("{captured:?} {value:?}").contains("Ask for terms")); +} + +#[test] +fn inactive_revisions_keep_the_original_coordinate_without_a_false_sold_status() { + let active = event(&input(ListingState::Active, "Original terms.")); + for state in [ListingState::Paused, ListingState::Withdrawn] { + let revised = event(&input(state, "Original terms.")); + assert_eq!(revised.fields().kind, active.fields().kind); + assert_eq!(tag(&revised, "d"), tag(&active, "d")); + assert_ne!(revised.event_id(), active.event_id()); + assert!(revised.fields().content.contains("unavailable")); + assert!(revised.fields().content.ends_with("Original terms.")); + assert!(tag(&revised, "summary")[1].contains("unavailable")); + assert!( + !revised + .fields() + .tags + .iter() + .any(|t| t[0] == "status" || t[0] == "price") + ); + } +} + +#[test] +fn measured_choice_and_opaque_metadata_supply_no_pool_or_endpoint_authority() { + use radroots_domain::{AuthorityRef, ExecutorId, Generation}; + let choice = ListingOption::quote_required( + ListingOptionId::from_bytes([3; 32]), + "Measured herbs", + SaleUnit::measured(MeasurementUnit::Kilogram), + "0.25".parse().unwrap(), + "0.5".parse().unwrap(), + Supply::Unknown, + LeadSeconds::new(60).unwrap(), + ) + .unwrap(); + let terms = ListingTerms::new( + ListingState::Active, + Product::new("Herbs", "Public description", Some(key()), None).unwrap(), + choice.id(), + vec![choice], + PublicFulfillment::new( + vec![FulfillmentMode::Pickup, FulfillmentMode::Delivery], + "Example region", + LeadSeconds::new(60).unwrap(), + ) + .unwrap(), + Some(AuthorityRef::new( + ExecutorId::from_bytes([4; 32]), + Generation::new(2).unwrap(), + )), + ) + .unwrap(); + let captured = PublishInput::new( + ListingId::from_bytes([1; 16]), + "Herbs", + "Half kilogram; quote required", + "", + UnixSeconds::new(100).unwrap(), + terms, + ) + .unwrap(); + let value = event(&captured); + assert_eq!( + tag(&value, "radroots:price_unit"), + ["radroots:price_unit", "kg"] + ); + let profile: serde_json::Value = + serde_json::from_str(&tag(&value, "radroots:listing")[1]).unwrap(); + assert_eq!( + profile["authority"], + serde_json::json!({"executor_id":"04".repeat(32),"generation":"2"}) + ); + assert_eq!(profile["product"]["producer"], key().to_hex()); + assert_eq!( + profile["options"][0]["unit"], + serde_json::json!({"type":"measured","unit":"kg"}) + ); + assert_eq!( + profile["options"][0]["supply"], + serde_json::json!({"type":"unknown"}) + ); + assert_eq!(profile["options"][0]["lead_seconds"], "60"); + assert_eq!(profile["authority"].as_object().unwrap().len(), 2); +} + +#[test] +fn complete_signed_event_limit_counts_escaping_and_fixed_signature_framing() { + let empty = event(&input(ListingState::Active, "")); + let overhead = nip01::signed_json_len(&empty.fields(), LISTING_EVENT_MAX_BYTES).unwrap(); + let free = LISTING_EVENT_MAX_BYTES - overhead; + let body = "\u{0001}".repeat(free / 6) + &"a".repeat(free % 6); + assert!(body.chars().count() <= 16_384); + let exact = event(&input(ListingState::Active, &body)); + assert_eq!( + nip01::signed_json_len(&exact.fields(), LISTING_EVENT_MAX_BYTES).unwrap(), + LISTING_EVENT_MAX_BYTES + ); + assert!(matches!( + ListingEvent::new( + &input(ListingState::Active, &(body + "a")), + key(), + UnixSeconds::new(101).unwrap() + ), + Err(WireError::LimitExceeded) + )); + assert!(matches!( + ListingEvent::new( + &input(ListingState::Active, ""), + key(), + UnixSeconds::new(99).unwrap() + ), + Err(WireError::InvalidInput) + )); +}