lib

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

read.rs (5701B)


      1 //! Passive complete listing decoding; no signature, freshness or stock proof.
      2 use super::{LISTING_KIND, decode_profile};
      3 use crate::{command::CommandError, nip01::EventFields};
      4 use radroots_domain::{
      5     EnvelopeEventId, UnixSeconds,
      6     listing::{Listing, ListingId, ListingState, ListingText, Price},
      7 };
      8 
      9 /// Complete validated values whose event identity remains a caller claim.
     10 #[derive(Debug)]
     11 pub struct DecodedListing(Listing);
     12 impl DecodedListing {
     13     /// Borrows passive public values; the concrete adapter authenticates them.
     14     pub const fn listing(&self) -> &Listing {
     15         &self.0
     16     }
     17 }
     18 fn tag<'a>(
     19     tags: &'a [alloc::vec::Vec<alloc::string::String>],
     20     name: &str,
     21     arity: usize,
     22 ) -> Result<Option<&'a [alloc::string::String]>, CommandError> {
     23     let mut found = None;
     24     for tag in tags {
     25         if tag.first().is_some_and(|key| key == name) {
     26             if found.is_some() || tag.len() != arity {
     27                 return Err(CommandError::InvalidInput);
     28             }
     29             found = Some(tag.as_slice());
     30         }
     31     }
     32     Ok(found)
     33 }
     34 fn required<'a>(fields: &EventFields<'a>, name: &str) -> Result<&'a str, CommandError> {
     35     tag(fields.tags, name, 2)?
     36         .map(|tag| tag[1].as_str())
     37         .ok_or(CommandError::InvalidInput)
     38 }
     39 /// Decode exact incoming projections in any tag order. Unknown generic Nostr
     40 /// tags confer no authority; duplicate known projections are rejected. The
     41 /// default price tag is exact amount/currency only, never a unit/frequency hack.
     42 pub fn decode_observed(
     43     fields: &EventFields<'_>,
     44     event_id: [u8; 32],
     45 ) -> Result<DecodedListing, CommandError> {
     46     if fields.kind != LISTING_KIND {
     47         return Err(CommandError::InvalidInput);
     48     }
     49     crate::nip01::signed_json_len(fields, super::LISTING_EVENT_MAX_BYTES).map_err(|error| {
     50         match error {
     51             crate::nip01::WireError::LimitExceeded => CommandError::LimitExceeded,
     52             _ => CommandError::InvalidInput,
     53         }
     54     })?;
     55     let terms = decode_profile(required(fields, "radroots:listing")?.as_bytes())?;
     56     let id: ListingId = required(fields, "d")?
     57         .parse()
     58         .map_err(|_| CommandError::InvalidInput)?;
     59     let created_at = UnixSeconds::new(fields.created_at).map_err(|_| CommandError::InvalidInput)?;
     60     let published_at: UnixSeconds = required(fields, "published_at")?
     61         .parse()
     62         .map_err(|_| CommandError::InvalidInput)?;
     63     let text = ListingText::new(
     64         required(fields, "title")?,
     65         required(fields, "summary")?,
     66         fields.content,
     67     )
     68     .map_err(|_| CommandError::InvalidInput)?;
     69     if required(fields, "location")? != terms.fulfillment().area()
     70         || required(fields, "radroots:price_unit")? != terms.default_option().unit().label()
     71     {
     72         return Err(CommandError::InvalidInput);
     73     }
     74     let status = tag(fields.tags, "status", 2)?;
     75     match terms.state() {
     76         ListingState::Active if status.is_none_or(|tag| tag[1] != "active") => {
     77             return Err(CommandError::InvalidInput);
     78         }
     79         ListingState::Paused | ListingState::Withdrawn if status.is_some() => {
     80             return Err(CommandError::InvalidInput);
     81         }
     82         _ => {}
     83     }
     84     let price = tag(fields.tags, "price", 3)?;
     85     match terms.default_option().price() {
     86         Price::Fixed(value)
     87             if price.is_none_or(|tag| {
     88                 !price_matches(&tag[1], value.rate()) || tag[2] != value.rate().currency().code()
     89             }) =>
     90         {
     91             return Err(CommandError::InvalidInput);
     92         }
     93         Price::QuoteRequired | Price::VariableWeight(_) if price.is_some() => {
     94             return Err(CommandError::InvalidInput);
     95         }
     96         _ => {}
     97     }
     98     Listing::new(
     99         id,
    100         fields.author,
    101         EnvelopeEventId::from_bytes(event_id),
    102         created_at,
    103         published_at,
    104         text,
    105         terms,
    106     )
    107     .map(DecodedListing)
    108     .map_err(|_| CommandError::InvalidInput)
    109 }
    110 
    111 // Standard NIP99 decimal spellings may vary without changing exact minor
    112 // value. This compares checked integer coefficients, never floating point or
    113 // rounded excess precision, and never modifies the signed tag representation.
    114 fn price_matches(amount: &str, expected: radroots_domain::Money) -> bool {
    115     let (whole, fraction) = match amount.split_once('.') {
    116         Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction),
    117         Some(_) => return false,
    118         None => (amount, ""),
    119     };
    120     if whole.is_empty()
    121         || !whole
    122             .bytes()
    123             .chain(fraction.bytes())
    124             .all(|b| b.is_ascii_digit())
    125     {
    126         return false;
    127     }
    128     let mut integral = 0_u64;
    129     for digit in whole.bytes() {
    130         let Some(value) = integral
    131             .checked_mul(10)
    132             .and_then(|v| v.checked_add(u64::from(digit - b'0')))
    133         else {
    134             return false;
    135         };
    136         integral = value;
    137     }
    138     // Currency's pinned registry admits exponents0..4 only.
    139     let Some(scale) = 10_u64.checked_pow(u32::from(expected.currency().exponent())) else {
    140         return false;
    141     };
    142     let Some(mut minor) = integral.checked_mul(scale) else {
    143         return false;
    144     };
    145     let mut place = scale;
    146     for digit in fraction.bytes() {
    147         if place == 1 {
    148             if digit != b'0' {
    149                 return false;
    150             }
    151         } else {
    152             place /= 10;
    153             let Some(next) = u64::from(digit - b'0')
    154                 .checked_mul(place)
    155                 .and_then(|part| minor.checked_add(part))
    156             else {
    157                 return false;
    158             };
    159             minor = next;
    160         }
    161     }
    162     minor == expected.minor().get()
    163 }