nostr 0.44.3

Rust implementation of the Nostr protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (c) 2022-2023 Yuki Kishimoto
// Copyright (c) 2023-2025 Rust Nostr Developers
// Distributed under the MIT software license

//! Urls

use alloc::string::String;
use core::cmp::Ordering;
use core::convert::Infallible;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::str::FromStr;
#[cfg(feature = "std")]
use std::net::IpAddr; // TODO: use `core::net` when MSRV will be at 1.77.0

use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[cfg(feature = "std")]
pub use url::*;
#[cfg(not(feature = "std"))]
pub use url_fork::*;

/// Relay URL error
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    /// Url parse error
    Url(ParseError),
    /// Unsupported URL scheme
    UnsupportedScheme,
    /// Multiple scheme separators
    MultipleSchemeSeparators,
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Url(e) => e.fmt(f),
            Self::UnsupportedScheme => f.write_str("Unsupported scheme"),
            Self::MultipleSchemeSeparators => f.write_str("Multiple scheme separators"),
        }
    }
}

impl From<ParseError> for Error {
    fn from(e: ParseError) -> Self {
        Self::Url(e)
    }
}

/// Relay URL
#[derive(Clone)]
pub struct RelayUrl {
    url: Url,
    has_trailing_slash: bool,
}

impl fmt::Debug for RelayUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let url: &str = self.as_str();
        f.debug_tuple("RelayUrl").field(&url).finish()
    }
}

impl PartialEq for RelayUrl {
    fn eq(&self, other: &Self) -> bool {
        self.url == other.url
    }
}

impl Eq for RelayUrl {}

impl PartialOrd for RelayUrl {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RelayUrl {
    fn cmp(&self, other: &Self) -> Ordering {
        self.url.cmp(&other.url)
    }
}

impl Hash for RelayUrl {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.url.hash(state);
    }
}

impl RelayUrl {
    /// Parse relay URL
    #[inline]
    pub fn parse(url: &str) -> Result<Self, Error> {
        // Check that "://" appears only once in the URL
        if url.matches("://").count() > 1 {
            return Err(Error::MultipleSchemeSeparators);
        }

        // Check if has trailing slash
        let has_trailing_slash: bool = url.ends_with('/');

        // Parse URL
        let url: Url = Url::parse(url)?;

        // Check scheme
        match url.scheme() {
            "ws" | "wss" => Ok(Self {
                url,
                has_trailing_slash,
            }),
            _ => Err(Error::UnsupportedScheme),
        }
    }

    /// Check if the host is a local network address.
    ///
    /// IPv4 address ranges:
    /// * `127.0.0.0/8`
    /// * `10.0.0.0/8`
    /// * `172.16.0.0/12`
    /// * `192.168.0.0/16`
    ///
    /// IPv6 address ranges:
    /// * `::1`
    #[cfg(feature = "std")]
    pub fn is_local_addr(&self) -> bool {
        if let Some(host) = self.url.host_str() {
            if let Ok(addr) = IpAddr::from_str(host) {
                return match addr {
                    IpAddr::V4(ipv4) => ipv4.is_loopback() || ipv4.is_private(),
                    IpAddr::V6(ipv6) => ipv6.is_loopback(),
                };
            }
        }

        false
    }

    /// Check if the URL is a hidden onion service address
    #[inline]
    pub fn is_onion(&self) -> bool {
        self.url
            .domain()
            .is_some_and(|host| host.ends_with(".onion"))
    }

    /// If this URL has a host, and it is a domain name (not an IP address), return it.
    /// Non-ASCII domains are punycode-encoded per IDNA if this is the host
    /// of a special URL, or percent encoded for non-special URLs.
    ///
    /// # Examples
    ///
    /// ```
    /// use nostr::types::url::{Error, RelayUrl};
    ///
    /// let url = RelayUrl::parse("wss://127.0.0.1:7777").unwrap();
    /// assert_eq!(url.domain(), None);
    ///
    /// let url = RelayUrl::parse("wss://relay.example.com").unwrap();
    /// assert_eq!(url.domain(), Some("relay.example.com"));
    /// ```
    #[inline]
    pub fn domain(&self) -> Option<&str> {
        self.url.domain()
    }

