Skip to main content

cosmic_applet_avestruz/nostr/
trust.rs

1// SPDX-License-Identifier: MIT
2
3//! Who is in the account's network, as a provider of trust scores says
4//! (NIP-85).
5//!
6//! An account may name, in a list of its own (kind 10040), somebody who
7//! works out how far it can trust other people: a *provider*, and the
8//! relay the provider keeps its answers on. An answer is a card (kind
9//! 30382) the provider signs about one person, for this account, with
10//! their rank from 0 to 100 on it. The account's network is then itself,
11//! those it follows, and whoever the provider ranks at
12//! [`MIN_RANK`] or higher. Somebody the provider has no card for is
13//! outside it.
14//!
15//! Nothing here is built in: with no such list, there is no network, and
16//! nothing is told apart by it. Which provider to trust, and with whose
17//! notes, is the account's to say.
18//!
19//! A card is asked for when there is a use for it, about the people a
20//! conversation on show is among and those who wrote to the account,
21//! and kept in the event store with
22//! everything else the relays sent. A person asked about once is not
23//! asked about again while Avestruz runs.
24//!
25//! That the provider had *no* card for somebody is no event, and the
26//! store can't keep it: it is kept beside it ([`Unranked`]), so that
27//! whoever was outside the network the last time is outside it at once
28//! the next time Avestruz runs, and not only when the provider's relay
29//! has answered again. It is asked again all the same, once each run,
30//! the first time they turn up: a provider may come to rank somebody.
31//! What was not asked about for [`UNRANKED_KEPT_DAYS`] days is let go of.
32//!
33//! ```mermaid
34//! flowchart TD
35//!     person["Somebody who wrote in a conversation"] --> own{"The account itself, or somebody it follows?"}
36//!     own -->|"yes"| inside["In the network"]
37//!     own -->|"no"| asked{"Did the provider's relay answer about them?"}
38//!     asked -->|"not yet, or it did not answer"| before{"Did it have no card for them, the last time it was asked?"}
39//!     before -->|"yes"| outside
40//!     before -->|"no"| unknown["Not known: nothing is made of it"]
41//!     asked -->|"yes"| card{"Is there a card, with a rank of 5 or more?"}
42//!     card -->|"yes"| inside
43//!     card -->|"no"| outside["Outside the network"]
44//! ```
45//!
46//! What is made of it is in [`crate::nostr::thread`] and in
47//! [`crate::nostr::notifications`]: a note from outside the network
48//! starts folded, in a conversation and among what the account is told
49//! of.
50//!
51//! Only what the list says in the open is read. A provider the list
52//! names in its encrypted part is not looked for: reading it would ask
53//! the signer, which may be remote, every time Avestruz starts.
54
55use std::collections::{HashMap, HashSet};
56use std::path::{Path, PathBuf};
57
58use nostr_sdk::prelude::{Event, Filter, Kind, PublicKey, RelayUrl};
59use serde::{Deserialize, Serialize};
60
61use crate::nostr::beside_store;
62
63/// The kind of the list an account names its providers in.
64pub const PROVIDERS_KIND: Kind = Kind::Custom(10040);
65
66/// The kind of a card: what a provider says of one person.
67pub const CARD_KIND: Kind = Kind::Custom(30382);
68
69/// What a list calls the provider of ranks: the kind of its cards, and
70/// which of the things on them it is trusted for.
71const RANK_SERVICE: &str = "30382:rank";
72
73/// The lowest rank that is in the network.
74pub const MIN_RANK: u32 = 5;
75
76/// How many people one filter asks about.
77const PEOPLE_PER_FILTER: usize = 100;
78
79/// Who works out ranks for the account, and where their cards are.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Provider {
82    /// Who signs the cards.
83    pub key: PublicKey,
84    /// The relay the cards are on.
85    pub relay: RelayUrl,
86}
87
88/// The provider of ranks that `list`, an account's list of providers,
89/// names in the open: the first it names, if it names several.
90pub fn rank_provider(list: &Event) -> Option<Provider> {
91    list.tags.iter().find_map(|tag| match tag.as_slice() {
92        [service, key, relay, ..] if service == RANK_SERVICE => {
93            Some(Provider { key: PublicKey::parse(key).ok()?, relay: RelayUrl::parse(relay).ok()? })
94        }
95        _ => None,
96    })
97}
98
99/// Who `card` is about, and the rank it gives them, if it gives one.
100/// `None` of a card that is about nobody.
101pub fn rank_on(card: &Event) -> Option<(PublicKey, Option<u32>)> {
102    let field = |name: &str| {
103        card.tags.iter().find_map(|tag| match tag.as_slice() {
104            [first, value, ..] if first == name => Some(value.as_str()),
105            _ => None,
106        })
107    };
108    let subject = PublicKey::parse(field("d")?).ok()?;
109    Some((subject, field("rank").and_then(|rank| rank.parse().ok())))
110}
111
112/// The filters that ask for the cards of `provider` about `people`.
113pub fn card_filters(provider: &Provider, people: &[PublicKey]) -> Vec<Filter> {
114    people
115        .chunks(PEOPLE_PER_FILTER)
116        .map(|chunk| Filter::new().kind(CARD_KIND).author(provider.key).identifiers(chunk.iter().map(PublicKey::to_hex)))
117        .collect()
118}
119
120/// What the provider said of the people it was asked about: a rank, or
121/// that it has none for them. Of anybody else, nothing is known.
122#[derive(Debug, Clone, Default, PartialEq, Eq)]
123pub struct Ranks(HashMap<PublicKey, Option<u32>>);
124
125impl Ranks {
126    /// The provider gave `person` this rank, or has none for them.
127    pub fn set(&mut self, person: PublicKey, rank: Option<u32>) {
128        self.0.insert(person, rank);
129    }
130
131    /// Take in what `other` knows, which is newer.
132    pub fn extend(&mut self, other: Self) {
133        self.0.extend(other.0);
134    }
135
136    /// Whether the provider was asked about `person`, and answered.
137    pub fn has(&self, person: &PublicKey) -> bool {
138        self.0.contains_key(person)
139    }
140
141    /// Whether the provider was asked about `person` and gave them no
142    /// rank: it has no card for them, or one that says nothing of it.
143    pub fn unranked(&self, person: &PublicKey) -> bool {
144        self.0.get(person).is_some_and(Option::is_none)
145    }
146
147    /// Whether the provider ranks `person` high enough to be in the
148    /// network. `None` if it was not asked about them.
149    pub fn in_network(&self, person: &PublicKey) -> Option<bool> {
150        self.0.get(person).map(|rank| rank.is_some_and(|rank| rank >= MIN_RANK))
151    }
152
153    /// How many of those it was asked about it does not rank high
154    /// enough to be in the network.
155    pub fn outside(&self) -> usize {
156        self.0.values().filter(|rank| rank.is_none_or(|rank| rank < MIN_RANK)).count()
157    }
158
159    /// How many people it was asked about.
160    pub fn len(&self) -> usize {
161        self.0.len()
162    }
163
164    /// Whether it was asked about nobody.
165    pub fn is_empty(&self) -> bool {
166        self.0.is_empty()
167    }
168}
169
170/// The account's network, as things stand: who it is, who it follows,
171/// and what its provider said, if it has one.
172#[derive(Debug, Clone, Copy)]
173pub struct Network<'a> {
174    pub me: Option<PublicKey>,
175    pub follows: &'a HashSet<PublicKey>,
176    /// `None` with no provider: there is then no network to be outside of.
177    pub ranks: Option<&'a Ranks>,
178}
179
180impl Network<'_> {
181    /// Whether `person` is in the network: `Some(false)` only of
182    /// somebody the provider was asked about and does not rank high
183    /// enough. `None` while that is not known. With no provider,
184    /// everybody is.
185    pub fn has(&self, person: &PublicKey) -> Option<bool> {
186        let Some(ranks) = self.ranks else {
187            return Some(true);
188        };
189        if self.me == Some(*person) || self.follows.contains(person) {
190            return Some(true);
191        }
192        ranks.in_network(person)
193    }
194
195    /// Those of `people` the provider is still to be asked about, each
196    /// once: not the account, nor who it follows, nor anybody it
197    /// answered about already. Nobody, with no provider.
198    pub fn to_ask_about(&self, people: impl IntoIterator<Item = PublicKey>) -> Vec<PublicKey> {
199        let Some(ranks) = self.ranks else {
200            return Vec::new();
201        };
202        let mut seen = HashSet::new();
203        people
204            .into_iter()
205            .filter(|person| self.me != Some(*person) && !self.follows.contains(person) && !ranks.has(person))
206            .filter(|person| seen.insert(*person))
207            .collect()
208    }
209}
210
211/// For how many days it is kept that a provider had no card for
212/// somebody, counted from when it was last asked about them.
213pub const UNRANKED_KEPT_DAYS: u64 = 30;
214
215/// The file that is kept in, in the directory of the event store.
216const UNRANKED_FILE: &str = "unranked.json";
217
218/// Who each provider had no card for, and when it last said so: what
219/// the event store can't keep, there being no event that says it.
220#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
221pub struct Unranked {
222    /// By provider, and then by whom it had no card for, both as hex:
223    /// when it was last asked about them, in seconds.
224    by: HashMap<String, HashMap<String, u64>>,
225}
226
227impl Unranked {
228    /// Whether `provider` had no card for `person` when it was last
229    /// asked about them, and that is not too long before `now`.
230    pub fn has(&self, provider: &PublicKey, person: &PublicKey, now: u64) -> bool {
231        let asked = self.by.get(&provider.to_hex()).and_then(|people| people.get(&person.to_hex()));
232        asked.is_some_and(|asked| now.saturating_sub(*asked) <= UNRANKED_KEPT_DAYS * 24 * 60 * 60)
233    }
234
235    /// `provider` was asked about `person` at `now`, and had a card for
236    /// them or (`unranked`) had none.
237    pub fn set(&mut self, provider: &PublicKey, person: &PublicKey, unranked: bool, now: u64) {
238        let people = self.by.entry(provider.to_hex()).or_default();
239        if unranked {
240            people.insert(person.to_hex(), now);
241        } else {
242            people.remove(&person.to_hex());
243        }
244    }
245
246    /// Let go of what was last said too long before `now`.
247    pub fn forget_old(&mut self, now: u64) {
248        for people in self.by.values_mut() {
249            people.retain(|_, asked| now.saturating_sub(*asked) <= UNRANKED_KEPT_DAYS * 24 * 60 * 60);
250        }
251        self.by.retain(|_, people| !people.is_empty());
252    }
253
254    /// Where this is kept, for the store in `store`.
255    pub fn path_in(store: &Path) -> PathBuf {
256        store.join(UNRANKED_FILE)
257    }
258
259    /// What `path` says, less what is too old at `now`; or nothing, if
260    /// it says nothing that can be read.
261    pub async fn load(path: &Path, now: u64) -> Self {
262        let mut kept: Self = beside_store::load(path).await;
263        kept.forget_old(now);
264        kept
265    }
266
267    /// Write this to `path`, whole or not at all.
268    pub async fn save(&self, path: &Path) -> std::io::Result<()> {
269        beside_store::save(self, path).await
270    }
271}
272
273/// What the provider is asked with, about those who wrote in a
274/// conversation: who it is, and the network as it stood when the
275/// question was put together, which says who need not be asked about.
276#[derive(Debug, Clone)]
277pub struct Asking {
278    pub provider: Provider,
279    pub me: Option<PublicKey>,
280    pub follows: HashSet<PublicKey>,
281    pub ranks: Ranks,
282}
283
284impl Asking {
285    /// Those of `people` the provider is to be asked about (see
286    /// [`Network::to_ask_about`]).
287    pub fn about(&self, people: impl IntoIterator<Item = PublicKey>) -> Vec<PublicKey> {
288        Network { me: self.me, follows: &self.follows, ranks: Some(&self.ranks) }.to_ask_about(people)
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::{
295        Asking, CARD_KIND, MIN_RANK, Network, PROVIDERS_KIND, Provider, Ranks, UNRANKED_KEPT_DAYS, Unranked, card_filters,
296        rank_on, rank_provider,
297    };
298    use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, PublicKey, RelayUrl, Tag};
299    use std::collections::HashSet;
300
301    fn provider() -> Provider {
302        Provider { key: Keys::generate().public_key(), relay: RelayUrl::parse("wss://scores.example.com").unwrap() }
303    }
304
305    fn list(tags: &[&[&str]]) -> Event {
306        let tags = tags.iter().map(|tag| Tag::parse(tag.iter().copied()).unwrap());
307        EventBuilder::new(PROVIDERS_KIND, "").tags(tags).finalize(&Keys::generate()).unwrap()
308    }
309
310    fn card(provider: &Keys, tags: &[&[&str]]) -> Event {
311        let tags = tags.iter().map(|tag| Tag::parse(tag.iter().copied()).unwrap());
312        EventBuilder::new(CARD_KIND, "").tags(tags).finalize(provider).unwrap()
313    }
314
315    #[test]
316    fn the_provider_of_ranks_is_the_one_the_list_names_for_them() {
317        let (provider, other) = (Keys::generate().public_key().to_hex(), Keys::generate().public_key().to_hex());
318        // As a list is written: one provider for several things, and
319        // what wrote the list.
320        let named = list(&[
321            &["30382:followers", &other, "wss://other.example.com"],
322            &["30382:rank", &provider, "wss://scores.example.com"],
323            &["30382:rank", &other, "wss://other.example.com"],
324            &["client", "Something"],
325        ]);
326        let found = rank_provider(&named).unwrap();
327        assert_eq!(found.key.to_hex(), provider);
328        assert_eq!(found.relay, RelayUrl::parse("wss://scores.example.com").unwrap());
329
330        // One that names none for ranks, or names it badly, has none.
331        assert_eq!(rank_provider(&list(&[&["30382:followers", &other, "wss://other.example.com"]])), None);
332        assert_eq!(rank_provider(&list(&[&["30382:rank", &provider]])), None);
333        assert_eq!(rank_provider(&list(&[&["30382:rank", "nobody", "wss://scores.example.com"]])), None);
334        assert_eq!(rank_provider(&list(&[&["30382:rank", &provider, "not a relay"]])), None);
335        assert_eq!(rank_provider(&list(&[])), None);
336    }
337
338    #[test]
339    fn a_card_says_who_it_is_about_and_their_rank() {
340        let provider = Keys::generate();
341        let subject = Keys::generate().public_key();
342        let about = subject.to_hex();
343        let read = rank_on(&card(&provider, &[&["d", &about], &["rank", "90"], &["followers", "531"]]));
344        assert_eq!(read, Some((subject, Some(90))));
345        // A card may say other things and no rank, or a rank that is none.
346        assert_eq!(rank_on(&card(&provider, &[&["d", &about], &["followers", "3"]])), Some((subject, None)));
347        assert_eq!(rank_on(&card(&provider, &[&["d", &about], &["rank", "high"]])), Some((subject, None)));
348        assert_eq!(rank_on(&card(&provider, &[&["d", &about], &["rank", "-3"]])), Some((subject, None)));
349        // One about nobody says nothing.
350        assert_eq!(rank_on(&card(&provider, &[&["rank", "90"]])), None);
351        assert_eq!(rank_on(&card(&provider, &[&["d", "somebody"], &["rank", "90"]])), None);
352    }
353
354    #[test]
355    fn who_a_provider_had_no_card_for_is_kept_for_a_while() {
356        const DAY: u64 = 24 * 60 * 60;
357        let [provider, other, spammer, stranger] = [(); 4].map(|()| Keys::generate().public_key());
358        let mut unranked = Unranked::default();
359        let asked = 1_000 * DAY;
360        unranked.set(&provider, &spammer, true, asked);
361        assert!(unranked.has(&provider, &spammer, asked));
362        // Of nobody else, and not on another provider's word.
363        assert!(!unranked.has(&provider, &stranger, asked));
364        assert!(!unranked.has(&other, &spammer, asked));
365        // For so many days, and no longer.
366        assert!(unranked.has(&provider, &spammer, asked + UNRANKED_KEPT_DAYS * DAY));
367        assert!(!unranked.has(&provider, &spammer, asked + UNRANKED_KEPT_DAYS * DAY + 1));
368        // Asked again, it is kept from then.
369        unranked.set(&provider, &spammer, true, asked + 10 * DAY);
370        assert!(unranked.has(&provider, &spammer, asked + UNRANKED_KEPT_DAYS * DAY + 1));
371        // What is too old is let go of, and a provider with nobody left.
372        unranked.set(&other, &stranger, true, asked);
373        unranked.forget_old(asked + UNRANKED_KEPT_DAYS * DAY + 1);
374        assert_eq!(unranked.by.len(), 1);
375        assert!(unranked.has(&provider, &spammer, asked + 11 * DAY));
376        // A card turned up: they are no longer among those without one.
377        unranked.set(&provider, &spammer, false, asked + 11 * DAY);
378        assert!(!unranked.has(&provider, &spammer, asked + 11 * DAY));
379
380        // It is read back as it was written, less what is too old by then.
381        let directory = std::env::temp_dir().join(format!("avestruz-test-unranked-{}", std::process::id()));
382        let _ = std::fs::remove_dir_all(&directory);
383        std::fs::create_dir_all(&directory).unwrap();
384        let path = Unranked::path_in(&directory);
385        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
386        runtime.block_on(async {
387            assert_eq!(Unranked::load(&path, asked).await, Unranked::default());
388            let mut kept = Unranked::default();
389            kept.set(&provider, &spammer, true, asked);
390            kept.set(&provider, &stranger, true, asked + 20 * DAY);
391            kept.save(&path).await.unwrap();
392            assert_eq!(Unranked::load(&path, asked + 20 * DAY).await, kept);
393            let later = Unranked::load(&path, asked + 40 * DAY).await;
394            assert!(!later.has(&provider, &spammer, asked + 40 * DAY) && later.has(&provider, &stranger, asked + 40 * DAY));
395            assert_eq!(later.by.values().map(|people| people.len()).sum::<usize>(), 1);
396        });
397        let _ = std::fs::remove_dir_all(&directory);
398    }
399
400    #[test]
401    fn cards_are_asked_of_the_provider_about_so_many_people_at_a_time() {
402        let provider = provider();
403        let people: Vec<PublicKey> = (0..150).map(|_| Keys::generate().public_key()).collect();
404        let filters = card_filters(&provider, &people);
405        assert_eq!(filters.len(), 2);
406        let about = card(&Keys::generate(), &[&["d", &people[0].to_hex()], &["rank", "9"]]);
407        // Only the provider's own cards are asked for.
408        assert!(!filters[0].match_event(&about, Default::default()));
409        assert!(card_filters(&provider, &[]).is_empty());
410    }
411
412    #[test]
413    fn the_network_is_the_account_who_it_follows_and_who_is_ranked_high_enough() {
414        let [me, friend, ranked, low, unranked, stranger] = [(); 6].map(|()| Keys::generate().public_key());
415        let follows: HashSet<PublicKey> = [friend].into();
416        let mut ranks = Ranks::default();
417        ranks.set(ranked, Some(MIN_RANK));
418        ranks.set(low, Some(MIN_RANK - 1));
419        ranks.set(unranked, None);
420        // Somebody followed is in it whatever the provider says.
421        ranks.set(friend, None);
422        let network = Network { me: Some(me), follows: &follows, ranks: Some(&ranks) };
423
424        assert_eq!(network.has(&me), Some(true));
425        assert_eq!(network.has(&friend), Some(true));
426        assert_eq!(network.has(&ranked), Some(true));
427        assert_eq!(network.has(&low), Some(false));
428        assert_eq!(network.has(&unranked), Some(false));
429        assert_eq!(network.has(&stranger), None, "not asked about yet");
430        // Only who nothing is known of is asked about, each once.
431        assert_eq!(network.to_ask_about([me, stranger, friend, ranked, stranger, low]), [stranger]);
432
433        // With no provider there is no outside, and nobody to ask about.
434        let none = Network { me: Some(me), follows: &follows, ranks: None };
435        assert_eq!(none.has(&stranger), Some(true));
436        assert!(none.to_ask_about([stranger]).is_empty());
437
438        // What is known later replaces what was known.
439        let mut newer = Ranks::default();
440        newer.set(low, Some(50));
441        ranks.extend(newer);
442        assert_eq!((ranks.in_network(&low), ranks.len(), ranks.is_empty()), (Some(true), 4, false));
443        // The friend the provider has no card for, and the one unranked.
444        assert_eq!(ranks.outside(), 2);
445        assert!(ranks.unranked(&unranked) && !ranks.unranked(&low) && !ranks.unranked(&stranger));
446
447        // A question put together from the same is about the same people.
448        let asking = Asking { provider: provider(), me: Some(me), follows, ranks };
449        assert_eq!(asking.about([me, stranger, friend, ranked, stranger]), [stranger]);
450    }
451}