Skip to main content

cosmic_applet_avestruz/nostr/
relay_info.rs

1// SPDX-License-Identifier: MIT
2
3//! What a relay says of itself (NIP-11): its name, a few words about it,
4//! which NIPs it supports, and whom it takes.
5//!
6//! A relay answers at its own address, over `https` where it is reached
7//! over `wss`, to whoever asks for `application/nostr+json` instead of a
8//! page. What it says is its own word, and is shown as that.
9
10use nostr_sdk::prelude::RelayUrl;
11use serde_json::Value;
12
13use crate::http;
14
15/// The most a relay's account of itself may weigh.
16const DOCUMENT_MAX_BYTES: usize = 256 * 1024;
17
18/// How many characters of a relay's name, and of what it says about
19/// itself, are kept.
20const NAME_MAX_CHARS: usize = 60;
21const DESCRIPTION_MAX_CHARS: usize = 200;
22
23/// Whom a relay says it takes: what it asks of whoever connects, or
24/// writes. What it doesn't say it asks, it is taken not to.
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub struct Limits {
27    /// Whoever connects has to say who they are (NIP-42) before anything
28    /// else.
29    pub auth_required: bool,
30    /// Whoever connects has to have paid.
31    pub payment_required: bool,
32    /// It takes events only of some: those it knows, or what it is for.
33    pub restricted_writes: bool,
34}
35
36/// What a relay says of itself.
37#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct RelayInfo {
39    /// What it calls itself.
40    pub name: Option<String>,
41    /// A few words about it: the first line of what it says.
42    pub description: Option<String>,
43    /// The NIPs it says it supports. `None` if it names none, which says
44    /// nothing of what it does.
45    pub nips: Option<Vec<u16>>,
46    /// Whom it says it takes.
47    pub limits: Limits,
48}
49
50impl RelayInfo {
51    /// Whether it says it supports `nip`. `None` if it doesn't say what it
52    /// supports.
53    pub fn supports(&self, nip: u16) -> Option<bool> {
54        self.nips.as_ref().map(|nips| nips.contains(&nip))
55    }
56}
57
58/// Where `relay` says what it is: its own address, as a page is asked
59/// for. Only for a relay reached with encryption: the other kind is on
60/// this machine or this network, and is not asked over the web.
61pub fn document_url(relay: &RelayUrl) -> Option<String> {
62    relay.as_str().strip_prefix("wss://").map(|rest| format!("https://{rest}"))
63}
64
65/// What the document `json` says of the relay that sent it. `None` if it
66/// is no such document.
67pub fn parse(json: &str) -> Option<RelayInfo> {
68    let document: Value = serde_json::from_str(json).ok()?;
69    let document = document.as_object()?;
70    let said = |field: &str, max: usize| {
71        let words = document.get(field)?.as_str()?.lines().next()?.trim();
72        (!words.is_empty()).then(|| words.chars().take(max).collect::<String>())
73    };
74    let nips: Option<Vec<u16>> = document
75        .get("supported_nips")
76        .and_then(Value::as_array)
77        .map(|nips| nips.iter().filter_map(|nip| u16::try_from(nip.as_u64()?).ok()).collect())
78        .filter(|nips: &Vec<u16>| !nips.is_empty());
79    let asked =
80        |limit: &str| document.get("limitation").and_then(|limits| limits.get(limit)).and_then(Value::as_bool).unwrap_or(false);
81    let limits = Limits {
82        auth_required: asked("auth_required"),
83        payment_required: asked("payment_required"),
84        restricted_writes: asked("restricted_writes"),
85    };
86    Some(RelayInfo { name: said("name", NAME_MAX_CHARS), description: said("description", DESCRIPTION_MAX_CHARS), nips, limits })
87}
88
89/// What `relay` says of itself, if it says: asked over `https`.
90pub async fn fetch(http: &reqwest::Client, relay: &RelayUrl) -> Option<RelayInfo> {
91    let url = document_url(relay)?;
92    match http::get_as(http, &url, "application/nostr+json", DOCUMENT_MAX_BYTES).await {
93        Ok(answer) => parse(&String::from_utf8_lossy(&answer)),
94        Err(e) => {
95            tracing::debug!("{relay} did not say what it is: {e}");
96            None
97        }
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::{Limits, RelayInfo, document_url, parse};
104    use nostr_sdk::prelude::RelayUrl;
105
106    #[test]
107    fn a_relay_is_asked_what_it_is_at_its_own_address() {
108        let url = |relay: &str| document_url(&RelayUrl::parse(relay).unwrap());
109        assert_eq!(url("wss://relay.example.com").as_deref(), Some("https://relay.example.com"));
110        assert_eq!(url("wss://relay.example.com/inbox").as_deref(), Some("https://relay.example.com/inbox"));
111        assert_eq!(url("ws://127.0.0.1:7777"), None);
112    }
113
114    #[test]
115    fn what_a_relay_says_of_itself_is_its_name_a_line_about_it_and_what_it_supports() {
116        let document =
117            r#"{"name":" Example relay ","description":"A relay.\nWith rules.","supported_nips":[1,11,50],"software":"x"}"#;
118        let info = parse(document).unwrap();
119        assert_eq!(info.name.as_deref(), Some("Example relay"));
120        assert_eq!(info.description.as_deref(), Some("A relay."));
121        assert_eq!(info.nips, Some(vec![1, 11, 50]));
122        assert_eq!((info.supports(50), info.supports(42)), (Some(true), Some(false)));
123
124        assert_eq!(info.limits, Limits::default());
125
126        // Whom it takes is what it says of that, and anyone otherwise.
127        let limited = r#"{"limitation":{"auth_required":true,"payment_required":false,"restricted_writes":true,"max_limit":5}}"#;
128        let limits = Limits { auth_required: true, payment_required: false, restricted_writes: true };
129        assert_eq!(parse(limited), Some(RelayInfo { limits, ..RelayInfo::default() }));
130        let paid = Limits { payment_required: true, ..Limits::default() };
131        assert_eq!(parse(r#"{"supported_nips":[],"limitation":{"payment_required":true}}"#).unwrap().limits, paid);
132        assert_eq!(parse(r#"{"limitation":{"payment_required":"yes"}}"#).unwrap().limits, Limits::default());
133        assert_eq!(parse(r#"{"limitation":[true]}"#).unwrap().limits, Limits::default());
134
135        // Little said, or said oddly, is still an answer; and what is no
136        // such document is none.
137        assert_eq!(parse(r#"{"supported_nips":[1],"name":""}"#), Some(RelayInfo { nips: Some(vec![1]), ..RelayInfo::default() }));
138        // One that names no NIP it supports says nothing of what it does.
139        for unsaid in [r#"{"supported_nips":"50","name":7}"#, r#"{"supported_nips":[]}"#, r#"{"supported_nips":["50",-1]}"#, "{}"]
140        {
141            assert_eq!(parse(unsaid), Some(RelayInfo::default()), "{unsaid}");
142            assert_eq!(parse(unsaid).unwrap().supports(50), None);
143        }
144        let long = format!(r#"{{"name":"{}"}}"#, "n".repeat(500));
145        assert_eq!(parse(&long).unwrap().name.unwrap().chars().count(), 60);
146        assert_eq!(parse("<html></html>"), None);
147        assert_eq!(parse("[]"), None);
148    }
149}