    /// Return the parsed representation of the host for this URL.
    /// Non-ASCII domain labels are punycode-encoded per IDNA if this is the host
    /// of a special URL, or percent encoded for non-special URLs.
    #[inline]
    pub fn host(&self) -> Option<Host<&str>> {
        self.url.host()
    }

    /// Return the serialization of this relay URL without the trailing slash.
    ///
    /// This method will always remove the trailing slash.
    #[inline]
    pub fn as_str_without_trailing_slash(&self) -> &str {
        self.url.as_str().trim_end_matches('/')
    }

    /// Return the serialization of this relay URL.
    ///
    /// The trailing slash will be removed only if the parsed URL hadn't it.
    #[inline]
    pub fn as_str(&self) -> &str {
        if !self.has_trailing_slash {
            return self.as_str_without_trailing_slash();
        }

        self.url.as_str()
    }
}

impl fmt::Display for RelayUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for RelayUrl {
    type Err = Error;

    fn from_str(relay_url: &str) -> Result<Self, Self::Err> {
        Self::parse(relay_url)
    }
}

impl Serialize for RelayUrl {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for RelayUrl {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let url: String = String::deserialize(deserializer)?;
        Self::parse(&url).map_err(serde::de::Error::custom)
    }
}

impl From<RelayUrl> for Url {
    fn from(relay_url: RelayUrl) -> Self {
        relay_url.url
    }
}

impl<'a> From<&'a RelayUrl> for &'a Url {
    fn from(relay_url: &'a RelayUrl) -> Self {
        &relay_url.url
    }
}

/// Try into relay URL
pub trait TryIntoUrl {
    /// Error
    type Err: fmt::Debug;

    /// Try into relay URL
    fn try_into_url(self) -> Result<RelayUrl, Self::Err>;
}

impl TryIntoUrl for RelayUrl {
    type Err = Infallible;

    #[inline]
    fn try_into_url(self) -> Result<RelayUrl, Self::Err> {
        Ok(self)
    }
}

impl TryIntoUrl for &RelayUrl {
    type Err = Infallible;

    #[inline]
    fn try_into_url(self) -> Result<RelayUrl, Self::Err> {
        Ok(self.clone())
    }
}

impl TryIntoUrl for Url {
    type Err = Error;

    #[inline]
    fn try_into_url(self) -> Result<RelayUrl, Self::Err> {
        RelayUrl::parse(self.as_str())
    }
}

impl TryIntoUrl for &Url {
    type Err = Error;

    #[inline]
    fn try_into_url(self) -> Result<RelayUrl, Self::Err> {
        RelayUrl::parse(self.as_str())
    }
}

impl TryIntoUrl for String {
    type Err = Error;

    #[inline]
    fn try_into_url(self) -> Result<RelayUrl, Self::Err> {
        RelayUrl::parse(self.as_str())
    }
}

impl TryIntoUrl for &String {
    type Err = Error;

    #[inline]
    fn try_into_url(self) -> Result<RelayUrl, Self::Err> {
        RelayUrl::parse(self)
    }
}

impl TryIntoUrl for &str {
    type Err = Error;

