Skip to main content

cosmic_applet_avestruz/nostr/
sightings.rs

1// SPDX-License-Identifier: MIT
2
3//! Which relays a note was seen on: every relay that sent it, for as long
4//! as the applet has been running.
5//!
6//! A note comes from as many relays as have it, and is one note all the
7//! same. Which relays those were says how far it went, and where someone
8//! else can find it. The event store doesn't keep that, so it is kept
9//! here, in memory: a note read from the store has been seen nowhere until
10//! a relay sends it again.
11//!
12//! There are few relays and many notes, so each note has a bit for every
13//! relay rather than a list of them.
14
15use std::collections::HashMap;
16
17use nostr_sdk::prelude::{EventId, RelayUrl};
18
19/// How many relays can be told apart: as many as a note has bits. A relay
20/// past that many is not kept track of.
21const MAX_RELAYS: usize = u64::BITS as usize;
22
23/// Which relays each note was seen on.
24#[derive(Debug, Default)]
25pub struct Sightings {
26    /// The relays anything was seen on, in the order they first sent
27    /// something: a relay's place here is its bit in `seen`.
28    relays: Vec<RelayUrl>,
29    seen: HashMap<EventId, u64>,
30}
31
32impl Sightings {
33    /// The bit that stands for `relay`, which gets one if it has none and
34    /// there is one left.
35    fn bit(&mut self, relay: &RelayUrl) -> Option<u64> {
36        let place = match self.relays.iter().position(|known| known == relay) {
37            Some(place) => place,
38            None if self.relays.len() < MAX_RELAYS => {
39                self.relays.push(relay.clone());
40                self.relays.len() - 1
41            }
42            None => return None,
43        };
44        Some(1 << place)
45    }
46
47    /// The note `id` was sent by `relay`.
48    pub fn record(&mut self, id: EventId, relay: &RelayUrl) {
49        if let Some(bit) = self.bit(relay) {
50            *self.seen.entry(id).or_default() |= bit;
51        }
52    }
53
54    /// The relays the note `id` was seen on, in the order relays were first
55    /// heard from. None, for a note no relay sent.
56    pub fn of(&self, id: &EventId) -> Vec<RelayUrl> {
57        let seen = self.seen.get(id).copied().unwrap_or_default();
58        self.relays.iter().enumerate().filter(|(place, _)| seen & (1 << place) != 0).map(|(_, relay)| relay.clone()).collect()
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::{MAX_RELAYS, Sightings};
65    use nostr_sdk::prelude::{EventId, RelayUrl};
66
67    fn relay(name: &str) -> RelayUrl {
68        RelayUrl::parse(&format!("wss://{name}.example.com")).unwrap()
69    }
70
71    fn id(byte: u8) -> EventId {
72        EventId::from_byte_array([byte; 32])
73    }
74
75    #[test]
76    fn a_note_is_seen_on_every_relay_that_sent_it_each_once() {
77        let mut sightings = Sightings::default();
78        sightings.record(id(1), &relay("a"));
79        sightings.record(id(2), &relay("b"));
80        sightings.record(id(1), &relay("c"));
81        sightings.record(id(1), &relay("a"));
82
83        assert_eq!(sightings.of(&id(1)), [relay("a"), relay("c")]);
84        assert_eq!(sightings.of(&id(2)), [relay("b")]);
85        assert!(sightings.of(&id(3)).is_empty(), "a note no relay sent");
86    }
87
88    #[test]
89    fn relays_past_what_can_be_told_apart_are_not_kept_track_of() {
90        let mut sightings = Sightings::default();
91        for number in 0..MAX_RELAYS + 5 {
92            sightings.record(id(1), &relay(&format!("r{number}")));
93        }
94        let seen = sightings.of(&id(1));
95        assert_eq!(seen.len(), MAX_RELAYS);
96        assert_eq!(seen.last(), Some(&relay(&format!("r{}", MAX_RELAYS - 1))));
97    }
98}