Skip to main content

cosmic_applet_avestruz/nostr/
outbox.rs

1// SPDX-License-Identifier: MIT
2
3//! Where people's events are: their relay lists (NIP-65), and which of the
4//! relays those name are worth asking.
5//!
6//! Someone's relay list (kind 10002) says where they write, which is where
7//! their notes are to be read, and where they read, which is where what is
8//! meant for them is to be sent. Reading the people an account follows from
9//! the relays they write to, rather than from the account's own alone, is
10//! what finds the notes of those who write elsewhere (the outbox model).
11//!
12//! Everyone names several relays and everyone's differ, so asking all of
13//! them would be a connection to half the network. [`plan`] picks few: the
14//! relays that between them have the most people, so many for each person
15//! and so many in all, counting the account's own relays, which are asked
16//! anyway, as the ones they are.
17//!
18//! What a relay list names is somebody else's word, as is the relay the
19//! address of a note names, and is not connected to without a look: see
20//! [`public`].
21//!
22//! ```mermaid
23//! flowchart TD
24//!     start["Everyone is short of so many relays, less those of the account's own they list"] --> best["Of the relays not yet taken: which helps the most people who are still short?"]
25//!     best --> any{"Does any help anyone?"}
26//!     any -->|"no"| done["Done"]
27//!     any -->|"yes"| take["Take it. Everyone who lists it is short of one fewer"]
28//!     take --> cap{"As many taken as may be?"}
29//!     cap -->|"yes"| done
30//!     cap -->|"no"| best
31//! ```
32//!
33//! A worked example of a plan, and the rest of what is decided about
34//! relays, is in [`crate::guide::relays`].
35
36use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
37use std::time::Duration;
38
39use nostr_sdk::prelude::{Event, PublicKey, RelayMetadata, RelayUrl, RelayUrlScheme, nip65};
40
41/// Which of the relays someone lists are meant.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Listed {
44    /// Those they write to: where their own events are.
45    Write,
46    /// Those they read: where events meant for them are sent, and so are.
47    Read,
48    /// Both: where a conversation of theirs is, their side of it and the
49    /// others'.
50    Either,
51}
52
53/// What is known of where a note is, beside that it may be on the
54/// account's own relays: what whoever named the note said of it.
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct Whereabouts {
57    /// Who wrote it: it is on the relays they write to.
58    pub author: Option<PublicKey>,
59    /// A relay said to have it.
60    pub relay: Option<RelayUrl>,
61}
62
63/// The relays the relay list `list` names for `listed`, each once, in the
64/// list's order. A relay named without saying which it is for is for both.
65pub fn relays(list: &Event, listed: Listed) -> Vec<RelayUrl> {
66    let mut seen = HashSet::new();
67    nip65::extract_relay_list(list)
68        .filter(|(_, marked)| match (listed, marked) {
69            (Listed::Either, _) | (_, None) => true,
70            (Listed::Write, Some(marked)) => *marked == RelayMetadata::Write,
71            (Listed::Read, Some(marked)) => *marked == RelayMetadata::Read,
72        })
73        .map(|(relay, _)| relay)
74        .filter(|relay| seen.insert(relay.clone()))
75        .collect()
76}
77
78/// Whether `relay`, which somebody else names (in their relay list, or in
79/// the address of a note), is one to connect to: on the open internet, and
80/// encrypted.
81///
82/// Not a relay on this machine or this network, which a list could name to
83/// have its readers knock on doors at home; not one without encryption,
84/// which shows whoever is on the way what is asked; and not an onion
85/// service, which is not reached from here.
86pub fn public(relay: &RelayUrl) -> bool {
87    relay.scheme() == RelayUrlScheme::Wss && !relay.is_localhost() && !relay.is_local_addr() && !relay.is_onion()
88}
89
90/// The relays to ask about the people in `listed`, beside the account's
91/// own, and whom to ask each about: a relay is asked about everyone who
92/// lists it.
93///
94/// `listed` is, for each person, the relays their events are on. Each
95/// person is to be had from `per_person` relays, of which those in `home`,
96/// the account's own, count: they are asked about everyone as it is. The
97/// relay that helps the most people who are still short is taken first
98/// (of several that help as many, the one more people list), then the
99/// next, until nobody is short or `cap` relays are taken. A relay in
100/// `avoid` is never taken.
101///
102/// The same people and lists always give the same relays, in the same
103/// order.
104pub fn plan(
105    listed: &HashMap<PublicKey, Vec<RelayUrl>>,
106    home: &HashSet<RelayUrl>,
107    avoid: &HashSet<RelayUrl>,
108    per_person: usize,
109    cap: usize,
110) -> Vec<(RelayUrl, Vec<PublicKey>)> {
111    // Who lists each relay that could be taken, and how many relays each
112    // person is still short of. Ordered, so that ties fall the same way
113    // every time.
114    let mut listing: BTreeMap<&RelayUrl, BTreeSet<PublicKey>> = BTreeMap::new();
115    let mut short: HashMap<PublicKey, usize> = HashMap::new();
116    for (person, relays) in listed {
117        let at_home = relays.iter().filter(|relay| home.contains(relay)).count();
118        short.insert(*person, per_person.saturating_sub(at_home));
119        for relay in relays.iter().filter(|relay| !home.contains(relay) && !avoid.contains(relay)) {
120            listing.entry(relay).or_default().insert(*person);
121        }
122    }
123
124    let mut taken = Vec::new();
125    while taken.len() < cap {
126        let helps = |people: &BTreeSet<PublicKey>| {
127            people.iter().filter(|person| short.get(person).is_some_and(|short| *short > 0)).count()
128        };
129        // The relay that helps the most people; of several that do, the
130        // one the most people list, and of those the first.
131        let worth = listing.iter().map(|(relay, people)| ((helps(people), people.len()), *relay));
132        let best =
133            worth.filter(|((helped, _), _)| *helped > 0).fold(
134                None,
135                |best: Option<((usize, usize), &RelayUrl)>, found| match best {
136                    Some(best) if best.0 >= found.0 => Some(best),
137                    _ => Some(found),
138                },
139            );
140        let Some((_, relay)) = best else {
141            break;
142        };
143        let people = listing.remove(relay).unwrap_or_default();
144        for person in &people {
145            if let Some(short) = short.get_mut(person) {
146                *short = short.saturating_sub(1);
147            }
148        }
149        taken.push((relay.clone(), people.into_iter().collect()));
150    }
151    taken
152}
153
154/// Which of the relays in the pool of other people's to take out of it.
155/// `pooled` is each with how long it has gone unused. Those unused for
156/// `keep` or longer go; and if more than `cap` are left, the ones used
157/// longest ago go too, but none used within `busy`, which may be in the
158/// middle of answering.
159pub fn to_let_go(mut pooled: Vec<(Duration, RelayUrl)>, cap: usize, keep: Duration, busy: Duration) -> Vec<RelayUrl> {
160    // The one used last first: those are the ones kept.
161    pooled.sort();
162    pooled
163        .into_iter()
164        .enumerate()
165        .filter(|(place, (unused, _))| *unused >= keep || (*place >= cap && *unused >= busy))
166        .map(|(_, (_, relay))| relay)
167        .collect()
168}
169
170#[cfg(test)]
171mod tests {
172    use super::{Listed, plan, public, relays, to_let_go};
173    use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, Kind, PublicKey, RelayUrl, Tag};
174    use std::collections::{HashMap, HashSet};
175    use std::time::Duration;
176
177    fn relay(name: &str) -> RelayUrl {
178        RelayUrl::parse(&format!("wss://{name}.example.com")).unwrap()
179    }
180
181    fn people(count: usize) -> Vec<PublicKey> {
182        let mut people: Vec<PublicKey> = (0..count).map(|_| Keys::generate().public_key()).collect();
183        people.sort();
184        people
185    }
186
187    fn list(tags: &[&[&str]]) -> Event {
188        EventBuilder::new(Kind::RelayList, "")
189            .tags(tags.iter().map(|tag| Tag::parse(tag.iter().copied()).unwrap()))
190            .finalize(&Keys::generate())
191            .unwrap()
192    }
193
194    fn names(relays: &[RelayUrl]) -> Vec<&str> {
195        relays.iter().map(RelayUrl::as_str_without_trailing_slash).collect()
196    }
197
198    #[test]
199    fn a_relay_list_says_where_someone_writes_and_where_they_read() {
200        let named = list(&[
201            &["r", "wss://both.example.com"],
202            &["r", "wss://out.example.com/", "write"],
203            &["r", "wss://in.example.com", "read"],
204            // Named twice, not a relay, and not a relay tag at all.
205            &["r", "wss://both.example.com/"],
206            &["r", "https://example.com"],
207            &["p", "wss://other.example.com"],
208        ]);
209        assert_eq!(names(&relays(&named, Listed::Write)), ["wss://both.example.com", "wss://out.example.com"]);
210        assert_eq!(names(&relays(&named, Listed::Read)), ["wss://both.example.com", "wss://in.example.com"]);
211        assert_eq!(
212            names(&relays(&named, Listed::Either)),
213            ["wss://both.example.com", "wss://out.example.com", "wss://in.example.com"]
214        );
215        assert!(relays(&list(&[]), Listed::Either).is_empty());
216    }
217
218    #[test]
219    fn only_an_encrypted_relay_on_the_open_internet_is_connected_to_on_somebody_elses_word() {
220        for open in ["wss://relay.example.com", "wss://relay.example.com:4443/path", "wss://8.8.8.8"] {
221            assert!(public(&RelayUrl::parse(open).unwrap()), "{open}");
222        }
223        for closed in [
224            "ws://relay.example.com",
225            "wss://localhost",
226            "wss://127.0.0.1:7777",
227            "ws://127.0.0.1:7777",
228            "wss://192.168.1.1",
229            "wss://10.0.0.7:8080",
230            "wss://[::1]",
231            "wss://abcdefghijklmnop.onion",
232        ] {
233            assert!(!public(&RelayUrl::parse(closed).unwrap()), "{closed}");
234        }
235    }
236
237    #[test]
238    fn the_relays_that_have_the_most_people_are_taken_first() {
239        let people = people(6);
240        let (big, small, lone) = (relay("big"), relay("small"), relay("lone"));
241        let mut listed: HashMap<PublicKey, Vec<RelayUrl>> = HashMap::new();
242        for person in &people[..4] {
243            listed.insert(*person, vec![big.clone()]);
244        }
245        listed.insert(people[4], vec![small.clone(), big.clone()]);
246        listed.insert(people[5], vec![small.clone(), lone.clone()]);
247        let (home, avoid) = (HashSet::new(), HashSet::new());
248
249        // One relay each: the big one has five, and the small one the last.
250        let taken = plan(&listed, &home, &avoid, 1, 10);
251        assert_eq!(taken.len(), 2);
252        assert_eq!(taken[0], (big.clone(), people[..5].to_vec()), "asked about everyone who lists it");
253        assert_eq!(taken[1], (small.clone(), people[4..].to_vec()));
254
255        // Two each, for those who list two.
256        let taken = plan(&listed, &home, &avoid, 2, 10);
257        assert_eq!(taken.iter().map(|(relay, _)| relay).collect::<Vec<_>>(), [&big, &small, &lone]);
258
259        // No more relays than may be had, and the ones that help most.
260        assert_eq!(plan(&listed, &home, &avoid, 2, 1), [(big.clone(), people[..5].to_vec())]);
261        assert!(plan(&listed, &home, &avoid, 2, 0).is_empty());
262        assert_eq!(plan(&listed, &home, &avoid, 2, 10), plan(&listed, &home, &avoid, 2, 10), "the same every time");
263    }
264
265    /// The example [`crate::guide::relays`] works through, so that the
266    /// guide can't say one thing and the plan do another.
267    #[test]
268    fn the_plan_the_guide_works_through_is_the_plan_that_is_made() {
269        let [ana, bia, caio, davi, eva] = people(5)[..] else {
270            unreachable!("five people were asked for");
271        };
272        let [h, a, b, c, d, e, f] = ["h", "a", "b", "c", "d", "e", "f"].map(relay);
273        let listed = HashMap::from([
274            (ana, vec![h.clone(), a.clone()]),
275            (bia, vec![a.clone(), b.clone()]),
276            (caio, vec![a.clone(), c.clone()]),
277            (davi, vec![b.clone(), d.clone()]),
278            (eva, vec![h.clone(), e.clone(), f.clone()]),
279        ]);
280        let home = HashSet::from([h]);
281
282        let taken = plan(&listed, &home, &HashSet::new(), 2, 20);
283        let expected = [(a, vec![ana, bia, caio]), (b, vec![bia, davi]), (c, vec![caio]), (d, vec![davi]), (e, vec![eva])];
284        assert_eq!(taken, expected, "f is not taken: Eva has her two");
285    }
286
287    #[test]
288    fn relays_long_unused_are_let_go_of_and_the_least_used_when_there_are_too_many() {
289        let unused = |minutes: u64, name: &str| (Duration::from_secs(60 * minutes), relay(name));
290        let (keep, busy) = (Duration::from_secs(15 * 60), Duration::from_secs(60));
291        let pooled = vec![unused(20, "stale"), unused(0, "now"), unused(5, "lately"), unused(9, "a-while")];
292
293        // Room for all: only the one unused for too long goes.
294        assert_eq!(to_let_go(pooled.clone(), 20, keep, busy), [relay("stale")]);
295        // Room for two: the two used last stay.
296        assert_eq!(to_let_go(pooled.clone(), 2, keep, busy), [relay("a-while"), relay("stale")]);
297        // Room for none, and still the one in use stays.
298        assert_eq!(to_let_go(pooled, 0, keep, busy), [relay("lately"), relay("a-while"), relay("stale")]);
299        assert!(to_let_go(Vec::new(), 0, keep, busy).is_empty());
300    }
301
302    #[test]
303    fn the_accounts_own_relays_count_and_are_not_taken_again() {
304        let people = people(3);
305        let (mine, theirs, other) = (relay("mine"), relay("theirs"), relay("other"));
306        let listed = HashMap::from([
307            // On one of mine and one of theirs: short of one, of two.
308            (people[0], vec![mine.clone(), theirs.clone()]),
309            // On mine alone: nothing to add.
310            (people[1], vec![mine.clone()]),
311            // On none of mine.
312            (people[2], vec![other.clone(), theirs.clone()]),
313        ]);
314        let home = HashSet::from([mine.clone()]);
315
316        let taken = plan(&listed, &home, &HashSet::new(), 2, 10);
317        assert_eq!(taken, [(theirs.clone(), vec![people[0], people[2]]), (other.clone(), vec![people[2]])]);
318        // With one relay each, whoever is on mine is had already.
319        assert_eq!(plan(&listed, &home, &HashSet::new(), 1, 10), [(theirs.clone(), vec![people[0], people[2]])]);
320
321        // A relay to avoid is passed over, and another takes its people
322        // if another has them.
323        let avoid = HashSet::from([theirs]);
324        assert_eq!(plan(&listed, &home, &avoid, 2, 10), [(other, vec![people[2]])]);
325        // Nobody listed, nothing to ask.
326        assert!(plan(&HashMap::new(), &home, &avoid, 2, 10).is_empty());
327    }
328}