Skip to main content

cosmic_applet_avestruz/nostr/
relay_lists.rs

1// SPDX-License-Identifier: MIT
2
3//! The relays an account says are its own, by what they are for, as the
4//! relays page shows and changes them.
5//!
6//! Seven sets, in six lists:
7//!
8//! - **Outbox** and **inbox**: the relays the account writes to, where its
9//!   notes are to be found, and the relays it reads, where what is meant
10//!   for it is to be sent. Both are in its relay list (NIP-65, kind 10002):
11//!   one `r` tag for each relay, marked `write` or `read`, or unmarked
12//!   when it is both.
13//! - The others are each a list of `relay` tags (NIP-51): in the list's
14//!   tags, for anyone to read, or among the tags it keeps to itself,
15//!   encrypted in its content as a bookmark list's are. Where direct
16//!   messages go (NIP-17, kind 10050), which is for anyone to read; the
17//!   relays it searches (kind 10007); the relays profiles and relay lists
18//!   are looked up on (kind 10086); the relays it trusts (kind 10089);
19//!   and the relays it never connects to (kind 10006).
20//!
21//! The list of relays an account keeps what is its alone on (kind 10013)
22//! is not among them: what is kept here and not published, a draft, is
23//! kept on this machine, and that list is neither read nor written.
24//!
25//! A list is changed as Amethyst changes it, so that each client finds
26//! what the other left: everything in it that is not a relay stays as it
27//! was, and a relay stays where it was, said to anyone or kept private.
28//! One that is new goes where the list keeps its relays: among the public
29//! ones if those are all it has, and among the private ones otherwise;
30//! and in a first list, where lists of its kind keep them.
31//!
32//! ```mermaid
33//! flowchart LR
34//!     subgraph page["The relays page"]
35//!         outbox["Outbox"]
36//!         inbox["Inbox"]
37//!         dm["Direct messages"]
38//!         search["Search"]
39//!         indexer["Indexer"]
40//!         trusted["Trusted"]
41//!         blocked["Blocked"]
42//!     end
43//!     outbox --> k10002["Kind 10002: r tags, marked write or read"]
44//!     inbox --> k10002
45//!     dm --> k10050["Kind 10050: relay tags, public"]
46//!     search --> k10007["Kind 10007"]
47//!     indexer --> k10086["Kind 10086"]
48//!     trusted --> k10089["Kind 10089"]
49//!     blocked --> k10006["Kind 10006"]
50//!     k10007 --> halves["relay tags, in the list's tags or encrypted in its content"]
51//!     k10086 --> halves
52//!     k10089 --> halves
53//!     k10006 --> halves
54//! ```
55//!
56//! What each set is used for, and what a relay has to do to be of use in
57//! one ([`Section::hindrances`]), is in [`crate::guide::relays`].
58
59use std::collections::{HashMap, HashSet};
60use std::fmt;
61
62use nostr_sdk::prelude::{Event, EventBuilder, Kind, RelayUrl, Tag, Timestamp};
63
64use crate::nostr::account::SignError;
65use crate::nostr::bookmarks::PrivateTags;
66use crate::nostr::outbox::{self, Listed};
67use crate::nostr::relay_info::RelayInfo;
68
69/// The name of the tag that names a relay in a relay list (NIP-65), and
70/// in the other lists of relays (NIP-51, NIP-17).
71const ADVERTISED_TAG: &str = "r";
72const RELAY_TAG: &str = "relay";
73
74/// The NIPs a relay has to support to be of use in one of the sets:
75/// search, and saying who is asking.
76pub const NIP_SEARCH: u16 = 50;
77pub const NIP_AUTH: u16 = 42;
78
79/// What a relay says of itself that gets in the way of what the set it is
80/// in is for.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum Hindrance {
83    /// It names the NIPs it supports, and not this one, which the set
84    /// needs.
85    Lacks(u16),
86    /// It takes events only of some, where anyone is to write.
87    RestrictedWrites,
88    /// It has to be paid, where anyone is to write.
89    PaymentRequired,
90    /// Whoever connects has to say who they are first, where anyone is to
91    /// write: a client that doesn't is turned away.
92    AuthToWrite,
93    /// Whoever connects has to say who they are first, where anyone is to
94    /// read: a client that doesn't sees nothing.
95    AuthToRead,
96}
97
98/// One of an account's sets of relays.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub enum Section {
101    /// The relays it writes to (NIP-65).
102    Outbox,
103    /// The relays it reads (NIP-65).
104    Inbox,
105    /// The relays its direct messages are sent to (NIP-17, kind 10050).
106    Messages,
107    /// The relays it searches (NIP-51, kind 10007).
108    Search,
109    /// The relays that keep everyone's profile and relay list, where
110    /// those are looked up (kind 10086).
111    Indexer,
112    /// The relays it trusts with who it is (kind 10089).
113    Trusted,
114    /// The relays it never connects to (NIP-51, kind 10006).
115    Blocked,
116}
117
118impl Section {
119    /// Every section, in the order the page shows them.
120    pub const ALL: [Self; 7] =
121        [Self::Outbox, Self::Inbox, Self::Messages, Self::Search, Self::Indexer, Self::Trusted, Self::Blocked];
122
123    /// The sections that are a list of their own, of `relay` tags: all
124    /// but the two of the relay list.
125    pub const LISTS: [Self; 5] = [Self::Messages, Self::Search, Self::Indexer, Self::Trusted, Self::Blocked];
126
127    /// The kind of the list this set of relays is in.
128    pub fn kind(self) -> Kind {
129        match self {
130            Self::Outbox | Self::Inbox => Kind::RelayList,
131            Self::Messages => Kind::InboxRelays,
132            Self::Search => Kind::SearchRelays,
133            Self::Indexer => Kind::Custom(10086),
134            Self::Trusted => Kind::Custom(10089),
135            Self::Blocked => Kind::BlockedRelays,
136        }
137    }
138
139    /// The NIP a relay has to support to do what the relays of this set
140    /// are for, where there is one beyond the protocol itself. A search
141    /// relay is asked to search (NIP-50). A relay direct messages are
142    /// sent to is to give them to nobody but whom they are for, which
143    /// takes knowing who is asking (NIP-17, by NIP-42). The other sets
144    /// ask nothing of a relay that every relay doesn't do.
145    pub fn needs(self) -> Option<u16> {
146        match self {
147            Self::Search => Some(NIP_SEARCH),
148            Self::Messages => Some(NIP_AUTH),
149            Self::Outbox | Self::Inbox | Self::Indexer | Self::Trusted | Self::Blocked => None,
150        }
151    }
152
153    /// Whether the relays of this set are where other people write to
154    /// reach the account: what is meant for it, and its direct messages.
155    fn written_to_by_others(self) -> bool {
156        matches!(self, Self::Inbox | Self::Messages)
157    }
158
159    /// Whether the relays of this set are where other people read what
160    /// the account writes.
161    fn read_by_others(self) -> bool {
162        self == Self::Outbox
163    }
164
165    /// Whether what a relay says of itself can get in the way of what
166    /// this set is for: whether its relays are worth asking.
167    pub fn asks_of_relays(self) -> bool {
168        self.needs().is_some() || self.written_to_by_others() || self.read_by_others()
169    }
170
171    /// What `info`, which a relay of this set says of itself, has that
172    /// gets in the way of what the set is for: a NIP it needs and the
173    /// relay doesn't name; where other people are to write, what the
174    /// relay asks before it takes anything; and where they are to read,
175    /// that it asks who they are. Not that it asks who is connecting
176    /// where that is what the set needs of it. Whether a relay the
177    /// account writes to takes what it writes, or is paid for, is the
178    /// account's own business.
179    pub fn hindrances(self, info: &RelayInfo) -> Vec<Hindrance> {
180        let mut found = Vec::new();
181        if let Some(nip) = self.needs()
182            && info.supports(nip) == Some(false)
183        {
184            found.push(Hindrance::Lacks(nip));
185        }
186        if self.written_to_by_others() {
187            let limits = info.limits;
188            found.extend(limits.restricted_writes.then_some(Hindrance::RestrictedWrites));
189            found.extend(limits.payment_required.then_some(Hindrance::PaymentRequired));
190            found.extend((limits.auth_required && self.needs() != Some(NIP_AUTH)).then_some(Hindrance::AuthToWrite));
191        }
192        if self.read_by_others() {
193            found.extend(info.limits.auth_required.then_some(Hindrance::AuthToRead));
194        }
195        found
196    }
197
198    /// Whether the list says its relays to anyone, always: where direct
199    /// messages go is for whoever writes one to read.
200    fn always_public(self) -> bool {
201        self == Self::Messages
202    }
203
204    /// Whether a first list of this kind says its relays to anyone, as
205    /// Amethyst writes one: the others keep them to themselves.
206    fn first_is_public(self) -> bool {
207        matches!(self, Self::Messages | Self::Search)
208    }
209}
210
211/// An account's relays, by what they are for.
212#[derive(Debug, Clone, Default, PartialEq, Eq)]
213pub struct RelaySets(HashMap<Section, Vec<RelayUrl>>);
214
215impl RelaySets {
216    /// The relays of `section`, in their order.
217    pub fn of(&self, section: Section) -> &[RelayUrl] {
218        self.0.get(&section).map_or(&[], Vec::as_slice)
219    }
220
221    /// Have `relays` for the relays of `section`.
222    pub fn set(&mut self, section: Section, relays: Vec<RelayUrl>) {
223        self.0.insert(section, relays);
224    }
225
226    /// Have `relay` in `section`, after the others. Returns whether it
227    /// wasn't there already.
228    pub fn add(&mut self, section: Section, relay: RelayUrl) -> bool {
229        let relays = self.0.entry(section).or_default();
230        let new = !relays.contains(&relay);
231        if new {
232            relays.push(relay);
233        }
234        new
235    }
236
237    /// Take `relay` out of `section`.
238    pub fn remove(&mut self, section: Section, relay: &RelayUrl) {
239        self.0.entry(section).or_default().retain(|listed| listed != relay);
240    }
241
242    /// Move `relay` one place towards the start of `section` (`up`), or
243    /// towards its end. Nothing moves past either.
244    pub fn shift(&mut self, section: Section, relay: &RelayUrl, up: bool) {
245        let relays = self.0.entry(section).or_default();
246        let Some(place) = relays.iter().position(|listed| listed == relay) else {
247            return;
248        };
249        let other = if up { place.checked_sub(1) } else { Some(place + 1).filter(|next| *next < relays.len()) };
250        if let Some(other) = other {
251            relays.swap(place, other);
252        }
253    }
254
255    /// Whether these are the relays `other` has, set for set and in the
256    /// same order.
257    pub fn same_as(&self, other: &Self) -> bool {
258        Section::ALL.iter().all(|section| self.of(*section) == other.of(*section))
259    }
260}
261
262/// The relay `typed` names, as someone types one: its address, with or
263/// without the `wss://` nearly all of them start with.
264pub fn typed_relay(typed: &str) -> Option<RelayUrl> {
265    let typed = typed.trim();
266    if typed.is_empty() || typed.contains(char::is_whitespace) {
267        return None;
268    }
269    let address = if typed.contains("://") { typed.to_string() } else { format!("wss://{typed}") };
270    RelayUrl::parse(&address).ok()
271}
272
273/// When the list that replaces `earlier` is written: at `now` or, if
274/// `earlier` claims to be from later, after it. It has to be the newer of
275/// the two.
276fn replacing(earlier: Option<&Event>, now: Timestamp) -> Timestamp {
277    earlier.map_or(now, |earlier| now.max(Timestamp::from_secs(earlier.created_at.as_secs() + 1)))
278}
279
280/// Whether `tag` names a relay, as tags called `name` do in a list.
281fn names_relay(fields: &[String], name: &str) -> bool {
282    matches!(fields, [called, relay, ..] if called == name && RelayUrl::parse(relay).is_ok())
283}
284
285/// The relays that the tags `fields` call `name`, each once, in their order.
286fn relays_named<'a>(tags: impl IntoIterator<Item = &'a [String]>, name: &str) -> Vec<RelayUrl> {
287    let mut seen = HashSet::new();
288    tags.into_iter()
289        .filter(|fields| fields.first().is_some_and(|called| called == name))
290        .filter_map(|fields| fields.get(1).and_then(|relay| RelayUrl::parse(relay).ok()))
291        .filter(|relay| seen.insert(relay.clone()))
292        .collect()
293}
294
295/// The relays the relay list `list` says its account writes to, and those
296/// it says it reads. None of either without a list.
297pub fn advertised(list: Option<&Event>) -> (Vec<RelayUrl>, Vec<RelayUrl>) {
298    list.map(|list| (outbox::relays(list, Listed::Write), outbox::relays(list, Listed::Read))).unwrap_or_default()
299}
300
301/// The relay list (NIP-65) that replaces `earlier`, if there is one to
302/// replace: with `outbox` for the relays written to and `inbox` for those
303/// read, a relay in both named once, and whatever else `earlier` had in
304/// it as it was. The relays written to come in their order, and after
305/// them those that are only read, in theirs: a list has one order for
306/// both.
307///
308/// `None` when `earlier` names the same relays for the same things in
309/// the same order: there is nothing to write.
310pub fn advertised_list(earlier: Option<&Event>, outbox: &[RelayUrl], inbox: &[RelayUrl], now: Timestamp) -> Option<EventBuilder> {
311    let names = |tag: &&Tag| names_relay(tag.as_slice(), ADVERTISED_TAG);
312    let naming = |relay: &RelayUrl, marker: Option<&str>| {
313        let fields = [ADVERTISED_TAG, relay.as_str()].into_iter().chain(marker);
314        Tag::parse(fields).ok()
315    };
316    let written = outbox.iter().filter_map(|relay| naming(relay, (!inbox.contains(relay)).then_some("write")));
317    let read = inbox.iter().filter(|relay| !outbox.contains(relay)).filter_map(|relay| naming(relay, Some("read")));
318    let relays: Vec<Tag> = written.chain(read).collect();
319
320    // Said already, whatever form the addresses were written in.
321    let said = |tags: &[Tag]| -> Vec<(Option<RelayUrl>, Option<String>)> {
322        tags.iter()
323            .map(|tag| (tag.as_slice().get(1).and_then(|relay| RelayUrl::parse(relay).ok()), tag.as_slice().get(2).cloned()))
324            .collect()
325    };
326    let before: Vec<Tag> = earlier.into_iter().flat_map(|earlier| earlier.tags.iter()).filter(names).cloned().collect();
327    if said(&before) == said(&relays) {
328        return None;
329    }
330    let kept = earlier.into_iter().flat_map(|earlier| earlier.tags.iter()).filter(|tag| !names(tag));
331    let tags: Vec<Tag> = kept.cloned().chain(relays).collect();
332    let content = earlier.map(|earlier| earlier.content.clone()).unwrap_or_default();
333    Some(EventBuilder::new(Kind::RelayList, content).tags(tags).custom_created_at(replacing(earlier, now)))
334}
335
336/// What a list keeps to itself, as far as it was read.
337#[derive(Clone, PartialEq, Eq)]
338pub enum Kept {
339    /// These tags: none, for a list that keeps nothing to itself.
340    Read(PrivateTags),
341    /// Something, which was not asked to be decrypted: a signer may ask a
342    /// person about each request, and not every list is needed.
343    Unread,
344    /// Something that could not be read, and why.
345    Unreadable(SignError),
346}
347
348/// What is kept private is not printed: whatever is `Debug` ends up in a
349/// log sooner or later.
350impl fmt::Debug for Kept {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        match self {
353            Self::Read(private) => write!(f, "Read({} tag(s))", private.len()),
354            Self::Unread => f.write_str("Unread"),
355            Self::Unreadable(why) => write!(f, "Unreadable({why:?})"),
356        }
357    }
358}
359
360/// An account's relays of one kind, as its newest list of that kind has
361/// them: a list of `relay` tags, some for anyone to read and some kept to
362/// itself, encrypted in its content as a bookmark list's are.
363#[derive(Clone, PartialEq, Eq)]
364pub struct ListedRelays {
365    /// The list they were read from. `None` when the account has none.
366    list: Option<Event>,
367    /// What the list keeps to itself.
368    kept: Kept,
369}
370
371impl Default for ListedRelays {
372    fn default() -> Self {
373        Self { list: None, kept: Kept::Read(Vec::new()) }
374    }
375}
376
377/// What is kept private is not printed: whatever is `Debug` ends up in a
378/// log sooner or later.
379impl fmt::Debug for ListedRelays {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        f.debug_struct("ListedRelays")
382            .field("list", &self.list.as_ref().map(|list| list.id))
383            .field("relays", &self.relays().len())
384            .finish_non_exhaustive()
385    }
386}
387
388impl ListedRelays {
389    /// The relays of `list`, which keeps `kept` to itself.
390    pub fn new(list: Option<Event>, kept: Kept) -> Self {
391        Self { list, kept }
392    }
393
394    /// The list they were read from, if the account has one.
395    pub fn list(&self) -> Option<&Event> {
396        self.list.as_ref()
397    }
398
399    /// What the list keeps to itself, as far as it was read.
400    pub fn kept(&self) -> &Kept {
401        &self.kept
402    }
403
404    /// The relays the list names for anyone to read.
405    fn public(&self) -> Vec<RelayUrl> {
406        relays_named(self.list.iter().flat_map(|list| list.tags.iter()).map(Tag::as_slice), RELAY_TAG)
407    }
408
409    /// The relays the list keeps to itself, as far as they were read.
410    fn private(&self) -> Vec<RelayUrl> {
411        match &self.kept {
412            Kept::Read(private) => relays_named(private.iter().map(Vec::as_slice), RELAY_TAG),
413            Kept::Unread | Kept::Unreadable(_) => Vec::new(),
414        }
415    }
416
417    /// The relays, as far as they were read: those the list names for
418    /// anyone, then those it keeps to itself, each once.
419    pub fn relays(&self) -> Vec<RelayUrl> {
420        let mut relays = self.public();
421        for relay in self.private() {
422            if !relays.contains(&relay) {
423                relays.push(relay);
424            }
425        }
426        relays
427    }
428
429    /// The list's tags and what it keeps to itself, with `relays` for the
430    /// relays of `section` and everything else as it is: each relay where
431    /// it was, and a new one where the list keeps its relays (see the
432    /// module documentation), in the order of `relays` there.
433    ///
434    /// `None` when there is nothing to write: the list says the same
435    /// already. And when what the list keeps to itself was not read: a
436    /// list written without it would lose it.
437    pub fn changed(&self, section: Section, relays: &[RelayUrl]) -> Option<(Vec<Tag>, PrivateTags)> {
438        let Kept::Read(kept) = &self.kept else {
439            return None;
440        };
441        let (was_public, was_private) = (self.public(), self.private());
442        let new_are_public = section.always_public()
443            || if self.list.is_none() { section.first_is_public() } else { !was_public.is_empty() && was_private.is_empty() };
444        let is_public = |relay: &&RelayUrl| {
445            section.always_public() || was_public.contains(relay) || (!was_private.contains(relay) && new_are_public)
446        };
447        let (public, private): (Vec<&RelayUrl>, Vec<&RelayUrl>) = relays.iter().partition(is_public);
448        let same =
449            |one: &[&RelayUrl], other: &[RelayUrl]| one.len() == other.len() && one.iter().zip(other).all(|(a, b)| *a == b);
450        // In the order each half has them, which is all a list can say.
451        let was_private_alone: Vec<RelayUrl> = was_private.iter().filter(|relay| !was_public.contains(relay)).cloned().collect();
452        if same(&public, &was_public) && same(&private, &was_private_alone) {
453            return None;
454        }
455        let naming = |relay: &RelayUrl| vec![RELAY_TAG.to_string(), relay.to_string()];
456        let others = self.list.iter().flat_map(|list| list.tags.iter()).filter(|tag| !names_relay(tag.as_slice(), RELAY_TAG));
457        let tags: Vec<Tag> =
458            others.cloned().chain(public.into_iter().filter_map(|relay| Tag::parse(naming(relay)).ok())).collect();
459        let mut private_tags: PrivateTags = kept.iter().filter(|fields| !names_relay(fields, RELAY_TAG)).cloned().collect();
460        private_tags.extend(private.into_iter().map(naming));
461        Some((tags, private_tags))
462    }
463}
464
465/// The list of `section` that replaces `earlier`, if there is one to
466/// replace: with `tags`, and `content` for what it keeps to itself.
467pub fn listed(section: Section, earlier: Option<&Event>, tags: Vec<Tag>, content: String, now: Timestamp) -> EventBuilder {
468    EventBuilder::new(section.kind(), content).tags(tags).custom_created_at(replacing(earlier, now))
469}
470
471/// An account's relay lists, as they were last read.
472#[derive(Debug, Clone, Default, PartialEq, Eq)]
473pub struct RelayLists {
474    /// Its relay list (NIP-65), if it has one.
475    pub advertised: Option<Event>,
476    /// Its other lists of relays, each as far as it was read.
477    pub listed: HashMap<Section, ListedRelays>,
478}
479
480impl RelayLists {
481    /// The list of `section`, for the sections that are a list of their
482    /// own: an account with none has no relays there.
483    pub fn of(&self, section: Section) -> ListedRelays {
484        self.listed.get(&section).cloned().unwrap_or_default()
485    }
486
487    /// The relays the lists name, by what they are for, as far as the
488    /// lists were read.
489    pub fn sets(&self) -> RelaySets {
490        let (outbox, inbox) = advertised(self.advertised.as_ref());
491        let mut sets = RelaySets::default();
492        sets.set(Section::Outbox, outbox);
493        sets.set(Section::Inbox, inbox);
494        for section in Section::LISTS {
495            sets.set(section, self.listed.get(&section).map(ListedRelays::relays).unwrap_or_default());
496        }
497        sets
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::{
504        Hindrance, Kept, ListedRelays, NIP_AUTH, NIP_SEARCH, RelayLists, RelaySets, Section, advertised, advertised_list, listed,
505        typed_relay,
506    };
507    use crate::nostr::account::SignError;
508    use crate::nostr::relay_info::{Limits, RelayInfo};
509    use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, Kind, RelayUrl, Tag, Timestamp};
510
511    fn relay(name: &str) -> RelayUrl {
512        RelayUrl::parse(&format!("wss://{name}.example.com")).unwrap()
513    }
514
515    fn tag(fields: &[&str]) -> Tag {
516        Tag::parse(fields.iter().copied()).unwrap()
517    }
518
519    fn a_list(kind: Kind, tags: Vec<Tag>, content: &str, at: u64) -> Event {
520        EventBuilder::new(kind, content)
521            .tags(tags)
522            .custom_created_at(Timestamp::from_secs(at))
523            .finalize(&Keys::generate())
524            .unwrap()
525    }
526
527    fn fields(event: &Event) -> Vec<Vec<String>> {
528        event.tags.iter().map(|tag| tag.as_slice().to_vec()).collect()
529    }
530
531    fn private(relays: &[&RelayUrl]) -> Vec<Vec<String>> {
532        relays.iter().map(|relay| vec!["relay".to_string(), relay.to_string()]).collect()
533    }
534
535    #[test]
536    fn what_a_relay_says_of_itself_gets_in_the_way_of_some_sets_and_not_of_others() {
537        let says = |nips: &[u16], limits: Limits| RelayInfo { nips: Some(nips.to_vec()), limits, ..RelayInfo::default() };
538        let open = Limits::default();
539        let closed = Limits { auth_required: true, payment_required: true, restricted_writes: true };
540
541        // A set that needs a NIP is hindered by a relay that names
542        // others, and not by one that names none.
543        assert_eq!(Section::Search.hindrances(&says(&[1, 11], open)), [Hindrance::Lacks(NIP_SEARCH)]);
544        assert_eq!(Section::Search.hindrances(&says(&[1, 50], open)), []);
545        assert_eq!(Section::Search.hindrances(&RelayInfo::default()), []);
546        assert_eq!(Section::Messages.hindrances(&says(&[1], open)), [Hindrance::Lacks(NIP_AUTH)]);
547
548        // Where others write, by what a relay asks before it takes
549        // anything, whatever NIPs it names.
550        let all = [Hindrance::RestrictedWrites, Hindrance::PaymentRequired, Hindrance::AuthToWrite];
551        assert_eq!(Section::Inbox.hindrances(&says(&[1], closed)), all);
552        assert_eq!(Section::Inbox.hindrances(&RelayInfo { limits: closed, ..RelayInfo::default() }), all);
553        assert_eq!(Section::Inbox.hindrances(&says(&[1], open)), []);
554        let asking = Limits { auth_required: true, ..open };
555        assert_eq!(Section::Inbox.hindrances(&says(&[1, 42], asking)), [Hindrance::AuthToWrite]);
556        // A relay direct messages go to is to ask who connects.
557        assert_eq!(Section::Messages.hindrances(&says(&[1, 42], asking)), []);
558        assert_eq!(Section::Messages.hindrances(&says(&[1, 42], closed)), all[..2]);
559
560        // Where others read, by a relay asking who they are; whom it
561        // takes events of, and whether it is paid, is the account's own
562        // business there.
563        assert_eq!(Section::Outbox.hindrances(&says(&[1, 42], closed)), [Hindrance::AuthToRead]);
564        let members = Limits { payment_required: true, restricted_writes: true, ..open };
565        assert_eq!(Section::Outbox.hindrances(&says(&[1], members)), []);
566        assert!(Section::Outbox.asks_of_relays());
567
568        // Nothing gets in the way of the other sets.
569        for section in [Section::Indexer, Section::Trusted, Section::Blocked] {
570            assert_eq!(section.hindrances(&says(&[1], closed)), [], "{section:?}");
571            assert!(!section.asks_of_relays());
572        }
573        assert!(Section::Inbox.asks_of_relays() && Section::Messages.asks_of_relays() && Section::Search.asks_of_relays());
574        assert_eq!(Section::Search.hindrances(&says(&[1, 50], closed)), []);
575    }
576
577    #[test]
578    fn a_relay_is_typed_with_or_without_its_scheme() {
579        let ditto = RelayUrl::parse("wss://relay.ditto.pub").unwrap();
580        for typed in ["relay.ditto.pub", " wss://relay.ditto.pub/ ", "wss://relay.ditto.pub"] {
581            assert_eq!(typed_relay(typed), Some(ditto.clone()), "{typed}");
582        }
583        assert_eq!(typed_relay("ws://127.0.0.1:7777"), RelayUrl::parse("ws://127.0.0.1:7777").ok());
584        for not_a_relay in ["", "   ", "https://example.com", "two words", "wss://"] {
585            assert_eq!(typed_relay(not_a_relay), None, "{not_a_relay:?}");
586        }
587    }
588
589    #[test]
590    fn relays_are_added_once_taken_out_and_moved() {
591        let mut sets = RelaySets::default();
592        assert!(sets.add(Section::Search, relay("one")));
593        assert!(sets.add(Section::Search, relay("two")));
594        assert!(!sets.add(Section::Search, relay("one")), "there already");
595        assert!(sets.add(Section::Outbox, relay("one")), "each set for itself");
596        assert_eq!(sets.of(Section::Search), [relay("one"), relay("two")]);
597        sets.remove(Section::Search, &relay("one"));
598        assert_eq!(sets.of(Section::Search), [relay("two")]);
599        assert_eq!(sets.of(Section::Outbox), [relay("one")]);
600        assert!(sets.of(Section::Inbox).is_empty());
601
602        // Moved a place at a time, and not past either end.
603        let mut sets = RelaySets::default();
604        for name in ["a", "b", "c"] {
605            sets.add(Section::Outbox, relay(name));
606        }
607        sets.shift(Section::Outbox, &relay("c"), true);
608        assert_eq!(sets.of(Section::Outbox), [relay("a"), relay("c"), relay("b")]);
609        sets.shift(Section::Outbox, &relay("a"), true);
610        sets.shift(Section::Outbox, &relay("b"), false);
611        sets.shift(Section::Outbox, &relay("nowhere"), false);
612        assert_eq!(sets.of(Section::Outbox), [relay("a"), relay("c"), relay("b")]);
613        sets.shift(Section::Outbox, &relay("a"), false);
614        assert_eq!(sets.of(Section::Outbox), [relay("c"), relay("a"), relay("b")]);
615
616        // The same relays in another order are not the same sets.
617        let mut other = sets.clone();
618        assert!(sets.same_as(&other));
619        other.shift(Section::Outbox, &relay("b"), true);
620        assert!(!sets.same_as(&other));
621    }
622
623    #[test]
624    fn a_relay_list_is_written_with_each_relay_marked_for_what_it_is_for() {
625        // As Amethyst leaves it: unmarked relays, and a tag of its own.
626        let (both, out, into, new) = (relay("both"), relay("out"), relay("in"), relay("new"));
627        let tags = vec![
628            tag(&["r", both.as_str()]),
629            tag(&["r", out.as_str(), "write"]),
630            tag(&["r", into.as_str(), "read"]),
631            tag(&["client", "Amethyst"]),
632        ];
633        let earlier = a_list(Kind::RelayList, tags, "", 100);
634        assert_eq!(advertised(Some(&earlier)), (vec![both.clone(), out.clone()], vec![both.clone(), into.clone()]));
635        assert_eq!(advertised(None), (vec![], vec![]));
636
637        // One taken out of the outbox, one added to it, one moved to both.
638        let keys = Keys::generate();
639        let now = Timestamp::from_secs(200);
640        let (outbox, inbox) = (vec![both.clone(), new.clone(), into.clone()], vec![both.clone(), into.clone()]);
641        let changed = advertised_list(Some(&earlier), &outbox, &inbox, now).unwrap().finalize(&keys).unwrap();
642        assert_eq!(
643            fields(&changed),
644            [vec!["client", "Amethyst"], vec!["r", both.as_str()], vec!["r", new.as_str(), "write"], vec!["r", into.as_str()],]
645        );
646        assert_eq!(changed.created_at, now);
647        assert_eq!(advertised(Some(&changed)), (outbox.clone(), inbox.clone()));
648
649        // The same relays for the same things: nothing to write. In
650        // another order, there is.
651        assert!(advertised_list(Some(&changed), &outbox, &inbox, now).is_none());
652        let reordered = vec![new.clone(), both.clone(), into.clone()];
653        let moved = advertised_list(Some(&changed), &reordered, &inbox, now).unwrap().finalize(&keys).unwrap();
654        assert_eq!(advertised(Some(&moved)).0, reordered);
655
656        // A first list, and one that replaces a list from the future.
657        let first = advertised_list(None, &[out.clone()], &[into.clone()], now).unwrap().finalize(&keys).unwrap();
658        assert_eq!(fields(&first), [vec!["r", out.as_str(), "write"], vec!["r", into.as_str(), "read"]]);
659        assert!(advertised_list(None, &[], &[], now).is_none(), "no relays and no list");
660        let ahead = a_list(Kind::RelayList, vec![tag(&["r", out.as_str()])], "", 500);
661        assert_eq!(advertised_list(Some(&ahead), &[], &[], now).unwrap().finalize(&keys).unwrap().created_at.as_secs(), 501);
662    }
663
664    #[test]
665    fn listed_relays_are_those_said_to_anyone_and_those_kept_private() {
666        let (open, kept, twice) = (relay("open"), relay("kept"), relay("twice"));
667        let list = a_list(Kind::SearchRelays, vec![tag(&["relay", open.as_str()]), tag(&["relay", twice.as_str()])], "x", 100);
668        let search = ListedRelays::new(Some(list.clone()), Kept::Read(private(&[&kept, &twice])));
669        assert_eq!(search.relays(), [open.clone(), twice.clone(), kept.clone()]);
670        assert_eq!(search.list(), Some(&list));
671        assert!(ListedRelays::default().relays().is_empty());
672        // What is kept private is not in what is printed.
673        assert!(!format!("{search:?}").contains("kept"));
674
675        // What was not read, or could not be, shows what anyone can read,
676        // and is not written from.
677        for unread in [Kept::Unread, Kept::Unreadable(SignError::Cipher("no".to_string()))] {
678            let closed = ListedRelays::new(Some(list.clone()), unread);
679            assert_eq!(closed.relays(), [open.clone(), twice.clone()]);
680            assert!(closed.changed(Section::Search, &[open.clone()]).is_none());
681        }
682
683        let lists = RelayLists { advertised: None, listed: [(Section::Search, search.clone())].into() };
684        assert_eq!(lists.sets().of(Section::Search), search.relays());
685        assert_eq!(lists.of(Section::Blocked), ListedRelays::default());
686    }
687
688    #[test]
689    fn a_listed_relay_stays_where_it_was_and_a_new_one_goes_where_the_list_keeps_them() {
690        let (open, kept, new) = (relay("open"), relay("kept"), relay("new"));
691        let other = vec!["t".to_string(), "nostr".to_string()];
692        let said = |tags: &[Tag]| -> Vec<Vec<String>> { tags.iter().map(|tag| tag.as_slice().to_vec()).collect() };
693
694        // A list that keeps relays to itself, as Amethyst writes one.
695        let list = a_list(Kind::SearchRelays, vec![tag(&["client", "Amethyst"]), tag(&["relay", open.as_str()])], "x", 100);
696        let mut kept_private = private(&[&kept]);
697        kept_private.push(other.clone());
698        let search = ListedRelays::new(Some(list), Kept::Read(kept_private));
699        assert!(search.changed(Section::Search, &[open.clone(), kept.clone()]).is_none(), "as it is");
700
701        let (tags, private_tags) = search.changed(Section::Search, &[open.clone(), kept.clone(), new.clone()]).unwrap();
702        assert_eq!(said(&tags), [vec!["client", "Amethyst"], vec!["relay", open.as_str()]]);
703        assert_eq!(private_tags, [other.clone(), private(&[&kept])[0].clone(), private(&[&new])[0].clone()]);
704        // The new one before the old: that is the order it is kept in.
705        let (_, private_tags) = search.changed(Section::Search, &[new.clone(), open.clone(), kept.clone()]).unwrap();
706        assert_eq!(private_tags, [other.clone(), private(&[&new])[0].clone(), private(&[&kept])[0].clone()]);
707
708        // Taking the private one out leaves what else is kept private.
709        let (tags, private_tags) = search.changed(Section::Search, &[open.clone()]).unwrap();
710        assert_eq!(tags.len(), 2);
711        assert_eq!(private_tags, [other]);
712
713        // A list with public relays alone gets the new one in public.
714        let public = a_list(Kind::SearchRelays, vec![tag(&["relay", open.as_str()])], "", 100);
715        let public = ListedRelays::new(Some(public), Kept::Read(vec![]));
716        let (tags, private_tags) = public.changed(Section::Search, &[open.clone(), new.clone()]).unwrap();
717        assert_eq!(tags.len(), 2);
718        assert!(private_tags.is_empty());
719
720        // A list with no relays at all keeps a new one to itself.
721        let empty = ListedRelays::new(Some(a_list(Kind::SearchRelays, vec![], "", 100)), Kept::Read(vec![]));
722        let (tags, private_tags) = empty.changed(Section::Search, &[new.clone()]).unwrap();
723        assert!(tags.is_empty());
724        assert_eq!(private_tags, private(&[&new]));
725        assert!(ListedRelays::default().changed(Section::Search, &[]).is_none());
726    }
727
728    #[test]
729    fn a_first_list_says_its_relays_or_keeps_them_as_its_kind_does() {
730        let new = relay("new");
731        let none = ListedRelays::default();
732        // Search relays and where messages go are for anyone to read.
733        for section in [Section::Search, Section::Messages] {
734            let (tags, private_tags) = none.changed(section, &[new.clone()]).unwrap();
735            assert_eq!(tags, [tag(&["relay", new.as_str()])], "{section:?}");
736            assert!(private_tags.is_empty());
737        }
738        // The others are kept private.
739        for section in [Section::Indexer, Section::Trusted, Section::Blocked] {
740            let (tags, private_tags) = none.changed(section, &[new.clone()]).unwrap();
741            assert!(tags.is_empty(), "{section:?}");
742            assert_eq!(private_tags, private(&[&new]));
743        }
744        // Where messages go is said to anyone even by a list that says nothing yet.
745        let empty = ListedRelays::new(Some(a_list(Kind::InboxRelays, vec![], "", 100)), Kept::Read(vec![]));
746        let (tags, private_tags) = empty.changed(Section::Messages, &[new.clone()]).unwrap();
747        assert_eq!(tags.len(), 1);
748        assert!(private_tags.is_empty());
749
750        assert_eq!(Section::Blocked.kind().as_u16(), 10006);
751        assert_eq!(Section::Search.kind().as_u16(), 10007);
752        // The list of private relays is nobody's to read or write here.
753        assert!(Section::ALL.iter().all(|section| section.kind().as_u16() != 10013));
754        assert_eq!(Section::Messages.kind().as_u16(), 10050);
755        assert_eq!(Section::Indexer.kind().as_u16(), 10086);
756        assert_eq!(Section::Trusted.kind().as_u16(), 10089);
757        let ahead = a_list(Kind::SearchRelays, vec![], "", 500);
758        let written = listed(Section::Blocked, Some(&ahead), vec![], String::new(), Timestamp::from_secs(200));
759        let written = written.finalize(&Keys::generate()).unwrap();
760        assert_eq!((written.kind.as_u16(), written.created_at.as_secs()), (10006, 501));
761    }
762}