lib

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

public_profiles.rs (12200B)


      1 use radroots_protocol::{
      2     advertisement::{self, Feature, Profile},
      3     command::CommandError,
      4     listing,
      5     nip01::EventFields,
      6 };
      7 use serde_json::Value;
      8 fn fixture() -> Value {
      9     serde_json::from_str(include_str!("fixtures/public_profiles.v1.json")).unwrap()
     10 }
     11 
     12 fn decoded_wire(wire: &Value) -> Result<listing::DecodedListing, CommandError> {
     13     let tags: Vec<Vec<String>> = serde_json::from_value(wire["tags"].clone()).unwrap();
     14     let fields = EventFields {
     15         author: wire["pubkey"].as_str().unwrap().parse().unwrap(),
     16         created_at: wire["created_at"].as_u64().unwrap(),
     17         kind: wire["kind"].as_u64().unwrap() as u32,
     18         tags: &tags,
     19         content: wire["content"].as_str().unwrap(),
     20     };
     21     listing::decode_observed(&fields, [0; 32])
     22 }
     23 
     24 #[test]
     25 fn exact_standard_projection_handles_supported_exponents_and_free_prices() {
     26     let data = fixture();
     27     let base = &data["vectors"]
     28         .as_array()
     29         .unwrap()
     30         .iter()
     31         .find(|r| r["name"] == "listing_fixed")
     32         .unwrap()["raw"];
     33     for (currency, exponent, minor, amount) in [
     34         ("JPY", 0, "325", "325.000"),
     35         ("KWD", 3, "325", "0.3250"),
     36         ("CLF", 4, "325", "0.032500"),
     37         ("CAD", 2, "0", "0"),
     38         ("CAD", 2, "0", "0.0000"),
     39     ] {
     40         let mut wire: Value = serde_json::from_str(base.as_str().unwrap()).unwrap();
     41         let tags = wire["tags"].as_array_mut().unwrap();
     42         let profile_tag = tags
     43             .iter_mut()
     44             .find(|t| t[0] == "radroots:listing")
     45             .unwrap();
     46         let mut profile: Value = serde_json::from_str(profile_tag[1].as_str().unwrap()).unwrap();
     47         profile["options"][0]["price"]["rate"]["currency"] = serde_json::json!(currency);
     48         profile["options"][0]["price"]["rate"]["exponent"] = serde_json::json!(exponent);
     49         profile["options"][0]["price"]["rate"]["minor"] = serde_json::json!(minor);
     50         profile_tag[1] = serde_json::json!(profile.to_string());
     51         *tags.iter_mut().find(|t| t[0] == "price").unwrap() =
     52             serde_json::json!(["price", amount, currency]);
     53         *tags.iter_mut().find(|t| t[0] == "summary").unwrap() =
     54             serde_json::json!(["summary", "One bunch, exact published rate."]);
     55         assert!(decoded_wire(&wire).is_ok(), "{currency} {amount}");
     56     }
     57 }
     58 
     59 #[test]
     60 fn complete_public_projections_refuse_missing_duplicate_and_contradictory_fields() {
     61     let data = fixture();
     62     let base: Value = serde_json::from_str(
     63         data["vectors"]
     64             .as_array()
     65             .unwrap()
     66             .iter()
     67             .find(|r| r["name"] == "listing_fixed")
     68             .unwrap()["raw"]
     69             .as_str()
     70             .unwrap(),
     71     )
     72     .unwrap();
     73     for name in [
     74         "d",
     75         "title",
     76         "summary",
     77         "published_at",
     78         "location",
     79         "radroots:price_unit",
     80         "radroots:listing",
     81         "status",
     82         "price",
     83     ] {
     84         let mut wire = base.clone();
     85         wire["tags"]
     86             .as_array_mut()
     87             .unwrap()
     88             .retain(|tag| tag[0] != name);
     89         assert!(decoded_wire(&wire).is_err(), "missing {name}");
     90         wire = base.clone();
     91         let tags = wire["tags"].as_array_mut().unwrap();
     92         let duplicate = tags.iter().find(|tag| tag[0] == name).unwrap().clone();
     93         tags.push(duplicate);
     94         assert!(decoded_wire(&wire).is_err(), "duplicate {name}");
     95     }
     96     for (name, value) in [
     97         ("d", "noncanonical"),
     98         ("published_at", "099"),
     99         ("published_at", "101"),
    100         ("title", ""),
    101         ("location", "Other area"),
    102         ("radroots:price_unit", "kg"),
    103         ("status", "sold"),
    104     ] {
    105         let mut wire = base.clone();
    106         wire["tags"]
    107             .as_array_mut()
    108             .unwrap()
    109             .iter_mut()
    110             .find(|tag| tag[0] == name)
    111             .unwrap()[1] = serde_json::json!(value);
    112         assert!(decoded_wire(&wire).is_err(), "{name}={value}");
    113     }
    114     let mut wire = base.clone();
    115     wire["created_at"] = serde_json::json!(u64::MAX);
    116     assert!(decoded_wire(&wire).is_err());
    117     wire = base.clone();
    118     wire["kind"] = serde_json::json!(1);
    119     assert!(decoded_wire(&wire).is_err());
    120     wire = base.clone();
    121     wire["tags"]
    122         .as_array_mut()
    123         .unwrap()
    124         .iter_mut()
    125         .find(|tag| tag[0] == "price")
    126         .unwrap()[2] = serde_json::json!("USD");
    127     assert!(decoded_wire(&wire).is_err());
    128     for name in ["listing_paused", "listing_quote", "listing_variable"] {
    129         let mut wire: Value = serde_json::from_str(
    130             data["vectors"]
    131                 .as_array()
    132                 .unwrap()
    133                 .iter()
    134                 .find(|r| r["name"] == name)
    135                 .unwrap()["raw"]
    136                 .as_str()
    137                 .unwrap(),
    138         )
    139         .unwrap();
    140         wire["tags"]
    141             .as_array_mut()
    142             .unwrap()
    143             .push(if name == "listing_paused" {
    144                 serde_json::json!(["status", "active"])
    145             } else {
    146                 serde_json::json!(["price", "0", "CAD"])
    147             });
    148         assert!(decoded_wire(&wire).is_err(), "{name}");
    149     }
    150 }
    151 #[test]
    152 fn independently_signed_profile_projections_decode_without_claiming_authenticity() {
    153     for row in fixture()["vectors"].as_array().unwrap() {
    154         let wire: Value = serde_json::from_str(row["raw"].as_str().unwrap()).unwrap();
    155         let tags: Vec<Vec<String>> = serde_json::from_value(wire["tags"].clone()).unwrap();
    156         let kind = wire["kind"].as_u64().unwrap() as u32;
    157         let result = if kind == 30402 {
    158             let fields = EventFields {
    159                 author: wire["pubkey"].as_str().unwrap().parse().unwrap(),
    160                 created_at: wire["created_at"].as_u64().unwrap(),
    161                 kind,
    162                 tags: &tags,
    163                 content: wire["content"].as_str().unwrap(),
    164             };
    165             listing::decode_observed(&fields, [0; 32]).map(|v| {
    166                 let terms = serde_json::to_value(v.listing().terms()).unwrap();
    167                 assert_eq!(terms["product"]["name"], "Carrots 🥕");
    168                 "listing"
    169             })
    170         } else {
    171             advertisement::decode(
    172                 wire["content"].as_str().unwrap().as_bytes(),
    173                 wire["created_at"].as_u64().unwrap(),
    174             )
    175             .map(|v| {
    176                 assert!(!v.claims().is_empty());
    177                 "capabilities"
    178             })
    179         };
    180         // Nonempty tags are an outer carrier rule, checked by Nostr after auth.
    181         if row["name"] == "capability_tag" {
    182             assert!(result.is_ok());
    183             continue;
    184         }
    185         match result {
    186             Ok(value) => assert_eq!(value, row["expected"].as_str().unwrap(), "{}", row["name"]),
    187             Err(CommandError::UnsupportedProfile) => {
    188                 assert_eq!(row["expected"], "unsupported", "{}", row["name"])
    189             }
    190             Err(_) => assert_eq!(row["expected"], "invalid", "{}", row["name"]),
    191         }
    192     }
    193 }
    194 #[test]
    195 fn capability_claims_enforce_closed_arrays_numbers_and_calendar_bounds() {
    196     let mut cap = serde_json::json!({"profile":"radroots.capabilities","version":1,"supported_profiles":[{"profile":"radroots.commerce","versions":[1,65535],"features":["base-order-v1","bounded-variable-weight-v1"]}],"valid_until":"200"});
    197     let decoded = advertisement::decode(cap.to_string().as_bytes(), 100).unwrap();
    198     assert_eq!(decoded.valid_until().get(), 200);
    199     assert_eq!(decoded.claims()[0].profile(), Profile::Commerce);
    200     assert_eq!(decoded.claims()[0].versions(), [1, 65535]);
    201     assert_eq!(
    202         decoded.claims()[0].features(),
    203         [Feature::BaseOrder, Feature::BoundedVariableWeight]
    204     );
    205     let original = cap.clone();
    206     for value in [
    207         serde_json::json!([]),
    208         serde_json::json!([0]),
    209         serde_json::json!([65536]),
    210         serde_json::json!([1.0]),
    211         serde_json::json!(["1"]),
    212         serde_json::json!([1, 2, 3, 4, 5, 6, 7, 8, 9]),
    213     ] {
    214         cap = original.clone();
    215         cap["supported_profiles"][0]["versions"] = value;
    216         assert!(advertisement::decode(cap.to_string().as_bytes(), 100).is_err());
    217     }
    218     for value in [
    219         serde_json::json!([]),
    220         serde_json::json!(["base-order-v1", "base-order-v1"]),
    221         serde_json::json!([false]),
    222     ] {
    223         cap = original.clone();
    224         cap["supported_profiles"][0]["features"] = value;
    225         assert!(advertisement::decode(cap.to_string().as_bytes(), 100).is_err());
    226     }
    227     for time in ["0", "99", "100", "2592101", "0200", "253402300800"] {
    228         cap = original.clone();
    229         cap["valid_until"] = serde_json::json!(time);
    230         assert!(advertisement::decode(cap.to_string().as_bytes(), 100).is_err());
    231     }
    232     assert!(advertisement::decode(original.to_string().as_bytes(), u64::MAX).is_err());
    233     assert!(advertisement::decode(&vec![b' '; 65537], 100).is_err());
    234     for raw in [
    235         "[]",
    236         "{}",
    237         r#"{"profile":"radroots.capabilities","profile":"radroots.capabilities","version":1}"#,
    238         r#"{"profile":"radroots.capabilities","version":1,"supported_profiles":[],"valid_until":"200","extra":true}"#,
    239     ] {
    240         assert!(advertisement::decode(raw.as_bytes(), 100).is_err());
    241     }
    242 }
    243 
    244 #[test]
    245 fn direct_listing_entry_enforces_complete_event_budget_before_domain_values() {
    246     let data = fixture();
    247     let row = data["vectors"]
    248         .as_array()
    249         .unwrap()
    250         .iter()
    251         .find(|row| row["name"] == "listing_fixed")
    252         .unwrap();
    253     let mut wire: Value = serde_json::from_str(row["raw"].as_str().unwrap()).unwrap();
    254     wire["content"] = serde_json::json!("");
    255     // Independent physical JSON framing, rather than the production counter,
    256     // determines the exact boundary; this test makes no signature claim.
    257     let available = 65536 - wire.to_string().len();
    258     let exact = "🥬".repeat(available / 4) + &"x".repeat(available % 4);
    259     assert!(exact.chars().count() <= 16384);
    260     wire["content"] = serde_json::json!(&exact);
    261     assert_eq!(wire.to_string().len(), 65536);
    262     let tags: Vec<Vec<String>> = serde_json::from_value(wire["tags"].clone()).unwrap();
    263     let mut fields = EventFields {
    264         author: wire["pubkey"].as_str().unwrap().parse().unwrap(),
    265         created_at: 100,
    266         kind: 30402,
    267         tags: &tags,
    268         content: &exact,
    269     };
    270     assert!(listing::decode_observed(&fields, [0; 32]).is_ok());
    271     let over = exact.clone() + "x";
    272     fields.content = &over;
    273     assert_eq!(
    274         listing::decode_observed(&fields, [0; 32]).unwrap_err(),
    275         CommandError::LimitExceeded
    276     );
    277 }
    278 
    279 #[test]
    280 fn standard_price_projection_compares_exact_value_without_a_builder_format_requirement() {
    281     let data = fixture();
    282     let row = data["vectors"]
    283         .as_array()
    284         .unwrap()
    285         .iter()
    286         .find(|row| row["name"] == "listing_fixed")
    287         .unwrap();
    288     let wire: Value = serde_json::from_str(row["raw"].as_str().unwrap()).unwrap();
    289     let original: Vec<Vec<String>> = serde_json::from_value(wire["tags"].clone()).unwrap();
    290     for (amount, accepted) in [
    291         ("3.25", true),
    292         ("3.250", true),
    293         ("3.2500", true),
    294         ("3.250000000000000000000000000000000", true),
    295         ("3.251", false),
    296         ("3.2501", false),
    297         ("3.24", false),
    298         ("-3.25", false),
    299         ("+3.25", false),
    300         (" 3.25", false),
    301         ("3.25 ", false),
    302         ("3.25e0", false),
    303         ("NaN", false),
    304         ("", false),
    305         (".325", false),
    306         ("3.", false),
    307         ("3..25", false),
    308         ("99999999999999999999999999999999999999999", false),
    309     ] {
    310         let mut tags = original.clone();
    311         tags.iter_mut().find(|tag| tag[0] == "price").unwrap()[1] = amount.into();
    312         let fields = EventFields {
    313             author: wire["pubkey"].as_str().unwrap().parse().unwrap(),
    314             created_at: 100,
    315             kind: 30402,
    316             tags: &tags,
    317             content: wire["content"].as_str().unwrap(),
    318         };
    319         assert_eq!(
    320             listing::decode_observed(&fields, [0; 32]).is_ok(),
    321             accepted,
    322             "{amount}"
    323         );
    324     }
    325 }