Skip to main content

cosmic_applet_avestruz/nostr/
search.rs

1// SPDX-License-Identifier: MIT
2
3//! Searching for people and notes (NIP-50): what is asked of the relays
4//! that search, and what is made of their answers.
5//!
6//! A search is a filter with the words in its `search` field, which only
7//! some relays answer: the account's search relays (see
8//! [`crate::nostr::relay_lists`]). Each sends what it found with the best
9//! match first, as NIP-50 has it, and that order is all that says how
10//! good a match is: the answers of several relays are taken a rank at a
11//! time, the best of each first.
12//!
13//! What is typed may also name a person or a note outright, by its
14//! address (NIP-19). That is no search: it is opened, and no relay is
15//! told what was typed. A name at a domain (NIP-05) is asked of its
16//! domain, and the address of a relay shows what that relay has. And a
17//! secret key is none of these: it is sent nowhere.
18
19use std::collections::HashSet;
20
21use nostr_sdk::prelude::{Event, EventId, Filter, FromBech32, Kind, Nip19, PublicKey, RelayUrl};
22
23use crate::nostr::models::{Note, Profile};
24use crate::nostr::nip05;
25use crate::nostr::outbox::Whereabouts;
26use crate::nostr::relay_lists::typed_relay;
27
28/// How many people, and how many notes, one search asks each relay for.
29const PEOPLE_LIMIT: usize = 30;
30const NOTES_LIMIT: usize = 50;
31
32/// What is searched for.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
34pub enum SearchFor {
35    /// People, by what their profile says.
36    #[default]
37    People,
38    /// Notes, by what they say.
39    Notes,
40}
41
42/// What a search found, the best match first.
43#[derive(Debug, Clone)]
44pub enum Found {
45    /// People, each with their profile.
46    People(Vec<(PublicKey, Profile)>),
47    /// Notes, each as a row shows it.
48    Notes(Vec<Note>),
49}
50
51impl Found {
52    /// What this is the answer to a search for.
53    pub fn what(&self) -> SearchFor {
54        match self {
55            Self::People(_) => SearchFor::People,
56            Self::Notes(_) => SearchFor::Notes,
57        }
58    }
59}
60
61/// What the words typed are: words to search for, or something else.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum Typed {
64    /// Nothing at all.
65    Nothing,
66    /// Words to search for.
67    Words(String),
68    /// The address of a person: an `npub` or an `nprofile`.
69    Person(PublicKey),
70    /// The address of a note, and where it says the note is: a `note` or
71    /// an `nevent`.
72    Note(EventId, Whereabouts),
73    /// A name at a domain (NIP-05), in lower case: whose it is is for
74    /// the domain to say.
75    Name(String),
76    /// The address of a relay, said in full: `wss://…`.
77    Relay(RelayUrl),
78    /// A secret: a key, or what leads to one. Not something to send to a
79    /// relay.
80    Secret,
81}
82
83/// What `typed` is: an address, with or without `nostr:` before it, a
84/// secret (a key, or the address of a remote signer), the address of a
85/// relay, a name at a domain, or words.
86pub fn typed(typed: &str) -> Typed {
87    let words = typed.trim();
88    if words.is_empty() {
89        return Typed::Nothing;
90    }
91    let address = words.strip_prefix("nostr:").unwrap_or(words);
92    // A key that is mistyped is still a key: nothing that starts as one
93    // is searched for.
94    // Nor is the address of a remote signer, which has its secret in it.
95    if ["nsec1", "ncryptsec1", "bunker://"].iter().any(|secret| address.starts_with(secret)) {
96        return Typed::Secret;
97    }
98    match Nip19::from_bech32(address) {
99        Ok(Nip19::Pubkey(person)) => Typed::Person(person),
100        Ok(Nip19::Profile(profile)) => Typed::Person(profile.public_key),
101        Ok(Nip19::EventId(note)) => Typed::Note(note, Whereabouts::default()),
102        Ok(Nip19::Event(note)) => {
103            Typed::Note(note.event_id, Whereabouts { author: note.author, relay: note.relays.into_iter().next() })
104        }
105        Ok(Nip19::Secret(_)) => Typed::Secret,
106        Ok(Nip19::Coordinate(_)) | Err(_) => named(words),
107    }
108}
109
110/// What `words`, which are no address of a person or a note, are: the
111/// address of a relay, when they start as one; a name at a domain; or
112/// words to search for.
113fn named(words: &str) -> Typed {
114    let relay = ["wss://", "ws://"].iter().any(|scheme| words.starts_with(scheme)).then(|| typed_relay(words)).flatten();
115    match relay {
116        Some(relay) => Typed::Relay(relay),
117        None if nip05::is_name(words) => Typed::Name(words.to_lowercase()),
118        None => Typed::Words(words.to_string()),
119    }
120}
121
122/// The filter that asks a relay for the notes it got last: what it has,
123/// for whoever wants to see what a relay is like.
124pub fn latest_notes() -> Filter {
125    Filter::new().kinds([Kind::TextNote, Kind::Comment]).limit(NOTES_LIMIT)
126}
127
128/// The filter that asks a relay that searches for what `words` find of
129/// `what`.
130pub fn filter(words: &str, what: SearchFor) -> Filter {
131    match what {
132        SearchFor::People => Filter::new().kind(Kind::Metadata).search(words).limit(PEOPLE_LIMIT),
133        SearchFor::Notes => Filter::new().kinds([Kind::TextNote, Kind::Comment]).search(words).limit(NOTES_LIMIT),
134    }
135}
136
137/// The answers of several relays as one: `answers` is what each relay
138/// sent, the best match first, and the result takes the best of each,
139/// then the second of each, and so on, every event once, as it first
140/// came.
141pub fn ranked(answers: Vec<Vec<Event>>) -> Vec<Event> {
142    let longest = answers.iter().map(Vec::len).max().unwrap_or(0);
143    let mut answers: Vec<_> = answers.into_iter().map(Vec::into_iter).collect();
144    let mut seen = HashSet::new();
145    let mut ranked = Vec::new();
146    for _ in 0..longest {
147        for answer in &mut answers {
148            if let Some(event) = answer.next()
149                && seen.insert(event.id)
150            {
151                ranked.push(event);
152            }
153        }
154    }
155    ranked
156}
157
158/// `people`, with those of them in `followed` first, and otherwise in the
159/// order they were in. A relay ranks by what a profile says, which anyone
160/// can say: the people an account follows are the ones it meant, when a
161/// name is theirs and others' too.
162pub fn followed_first(mut people: Vec<PublicKey>, followed: &HashSet<PublicKey>) -> Vec<PublicKey> {
163    people.sort_by_key(|person| !followed.contains(person));
164    people
165}
166
167#[cfg(test)]
168mod tests {
169    use super::{SearchFor, Typed, filter, followed_first, ranked, typed};
170    use crate::nostr::outbox::Whereabouts;
171    use nostr_sdk::prelude::{
172        Event, EventBuilder, EventId, FinalizeEvent, Keys, Kind, Nip19Event, Nip19Profile, RelayUrl, ToBech32,
173    };
174    use std::collections::HashSet;
175
176    #[test]
177    fn an_address_is_opened_and_a_secret_key_goes_nowhere() {
178        let keys = Keys::generate();
179        let person = keys.public_key();
180        let note = EventId::from_byte_array([7; 32]);
181        let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
182
183        assert_eq!(typed("  "), Typed::Nothing);
184        assert_eq!(typed(" tokens for friends "), Typed::Words("tokens for friends".to_string()));
185        assert_eq!(typed(&person.to_bech32().unwrap()), Typed::Person(person));
186        let nprofile = Nip19Profile::new(person, [relay.clone()]).to_bech32().unwrap();
187        assert_eq!(typed(&format!("nostr:{nprofile}")), Typed::Person(person));
188        assert_eq!(typed(&note.to_bech32().unwrap()), Typed::Note(note, Whereabouts::default()));
189        let nevent = Nip19Event::new(note).author(person).relays([relay.clone()]).to_bech32().unwrap();
190        assert_eq!(typed(&nevent), Typed::Note(note, Whereabouts { author: Some(person), relay: Some(relay) }));
191
192        // A secret key, whole or mistyped, is not words to search for.
193        let nsec = keys.secret_key().to_bech32().unwrap();
194        assert_eq!(typed(&nsec), Typed::Secret);
195        assert_eq!(typed(&nsec[..20]), Typed::Secret);
196        assert_eq!(
197            typed(
198                "ncryptsec1qgg9947rlpvqu76pj5ecreduf9jxhselq2nae2kghhvd5g7dgjtcxfqtd67p9m0w57lspw8gsq6yphnm8623nsl8xn9j4jdzz84zm3frztj3z7s35vpzmqf6ksu8r89qk5z2zxfmu5gv8th8wclt0h4p"
199            ),
200            Typed::Secret
201        );
202        assert_eq!(typed("bunker://abcdef?relay=wss://relay.example.com&secret=hush"), Typed::Secret);
203        // A relay said in full is a relay, and a name at a domain a name.
204        assert_eq!(typed("wss://relay.example.com"), Typed::Relay(RelayUrl::parse("wss://relay.example.com").unwrap()));
205        assert_eq!(typed("Ana@Example.com"), Typed::Name("ana@example.com".to_string()));
206        for words in ["relay.example.com", "wss://", "wss://two words", "ana@ example.com", "mail me @ana"] {
207            assert_eq!(typed(words), Typed::Words(words.to_string()), "{words}");
208        }
209        // What only looks like an address is words.
210        assert_eq!(typed("npub1notakey"), Typed::Words("npub1notakey".to_string()));
211    }
212
213    #[test]
214    fn people_are_searched_by_their_profiles_and_notes_by_what_they_say() {
215        let people = filter("karnage", SearchFor::People);
216        assert_eq!(people.search.as_deref(), Some("karnage"));
217        assert_eq!(people.kinds.unwrap().into_iter().collect::<Vec<_>>(), [Kind::Metadata]);
218        let notes = filter("tokens for friends", SearchFor::Notes);
219        assert_eq!(notes.search.as_deref(), Some("tokens for friends"));
220        assert!(notes.kinds.unwrap().contains(&Kind::TextNote));
221        assert_eq!(notes.limit, Some(50));
222    }
223
224    #[test]
225    fn the_people_followed_come_before_the_others_who_go_by_the_same_name() {
226        let people: Vec<_> = (0..5).map(|_| Keys::generate().public_key()).collect();
227        let followed = HashSet::from([people[3], people[1]]);
228        assert_eq!(followed_first(people.clone(), &followed), [people[1], people[3], people[0], people[2], people[4]]);
229        assert_eq!(followed_first(people.clone(), &HashSet::new()), people);
230    }
231
232    #[test]
233    fn the_answers_of_several_relays_are_taken_a_rank_at_a_time() {
234        let keys = Keys::generate();
235        let event = |text: &str| -> Event { EventBuilder::new(Kind::TextNote, text).finalize(&keys).unwrap() };
236        let (a, b, c, d) = (event("a"), event("b"), event("c"), event("d"));
237        // The second relay's best is the first's second, and it has more.
238        let answers = vec![vec![a.clone(), b.clone()], vec![b.clone(), c.clone(), d.clone()], vec![]];
239        let ids = |events: &[Event]| events.iter().map(|event| event.id).collect::<Vec<_>>();
240        assert_eq!(ids(&ranked(answers)), [a.id, b.id, c.id, d.id]);
241        assert!(ranked(Vec::new()).is_empty());
242    }
243}