commit 8025df736993c16f2f69069a491a295b8800bdc3
parent 3699beea978b6772aefdd0bbb7cd8a69cd0e08eb
Author: triesap <tyson@radroots.org>
Date: Thu, 22 Oct 2026 19:06:30 +0000
listing: Carry bounded media references through public profiles
- Require explicit bounded media and canonical declared digests in listing terms.
- Reject malformed references while preserving exact metadata and empty-media wire.
- Box validated publication input to keep captured commands compact.
- Verify native publication and original replay through durable reopen.
Diffstat:
13 files changed, 419 insertions(+), 22 deletions(-)
diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt
@@ -8,12 +8,14 @@ pub radroots_domain::listing::FulfillmentMode::Pickup
pub radroots_domain::listing::ListingError::InvalidDuration
pub radroots_domain::listing::ListingError::InvalidFulfillment
pub radroots_domain::listing::ListingError::InvalidIdentifier
+pub radroots_domain::listing::ListingError::InvalidMediaDigest
pub radroots_domain::listing::ListingError::InvalidOptions
pub radroots_domain::listing::ListingError::InvalidQuantity
pub radroots_domain::listing::ListingError::InvalidText
pub radroots_domain::listing::ListingError::InvalidTime
pub radroots_domain::listing::ListingError::NotFixedPrice
pub radroots_domain::listing::ListingError::Pricing(radroots_domain::PricingError)
+pub radroots_domain::listing::ListingError::TooManyMedia
impl core::error::Error for radroots_domain::listing::ListingError
pub fn radroots_domain::listing::ListingError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)>
impl core::fmt::Display for radroots_domain::listing::ListingError
@@ -85,9 +87,11 @@ 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 const radroots_domain::listing::ListingTerms::MAX_MEDIA: usize
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::media(&self) -> &[radroots_domain::listing::Media]
+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>, alloc::vec::Vec<radroots_domain::listing::Media>) -> 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
@@ -100,6 +104,16 @@ pub fn radroots_domain::listing::ListingText::summary(&self) -> &str
pub fn radroots_domain::listing::ListingText::title(&self) -> &str
impl core::fmt::Debug for radroots_domain::listing::ListingText
pub fn radroots_domain::listing::ListingText::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub struct radroots_domain::listing::Media
+impl radroots_domain::listing::Media
+pub fn radroots_domain::listing::Media::alt(&self) -> &str
+pub fn radroots_domain::listing::Media::from_hex_digest(&str, &str, &str, &str) -> core::result::Result<Self, radroots_domain::listing::ListingError>
+pub fn radroots_domain::listing::Media::mime(&self) -> &str
+pub fn radroots_domain::listing::Media::new(&str, [u8; 32], &str, &str) -> core::result::Result<Self, radroots_domain::listing::ListingError>
+pub const fn radroots_domain::listing::Media::sha256(&self) -> &[u8; 32]
+pub fn radroots_domain::listing::Media::url(&self) -> &str
+impl core::fmt::Debug for radroots_domain::listing::Media
+pub fn radroots_domain::listing::Media::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
diff --git a/crates/domain/README.md b/crates/domain/README.md
@@ -69,6 +69,13 @@ Optional opaque authority and
producer metadata establish no permission or endpoint trust. These immutable
terms serialize public data explicitly and redact ordinary diagnostics.
+`listing::Media` retains bounded, nonempty URL/MIME claims, exact alternative
+text and a declared SHA-256 digest. Construction does not normalize claims,
+approve an endpoint, fetch a file, verify its contents or promise a decoder.
+`ListingTerms::new` requires the explicit media list, with at most eight
+references and preserved order. Empty media is explicit. Media descriptors
+serialize complete exact strings and have no unchecked deserialization route.
+
Namespaces remain separate across native calls:
```compile_fail
diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs
@@ -12,6 +12,8 @@ mod view;
pub use view::{Listing, ListingText};
mod price;
pub use price::Price;
+mod media;
+pub use media::Media;
/// A fixed, input-free public-offer value failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -35,6 +37,10 @@ pub enum ListingError {
NotFixedPrice,
/// Exact price calculation cannot be represented within the approved bounds.
Pricing(PricingError),
+ /// A media digest is not exactly64 lowercase hexadecimal digits.
+ InvalidMediaDigest,
+ /// More than eight public object references were supplied.
+ TooManyMedia,
}
impl fmt::Display for ListingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -48,6 +54,8 @@ impl fmt::Display for ListingError {
Self::InvalidTime => "invalid listing time",
Self::NotFixedPrice => "listing option has no fixed price",
Self::Pricing(error) => return error.fmt(f),
+ Self::InvalidMediaDigest => "invalid media digest",
+ Self::TooManyMedia => "too many public media references",
})
}
}
@@ -497,10 +505,13 @@ pub struct ListingTerms {
options: Box<[ListingOption]>,
fulfillment: PublicFulfillment,
authority: Option<AuthorityRef>,
+ media: Box<[Media]>,
#[cfg_attr(feature = "serde", serde(skip))]
default_index: usize,
}
impl ListingTerms {
+ /// Largest number of public object references in one complete profile.
+ pub const MAX_MEDIA: usize = 8;
/// Checks bounded unique choices and exact default membership before capture.
pub fn new(
state: ListingState,
@@ -509,7 +520,11 @@ impl ListingTerms {
options: Vec<ListingOption>,
fulfillment: PublicFulfillment,
authority: Option<AuthorityRef>,
+ media: Vec<Media>,
) -> Result<Self, ListingError> {
+ if media.len() > Self::MAX_MEDIA {
+ return Err(ListingError::TooManyMedia);
+ }
if options.is_empty()
|| options.len() > 16
|| options
@@ -530,6 +545,7 @@ impl ListingTerms {
options: options.into_boxed_slice(),
fulfillment,
authority,
+ media: media.into_boxed_slice(),
default_index,
})
}
@@ -551,6 +567,10 @@ impl ListingTerms {
pub const fn fulfillment(&self) -> &PublicFulfillment {
&self.fulfillment
}
+ /// Borrows bounded declared references without fetching or verifying files.
+ pub fn media(&self) -> &[Media] {
+ &self.media
+ }
}
impl fmt::Debug for ListingTerms {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
diff --git a/crates/domain/src/listing/media.rs b/crates/domain/src/listing/media.rs
@@ -0,0 +1,91 @@
+use super::{ListingError, text};
+use alloc::string::String;
+use core::fmt;
+
+/// Bounded public object-reference claims, without network or decoder authority.
+/// The digest is a declared SHA-256 value, not evidence of obtained file bytes.
+#[derive(Clone, Eq, PartialEq)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize))]
+pub struct Media {
+ url: String,
+ #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_digest"))]
+ sha256: [u8; 32],
+ mime: String,
+ alt: String,
+}
+
+impl Media {
+ /// Bounds all claims before copying. URL/MIME claims are nonempty and kept
+ /// exactly; transport approval and actual content validation belong to use.
+ pub fn new(url: &str, sha256: [u8; 32], mime: &str, alt: &str) -> Result<Self, ListingError> {
+ text(url, 2048, false)?;
+ text(mime, 80, false)?;
+ text(alt, 240, true)?;
+ Ok(Self {
+ url: url.into(),
+ sha256,
+ mime: mime.into(),
+ alt: alt.into(),
+ })
+ }
+
+ /// Admits exactly64 lowercase hexadecimal digits before validated capture.
+ pub fn from_hex_digest(
+ url: &str,
+ sha256: &str,
+ mime: &str,
+ alt: &str,
+ ) -> Result<Self, ListingError> {
+ if sha256.len() != 64 {
+ return Err(ListingError::InvalidMediaDigest);
+ }
+ let digit = |byte| match byte {
+ b'0'..=b'9' => Ok(byte - b'0'),
+ b'a'..=b'f' => Ok(byte - b'a' + 10),
+ _ => Err(ListingError::InvalidMediaDigest),
+ };
+ let mut digest = [0; 32];
+ let (pairs, _) = sha256.as_bytes().as_chunks::<2>();
+ for (out, &[a, b]) in digest.iter_mut().zip(pairs) {
+ *out = digit(a)? * 16 + digit(b)?;
+ }
+ Self::new(url, digest, mime, alt)
+ }
+ /// Borrows the original claim; this grants no endpoint or fetch trust.
+ pub fn url(&self) -> &str {
+ &self.url
+ }
+ /// Borrows the exact declared digest; file verification is separate.
+ pub const fn sha256(&self) -> &[u8; 32] {
+ &self.sha256
+ }
+ /// Borrows the declared MIME claim; this is not a supported-codec promise.
+ pub fn mime(&self) -> &str {
+ &self.mime
+ }
+ /// Borrows the exact alternative text without rendering it.
+ pub fn alt(&self) -> &str {
+ &self.alt
+ }
+}
+impl fmt::Debug for Media {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("Media(<redacted>)")
+ }
+}
+#[cfg(feature = "serde")]
+fn serialize_digest<S: serde::Serializer>(
+ value: &[u8; 32],
+ serializer: S,
+) -> Result<S::Ok, S::Error> {
+ struct Digest<'a>(&'a [u8; 32]);
+ impl fmt::Display for Digest<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ for byte in self.0 {
+ write!(f, "{byte:02x}")?;
+ }
+ Ok(())
+ }
+ }
+ serializer.collect_str(&Digest(value))
+}
diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs
@@ -1,5 +1,8 @@
use radroots_domain::{ListingOptionId, listing::*};
+#[path = "support/listing_media.rs"]
+mod media;
+
#[test]
fn public_text_has_shared_unicode_bounds_and_revision_data_rejects_inverted_time() {
use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds};
@@ -30,6 +33,7 @@ fn public_text_has_shared_unicode_bounds_and_revision_data_rejects_inverted_time
vec![option(1, SaleUnit::measured(MeasurementUnit::Each), "1", "1", "10").unwrap()],
fulfillment(),
None,
+ vec![],
)
.unwrap();
let key =
@@ -121,6 +125,7 @@ fn spare_caller_capacity_preserves_exact_terms_and_default_selection() {
options,
PublicFulfillment::new(modes, "Example region", LeadSeconds::new(0).unwrap()).unwrap(),
None,
+ vec![],
)
.unwrap();
let expected = ListingTerms::new(
@@ -130,6 +135,7 @@ fn spare_caller_capacity_preserves_exact_terms_and_default_selection() {
compact,
fulfillment(),
None,
+ vec![],
)
.unwrap();
assert_eq!(expanded, expected);
@@ -356,6 +362,7 @@ fn bounded_unique_options_preserve_exact_default_without_fallback() {
choices,
fulfillment(),
None,
+ vec![],
)
};
assert!(terms(vec![], 1).is_err());
@@ -403,6 +410,7 @@ fn serialized_values_have_exact_string_numbers_and_no_private_or_derived_fields(
vec![choice],
fulfillment(),
None,
+ vec![],
)
.unwrap();
let value = serde_json::to_value(terms).unwrap();
@@ -420,5 +428,6 @@ fn serialized_values_have_exact_string_numbers_and_no_private_or_derived_fields(
serde_json::json!({"type":"available","amount":"10"})
);
assert!(value.get("default_index").is_none());
- assert_eq!(value.as_object().unwrap().len(), 6);
+ assert_eq!(value["media"], serde_json::json!([]));
+ assert_eq!(value.as_object().unwrap().len(), 7);
}
diff --git a/crates/domain/tests/support/listing_media.rs b/crates/domain/tests/support/listing_media.rs
@@ -0,0 +1,140 @@
+use super::*;
+
+fn reference() -> Media {
+ Media::new(
+ "https://media.fixture.invalid/carrot?version=1",
+ [0xab; 32],
+ "image/jpeg",
+ "Carrot 🥕\nExact alternative text",
+ )
+ .unwrap()
+}
+
+#[test]
+fn media_preserves_bounded_claims_and_exact_digests_without_normalization_or_trust() {
+ let value = reference();
+ assert_eq!(
+ value.url(),
+ "https://media.fixture.invalid/carrot?version=1"
+ );
+ assert_eq!(value.sha256(), &[0xab; 32]);
+ assert_eq!(value.mime(), "image/jpeg");
+ assert_eq!(value.alt(), "Carrot 🥕\nExact alternative text");
+ assert_eq!(
+ Media::from_hex_digest(value.url(), &"ab".repeat(32), value.mime(), value.alt()).unwrap(),
+ value
+ );
+ let debug = format!("{value:?}");
+ assert!(!debug.contains("fixture"));
+ assert!(!debug.contains("image/jpeg"));
+ assert!(!debug.contains("Carrot"));
+ assert_eq!(value.clone(), value);
+ for bad in [
+ "ab".repeat(31),
+ "ab".repeat(33),
+ "AB".repeat(32),
+ "g0".repeat(32),
+ "0g".repeat(32),
+ "é".repeat(32),
+ ] {
+ assert_eq!(
+ Media::from_hex_digest(value.url(), &bad, value.mime(), value.alt()).unwrap_err(),
+ ListingError::InvalidMediaDigest
+ );
+ }
+ assert!(
+ !ListingError::InvalidMediaDigest
+ .to_string()
+ .contains(value.url())
+ );
+}
+
+#[test]
+fn media_text_and_collection_bounds_reject_before_owned_capture() {
+ let prefix = "https://media.fixture.invalid/";
+ let url = prefix.to_owned() + &"a".repeat(2048 - prefix.len());
+ let mime = "application/".to_owned() + &"x".repeat(68);
+ let alt = "🥕".repeat(240);
+ assert_eq!(mime.len(), 80);
+ let value = Media::new(&url, [0; 32], &mime, &alt).unwrap();
+ assert_eq!(value.alt(), alt);
+ for (url, mime, alt) in [
+ (String::new(), mime.clone(), alt.clone()),
+ (url.clone() + "a", mime.clone(), alt.clone()),
+ (url.clone(), String::new(), alt.clone()),
+ (url.clone(), mime.clone() + "x", alt.clone()),
+ (url.clone(), mime.clone(), alt + "🥕"),
+ ] {
+ assert_eq!(
+ Media::new(&url, [0; 32], &mime, &alt).unwrap_err(),
+ ListingError::InvalidText
+ );
+ }
+ assert!(
+ Media::new(
+ "urn:sha256:declared-object",
+ [0; 32],
+ "application/octet-stream",
+ ""
+ )
+ .is_ok()
+ );
+ let make = |media| {
+ ListingTerms::new(
+ ListingState::Active,
+ product(),
+ ListingOptionId::from_bytes([1; 32]),
+ vec![option(1, SaleUnit::measured(MeasurementUnit::Each), "1", "1", "0").unwrap()],
+ fulfillment(),
+ None,
+ media,
+ )
+ };
+ assert_eq!(ListingTerms::MAX_MEDIA, 8);
+ assert!(make(vec![]).unwrap().media().is_empty());
+ let mut spare = Vec::with_capacity(4096);
+ for _ in 0..8 {
+ spare.push(reference());
+ }
+ let terms = make(spare).unwrap();
+ assert_eq!(terms.media(), vec![reference(); 8]);
+ assert_eq!(
+ make(vec![reference(); 9]).unwrap_err(),
+ ListingError::TooManyMedia
+ );
+ assert!(!ListingError::TooManyMedia.to_string().contains("fixture"));
+}
+
+#[cfg(feature = "serde")]
+#[test]
+fn media_serializes_closed_exact_strings_and_preserves_full_profile_order() {
+ use serde_json::json;
+ let value = reference();
+ assert_eq!(
+ serde_json::to_value(&value).unwrap(),
+ json!({
+ "url":"https://media.fixture.invalid/carrot?version=1","sha256":"ab".repeat(32),
+ "mime":"image/jpeg","alt":"Carrot 🥕\nExact alternative text"})
+ );
+ let second = Media::new(
+ "ipfs://declared-object",
+ [0; 32],
+ "application/octet-stream",
+ "",
+ )
+ .unwrap();
+ let terms = ListingTerms::new(
+ ListingState::Active,
+ product(),
+ ListingOptionId::from_bytes([1; 32]),
+ vec![option(1, SaleUnit::measured(MeasurementUnit::Each), "1", "1", "0").unwrap()],
+ fulfillment(),
+ None,
+ vec![value.clone(), second.clone()],
+ )
+ .unwrap();
+ let wire = serde_json::to_value(&terms).unwrap();
+ assert_eq!(wire["media"], json!([value, second]));
+ assert_eq!(wire.as_object().unwrap().len(), 7);
+ assert!(!format!("{terms:?}").contains("fixture"));
+}
diff --git a/crates/protocol/README.md b/crates/protocol/README.md
@@ -46,7 +46,10 @@ they use.
Public listing inputs retain fixed, quote-required or per-sale-unit variable
prices, with fixed/estimated/unspecified package metadata. Object fields reject
positional arrays, and the closed typed decoder rejects duplicate, missing and
-unknown fields. Media and estimated supply/windows remain unsupported.
+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.
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
diff --git a/crates/protocol/src/listing.rs b/crates/protocol/src/listing.rs
@@ -1,5 +1,5 @@
//! Closed public listing producer with exact default-option price projections.
-//! Unsupported media is never silently stripped or reduced to an empty value.
+//! Declared media references do not grant transport or decoder authority.
use crate::nip01::{self, EventFields, WireError};
use alloc::{
@@ -88,11 +88,17 @@ impl fmt::Debug for PublishInput {
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
+ if object.len() != 7
|| object.keys().any(|key| {
!matches!(
key.as_str(),
- "authority" | "default_option" | "fulfillment" | "options" | "product" | "state"
+ "authority"
+ | "default_option"
+ | "fulfillment"
+ | "options"
+ | "product"
+ | "state"
+ | "media"
)
})
{
@@ -100,9 +106,6 @@ fn profile_value(terms: &ListingTerms) -> Result<Value, WireError> {
}
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>(
diff --git a/crates/protocol/src/listing/command.rs b/crates/protocol/src/listing/command.rs
@@ -10,7 +10,7 @@ use zeroize::Zeroizing;
/// durable admission, event signing, installation or network work.
pub struct CapturedListingCommand {
context: CommandContextData,
- input: PublishInput,
+ input: Box<PublishInput>,
wire: Zeroizing<Box<[u8]>>,
digest: CommandDigest,
approval: ApprovalIntentDigest,
@@ -55,7 +55,7 @@ impl CapturedListingCommand {
));
Ok(Self {
context,
- input,
+ input: Box::new(input),
wire,
digest,
approval,
diff --git a/crates/protocol/src/listing/input.rs b/crates/protocol/src/listing/input.rs
@@ -31,8 +31,15 @@ struct Profile {
fulfillment: Fulfillment,
#[serde(deserialize_with = "required_nullable")]
authority: Option<AuthorityRef>,
- #[serde(rename = "media")]
- _media: [(); 0],
+ media: Vec<RawMedia>,
+}
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawMedia {
+ url: String,
+ sha256: String,
+ mime: String,
+ alt: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -265,6 +272,18 @@ impl Input {
options,
fulfillment,
profile.authority,
+ profile
+ .media
+ .into_iter()
+ .map(|media| {
+ invalid(Media::from_hex_digest(
+ &media.url,
+ &media.sha256,
+ &media.mime,
+ &media.alt,
+ ))
+ })
+ .collect::<Result<Vec<_>, _>>()?,
))?;
PublishInput::new(
self.id,
@@ -293,10 +312,6 @@ impl PublishInput {
.get("profile")
.is_some_and(|v| v != "radroots.listing")
|| profile.get("version").is_some_and(|v| v != 1)
- || profile
- .get("media")
- .and_then(serde_json::Value::as_array)
- .is_some_and(|v| !v.is_empty())
{
return Err(CommandError::UnsupportedProfile);
}
@@ -343,6 +358,15 @@ fn object_shapes(value: &serde_json::Value) -> Result<(), CommandError> {
object(profile)?;
object(&profile["product"])?;
object(&profile["fulfillment"])?;
+ let media = profile["media"]
+ .as_array()
+ .ok_or(CommandError::InvalidInput)?;
+ if media.len() > ListingTerms::MAX_MEDIA {
+ return Err(CommandError::LimitExceeded);
+ }
+ for reference in media {
+ object(reference)?;
+ }
if !profile["authority"].is_null() {
object(&profile["authority"])?;
}
diff --git a/crates/protocol/tests/listing.rs b/crates/protocol/tests/listing.rs
@@ -39,6 +39,7 @@ fn input(state: ListingState, body: &str) -> PublishInput {
)
.unwrap(),
None,
+ vec![],
)
.unwrap();
PublishInput::new(
@@ -146,6 +147,7 @@ fn measured_choice_and_opaque_metadata_supply_no_pool_or_endpoint_authority() {
ExecutorId::from_bytes([4; 32]),
Generation::new(2).unwrap(),
)),
+ vec![],
)
.unwrap();
let captured = PublishInput::new(
diff --git a/crates/protocol/tests/public_command.rs b/crates/protocol/tests/public_command.rs
@@ -105,6 +105,88 @@ fn fixed_price(code: &str, minor: &str, exponent: u8) -> Value {
}
#[test]
+fn media_references_round_trip_without_upload_fetch_or_empty_profile_fallback() {
+ use radroots_protocol::listing::ListingEvent;
+ let reference = json!({"url":"https://media.fixture.invalid/carrot?version=1",
+ "sha256":"ab".repeat(32),"mime":"image/jpeg","alt":"Carrot 🥕\nExact text"});
+ for count in [0, 1, 8] {
+ let mut wire = input();
+ wire["profile"]["media"] = Value::Array(vec![reference.clone(); count]);
+ let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap();
+ assert_eq!(parsed.terms().media().len(), count);
+ 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();
+ let observed: Value = serde_json::from_str(&profile[1]).unwrap();
+ assert_eq!(observed, wire["profile"]);
+ let public = CapturedListingCommand::capture(context(), parsed).unwrap();
+ assert_eq!(
+ CapturedListingCommand::parse(public.protected_wire())
+ .unwrap()
+ .protected_wire(),
+ public.protected_wire()
+ );
+ }
+}
+
+#[test]
+fn media_admission_refuses_missing_unknown_duplicate_array_and_out_of_bound_values() {
+ let reference = json!({"url":"https://media.fixture.invalid/carrot",
+ "sha256":"ab".repeat(32),"mime":"image/jpeg","alt":""});
+ let mut original = input();
+ original["profile"]["media"] = json!([reference.clone()]);
+ for (pointer, bad) in [
+ ("/profile/media", json!(vec![reference.clone(); 9])),
+ ("/profile/media", json!(null)),
+ (
+ "/profile/media/0",
+ json!([
+ "https://media.fixture.invalid/carrot",
+ "ab".repeat(32),
+ "image/jpeg",
+ ""
+ ]),
+ ),
+ (
+ "/profile/media/0",
+ json!({"url":"https://media.fixture.invalid/carrot"}),
+ ),
+ ("/profile/media/0/sha256", json!("AB".repeat(32))),
+ ("/profile/media/0/sha256", json!("ab".repeat(31))),
+ ("/profile/media/0/sha256", json!(vec![0; 32])),
+ ("/profile/media/0/url", json!("x".repeat(2049))),
+ ("/profile/media/0/mime", json!("x".repeat(81))),
+ ("/profile/media/0/alt", json!("🥕".repeat(241))),
+ ] {
+ let mut wire = original.clone();
+ *wire.pointer_mut(pointer).unwrap() = bad;
+ assert!(
+ PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).is_err(),
+ "{pointer}"
+ );
+ }
+ let mut missing = original.clone();
+ missing["profile"].as_object_mut().unwrap().remove("media");
+ assert!(PublishInput::parse(&serde_json::to_vec(&missing).unwrap()).is_err());
+ let mut extra = original.clone();
+ extra["profile"]["media"][0]["verified"] = json!(true);
+ assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err());
+ let raw = serde_json::to_string(&original).unwrap();
+ let duplicate = raw.replacen(
+ "\"mime\":\"image/jpeg\"",
+ "\"mime\":\"image/jpeg\",\"mime\":\"image/jpeg\"",
+ 1,
+ );
+ assert_ne!(duplicate, raw);
+ assert!(PublishInput::parse(duplicate.as_bytes()).is_err());
+}
+
+#[test]
fn fixed_default_projection_preserves_basis_currency_and_full_command_plan_replay() {
use radroots_protocol::{
listing::{ListingEvent, PublicSigningPlan},
@@ -435,15 +517,11 @@ fn closed_input_refuses_unknown_duplicate_missing_nullable_and_invalid_value_pat
}
#[test]
-fn unsupported_full_profile_features_are_refused_without_silent_quote_or_media_fallback() {
+fn unsupported_profile_features_are_refused_without_silent_fallback() {
for (pointer, bad) in [
("/profile/version", json!(2)),
("/profile/profile", json!("other.profile")),
(
- "/profile/media",
- json!([{"url":"https://example.invalid/image"}]),
- ),
- (
"/profile/options/0/price",
json!({"type":"future_price","rate":{"currency":"CAD","minor":"325","exponent":2}}),
),
diff --git a/crates/radroots/tests/support/receipt_listing_economics.rs b/crates/radroots/tests/support/receipt_listing_economics.rs
@@ -24,6 +24,10 @@ async fn monetary_listings_sign_install_deliver_and_reopen_without_repricing_or_
] {
let mut wire = serde_json::to_value(input(id)).unwrap();
wire["summary"] = json!("Native carrot offering");
+ wire["profile"]["media"] = json!([{"url":"https://media.fixture.invalid/carrot",
+ "sha256":"ab".repeat(32),"mime":"image/jpeg","alt":"Carrot 🥕"},
+ {"url":"ipfs://declared-object","sha256":"00".repeat(32),
+ "mime":"application/octet-stream","alt":""}]);
wire["profile"]["options"][0]["price"] = price;
wire["profile"]["options"][0]["unit"]["contents"] = contents;
let captured = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap();
@@ -70,6 +74,7 @@ async fn monetary_listings_sign_install_deliver_and_reopen_without_repricing_or_
.unwrap();
let actual: serde_json::Value = serde_json::from_str(&profile_tag.as_slice()[1]).unwrap();
assert_eq!(actual, wire["profile"]);
+ assert_eq!(listing.terms().media().len(), 2);
let replay = ready
.client
.listings()
@@ -89,6 +94,7 @@ async fn monetary_listings_sign_install_deliver_and_reopen_without_repricing_or_
}
assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2);
assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(relay.requests.load(Ordering::SeqCst), 0);
assert_eq!(relay.count.load(Ordering::SeqCst), 2);
ready.client.close().await.unwrap();
let store = ready.fixture.reopen(ready.input.clone()).await;