    #[inline]
    fn try_into_url(self) -> Result<RelayUrl, Self::Err> {
        RelayUrl::parse(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_relay_url_valid() {
        assert!(RelayUrl::parse("ws://127.0.0.1:7777").is_ok());
        assert!(RelayUrl::parse("wss://relay.damus.io").is_ok());
        assert!(RelayUrl::parse("ws://example.com").is_ok());
        assert!(RelayUrl::parse("wss://example.com/path/to/resource").is_ok());
    }

    #[test]
    fn test_relay_url_invalid() {
        assert_eq!(
            RelayUrl::parse("https://relay.damus.io").unwrap_err(),
            Error::UnsupportedScheme
        );
        assert_eq!(
            RelayUrl::parse("ftp://relay.damus.io").unwrap_err(),
            Error::UnsupportedScheme
        );
        assert_eq!(
            RelayUrl::parse("wss://relay.damus.io,ws://127.0.0.1:7777").unwrap_err(),
            Error::MultipleSchemeSeparators
        );
        assert_eq!(
            RelayUrl::parse("wss://relay.damus.iowss://127.0.0.1:8888").unwrap_err(),
            Error::MultipleSchemeSeparators
        );
        assert_eq!(
            RelayUrl::parse("wss://").unwrap_err(),
            Error::Url(ParseError::EmptyHost)
        );
    }

    #[test]
    fn test_relay_url_as_str() {
        let relay_url = RelayUrl::parse("ws://example.com").unwrap();
        assert_eq!(relay_url.as_str(), "ws://example.com");

        let relay_url = RelayUrl::parse("ws://example.com/").unwrap();
        assert_eq!(relay_url.as_str(), "ws://example.com/");

        let relay_url = RelayUrl::parse("ws://example.com/").unwrap();
        assert_eq!(
            relay_url.as_str_without_trailing_slash(),
            "ws://example.com"
        );
    }

    #[test]
    fn test_relay_url_from_str() {
        let relay_url: Result<RelayUrl, _> = "ws://example.com".parse();
        assert!(relay_url.is_ok());
    }

    #[test]
    fn test_serde_relay_url() {
        let relay_url = RelayUrl::parse("ws://example.com").unwrap();
        let serialized = serde_json::to_string(&relay_url).unwrap();
        let deserialized: RelayUrl = serde_json::from_str(&serialized).unwrap();
        assert_eq!(relay_url, deserialized);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_is_local() {
        // Local
        let url = RelayUrl::parse("ws://127.0.0.1:7777").unwrap();
        assert!(url.is_local_addr());
        let url = RelayUrl::parse("ws://10.10.10.10:7777").unwrap();
        assert!(url.is_local_addr());
        let url = RelayUrl::parse("ws://172.16.10.11:7777").unwrap();
        assert!(url.is_local_addr());
        let url = RelayUrl::parse("ws://192.168.1.10:7777").unwrap();
        assert!(url.is_local_addr());

        // Non local
        let onion_url =
            RelayUrl::parse("ws://oxtrdevav64z64yb7x6rjg4ntzqjhedm5b5zjqulugknhzr46ny2qbad.onion")
                .unwrap();
        assert!(!onion_url.is_local_addr());
        let url = RelayUrl::parse("wss://relay.damus.io").unwrap();
        assert!(!url.is_local_addr());
    }

    #[test]
    fn test_is_onion() {
        // Onion
        let onion_url =
            RelayUrl::parse("ws://oxtrdevav64z64yb7x6rjg4ntzqjhedm5b5zjqulugknhzr46ny2qbad.onion")
                .unwrap();
        assert!(onion_url.is_onion());

        // Non onion
        let non_onion_url = RelayUrl::parse("wss://relay.damus.io").unwrap();
        assert!(!non_onion_url.is_onion());
        let non_onion_url = RelayUrl::parse("ws://example.com:81").unwrap();
        assert!(!non_onion_url.is_onion());
        let non_onion_url = RelayUrl::parse("ws://127.0.0.1:7777").unwrap();
        assert!(!non_onion_url.is_onion());
    }

    #[test]
    fn test_domain() {
        let url = RelayUrl::parse("wss://example.com").unwrap();
        assert_eq!(url.domain(), Some("example.com"));

        let url = RelayUrl::parse("wss://relay.example.com/").unwrap();
        assert_eq!(url.domain(), Some("relay.example.com"));

        let url = RelayUrl::parse("wss://example.com/path/to/resource").unwrap();
        assert_eq!(url.domain(), Some("example.com"));

        let url = RelayUrl::parse("wss://127.0.0.1:7777").unwrap();
        assert_eq!(url.domain(), None);
    }
}