listing.rs (11003B)
1 //! Closed public listing producer with exact default-option price projections. 2 //! Declared media references do not grant transport or decoder authority. 3 4 use crate::nip01::{self, EventFields, WireError}; 5 use alloc::{ 6 format, 7 string::{String, ToString}, 8 vec, 9 vec::Vec, 10 }; 11 use core::fmt; 12 use radroots_domain::{ 13 Money, PublicKey, UnixSeconds, 14 listing::{ListingId, ListingState, ListingTerms, ListingText, Price}, 15 }; 16 use serde::Serialize; 17 use serde_json::Value; 18 use sha2::{Digest, Sha256}; 19 20 mod command; 21 mod input; 22 pub use input::decode_profile; 23 mod read; 24 pub use read::{DecodedListing, decode_observed}; 25 mod plan; 26 pub use command::CapturedListingCommand; 27 pub use plan::PublicSigningPlan; 28 29 /// Assigned NIP-99 addressable classified-listing kind. 30 pub const LISTING_KIND: u32 = 30402; 31 /// Complete public event cap, including NIP-01 key, ID and signature framing. 32 pub const LISTING_EVENT_MAX_BYTES: usize = 65_536; 33 /// At most eight ordinary two-field tags and one fixed-price three-field tag. 34 pub const LISTING_TAG_MAX_COUNT: usize = 9; 35 /// Both key and value count toward the closed public profile's field budget. 36 pub const LISTING_TAG_TOTAL_ELEMENT_MAX_COUNT: usize = 19; 37 38 /// Explicit immutable public-offer input; no IDs, time or authority are inferred. 39 #[derive(Clone, Serialize)] 40 pub struct PublishInput { 41 id: ListingId, 42 #[serde(flatten)] 43 text: ListingText, 44 published_at: UnixSeconds, 45 #[serde(rename = "profile", serialize_with = "serialize_profile")] 46 terms: ListingTerms, 47 } 48 impl PublishInput { 49 /// Captures bounded text and validated sale terms. Monetary event summaries 50 /// name the selected default's explicit rate/basis and pricing conditions. 51 pub fn new( 52 id: ListingId, 53 title: &str, 54 summary: &str, 55 description_markdown: &str, 56 published_at: UnixSeconds, 57 terms: ListingTerms, 58 ) -> Result<Self, WireError> { 59 let text = ListingText::new(title, summary, description_markdown) 60 .map_err(|_| WireError::InvalidInput)?; 61 Ok(Self { 62 id, 63 text, 64 published_at, 65 terms, 66 }) 67 } 68 /// Returns the independently selected stable coordinate discriminator. 69 pub const fn id(&self) -> ListingId { 70 self.id 71 } 72 /// Borrows the exact validated terms, without stock or publication claims. 73 pub const fn terms(&self) -> &ListingTerms { 74 &self.terms 75 } 76 /// Returns the captured original publication timestamp. 77 pub const fn published_at(&self) -> UnixSeconds { 78 self.published_at 79 } 80 /// Exact domain-owned public presentation values. 81 pub const fn text(&self) -> &ListingText { 82 &self.text 83 } 84 } 85 impl fmt::Debug for PublishInput { 86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 87 f.write_str("PublishInput(<redacted>)") 88 } 89 } 90 91 fn profile_value(terms: &ListingTerms) -> Result<Value, WireError> { 92 let mut value = serde_json::to_value(terms).map_err(|_| WireError::InvalidInput)?; 93 let object = value.as_object_mut().ok_or(WireError::InvalidInput)?; 94 if object.len() != 7 95 || object.keys().any(|key| { 96 !matches!( 97 key.as_str(), 98 "authority" 99 | "default_option" 100 | "fulfillment" 101 | "options" 102 | "product" 103 | "state" 104 | "media" 105 ) 106 }) 107 { 108 return Err(WireError::InvalidInput); 109 } 110 object.insert("profile".into(), Value::String("radroots.listing".into())); 111 object.insert("version".into(), Value::from(1_u8)); 112 Ok(value) 113 } 114 fn serialize_profile<S: serde::Serializer>( 115 terms: &ListingTerms, 116 serializer: S, 117 ) -> Result<S::Ok, S::Error> { 118 profile_value(terms) 119 .map_err(serde::ser::Error::custom)? 120 .serialize(serializer) 121 } 122 123 /// Retained exact public event fields. This value contains no signature and 124 /// supplies no evidence of T0/T1, signer invocation, installation or delivery. 125 #[derive(Clone)] 126 pub struct ListingEvent { 127 author: PublicKey, 128 created_at: UnixSeconds, 129 tags: Vec<Vec<String>>, 130 content: String, 131 id: [u8; 32], 132 } 133 impl ListingEvent { 134 /// Builds one bounded profile/projection from immutable captured input. 135 /// Inactive revisions retain kind30402 and the same `d`, visibly state 136 /// non-availability, and omit a standard status rather than asserting sold. 137 pub fn new( 138 input: &PublishInput, 139 author: PublicKey, 140 created_at: UnixSeconds, 141 ) -> Result<Self, WireError> { 142 if input.published_at > created_at { 143 return Err(WireError::InvalidInput); 144 } 145 let mut profile = String::new(); 146 canonical(&profile_value(&input.terms)?, &mut profile)?; 147 let inactive = match input.terms.state() { 148 ListingState::Active => None, 149 ListingState::Paused => Some("Paused: unavailable"), 150 ListingState::Withdrawn => Some("Withdrawn: unavailable"), 151 }; 152 let default = input.terms.default_option(); 153 let description = match default.price() { 154 Price::Fixed(value) => format!( 155 "[Default: {}; base {} {} per {} {}; discount {} bps; {} tiers] {}", 156 default.label(), 157 money_amount(value.rate()), 158 value.rate().currency().code(), 159 value.basis(), 160 default.unit().label(), 161 value.discount_bps().get(), 162 value.tiers().len(), 163 input.text.summary(), 164 ), 165 Price::VariableWeight(value) => format!( 166 "[Default: {} {}; {}..{} {} per sale unit; {} {} per {} {}; cap {} {}] {}", 167 default.label(), 168 default.unit().label(), 169 value.minimum(), 170 value.maximum(), 171 value.measurement_unit().symbol(), 172 money_amount(value.rate()), 173 value.rate().currency().code(), 174 value.basis(), 175 value.measurement_unit().symbol(), 176 money_amount(value.maximum_total()), 177 value.maximum_total().currency().code(), 178 input.text.summary(), 179 ), 180 Price::QuoteRequired => input.text.summary().into(), 181 _ => return Err(WireError::InvalidInput), 182 }; 183 let summary = match inactive { 184 Some(label) => format!("[{label}] {description}"), 185 None => description, 186 }; 187 let content = match inactive { 188 Some(label) => format!("[{label}]\n\n{}", input.text.description_markdown()), 189 None => input.text.description_markdown().into(), 190 }; 191 let mut tags = vec![ 192 vec!["d".into(), input.id.to_string()], 193 vec!["title".into(), input.text.title().into()], 194 vec!["summary".into(), summary], 195 vec!["published_at".into(), input.published_at.to_string()], 196 vec!["location".into(), input.terms.fulfillment().area().into()], 197 vec![ 198 "radroots:price_unit".into(), 199 input.terms.default_option().unit().label().into(), 200 ], 201 ]; 202 if inactive.is_none() { 203 tags.push(vec!["status".into(), "active".into()]); 204 } 205 if let Price::Fixed(value) = default.price() { 206 tags.push(vec![ 207 "price".into(), 208 money_amount(value.rate()), 209 value.rate().currency().code().into(), 210 ]); 211 } 212 tags.push(vec!["radroots:listing".into(), profile]); 213 let fields = EventFields { 214 author, 215 created_at: created_at.get(), 216 kind: LISTING_KIND, 217 tags: &tags, 218 content: &content, 219 }; 220 nip01::signed_json_len(&fields, LISTING_EVENT_MAX_BYTES)?; 221 let id = Sha256::digest(nip01::canonical_preimage(&fields).as_bytes()).into(); 222 Ok(Self { 223 author, 224 created_at, 225 tags, 226 content, 227 id, 228 }) 229 } 230 /// Borrows all original fields without sorting tags or reconstructing text. 231 pub fn fields(&self) -> EventFields<'_> { 232 EventFields { 233 author: self.author, 234 created_at: self.created_at.get(), 235 kind: LISTING_KIND, 236 tags: &self.tags, 237 content: &self.content, 238 } 239 } 240 /// Exact canonical unsigned NIP-01 event ID, not a signature or store receipt. 241 pub const fn event_id(&self) -> &[u8; 32] { 242 &self.id 243 } 244 } 245 246 fn money_amount(value: Money) -> String { 247 let exponent = value.currency().exponent(); 248 let minor = value.minor().get(); 249 if exponent == 0 { 250 return minor.to_string(); 251 } 252 let divisor = 10_u64.pow(u32::from(exponent)); 253 let whole = minor / divisor; 254 let fraction = minor % divisor; 255 format!("{whole}.{fraction:0width$}", width = usize::from(exponent)) 256 } 257 impl fmt::Debug for ListingEvent { 258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 259 f.write_str("ListingEvent(<redacted>)") 260 } 261 } 262 263 // RFC8785 subset: field names are fixed ASCII, quantities/IDs/times are strings, 264 // numeric fields are exact safe unsigned integers, and Unicode is preserved. 265 // Explicit sorting remains correct if a downstream crate enables preserve_order. 266 pub(crate) fn canonical(value: &Value, out: &mut String) -> Result<(), WireError> { 267 match value { 268 Value::Object(fields) => { 269 let mut keys: Vec<_> = fields.keys().collect(); 270 if keys.iter().any(|key| !key.is_ascii()) { 271 return Err(WireError::InvalidInput); 272 } 273 keys.sort_unstable(); 274 out.push('{'); 275 for (i, key) in keys.into_iter().enumerate() { 276 if i != 0 { 277 out.push(','); 278 } 279 out.push_str(&serde_json::to_string(key).map_err(|_| WireError::InvalidInput)?); 280 out.push(':'); 281 canonical(&fields[key], out)?; 282 } 283 out.push('}'); 284 } 285 Value::Array(values) => { 286 out.push('['); 287 for (i, value) in values.iter().enumerate() { 288 if i != 0 { 289 out.push(','); 290 } 291 canonical(value, out)?; 292 } 293 out.push(']'); 294 } 295 Value::Number(number) => { 296 if number 297 .as_u64() 298 .is_none_or(|value| value > 9_007_199_254_740_991) 299 { 300 return Err(WireError::InvalidInput); 301 } 302 out.push_str(&number.to_string()); 303 } 304 _ => out.push_str(&serde_json::to_string(value).map_err(|_| WireError::InvalidInput)?), 305 } 306 if out.len() > LISTING_EVENT_MAX_BYTES { 307 return Err(WireError::LimitExceeded); 308 } 309 Ok(()) 310 }