Skip to main content

cosmic_applet_avestruz/nostr/
client.rs

1// SPDX-License-Identifier: MIT
2
3//! The relay client and the local event store behind it.
4//!
5//! [`NostrService`] wraps the `nostr-sdk` relay pool. Every event a relay sends
6//! is checked (signature and id) by the SDK and kept in an LMDB store, so what
7//! was seen once is there at once on the next start, before any relay answers.
8//!
9//! Each relay is asked for itself, and which of them sent a note is kept
10//! (see [`Sightings`]): the pool, asked as one, gives each event once and
11//! says no more than who was first.
12//!
13//! There are two pools. One holds the account's own relays: those the
14//! config names, and those the account's relay list (NIP-65) says it writes
15//! to. They are asked about everything, and are where what the account
16//! writes goes. The other holds other people's relays, the ones their
17//! relay lists name: asked about those people alone, for what the
18//! account's own relays may not have, and sent what is meant for them (see
19//! [`crate::nostr::outbox`]). They come and go: so many at a time, each
20//! let go of when it has not been used for a while.
21//!
22//! ```mermaid
23//! flowchart TB
24//!     subgraph service["NostrService"]
25//!         home["The home pool: the account's own relays"]
26//!         others["The pool of other people's relays"]
27//!         private["The relay it runs itself"]
28//!         store[("One event store")]
29//!     end
30//!     asked["A question"] -->|"about anyone"| home
31//!     asked -->|"about the people who list a relay"| others
32//!     written["What the account writes"] --> home
33//!     written -->|"if it names someone"| others
34//!     draft["A draft"] --> private
35//!     home --> store
36//!     others --> store
37//!     private --> store
38//!     store -->|"what is shown is read from here"| shown["The model"]
39//! ```
40//!
41//! # Finding one's way in this file
42//!
43//! It is long, and in this order:
44//!
45//! | Part | What is there |
46//! |---|---|
47//! | The constants | Every timeout and limit, each with its reason |
48//! | The types | [`Reach`], [`Source`], [`RelayUse`], and the errors: [`FetchError`], [`PublishError`], [`FollowError`], [`ListError`] |
49//! | Opening, and asking a relay | [`NostrService::open`], and the private `ask`, `fetch`, `gather` |
50//! | Other people's relays | The private `relays_of`, `reach_for`, `connect_to`, `ask_their_relays` |
51//! | The account's own relays | [`NostrService::use_relays_of`], and the config's standing down |
52//! | Events | [`NostrService::event`], [`NostrService::publish`], [`NostrService::standing`] |
53//! | Notes | [`NostrService::thread`], [`NostrService::cached_feed`], [`NostrService::fetch_feed`] |
54//! | Lists | [`NostrService::set_following`], [`NostrService::set_bookmarked`], and the private `list_to_change` they both stand on |
55//! | Drafts | [`NostrService::keep_draft`], [`NostrService::kept_drafts`] |
56//! | Searching | [`NostrService::search`] |
57//! | The account's relay lists | [`NostrService::relay_lists`], [`NostrService::set_advertised_relays`], [`NostrService::set_listed_relays`] |
58//! | Profiles | [`NostrService::cached_profiles`], [`NostrService::fetch_profiles`] |
59//! | The tests | Against relays started in the test: see [`crate::guide::testing`] |
60//!
61//! The decisions all of this carries out (which relay is asked what,
62//! whose word is taken for a relay, where what is written goes) are told
63//! in one place, with their diagrams: [`crate::guide::relays`].
64
65use std::collections::hash_map::Entry;
66use std::collections::{BTreeMap, HashMap, HashSet};
67use std::fmt;
68use std::path::PathBuf;
69use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
70use std::time::{Duration, Instant};
71
72use futures_util::StreamExt;
73use futures_util::future::{join, join_all};
74use nostr_lmdb::NostrLmdb;
75use nostr_sdk::prelude::{
76    Client, Event, EventBuilder, EventId, Filter, Kind, PublicKey, RelayStatus, RelayUrl, ReqExitPolicy, SleepWhenIdle, Tag,
77    Timestamp, Url,
78};
79
80use crate::nostr::account::{SignError, Signer};
81use crate::nostr::blossom;
82use crate::nostr::bookmarks::{self, Bookmarks, PrivateTags};
83use crate::nostr::compose::Target;
84use crate::nostr::contacts;
85use crate::nostr::content::QUOTE_DEPTH;
86use crate::nostr::engagement::{self, Doer, Left, Standing};
87use crate::nostr::feed;
88use crate::nostr::kept_drafts::{self, DRAFT_KIND};
89use crate::nostr::models::{Note, Profile, reply_to};
90use crate::nostr::notifications::{self, NOTIFICATIONS_PAGE, Notification};
91use crate::nostr::outbox::{self, Listed, Whereabouts};
92use crate::nostr::private_relay::PrivateRelay;
93use crate::nostr::relay_lists::{self, Kept, ListedRelays, RelayLists, Section};
94use crate::nostr::search::{self, Found, SearchFor};
95use crate::nostr::sightings::Sightings;
96use crate::nostr::sweep;
97
98/// How many notes one page of a feed asks for.
99pub const FEED_PAGE: usize = 50;
100
101/// How long a request waits for a first relay to connect before giving up.
102const CONNECT_WAIT: Duration = Duration::from_secs(5);
103
104/// How long after startup a request still waits for relays that are in the
105/// middle of connecting, so the first page comes from all of them rather
106/// than from whichever answered first. After this, a relay that is still
107/// trying is left out of a request instead of holding it up.
108const CONNECT_GRACE: Duration = Duration::from_secs(2);
109
110/// How often the relays' connection states are looked at while waiting.
111const CONNECT_POLL: Duration = Duration::from_millis(100);
112
113/// How long relays get to answer a request. Every query has one, so nothing
114/// loads forever on a relay that stopped answering.
115pub(crate) const FETCH_TIMEOUT: Duration = Duration::from_secs(10);
116
117/// How many of other people's relays one question reaches for, and how
118/// many are kept in their pool once those in use are done with, unless
119/// said otherwise.
120pub(crate) const REACH_CAP: usize = 20;
121
122/// How many relays each person is read from, the account's own among them,
123/// when their relay list names as many; and how many of the relays each
124/// person reads are sent what is meant for them.
125pub(crate) const RELAYS_PER_PERSON: usize = 2;
126
127/// How long one of other people's relays gets to connect, and to answer.
128/// Shorter than the account's own get: they are asked for what may well be
129/// had already, and a list of notes waits for the slowest of them.
130pub(crate) const REACH_CONNECT_WAIT: Duration = Duration::from_secs(2);
131pub(crate) const REACH_TIMEOUT: Duration = Duration::from_secs(6);
132
133/// How long a relay that did not connect, said no to what it was asked,
134/// or did not answer in time is left alone, and the others asked without
135/// it; and how near the time it had counts as running out of it.
136pub(crate) const REACH_AVOID: Duration = Duration::from_secs(10 * 60);
137const TIMEOUT_SLACK: Duration = Duration::from_millis(250);
138
139/// How long one of other people's relays stays connected with nothing
140/// asked of it, how long it stays in the pool unused, and how lately it
141/// must have been used not to be let go of to make room for another.
142pub(crate) const REACH_SLEEP: Duration = Duration::from_secs(2 * 60);
143pub(crate) const REACH_KEEP: Duration = Duration::from_secs(15 * 60);
144const REACH_BUSY: Duration = Duration::from_secs(60);
145
146/// How long someone's relay list is taken as known before the relays are
147/// asked for it again.
148pub(crate) const RELAY_LISTS_FRESH: Duration = Duration::from_secs(60 * 60);
149
150/// How long a relay that searches gets to answer.
151pub(crate) const SEARCH_TIMEOUT: Duration = Duration::from_secs(8);
152
153/// How many of the relays an account's own relay list says it writes to
154/// are joined to the ones the config names.
155pub(crate) const ACCOUNT_RELAYS_MAX: usize = 8;
156
157/// How many of the people a note names are taken for part of its
158/// conversation, when their relays are asked about it.
159pub(crate) const THREAD_PEOPLE: usize = 5;
160
161/// The kinds of event that are sent to the people they name, as well as
162/// to the account's own relays: what is said to someone, or done to what
163/// they wrote. Not a contact list, say, which names everyone followed.
164const DELIVERED_KINDS: [Kind; 5] = [Kind::TextNote, Kind::Comment, Kind::Repost, Kind::GenericRepost, Kind::Reaction];
165
166/// How far other people's relays are reached for.
167#[derive(Debug, Clone, Copy)]
168pub struct Reach {
169    /// How many of them one question reaches for, and how many are kept
170    /// once those in use are done with.
171    pub cap: usize,
172    /// Whether a relay that somebody's relay list names is one to connect
173    /// to.
174    pub accepts: fn(&RelayUrl) -> bool,
175    /// Whether a relay the config names is on this machine or this
176    /// network: one that stays in use whatever the account's relay list
177    /// says, since no list would name it.
178    pub local: fn(&RelayUrl) -> bool,
179}
180
181impl Default for Reach {
182    fn default() -> Self {
183        Self { cap: REACH_CAP, accepts: outbox::public, local: |relay| relay.is_localhost() || relay.is_local_addr() }
184    }
185}
186
187/// The account's own relays: those the config names, those its relay
188/// list names, and which of them are in use.
189///
190/// The config's are where an account is until it says where it is: where
191/// its lists are looked for, and where it reads and writes while it has
192/// no relay list. Once one of the relays its list says it writes to is
193/// connected, those are its own, and the config's stand down: they are
194/// not asked and not written to. Except those on this machine or this
195/// network, which no list would name and which are there to be used.
196#[derive(Default)]
197struct Own {
198    /// The relays the config names.
199    config: Vec<RelayUrl>,
200    /// The relays the account's relay list says it writes to, so many of
201    /// them.
202    listed: Vec<RelayUrl>,
203    /// Those of `listed` that were put in the pool for it, the config not
204    /// naming them, and are taken out when the list no longer does.
205    added: Vec<RelayUrl>,
206    /// Whether the config's relays stand down.
207    stood_down: bool,
208}
209
210/// Which pool a relay is in.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212enum Pool {
213    /// The account's own relays.
214    Home,
215    /// Other people's.
216    Others,
217}
218
219/// What is remembered of reaching for other people's relays.
220#[derive(Default)]
221struct Reached {
222    /// When each person's relay list was last asked of the relays.
223    lists_asked: HashMap<PublicKey, Instant>,
224    /// When each of other people's relays was last used.
225    used: HashMap<RelayUrl, Instant>,
226    /// When each relay, of either pool, last failed: did not connect,
227    /// said no, or did not answer in time.
228    failed: HashMap<RelayUrl, Instant>,
229    /// The relays profiles and relay lists are looked up on, beside the
230    /// account's own: those its list of them names.
231    lookup: Vec<RelayUrl>,
232    /// The relays the account never connects to on anyone's word.
233    blocked: HashSet<RelayUrl>,
234}
235
236/// How a relay this is connected to has been doing, since the applet
237/// started: what the relays page says under its name.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct RelayUse {
240    /// Whether it is connected now.
241    pub connected: bool,
242    /// How many bytes it sent, and how many were sent to it.
243    pub received: usize,
244    pub sent: usize,
245    /// How many times it was connected to, and how many of those worked.
246    pub attempts: usize,
247    pub succeeded: usize,
248    /// How long it takes to answer, on average, if that was measured.
249    pub latency: Option<Duration>,
250}
251
252/// What a relay sent when it was asked.
253struct Asked {
254    events: Vec<Event>,
255    /// It said that was all before its time ran out.
256    in_time: bool,
257}
258
259/// How many notes of a conversation one request asks for. A thread that
260/// went everywhere has thousands; this many are read, and held, at most.
261const THREAD_LIMIT: usize = 300;
262
263/// A conversation with fewer notes than this naming its root is asked about
264/// again, for the notes that name only the note they answer. A larger one
265/// has enough to show without the second request.
266const THREAD_ASK_AGAIN_UNDER: usize = 50;
267
268/// How many notes up from the one a thread was opened for are looked for one
269/// by one, when nothing else brought them.
270const THREAD_ANCESTORS: usize = 5;
271
272/// Where events are looked for.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub enum Source {
275    /// The local event store: what is known already, at once.
276    Store,
277    /// The relays: what there is now, after a wait.
278    Relays,
279}
280
281/// How long the relays get to send the notes that the notes of a page
282/// quote, and again for those that these quote in turn. The page waits
283/// for them, so that a note is shown with what it quotes or without, and
284/// not first one way and then the other.
285const QUOTES_WAIT: Duration = Duration::from_secs(4);
286
287/// How many notes one filter asks for by id.
288const IDS_PER_FILTER: usize = 100;
289
290/// How long each relay gets to say whether it took an event.
291pub(crate) const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10);
292
293/// How long the relays get to say which of them has an event that is about
294/// to be pointed at. Short: what points at it goes out without, rather
295/// than late.
296const HOLDER_WAIT: Duration = Duration::from_secs(3);
297
298/// How many notes one request asks about at a time, when asking what was
299/// made of them, and how many events of a kind it asks for: a note that
300/// went everywhere has more reactions than are worth carrying.
301const ENGAGEMENT_NOTES_PER_REQUEST: usize = 25;
302const ENGAGEMENT_LIMIT: usize = 500;
303
304/// How many events of a kind the store is read for, for as many notes. More
305/// than a request brings, since the store keeps what earlier requests
306/// brought.
307const ENGAGEMENT_STORE_LIMIT: usize = 5_000;
308
309/// How long the receipt of a zap is waited for after its invoice is shown:
310/// about as long as such an invoice can be paid.
311const RECEIPT_WAIT: Duration = Duration::from_secs(10 * 60);
312
313/// How long to wait before listening again, when the relays stopped
314/// answering in the middle of waiting for a receipt.
315const RECEIPT_RETRY: Duration = Duration::from_secs(5);
316
317/// How many of a note's newest receipts are looked at when the listening
318/// starts: enough to find one that arrived just before.
319const RECEIPT_LIMIT: usize = 20;
320
321/// Why an event did not go out.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub enum PublishError {
324    /// It could not be signed.
325    Sign(SignError),
326    /// Not one relay is connected, nor became so while waiting.
327    NoRelayReachable,
328    /// Every relay asked turned it down, or didn't answer: what one of them
329    /// said.
330    Refused(String),
331    /// The relay pool refused the request.
332    Failed(String),
333}
334
335/// Why a request to the relays brought nothing back.
336#[derive(Debug, Clone, PartialEq, Eq)]
337pub enum FetchError {
338    /// Not one relay is connected, nor became so while waiting.
339    NoRelayReachable,
340    /// The relay pool refused the request.
341    Failed(String),
342    /// Some relays answered and some didn't, and those that did have no
343    /// list of the account's. Only said where that is not the same as
344    /// there being none: before a list is written, which would replace
345    /// the one a relay that didn't answer may have.
346    Incomplete,
347}
348
349/// One page of what an account is told of.
350#[derive(Debug, Clone, Default)]
351pub struct Notified {
352    /// What the events of the page tell of: fewer than there were events,
353    /// when some had nothing to tell.
354    pub notifications: Vec<Notification>,
355    /// When the oldest event of the page was written: where the page
356    /// before it ends.
357    pub oldest: Option<u64>,
358    /// Whether the page was as many events as were asked for: there may
359    /// be older ones.
360    pub full: bool,
361}
362
363/// How long the relays are given to send the notes notifications are
364/// about, which only say what was answered or reacted to.
365const ABOUT_WAIT: Duration = Duration::from_secs(4);
366
367/// Where the event store lives: the user's data directory, not the cache.
368/// It is what the embedded relay will serve, so it is not disposable.
369pub fn default_store_path() -> PathBuf {
370    dirs::data_dir().unwrap_or_else(|| PathBuf::from(".")).join("cosmic-applet-avestruz").join("events")
371}
372
373/// How many authors one filter names. Relays refuse filters past some size,
374/// each its own; a long follow list is asked about in filters of this many.
375const AUTHORS_PER_FILTER: usize = 250;
376
377/// The kinds of event a list of notes is made of: text notes, and comments
378/// (NIP-22), which are replies to what is not a text note.
379const FEED_KINDS: [Kind; 2] = [Kind::TextNote, Kind::Comment];
380
381/// The filters that ask for one page of the notes of `authors`: text notes
382/// and comments, the `limit` newest written at or before `until`. One filter for every
383/// [`AUTHORS_PER_FILTER`] authors, and none for nobody.
384///
385/// Each filter of a long list comes back with its own newest `limit`, which
386/// [`feed::newest`] cuts as it cuts the answers of several relays, and for
387/// the same reason.
388/// The filters that ask for the events `ids` name: one for every
389/// [`IDS_PER_FILTER`] of them.
390fn filters_by_id(ids: &[EventId]) -> Vec<Filter> {
391    ids.chunks(IDS_PER_FILTER).map(|chunk| Filter::new().ids(chunk.iter().copied())).collect()
392}
393
394fn feed_filters(authors: &[PublicKey], until: Option<u64>, limit: usize) -> Vec<Filter> {
395    let page = Filter::new().kinds(FEED_KINDS).limit(limit);
396    let page = match until {
397        Some(until) => page.until(Timestamp::from_secs(until)),
398        None => page,
399    };
400    authors.chunks(AUTHORS_PER_FILTER).map(|chunk| page.clone().authors(chunk.iter().copied())).collect()
401}
402
403/// The filters that ask what was made of `notes`: the replies (notes and
404/// comments), reposts, reactions and zap receipts that name them, `limit` of
405/// each at most, and the reactions and reposts of `account`, which must not
406/// be among those left out.
407fn engagement_filters(notes: &[EventId], account: Option<PublicKey>, limit: usize) -> Vec<Filter> {
408    let about = |kinds: &[Kind]| Filter::new().kinds(kinds.iter().copied()).events(notes.iter().copied());
409    let mut filters: Vec<Filter> = [
410        &[Kind::TextNote][..],
411        &[Kind::Comment],
412        // Of either kind, a repost is one repost.
413        &[Kind::Repost, Kind::GenericRepost],
414        &[Kind::Reaction],
415        &[Kind::ZapReceipt],
416    ]
417    .into_iter()
418    .map(|kinds| about(kinds).limit(limit))
419    .collect();
420    if let Some(account) = account {
421        filters.push(about(&[Kind::Reaction, Kind::Repost, Kind::GenericRepost]).author(account));
422    }
423    filters
424}
425
426/// Why an account's contact list was not changed.
427#[derive(Debug, Clone, PartialEq, Eq)]
428pub enum FollowError {
429    /// The newest list could not be asked for, and changing an older one
430    /// would undo whatever came after it.
431    Fetch(FetchError),
432    /// The relays have no list of the account's. Writing a first one is
433    /// for the account to decide: it replaces any list kept elsewhere.
434    NoList,
435    /// The changed list did not go out.
436    Publish(PublishError),
437}
438
439/// Why a list an account keeps part of to itself (its bookmarks, its
440/// search relays) or its relay list was not read, or not changed.
441#[derive(Debug, Clone, PartialEq, Eq)]
442pub enum ListError {
443    /// The newest list could not be asked for, and changing an older one
444    /// would undo whatever came after it.
445    Fetch(FetchError),
446    /// The relays have no list of the account's. Writing a first one is
447    /// for the account to decide: it replaces any list kept elsewhere.
448    NoList,
449    /// What the list keeps to itself could not be read: it was not
450    /// decrypted, or is not what such a list holds. A list written
451    /// without it would lose it.
452    Unreadable(SignError),
453    /// The changed list did not go out.
454    Publish(PublishError),
455}
456
457/// The newest of `events`, which are the versions of something only the
458/// last of which counts: a contact list, a bookmark list. `None` if there
459/// is none.
460fn newest(events: impl IntoIterator<Item = Event>) -> Option<Event> {
461    events.into_iter().max_by_key(|event| event.created_at)
462}
463
464/// Each author's newest profile among `events`.
465fn newest_profiles(events: impl IntoIterator<Item = Event>) -> Vec<(PublicKey, Profile)> {
466    let mut newest: HashMap<PublicKey, Event> = HashMap::new();
467    for event in events {
468        match newest.get(&event.pubkey) {
469            Some(known) if known.created_at >= event.created_at => {}
470            _ => {
471                newest.insert(event.pubkey, event);
472            }
473        }
474    }
475    newest.into_iter().map(|(author, event)| (author, Profile::from_content(&event.content))).collect()
476}
477
478/// The Nostr client: a relay pool over a local event store. Cheap to clone;
479/// clones share the pool and the store.
480#[derive(Clone)]
481pub struct NostrService {
482    /// The pool of the account's own relays, over the event store.
483    client: Client,
484    /// The pool of other people's relays, over the same store.
485    others: Client,
486    /// The relay this runs itself, over the same store, for what is the
487    /// account's alone.
488    private: PrivateRelay,
489    /// How far other people's relays are reached for.
490    reach: Reach,
491    /// What is remembered of reaching for them.
492    reached: Arc<Mutex<Reached>>,
493    /// Held while relays are being connected to in the pool of other
494    /// people's: two questions that reach for the same relay at once
495    /// would each take the other's connecting for a relay that didn't.
496    reaching: Arc<tokio::sync::Mutex<()>>,
497    /// The account's own relays, and which are in use.
498    own: Arc<Mutex<Own>>,
499    /// Held while the account's relays are changed, so that one
500    /// account's are out before another's are in.
501    joining: Arc<tokio::sync::Mutex<()>>,
502    /// When the relays were first told to connect.
503    opened_at: Instant,
504    /// Which relays each note was seen on, since then.
505    sightings: Arc<Mutex<Sightings>>,
506}
507
508impl fmt::Debug for NostrService {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        f.debug_struct("NostrService").finish_non_exhaustive()
511    }
512}
513
514impl NostrService {
515    /// Open the event store at `store_path` and start connecting to `relays`.
516    /// Returns once the store is open; relays connect in the background.
517    pub async fn open(store_path: PathBuf, relays: Vec<String>) -> Result<Self, String> {
518        Self::open_reaching(store_path, relays, Reach::default()).await
519    }
520
521    /// As [`Self::open`], reaching for other people's relays as far as
522    /// `reach` says.
523    pub async fn open_reaching(store_path: PathBuf, relays: Vec<String>, reach: Reach) -> Result<Self, String> {
524        tokio::fs::create_dir_all(&store_path).await.map_err(|e| format!("{}: {e}", store_path.display()))?;
525        let store = NostrLmdb::open(&store_path).await.map_err(|e| e.to_string())?;
526        let client = Client::builder().database(store).build();
527        // Other people's relays are let go of when nothing is asked of
528        // them, and woken when something is.
529        let others = Client::builder()
530            .database(client.database().clone())
531            .sleep_when_idle(SleepWhenIdle::Enabled { timeout: REACH_SLEEP })
532            .build();
533
534        let mut config = Vec::new();
535        for url in &relays {
536            match RelayUrl::parse(url) {
537                Ok(relay) => match client.add_relay(&relay).await {
538                    Ok(_) => config.push(relay),
539                    Err(e) => tracing::warn!("relay {url} was not added: {e}"),
540                },
541                Err(e) => tracing::warn!("relay {url} was not added: {e}"),
542            }
543        }
544        client.connect().await;
545        tracing::info!("event store open at {}; connecting to {} relay(s)", store_path.display(), relays.len());
546
547        // The relay of this machine, for what goes to no other.
548        let private = PrivateRelay::over(client.database().clone());
549
550        Ok(Self {
551            client,
552            others,
553            private,
554            reach,
555            reached: Arc::default(),
556            reaching: Arc::default(),
557            own: Arc::new(Mutex::new(Own { config, ..Own::default() })),
558            joining: Arc::default(),
559            opened_at: Instant::now(),
560            sightings: Arc::default(),
561        })
562    }
563
564    /// The relays a request can be sent to now: those that are connected.
565    ///
566    /// A request is only sent to these. Sent to the whole pool, it would
567    /// wait its full timeout on every relay that is down, and one dead relay
568    /// would make every page slow.
569    ///
570    /// With none connected, waits up to [`CONNECT_WAIT`] for the first. Just
571    /// after startup it also gives relays that are still connecting until
572    /// [`CONNECT_GRACE`] to join.
573    async fn reachable_relays(&self) -> Vec<RelayUrl> {
574        let deadline = Instant::now() + CONNECT_WAIT;
575        loop {
576            let mut reachable = Vec::new();
577            let mut connecting = false;
578            let in_use = self.in_use();
579            for (url, relay) in self.client.relays().await.into_iter().filter(|(url, _)| in_use.contains(url)) {
580                match relay.status() {
581                    // A sleeping relay was connected, idled, and wakes when asked.
582                    RelayStatus::Connected | RelayStatus::Sleeping => reachable.push(url),
583                    RelayStatus::Initialized | RelayStatus::Pending | RelayStatus::Connecting => connecting = true,
584                    RelayStatus::Disconnected | RelayStatus::Terminated | RelayStatus::Banned | RelayStatus::Shutdown => {}
585                }
586            }
587            let settled = !connecting || self.opened_at.elapsed() >= CONNECT_GRACE;
588            if (!reachable.is_empty() && settled) || Instant::now() >= deadline {
589                return reachable;
590            }
591            tokio::time::sleep(CONNECT_POLL).await;
592        }
593    }
594
595    /// Which relays each note was seen on. What is kept there is whole
596    /// after every change to it, so it is as good after a panic as before.
597    fn sightings(&self) -> MutexGuard<'_, Sightings> {
598        self.sightings.lock().unwrap_or_else(PoisonError::into_inner)
599    }
600
601    /// The relays each of `notes` was seen on, for those that were seen on
602    /// any.
603    pub fn seen_on(&self, notes: &[EventId]) -> HashMap<EventId, Vec<RelayUrl>> {
604        let sightings = self.sightings();
605        notes.iter().map(|note| (*note, sightings.of(note))).filter(|(_, relays)| !relays.is_empty()).collect()
606    }
607
608    /// The pool `pool` names.
609    fn pool(&self, pool: Pool) -> &Client {
610        match pool {
611            Pool::Home => &self.client,
612            Pool::Others => &self.others,
613        }
614    }
615
616    /// What `relay`, of the pool `pool`, sends for `filters`, until it says
617    /// that is all or `timeout` has passed. An event it sends that can't be
618    /// taken (a bad signature, say) is left out, and the rest still counts.
619    ///
620    /// A relay that says no to the question (it wants to know who asks, it
621    /// keeps no such events) and sends nothing is an error. One that ran
622    /// out of time is not, and what it sent counts; that it did is said
623    /// with what it sent.
624    async fn ask(&self, pool: Pool, relay: &RelayUrl, filters: Vec<Filter>, timeout: Duration) -> Result<Asked, String> {
625        let started = Instant::now();
626        let connection = self.pool(pool).relay(relay).await.map_err(|e| e.to_string())?.ok_or("not in the pool")?;
627        let mut sent = connection.stream_events(filters).timeout(timeout).await.map_err(|e| e.to_string())?;
628        let mut events = Vec::new();
629        let mut refusal = None;
630        while let Some(event) = sent.next().await {
631            match event {
632                Ok(event) => events.push(event),
633                Err(e) => refusal = Some(e.to_string()),
634            }
635        }
636        match refusal {
637            Some(refusal) if events.is_empty() => Err(refusal),
638            refusal => {
639                if let Some(refusal) = refusal {
640                    tracing::warn!("{relay} sent an event that was not taken: {refusal}");
641                }
642                Ok(Asked { events, in_time: started.elapsed() + TIMEOUT_SLACK < timeout })
643            }
644        }
645    }
646
647    /// Leave `relay` alone for a while: it said no, or did not answer in
648    /// time, and everything asked of it meanwhile would wait as long.
649    fn leave_alone(&self, relay: &RelayUrl, why: &str) {
650        tracing::debug!("{relay} is left alone for a while: {why}");
651        self.reached().failed.insert(relay.clone(), Instant::now());
652    }
653
654    /// The relays that are being left alone, and those the account has
655    /// blocked, which always are.
656    fn left_alone(&self) -> HashSet<RelayUrl> {
657        let now = Instant::now();
658        let mut reached = self.reached();
659        reached.failed.retain(|_, at| now.duration_since(*at) < REACH_AVOID);
660        reached.failed.keys().chain(&reached.blocked).cloned().collect()
661    }
662
663    /// The account's own relays to ask: those that are connected, less
664    /// the ones being left alone, unless that leaves none.
665    async fn answering_relays(&self) -> Vec<RelayUrl> {
666        let connected = self.reachable_relays().await;
667        let left_alone = self.left_alone();
668        let answering: Vec<RelayUrl> = connected.iter().filter(|relay| !left_alone.contains(relay)).cloned().collect();
669        if answering.is_empty() { connected } else { answering }
670    }
671
672    /// Ask the connected relays for the events any of `filters` matches,
673    /// newest first, and note which relay sent which note.
674    async fn fetch(&self, filters: Vec<Filter>) -> Result<impl Iterator<Item = Event>, FetchError> {
675        self.fetch_within(filters, FETCH_TIMEOUT).await
676    }
677
678    /// As [`Self::fetch`], giving the relays `timeout` to answer. A relay
679    /// that fails is left out; if every one does, that is the error.
680    async fn fetch_within(&self, filters: Vec<Filter>, timeout: Duration) -> Result<impl Iterator<Item = Event>, FetchError> {
681        Ok(self.fetch_from_each(filters, timeout).await?.0.into_iter())
682    }
683
684    /// As [`Self::fetch_within`], and whether every relay of the pool
685    /// answered: whether what didn't come is nowhere, as far as this
686    /// client can know.
687    async fn fetch_from_each(&self, filters: Vec<Filter>, timeout: Duration) -> Result<(Vec<Event>, bool), FetchError> {
688        let relays = self.answering_relays().await;
689        if relays.is_empty() {
690            return Err(FetchError::NoRelayReachable);
691        }
692        let asks = relays.into_iter().map(|relay| (relay, filters.clone())).collect();
693        let (events, answered, failure) = self.gather(Pool::Home, asks, timeout).await;
694        if answered == 0 {
695            return Err(FetchError::Failed(failure.unwrap_or_default()));
696        }
697        let everywhere = answered == self.in_use().len();
698        Ok((events, everywhere))
699    }
700
701    /// What the relays of `asks`, which are of the pool `pool`, send for
702    /// the filters each is asked with, each event once and the newest
703    /// first; how many of them answered; and what one that didn't said.
704    /// Which relay sent which note is noted, and a relay that said no, or
705    /// ran out of time, is left alone for a while.
706    async fn gather(
707        &self,
708        pool: Pool,
709        asks: Vec<(RelayUrl, Vec<Filter>)>,
710        timeout: Duration,
711    ) -> (Vec<Event>, usize, Option<String>) {
712        let answers = join_all(asks.iter().map(|(relay, filters)| self.ask(pool, relay, filters.clone(), timeout))).await;
713
714        let mut events: HashMap<EventId, Event> = HashMap::new();
715        let mut failure = None;
716        let mut answered = 0;
717        let (mut slow, mut refused) = (Vec::new(), Vec::new());
718        {
719            let mut sightings = self.sightings();
720            for ((relay, _), answer) in asks.iter().zip(answers) {
721                match answer {
722                    Ok(asked) => {
723                        answered += 1;
724                        if !asked.in_time {
725                            slow.push(relay);
726                        }
727                        for event in asked.events {
728                            if FEED_KINDS.contains(&event.kind) {
729                                sightings.record(event.id, relay);
730                            }
731                            events.entry(event.id).or_insert(event);
732                        }
733                    }
734                    Err(e) => {
735                        tracing::warn!("{relay} could not be asked: {e}");
736                        refused.push((relay, e.clone()));
737                        failure = Some(e);
738                    }
739                }
740            }
741        }
742        for relay in slow {
743            self.leave_alone(relay, "it did not answer in time");
744        }
745        // One of the account's own that says no to one question may have
746        // an answer to the next, and said no at once: it is asked again.
747        if pool == Pool::Others {
748            for (relay, why) in refused {
749                self.leave_alone(relay, &why);
750            }
751        }
752        let mut events: Vec<Event> = events.into_values().collect();
753        events.sort_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| a.id.cmp(&b.id)));
754        (events, answered, failure)
755    }
756
757    // =========================================================================
758    // Other people's relays
759    // =========================================================================
760
761    /// What is remembered of reaching for other people's relays. Whole
762    /// after every change to it, as [`Self::sightings`] is.
763    fn reached(&self) -> MutexGuard<'_, Reached> {
764        self.reached.lock().unwrap_or_else(PoisonError::into_inner)
765    }
766
767    /// The relays `people` list for `listed`, for those of them who have a
768    /// relay list with any that may be connected to.
769    ///
770    /// The account's own relays are asked for the lists of those not asked
771    /// about lately, and what they send is the store's, which is what is
772    /// read: a list seen once is known without a relay, and the newest
773    /// seen is the one that counts. With `patient`, their answer is
774    /// waited for; without, only when the store knows nobody's list, and
775    /// otherwise it serves the next time: a list of notes is not kept
776    /// waiting for lists that seldom change.
777    async fn relays_of(&self, people: &[PublicKey], listed: Listed, patient: bool) -> HashMap<PublicKey, Vec<RelayUrl>> {
778        let now = Instant::now();
779        let stale: Vec<PublicKey> = {
780            let mut reached = self.reached();
781            let stale: Vec<PublicKey> = people
782                .iter()
783                .filter(|person| reached.lists_asked.get(person).is_none_or(|at| now.duration_since(*at) >= RELAY_LISTS_FRESH))
784                .copied()
785                .collect();
786            // Marked before they are asked for, so that they are asked for once.
787            reached.lists_asked.extend(stale.iter().map(|person| (*person, now)));
788            stale
789        };
790        let mut lists = self.stored_relay_lists(people).await;
791        if !stale.is_empty() {
792            if patient || lists.is_empty() {
793                self.ask_for_relay_lists(stale).await;
794                lists = self.stored_relay_lists(people).await;
795            } else {
796                // What the store has serves now, and what the relays have
797                // since serves the next time.
798                let service = self.clone();
799                tokio::spawn(async move { service.ask_for_relay_lists(stale).await });
800            }
801        }
802        lists
803            .into_iter()
804            .map(|list| {
805                let mut relays = outbox::relays(&list, listed);
806                relays.retain(|relay| (self.reach.accepts)(relay));
807                (list.pubkey, relays)
808            })
809            .filter(|(_, relays)| !relays.is_empty())
810            .collect()
811    }
812
813    /// The filters that ask for the relay lists of `people`.
814    fn relay_lists_of(people: &[PublicKey]) -> Vec<Filter> {
815        people
816            .chunks(AUTHORS_PER_FILTER)
817            .map(|chunk| Filter::new().kind(Kind::RelayList).authors(chunk.iter().copied()))
818            .collect()
819    }
820
821    /// Ask the account's own relays for the relay lists of `people`, for
822    /// the store's sake: it is what is read. If they can't be asked,
823    /// `people` count as not asked about.
824    async fn ask_for_relay_lists(&self, people: Vec<PublicKey>) {
825        let filters = Self::relay_lists_of(&people);
826        let (own, _looked_up) = join(self.fetch_within(filters.clone(), REACH_TIMEOUT), self.ask_lookup(filters)).await;
827        if let Err(e) = own {
828            tracing::warn!("{} relay list(s) could not be asked for: {e:?}", people.len());
829            let mut reached = self.reached();
830            for person in &people {
831                reached.lists_asked.remove(person);
832            }
833        }
834    }
835
836    /// The newest relay list of each of `people` that the store has one of.
837    async fn stored_relay_lists(&self, people: &[PublicKey]) -> Vec<Event> {
838        let mut newest: HashMap<PublicKey, Event> = HashMap::new();
839        for list in self.events(Source::Store, Self::relay_lists_of(people)).await.unwrap_or_default() {
840            match newest.get(&list.pubkey) {
841                Some(known) if known.created_at >= list.created_at => {}
842                _ => {
843                    newest.insert(list.pubkey, list);
844                }
845            }
846        }
847        newest.into_values().collect()
848    }
849
850    /// The relays to ask about, or send to, the people of `listed`, beside
851    /// the account's own, and who is on each: so many for each person, as
852    /// many in all as may be reached for, none that failed lately, and
853    /// only those that are connected now. See [`outbox::plan`].
854    async fn reach_for(&self, listed: &HashMap<PublicKey, Vec<RelayUrl>>) -> Vec<(RelayUrl, Vec<PublicKey>)> {
855        if listed.is_empty() || self.reach.cap == 0 {
856            return Vec::new();
857        }
858        let home: HashSet<RelayUrl> = self.in_use().into_iter().collect();
859        let planned = outbox::plan(listed, &home, &self.left_alone(), RELAYS_PER_PERSON, self.reach.cap);
860        if planned.is_empty() {
861            return Vec::new();
862        }
863        let wanted = planned.len();
864        let reached = self.connected(planned).await;
865        let said = |(relay, people): &(RelayUrl, Vec<PublicKey>)| {
866            format!("{} for {}", relay.as_str_without_trailing_slash(), people.len())
867        };
868        tracing::debug!(
869            "{} people with a relay list: {} of {wanted} of their relays reached ({})",
870            listed.len(),
871            reached.len(),
872            reached.iter().map(said).collect::<Vec<_>>().join(", ")
873        );
874        reached
875    }
876
877    /// Those of `planned`, each a relay and what it is wanted for, whose
878    /// relay is in the pool of other people's relays and connected, once
879    /// all have been given the time to connect. The pool is then no bigger
880    /// than it may be, but for the relays in use.
881    ///
882    /// The only way into [`Self::connect_to`], which is not to be in
883    /// twice at once for the same relay.
884    async fn connected<T>(&self, planned: Vec<(RelayUrl, T)>) -> Vec<(RelayUrl, T)> {
885        // One question's relays at a time: the next finds those it shares
886        // with this one connected already.
887        let _reaching = self.reaching.lock().await;
888        let connected = join_all(planned.iter().map(|(relay, _)| self.connect_to(relay))).await;
889        self.let_go_of_unused().await;
890        planned.into_iter().zip(connected).filter(|(_, connected)| *connected).map(|(planned, _)| planned).collect()
891    }
892
893    /// What the relays `said` to have notes send of them: each relay is
894    /// asked for the notes it is said to have. A relay that may not be
895    /// connected to, or is being left alone, is not asked, and neither is
896    /// one of the account's own, which were asked; if there are more than
897    /// may be reached for, the ones said to have the most are. Nothing,
898    /// and never an error, when none is reached: this is on top of what
899    /// was had.
900    async fn ask_where_said(&self, said: &[(EventId, RelayUrl)]) -> Vec<Event> {
901        if said.is_empty() || self.reach.cap == 0 {
902            return Vec::new();
903        }
904        let home: HashSet<RelayUrl> = self.in_use().into_iter().collect();
905        let left_alone = self.left_alone();
906        // Ordered, so that the same relays are asked every time.
907        let mut having: BTreeMap<&RelayUrl, Vec<EventId>> = BTreeMap::new();
908        for (note, relay) in said {
909            if (self.reach.accepts)(relay) && !home.contains(relay) && !left_alone.contains(relay) {
910                having.entry(relay).or_default().push(*note);
911            }
912        }
913        let mut having: Vec<(RelayUrl, Vec<EventId>)> = having.into_iter().map(|(relay, notes)| (relay.clone(), notes)).collect();
914        having.sort_by_key(|(_, notes)| std::cmp::Reverse(notes.len()));
915        having.truncate(self.reach.cap);
916        let asks: Vec<(RelayUrl, Vec<Filter>)> =
917            self.connected(having).await.into_iter().map(|(relay, notes)| (relay, filters_by_id(&notes))).collect();
918        if asks.is_empty() {
919            return Vec::new();
920        }
921        let asked = asks.len();
922        let (events, answered, _) = self.gather(Pool::Others, asks, REACH_TIMEOUT).await;
923        tracing::debug!("{} note(s) from {answered} of {asked} relay(s) said to have them", events.len());
924        events
925    }
926
927    /// Have `relay` in the pool of other people's relays, connected.
928    /// Returns whether it is. One that doesn't connect is taken out again,
929    /// and left alone for a while.
930    async fn connect_to(&self, relay: &RelayUrl) -> bool {
931        if self.reached().blocked.contains(relay) {
932            return false;
933        }
934        let connected = |status: RelayStatus| matches!(status, RelayStatus::Connected | RelayStatus::Sleeping);
935        let status = match self.others.relay(relay).await {
936            Ok(Some(known)) => known.status(),
937            _ => {
938                if let Err(e) = self.others.add_relay(relay).await {
939                    tracing::warn!("{relay} was not added to the pool: {e}");
940                }
941                RelayStatus::Initialized
942            }
943        };
944        if !connected(status) {
945            let _connecting = self.others.try_connect_relay(relay, REACH_CONNECT_WAIT).await;
946        }
947        let now_connected = matches!(self.others.relay(relay).await, Ok(Some(known)) if connected(known.status()));
948        if now_connected {
949            self.reached().used.insert(relay.clone(), Instant::now());
950        } else {
951            self.leave_alone(relay, "it did not connect");
952            self.reached().used.remove(relay);
953            if let Err(e) = self.others.remove_relay(relay).force().await {
954                tracing::debug!("{relay} could not be taken out of the pool: {e}");
955            }
956        }
957        now_connected
958    }
959
960    /// Take out of the pool of other people's relays those that have not
961    /// been used for a while, and, if there are more than may be reached
962    /// for, the ones used longest ago; but none used just now, which may
963    /// be in the middle of answering.
964    async fn let_go_of_unused(&self) {
965        let pooled: Vec<RelayUrl> = self.others.relays().await.into_keys().collect();
966        let now = Instant::now();
967        let let_go: Vec<RelayUrl> = {
968            let mut reached = self.reached();
969            let unused = |relay: &RelayUrl| reached.used.get(relay).map_or(Duration::MAX, |at| now.duration_since(*at));
970            let pooled = pooled.into_iter().map(|relay| (unused(&relay), relay)).collect();
971            let let_go = outbox::to_let_go(pooled, self.reach.cap, REACH_KEEP, REACH_BUSY);
972            for relay in &let_go {
973                reached.used.remove(relay);
974            }
975            let_go
976        };
977        for relay in let_go {
978            tracing::debug!("{relay} is let go of");
979            if let Err(e) = self.others.remove_relay(&relay).force().await {
980                tracing::debug!("{relay} could not be taken out of the pool: {e}");
981            }
982        }
983    }
984
985    /// What the relays that `people` list for `listed` send about them,
986    /// beside what the account's own relays have: each relay reached for
987    /// is asked with the filters `asking` makes for the people who list it.
988    /// Nothing, when nobody lists a relay that is reached; never an error,
989    /// since what is asked for here is on top of what was had. See
990    /// [`Self::relays_of`] for `patient`.
991    async fn ask_their_relays(
992        &self,
993        people: &[PublicKey],
994        listed: Listed,
995        patient: bool,
996        asking: impl Fn(&[PublicKey]) -> Vec<Filter>,
997    ) -> Vec<Event> {
998        if people.is_empty() {
999            return Vec::new();
1000        }
1001        let listed = self.relays_of(people, listed, patient).await;
1002        let asks: Vec<(RelayUrl, Vec<Filter>)> = self
1003            .reach_for(&listed)
1004            .await
1005            .into_iter()
1006            .map(|(relay, people)| (relay, asking(&people)))
1007            .filter(|(_, filters)| !filters.is_empty())
1008            .collect();
1009        if asks.is_empty() {
1010            return Vec::new();
1011        }
1012        let asked = asks.len();
1013        let (events, answered, _) = self.gather(Pool::Others, asks, REACH_TIMEOUT).await;
1014        tracing::debug!("{} event(s) from {answered} of {asked} of other people's relays", events.len());
1015        events
1016    }
1017
1018    /// The account's own relays and which are in use, whole after every
1019    /// change, as [`Self::sightings`] is.
1020    fn own(&self) -> MutexGuard<'_, Own> {
1021        self.own.lock().unwrap_or_else(PoisonError::into_inner)
1022    }
1023
1024    /// The account's own relays that are in use, connected or not: those
1025    /// its relay list says it writes to, and those the config names
1026    /// unless they stand down (see [`Own`]).
1027    fn in_use(&self) -> Vec<RelayUrl> {
1028        let own = self.own();
1029        let stays = |relay: &&RelayUrl| !own.stood_down || (self.reach.local)(relay) || own.listed.contains(relay);
1030        let mut in_use: Vec<RelayUrl> = own.config.iter().filter(stays).cloned().collect();
1031        for relay in &own.listed {
1032            if !in_use.contains(relay) {
1033                in_use.push(relay.clone());
1034            }
1035        }
1036        in_use
1037    }
1038
1039    /// Have the relays that the relay list of `account` says it writes
1040    /// to, so many of them, be its own: where what it wrote is and where
1041    /// what it writes goes, in place of those the config names once one
1042    /// of them is connected (see [`Own`]). Those of the account before,
1043    /// if any, are taken out first; with no account, that is all, and the
1044    /// config's relays are the ones in use. Returns how many joined the
1045    /// pool.
1046    ///
1047    /// The list the store has is gone by at once, and the newest the
1048    /// relays have when they have answered.
1049    pub async fn use_relays_of(&self, account: Option<PublicKey>) -> usize {
1050        // The relay of this machine takes its account's events, and
1051        // nobody's when nobody is signed in.
1052        self.private.set_owner(account);
1053        let Some(account) = account else {
1054            return self.join_account_relays(Vec::new()).await;
1055        };
1056        // The account's own word: any relay it names, on this machine too.
1057        let writes = |list: &Event| outbox::relays(list, Listed::Write);
1058        let stored = self.stored_list(Kind::RelayList, account).await;
1059        if let Some(stored) = &stored {
1060            self.join_account_relays(writes(stored)).await;
1061        }
1062        let list = match self.newest_list(Kind::RelayList, account).await {
1063            Ok(list) => list,
1064            Err(e) => {
1065                tracing::warn!("the account's relay list could not be asked for: {e:?}");
1066                stored
1067            }
1068        };
1069        self.join_account_relays(list.as_ref().map(writes).unwrap_or_default()).await
1070    }
1071
1072    /// Have `writes`, so many of them, be the relays the account's relay
1073    /// list names as its own: those that were put in the pool for it and
1074    /// are not among them are taken out, those that are stay as they are,
1075    /// connected, and the new ones get a moment to connect. Whether the
1076    /// config's relays stand down is settled by whether any of `writes`
1077    /// is connected then. Returns how many are in the pool for the
1078    /// account's list.
1079    async fn join_account_relays(&self, writes: Vec<RelayUrl>) -> usize {
1080        let wanted: Vec<RelayUrl> = writes.into_iter().filter(|relay| !relay.is_onion()).take(ACCOUNT_RELAYS_MAX).collect();
1081        let _joining = self.joining.lock().await;
1082        let before = self.own().added.clone();
1083        for relay in before.iter().filter(|relay| !wanted.contains(relay)) {
1084            if let Err(e) = self.client.remove_relay(relay).force().await {
1085                tracing::warn!("{relay} could not be taken out of the pool: {e}");
1086            }
1087        }
1088        let (mut added, mut new) = (Vec::new(), Vec::new());
1089        for relay in &wanted {
1090            if before.contains(relay) {
1091                added.push(relay.clone());
1092                continue;
1093            }
1094            match self.client.add_relay(relay).await {
1095                // Not one the config names: it is here for the account.
1096                Ok(true) => new.push(relay.clone()),
1097                // One the config names, which may have been hung up on.
1098                Ok(false) => {
1099                    if let Err(e) = self.client.connect_relay(relay).await {
1100                        tracing::warn!("{relay} could not be told to connect: {e}");
1101                    }
1102                }
1103                Err(e) => tracing::warn!("{relay} was not added to the pool: {e}"),
1104            }
1105        }
1106        let connecting = new.iter().map(|relay| self.client.try_connect_relay(relay, REACH_CONNECT_WAIT));
1107        join_all(connecting).await;
1108        added.extend(new);
1109
1110        let pool = self.client.relays().await;
1111        let connected = |relay: &RelayUrl| {
1112            pool.get(relay).is_some_and(|known| matches!(known.status(), RelayStatus::Connected | RelayStatus::Sleeping))
1113        };
1114        let stood_down = wanted.iter().any(connected);
1115        let joined = added.len();
1116        {
1117            let mut own = self.own();
1118            (own.listed, own.added, own.stood_down) = (wanted, added, stood_down);
1119        }
1120        tracing::info!("{joined} relay(s) of the account's relay list joined its own; the config's stand down: {stood_down}");
1121        self.settle_config_relays().await;
1122        joined
1123    }
1124
1125    /// Have the config's relays that are in use connected, and hang up on
1126    /// those that stand down: after a while, so that what was asked of
1127    /// them before they did is answered.
1128    async fn settle_config_relays(&self) {
1129        let in_use = self.in_use();
1130        let config = self.own().config.clone();
1131        for relay in config.iter().filter(|relay| in_use.contains(relay)) {
1132            if let Err(e) = self.client.connect_relay(relay).await {
1133                tracing::warn!("{relay} could not be told to connect: {e}");
1134            }
1135        }
1136        if config.iter().all(|relay| in_use.contains(relay)) {
1137            return;
1138        }
1139        let service = self.clone();
1140        tokio::spawn(async move {
1141            tokio::time::sleep(FETCH_TIMEOUT).await;
1142            // As things stand by now: an account may have left meanwhile.
1143            let in_use = service.in_use();
1144            for relay in config.iter().filter(|relay| !in_use.contains(relay)) {
1145                tracing::debug!("{relay}, which the config names, stands down");
1146                if let Err(e) = service.client.disconnect_relay(relay).await {
1147                    tracing::debug!("{relay} could not be hung up on: {e}");
1148                }
1149            }
1150        });
1151    }
1152
1153    // =========================================================================
1154    // Events
1155    // =========================================================================
1156
1157    /// The event `id`, if the store has it.
1158    pub async fn stored_event(&self, id: EventId) -> Option<Event> {
1159        self.events(Source::Store, vec![Filter::new().id(id)]).await.ok()?.into_iter().next()
1160    }
1161
1162    /// The event `id`, which is a note on show: the store's, or, since
1163    /// the store lets go of what is old while it may still be showing (see
1164    /// [`sweep`]), the one the relays send again: the account's own, and
1165    /// then the ones `author` writes to. `None` if none of them has it.
1166    pub async fn event(&self, id: EventId, author: PublicKey) -> Option<Event> {
1167        if let Some(stored) = self.stored_event(id).await {
1168            return Some(stored);
1169        }
1170        let is_it = |event: &Event| event.id == id;
1171        if let Ok(mut fetched) = self.fetch_within(filters_by_id(&[id]), QUOTES_WAIT).await
1172            && let Some(event) = fetched.find(is_it)
1173        {
1174            return Some(event);
1175        }
1176        let whereabouts = Whereabouts { author: Some(author), relay: None };
1177        self.events_elsewhere(&[(id, &whereabouts)], QUOTES_WAIT).await.into_iter().find(is_it)
1178    }
1179
1180    /// Have the store let go of what was written at `before` or earlier
1181    /// and can be asked of the relays again (see [`sweep`]): not what
1182    /// `account` wrote or `bookmarked`. Returns how many events went.
1183    pub async fn sweep(&self, account: PublicKey, bookmarked: &HashSet<EventId>, before: Timestamp) -> Result<usize, String> {
1184        sweep::sweep(self.client.database().as_ref(), account, bookmarked, before).await
1185    }
1186
1187    /// A connected relay that has the event `id`: where someone else can be
1188    /// told to look for it. The first to send it; `None` if none does
1189    /// before long.
1190    pub async fn relay_holding(&self, id: EventId) -> Option<RelayUrl> {
1191        let filter = Filter::new().id(id).limit(1);
1192        let targets: HashMap<RelayUrl, Vec<Filter>> =
1193            self.answering_relays().await.into_iter().map(|url| (url, vec![filter.clone()])).collect();
1194        if targets.is_empty() {
1195            return None;
1196        }
1197        let mut answers = self.client.stream_events(targets).timeout(HOLDER_WAIT).await.ok()?;
1198        while let Some((relay, event)) = answers.next().await {
1199            if event.is_ok_and(|event| event.id == id) {
1200                return Some(relay);
1201            }
1202        }
1203        None
1204    }
1205
1206    /// Have `signer` sign the event `unsigned` describes as `author`, and
1207    /// send it to the connected relays.
1208    pub async fn sign_and_publish(
1209        &self,
1210        signer: &Signer,
1211        author: PublicKey,
1212        unsigned: EventBuilder,
1213    ) -> Result<Event, PublishError> {
1214        let event = signer.sign(author, unsigned).await.map_err(PublishError::Sign)?;
1215        let accepted = self.publish(&event).await?;
1216        tracing::info!("published {} (kind {}) to {accepted} relay(s)", event.id, event.kind.as_u16());
1217        Ok(event)
1218    }
1219
1220    /// How `notes` stand, as far as `source` knows: what was made of them,
1221    /// with the likes and reposts of `account` told apart, and which relays
1222    /// they were seen on.
1223    ///
1224    /// The count is always of what the store holds. Asking the relays
1225    /// brings what they have into the store first, so an answer from them
1226    /// is never less than the store's own.
1227    ///
1228    /// The relays are asked for the notes themselves as well: each that
1229    /// sends one has it, and is one of those it was [seen on](Standing).
1230    pub async fn standing(
1231        &self,
1232        source: Source,
1233        notes: Vec<EventId>,
1234        account: Option<PublicKey>,
1235    ) -> Result<Standing, FetchError> {
1236        let mut events = Vec::new();
1237        for chunk in notes.chunks(ENGAGEMENT_NOTES_PER_REQUEST) {
1238            if source == Source::Relays {
1239                let mut filters = engagement_filters(chunk, account, ENGAGEMENT_LIMIT);
1240                filters.push(Filter::new().ids(chunk.iter().copied()));
1241                // Fetched for the store's sake: it is what is counted.
1242                let _into_the_store = self.fetch(filters).await?;
1243            }
1244            events.extend(self.events(Source::Store, engagement_filters(chunk, account, ENGAGEMENT_STORE_LIMIT)).await?);
1245        }
1246        let seen_on = self.seen_on(&notes);
1247        Ok(Standing { engagement: engagement::tally(events, &notes.into_iter().collect(), account), seen_on })
1248    }
1249
1250    /// Who left `what` on `note`, as far as the store holds: the same
1251    /// events its count is of (see [`Self::standing`]), so that who is
1252    /// listed is who was counted.
1253    pub async fn who_did(&self, note: EventId, what: Left) -> Result<Vec<Doer>, FetchError> {
1254        let filter = Filter::new().kinds(what.kinds().iter().copied()).event(note).limit(ENGAGEMENT_STORE_LIMIT);
1255        let events = self.events(Source::Store, vec![filter]).await?;
1256        Ok(engagement::who_did(events, note, what))
1257    }
1258
1259    /// Listen on the connected relays for the receipts of `note` until one
1260    /// of them `is_it`. Returns whether one was; `false` when the relays
1261    /// stopped sending first.
1262    async fn receipts_until(&self, note: EventId, is_it: &impl Fn(&Event) -> bool) -> bool {
1263        let relays = self.reachable_relays().await;
1264        let filter = Filter::new().kind(Kind::ZapReceipt).event(note).limit(RECEIPT_LIMIT);
1265        let targets: HashMap<RelayUrl, Vec<Filter>> = relays.into_iter().map(|url| (url, vec![filter.clone()])).collect();
1266        if targets.is_empty() {
1267            return false;
1268        }
1269        // One request, kept open: what the relays have now, and whatever
1270        // arrives after.
1271        let listening = self
1272            .client
1273            .stream_events(targets)
1274            .timeout(RECEIPT_WAIT)
1275            .policy(ReqExitPolicy::WaitDurationAfterEOSE(RECEIPT_WAIT))
1276            .await;
1277        let Ok(mut receipts) = listening else {
1278            return false;
1279        };
1280        while let Some((_, receipt)) = receipts.next().await {
1281            if receipt.is_ok_and(|receipt| is_it(&receipt)) {
1282                return true;
1283            }
1284        }
1285        false
1286    }
1287
1288    /// Wait for the receipt that says the invoice `bolt11`, which zaps
1289    /// `note`, was paid. Returns whether it came within [`RECEIPT_WAIT`].
1290    ///
1291    /// The receipt is kept in the store as everything a relay sends is, so
1292    /// the note's count has it afterwards.
1293    pub async fn await_zap_receipt(&self, note: EventId, bolt11: String) -> bool {
1294        let is_it = |receipt: &Event| {
1295            receipt
1296                .tags
1297                .iter()
1298                .any(|tag| tag.kind() == "bolt11" && tag.content().is_some_and(|invoice| invoice.eq_ignore_ascii_case(&bolt11)))
1299        };
1300        let waiting = async {
1301            // Relays drop connections; a wait this long outlives some.
1302            while !self.receipts_until(note, &is_it).await {
1303                tokio::time::sleep(RECEIPT_RETRY).await;
1304            }
1305        };
1306        tokio::time::timeout(RECEIPT_WAIT, waiting).await.is_ok()
1307    }
1308
1309    /// Send `event` to the connected relays. It has gone out when at least
1310    /// one took it, and is then kept in the store as well, as anything a
1311    /// relay sends is. Returns how many took it.
1312    ///
1313    /// An event no relay took is not kept: the store would show as
1314    /// published what nobody else can see.
1315    pub async fn publish(&self, event: &Event) -> Result<usize, PublishError> {
1316        let (own, theirs) = join(self.send_home(event), self.deliver(event)).await;
1317        let took: Vec<RelayUrl> = match own {
1318            Ok(own) => own.into_iter().chain(theirs).collect(),
1319            Err(e) if theirs.is_empty() => return Err(e),
1320            Err(e) => {
1321                tracing::warn!("none of the account's own relays took the event: {e:?}");
1322                theirs
1323            }
1324        };
1325        if let Err(e) = self.client.database().save_event(event).await {
1326            tracing::warn!("the published event could not be kept in the store: {e}");
1327        }
1328        if FEED_KINDS.contains(&event.kind) {
1329            // The relays that took it have it.
1330            let mut sightings = self.sightings();
1331            for relay in &took {
1332                sightings.record(event.id, relay);
1333            }
1334        }
1335        Ok(took.len())
1336    }
1337
1338    /// Send `event` to the account's own relays that are connected: those
1339    /// that took it, or why none did.
1340    async fn send_home(&self, event: &Event) -> Result<Vec<RelayUrl>, PublishError> {
1341        let relays = self.reachable_relays().await;
1342        if relays.is_empty() {
1343            return Err(PublishError::NoRelayReachable);
1344        }
1345        let output = self
1346            .client
1347            .send_event(event)
1348            .to(relays)
1349            .save_into_database(false)
1350            .ok_timeout(PUBLISH_TIMEOUT)
1351            .await
1352            .map_err(|e| PublishError::Failed(e.to_string()))?;
1353        if output.success.is_empty() {
1354            let reason = output.failed.into_values().next().unwrap_or_default();
1355            return Err(PublishError::Refused(reason));
1356        }
1357        for (relay, reason) in &output.failed {
1358            tracing::warn!("{relay} did not take the event: {reason}");
1359        }
1360        Ok(output.success.into_keys().collect())
1361    }
1362
1363    /// Send `event` to the people it names, if it is of a kind that is
1364    /// meant for them: to the relays they read, as their relay lists have
1365    /// them, so many for each and no more in all than may be reached for.
1366    /// Returns those that took it. That none did is no error: it is on the
1367    /// account's own relays, where anyone can find it.
1368    async fn deliver(&self, event: &Event) -> Vec<RelayUrl> {
1369        if !DELIVERED_KINDS.contains(&event.kind) {
1370            return Vec::new();
1371        }
1372        let mut seen = HashSet::new();
1373        let people: Vec<PublicKey> =
1374            event.tags.public_keys().filter(|person| *person != event.pubkey && seen.insert(*person)).collect();
1375        if people.is_empty() {
1376            return Vec::new();
1377        }
1378        let listed = self.relays_of(&people, Listed::Read, true).await;
1379        let relays: Vec<RelayUrl> = self.reach_for(&listed).await.into_iter().map(|(relay, _)| relay).collect();
1380        if relays.is_empty() {
1381            return Vec::new();
1382        }
1383        match self.others.send_event(event).to(relays).save_into_database(false).ok_timeout(PUBLISH_TIMEOUT).await {
1384            Ok(output) => {
1385                for (relay, reason) in &output.failed {
1386                    tracing::debug!("{relay}, which someone named reads, did not take the event: {reason}");
1387                }
1388                output.success.into_keys().collect()
1389            }
1390            Err(e) => {
1391                tracing::warn!("the event could not be sent to the people it names: {e}");
1392                Vec::new()
1393            }
1394        }
1395    }
1396
1397    /// The events any of `filters` matches, according to `source`. A store
1398    /// that can't be read knows of none.
1399    async fn events(&self, source: Source, filters: Vec<Filter>) -> Result<Vec<Event>, FetchError> {
1400        match source {
1401            Source::Relays => Ok(self.fetch(filters).await?.collect()),
1402            Source::Store => {
1403                let mut events = Vec::new();
1404                for filter in filters {
1405                    match self.client.database().query(filter).await {
1406                        Ok(found) => events.extend(found),
1407                        Err(e) => tracing::warn!("the event store could not be read: {e}"),
1408                    }
1409                }
1410                Ok(events)
1411            }
1412        }
1413    }
1414
1415    /// The notes `wanted`, each as a row shows it, as far as `source` has
1416    /// them: the store, and for the relays' turn the relays as well, for
1417    /// the ones the store doesn't have, which get `wait` to send them: the
1418    /// account's own, and then, for a note `wanted` knows more of, the
1419    /// relays its author writes to and the relay it is said to be on. One
1420    /// that isn't found is left out, and so is one that is no note a row
1421    /// shows.
1422    async fn notes_by_id(
1423        &self,
1424        wanted: &HashMap<EventId, Whereabouts>,
1425        source: Source,
1426        wait: Duration,
1427    ) -> HashMap<EventId, Note> {
1428        let known = wanted;
1429        let wanted: Vec<EventId> = wanted.keys().copied().collect();
1430        let mut found: HashMap<EventId, Event> = HashMap::new();
1431        if let Ok(stored) = self.events(Source::Store, filters_by_id(&wanted)).await {
1432            found.extend(stored.into_iter().map(|event| (event.id, event)));
1433        }
1434        let missing: Vec<EventId> = wanted.iter().filter(|id| !found.contains_key(id)).copied().collect();
1435        if source == Source::Relays && !missing.is_empty() {
1436            match self.fetch_within(filters_by_id(&missing), wait).await {
1437                Ok(fetched) => found.extend(fetched.map(|event| (event.id, event))),
1438                Err(e) => tracing::warn!("{} note(s) could not be asked for by id: {e:?}", missing.len()),
1439            }
1440            // Those the account's own relays don't have may be elsewhere.
1441            // Given as long as the others were, and no longer: a list of
1442            // notes waits here.
1443            let elsewhere: Vec<(EventId, &Whereabouts)> = missing
1444                .iter()
1445                .filter(|id| !found.contains_key(id))
1446                .filter_map(|id| known.get(id).map(|whereabouts| (*id, whereabouts)))
1447                .collect();
1448            found.extend(self.events_elsewhere(&elsewhere, wait).await.into_iter().map(|event| (event.id, event)));
1449        }
1450
1451        found
1452            .into_values()
1453            .filter(|event| wanted.contains(&event.id) && FEED_KINDS.contains(&event.kind))
1454            .map(|event| (event.id, Note::from(event)))
1455            .collect()
1456    }
1457
1458    /// Those of the events `sought` that the relays they may be on have,
1459    /// beside the account's own: the relays an event's author writes to,
1460    /// if who that is is known, and the relay it is said to be on. They
1461    /// get `wait` between them; nothing, if that runs out, or if nothing
1462    /// is known of where any is.
1463    async fn events_elsewhere(&self, sought: &[(EventId, &Whereabouts)], wait: Duration) -> Vec<Event> {
1464        let written_by = |people: &[PublicKey]| -> Vec<EventId> {
1465            let written = |known: &Whereabouts| known.author.is_some_and(|author| people.contains(&author));
1466            sought.iter().filter(|(_, known)| written(known)).map(|(id, _)| *id).collect()
1467        };
1468        let people: Vec<PublicKey> = {
1469            let mut seen = HashSet::new();
1470            sought.iter().filter_map(|(_, known)| known.author).filter(|author| seen.insert(*author)).collect()
1471        };
1472        let said: Vec<(EventId, RelayUrl)> =
1473            sought.iter().filter_map(|(id, known)| known.relay.clone().map(|relay| (*id, relay))).collect();
1474        if people.is_empty() && said.is_empty() {
1475            return Vec::new();
1476        }
1477        let theirs = self.ask_their_relays(&people, Listed::Write, true, |people| filters_by_id(&written_by(people)));
1478        match tokio::time::timeout(wait, join(theirs, self.ask_where_said(&said))).await {
1479            Ok((theirs, said)) => theirs.into_iter().chain(said).collect(),
1480            Err(_) => {
1481                tracing::debug!("the relays {} event(s) may be on took too long to ask", sought.len());
1482                Vec::new()
1483            }
1484        }
1485    }
1486
1487    /// `notes`, each with the notes its row shows it quoting, and those
1488    /// with the notes they quote in turn, [`QUOTE_DEPTH`] notes deep and no
1489    /// deeper, as far as `source` has them (see [`Self::notes_by_id`]).
1490    async fn with_quotes(&self, notes: Vec<Note>, source: Source) -> Vec<Note> {
1491        // With where each is, as far as the address that names it says.
1492        let quoted_by = |notes: &mut dyn Iterator<Item = &Note>| -> HashMap<EventId, Whereabouts> {
1493            notes.flat_map(|note| note.quotes_shown().map(|quote| (quote.id, quote.whereabouts()))).collect()
1494        };
1495        // What is quoted is found a level at a time, from the notes down.
1496        let mut levels: Vec<HashMap<EventId, Note>> = Vec::new();
1497        let mut wanted = quoted_by(&mut notes.iter());
1498        while !wanted.is_empty() && levels.len() < QUOTE_DEPTH {
1499            let found = self.notes_by_id(&wanted, source, QUOTES_WAIT).await;
1500            wanted = quoted_by(&mut found.values());
1501            levels.push(found);
1502        }
1503        // And put together from the deepest up: each note with the notes
1504        // it quotes, which have theirs already.
1505        let mut quoted: HashMap<EventId, Note> = HashMap::new();
1506        for level in levels.into_iter().rev() {
1507            quoted = level.into_iter().map(|(id, note)| (id, note.with_quoted(&quoted))).collect();
1508        }
1509        notes.into_iter().map(|note| note.with_quoted(&quoted)).collect()
1510    }
1511
1512    /// The notes `listed` names, in its order, each as a row shows it,
1513    /// with the notes it quotes: from the store, and from the relays for
1514    /// those the store doesn't have, the account's own and then wherever
1515    /// `listed` says each may be. One that nobody has is left out, and so
1516    /// is one that is no note a row shows.
1517    pub async fn notes_listed(&self, listed: Vec<(EventId, Whereabouts)>) -> Vec<Note> {
1518        let ids: Vec<EventId> = listed.iter().map(|(id, _)| *id).collect();
1519        let wanted: HashMap<EventId, Whereabouts> = listed.into_iter().collect();
1520        let mut found = self.notes_by_id(&wanted, Source::Relays, FETCH_TIMEOUT).await;
1521        let notes = ids.iter().filter_map(|id| found.remove(id)).collect();
1522        self.with_quotes(notes, Source::Relays).await
1523    }
1524
1525    /// `event`, which the store just got, as a row shows it: with the
1526    /// notes it quotes, if the store has them.
1527    pub async fn note(&self, event: Event) -> Note {
1528        let mut notes = self.with_quotes(vec![Note::from(event.clone())], Source::Store).await;
1529        notes.pop().unwrap_or_else(|| Note::from(event))
1530    }
1531
1532    /// `note`, which is being written, with the notes it quotes: from the
1533    /// store, and from the relays for those the store doesn't have, as a
1534    /// list of notes would look for them.
1535    pub async fn quoting(&self, note: Note) -> Note {
1536        let mut notes = self.with_quotes(vec![note.clone()], Source::Relays).await;
1537        notes.pop().unwrap_or(note)
1538    }
1539
1540    /// The conversation the note `focused` is part of, as far as `source`
1541    /// knows it: the note in full, and the others as rows show them. Empty
1542    /// if the note itself is not to be found.
1543    ///
1544    /// Three questions are asked, as Vega asks them. Which notes name the
1545    /// conversation's root (and the root itself), which is asked of the
1546    /// relays of those whose conversation it is as well; then, if those are few,
1547    /// which notes name any of them, since some clients tag only the note
1548    /// they answer; and last, one at a time, the notes between the focused
1549    /// one and the root that neither brought.
1550    ///
1551    /// Naming a note is not answering it: a note that only cites one of
1552    /// these is no part of the conversation, and is left out.
1553    pub async fn thread(&self, source: Source, focused: EventId, whereabouts: &Whereabouts) -> Result<Vec<Note>, FetchError> {
1554        // The store may have the note when it is the relays' turn: they are
1555        // then not asked for it again.
1556        let mut note = self.events(Source::Store, vec![Filter::new().id(focused)]).await?.into_iter().next();
1557        if note.is_none() && source == Source::Relays {
1558            note = self.events(source, vec![Filter::new().id(focused)]).await?.into_iter().next();
1559        }
1560        // Not on the account's own relays: where whatever named it said.
1561        if note.is_none() && source == Source::Relays {
1562            let elsewhere = self.events_elsewhere(&[(focused, whereabouts)], FETCH_TIMEOUT).await;
1563            note = elsewhere.into_iter().find(|event| event.id == focused);
1564        }
1565        let Some(note) = note else {
1566            return Ok(Vec::new());
1567        };
1568        let root = reply_to(&note).map_or(focused, |reply| reply.root);
1569        let mut parent = reply_to(&note).map(|reply| reply.parent);
1570        // Whose conversation it is, as far as the note says: who wrote
1571        // it, and the first few of those it names.
1572        let people: Vec<PublicKey> = {
1573            let mut seen = HashSet::new();
1574            let named = std::iter::once(note.pubkey).chain(note.tags.public_keys());
1575            named.filter(|person| seen.insert(*person)).take(THREAD_PEOPLE).collect()
1576        };
1577        let mut found: HashMap<EventId, Event> = HashMap::from([(focused, note)]);
1578
1579        let naming = |ids: Vec<EventId>| Filter::new().kinds(FEED_KINDS).events(ids).limit(THREAD_LIMIT);
1580        // Relays are free to send more than the limit asks for, so it is
1581        // kept to here: the root, and so many of the rest.
1582        let keep = |found: &mut HashMap<EventId, Event>, events: Vec<Event>| {
1583            let (roots, rest): (Vec<Event>, Vec<Event>) = events.into_iter().partition(|event| event.id == root);
1584            found.extend(roots.into_iter().chain(rest.into_iter().take(THREAD_LIMIT)).map(|event| (event.id, event)));
1585        };
1586
1587        let mut filters = vec![naming(vec![root])];
1588        if root != focused {
1589            filters.push(Filter::new().id(root));
1590        }
1591        // The account's own relays, and the relays of those whose
1592        // conversation it is: what they wrote is where they write, and
1593        // what was written to them is where they read.
1594        let theirs = async {
1595            match source {
1596                Source::Relays => self.ask_their_relays(&people, Listed::Either, true, |_| filters.clone()).await,
1597                Source::Store => Vec::new(),
1598            }
1599        };
1600        let (own, theirs) = join(self.events(source, filters.clone()), theirs).await;
1601        keep(&mut found, own?);
1602        keep(&mut found, theirs);
1603
1604        if found.len() < THREAD_ASK_AGAIN_UNDER {
1605            let known = found.keys().copied().collect();
1606            keep(&mut found, self.events(source, vec![naming(known)]).await?);
1607        }
1608
1609        let mut ancestors = HashSet::new();
1610        for _ in 0..THREAD_ANCESTORS {
1611            let Some(id) = parent else {
1612                break;
1613            };
1614            if let Entry::Vacant(missing) = found.entry(id) {
1615                let Some(event) = self.events(source, vec![Filter::new().id(id)]).await?.into_iter().next() else {
1616                    break;
1617                };
1618                missing.insert(event);
1619            }
1620            ancestors.insert(id);
1621            parent = found.get(&id).and_then(reply_to).map(|reply| reply.parent);
1622        }
1623
1624        let belongs = |event: &Event| {
1625            event.id == focused
1626                || event.id == root
1627                || ancestors.contains(&event.id)
1628                || reply_to(event).is_some_and(|reply| reply.root == root || found.contains_key(&reply.parent))
1629        };
1630        let strangers: Vec<EventId> = found.values().filter(|event| !belongs(event)).map(|event| event.id).collect();
1631        for id in strangers {
1632            found.remove(&id);
1633        }
1634
1635        let notes = found.into_values().map(|event| if event.id == focused { Note::in_full(&event) } else { Note::from(event) });
1636        Ok(self.with_quotes(notes.collect(), source).await)
1637    }
1638
1639    /// The newest notes of `authors` that are already in the store.
1640    pub async fn cached_feed(&self, authors: &[PublicKey], limit: usize) -> Result<Vec<Note>, String> {
1641        let mut notes = Vec::new();
1642        for filter in feed_filters(authors, None, limit) {
1643            let events = self.client.database().query(filter).await.map_err(|e| e.to_string())?;
1644            notes.extend(events.into_iter().map(Note::from));
1645        }
1646        Ok(self.with_quotes(feed::newest(notes, limit), Source::Store).await)
1647    }
1648
1649    /// One page of the notes of `authors` from the relays: the `limit`
1650    /// newest written at or before `until`, or the newest of all, of what
1651    /// the account's own relays have and what the relays the authors
1652    /// write to have. Nobody's notes are none, without asking.
1653    pub async fn fetch_feed(&self, authors: &[PublicKey], until: Option<u64>, limit: usize) -> Result<Vec<Note>, FetchError> {
1654        let filters = feed_filters(authors, until, limit);
1655        if filters.is_empty() {
1656            return Ok(Vec::new());
1657        }
1658        // The account's own relays about everyone, and at the same time
1659        // the relays the authors write to, each about those who do.
1660        let theirs = self.ask_their_relays(authors, Listed::Write, false, |people| feed_filters(people, until, limit));
1661        let (own, theirs) = join(self.fetch(filters), theirs).await;
1662        let events: Vec<Event> = match own {
1663            Ok(own) => own.chain(theirs).collect(),
1664            Err(e) if theirs.is_empty() => return Err(e),
1665            Err(e) => {
1666                tracing::warn!("the account's own relays could not be asked for notes: {e:?}");
1667                theirs
1668            }
1669        };
1670        Ok(self.with_quotes(feed::newest(events.into_iter().map(Note::from), limit), Source::Relays).await)
1671    }
1672
1673    // =========================================================================
1674    // Notifications
1675    // =========================================================================
1676
1677    /// What `source` has to tell `account` of: one page of the events
1678    /// that name it, the newest written after `since` and at or before
1679    /// `until` where those are given, each read with the note it is about
1680    /// (see [`notifications`]).
1681    ///
1682    /// The relays asked are the account's own and the ones its relay list
1683    /// says it reads: where others send what they write to it (NIP-65).
1684    pub async fn notifications(
1685        &self,
1686        source: Source,
1687        account: PublicKey,
1688        since: Option<u64>,
1689        until: Option<u64>,
1690    ) -> Result<Notified, FetchError> {
1691        let filter = notifications::filter(account, since, until, NOTIFICATIONS_PAGE);
1692        let mut events: Vec<Event> = match source {
1693            Source::Store => self.events(Source::Store, vec![filter]).await?,
1694            Source::Relays => {
1695                let whose = [account];
1696                let inbox = self.ask_their_relays(&whose, Listed::Read, true, |_| vec![filter.clone()]);
1697                let (own, inbox) = join(self.fetch(vec![filter.clone()]), inbox).await;
1698                match own {
1699                    Ok(own) => own.chain(inbox).collect(),
1700                    Err(e) if inbox.is_empty() => return Err(e),
1701                    Err(e) => {
1702                        tracing::warn!("the account's own relays could not be asked what names it: {e:?}");
1703                        inbox
1704                    }
1705                }
1706            }
1707        };
1708        let mut seen = HashSet::new();
1709        events.retain(|event| seen.insert(event.id));
1710        events.sort_by(|a, b| b.created_at.cmp(&a.created_at).then(a.id.cmp(&b.id)));
1711        // A page is the newest so many, whatever the relays sent: what is
1712        // older is asked for from where this one ends.
1713        let full = events.len() >= NOTIFICATIONS_PAGE;
1714        events.truncate(NOTIFICATIONS_PAGE);
1715        let oldest = events.last().map(|event| event.created_at.as_secs());
1716
1717        // The notes they are about say what they are: an answer to the
1718        // account, or to someone else; a reaction to a note of its own.
1719        let wanted: HashMap<EventId, Whereabouts> =
1720            events.iter().filter_map(notifications::about).map(|id| (id, Whereabouts::default())).collect();
1721        let at_hand = self.notes_by_id(&wanted, source, ABOUT_WAIT).await;
1722        let mut read: Vec<Notification> =
1723            events.iter().filter_map(|event| notifications::read(event, account, &at_hand)).collect();
1724
1725        // Those that are notes show as notes do: with what they quote.
1726        let notes: Vec<Note> = read.iter().filter_map(|notification| notification.note.clone()).collect();
1727        let mut with_quotes: HashMap<EventId, Note> =
1728            self.with_quotes(notes, source).await.into_iter().map(|note| (note.id, note)).collect();
1729        for notification in &mut read {
1730            if let Some(note) = with_quotes.remove(&notification.id) {
1731                notification.note = Some(note);
1732            }
1733        }
1734        Ok(Notified { notifications: read, oldest, full })
1735    }
1736
1737    /// The newest list of `kind` that `account` wrote, of those in the
1738    /// store, if it has one: a contact list, a bookmark list.
1739    async fn stored_list(&self, kind: Kind, account: PublicKey) -> Option<Event> {
1740        let filter = Filter::new().kind(kind).author(account);
1741        match self.client.database().query(filter).await {
1742            Ok(events) => newest(events),
1743            Err(e) => {
1744                tracing::warn!("a list (kind {}) could not be read from the store: {e}", kind.as_u16());
1745                None
1746            }
1747        }
1748    }
1749
1750    /// The newest list of `kind` that `account` wrote, after asking the
1751    /// relays for it, and whether every relay of the pool answered. What
1752    /// the relays send is kept in the store, which only ever keeps the
1753    /// newest list, so the store is read as well: a relay that is behind
1754    /// doesn't undo a newer list already seen.
1755    async fn asked_list(&self, kind: Kind, account: PublicKey) -> Result<(Option<Event>, bool), FetchError> {
1756        let filter = Filter::new().kind(kind).author(account).limit(1);
1757        let (fetched, everywhere) = self.fetch_from_each(vec![filter], FETCH_TIMEOUT).await?;
1758        Ok((newest(self.stored_list(kind, account).await.into_iter().chain(fetched)), everywhere))
1759    }
1760
1761    /// The newest list of `kind` that `account` wrote, after asking the
1762    /// relays for it. `None` if none of those that answered has one.
1763    async fn newest_list(&self, kind: Kind, account: PublicKey) -> Result<Option<Event>, FetchError> {
1764        Ok(self.asked_list(kind, account).await?.0)
1765    }
1766
1767    /// The newest list of `kind` that `account` wrote, to be written again
1768    /// with a change. `None`, which is leave to write a first one, only if
1769    /// every relay of the pool answered and none has one: a relay that
1770    /// didn't answer may be the one that does, and a first list would
1771    /// replace it there as everywhere.
1772    async fn list_to_change(&self, kind: Kind, account: PublicKey) -> Result<Option<Event>, FetchError> {
1773        match self.asked_list(kind, account).await? {
1774            (None, false) => Err(FetchError::Incomplete),
1775            (list, _) => Ok(list),
1776        }
1777    }
1778
1779    /// Who `account` follows, by the contact list already in the store.
1780    /// `None` if the store has no list of theirs.
1781    pub async fn cached_contacts(&self, account: PublicKey) -> Option<Vec<PublicKey>> {
1782        self.stored_list(Kind::ContactList, account).await.as_ref().map(contacts::followed)
1783    }
1784
1785    /// Who `account` follows, after asking the relays for their contact
1786    /// list. `None` if nobody has a list of theirs.
1787    pub async fn fetch_contacts(&self, account: PublicKey) -> Result<Option<Vec<PublicKey>>, FetchError> {
1788        Ok(self.newest_list(Kind::ContactList, account).await?.as_ref().map(contacts::followed))
1789    }
1790
1791    /// Have `account` follow `person` (`follow`) or stop following them:
1792    /// its newest contact list, asked of the relays just now, signed again
1793    /// with that one change and sent out. Returns who `account` follows
1794    /// after it.
1795    ///
1796    /// With no list anywhere, a first one is only written if `first_list`
1797    /// says so; otherwise that is the error, and nothing is sent.
1798    pub async fn set_following(
1799        &self,
1800        signer: &Signer,
1801        account: PublicKey,
1802        person: PublicKey,
1803        follow: bool,
1804        first_list: bool,
1805    ) -> Result<Vec<PublicKey>, FollowError> {
1806        let list = self.list_to_change(Kind::ContactList, account).await.map_err(FollowError::Fetch)?;
1807        if list.is_none() && follow && !first_list {
1808            return Err(FollowError::NoList);
1809        }
1810        let unchanged = || list.as_ref().map(contacts::followed).unwrap_or_default();
1811        let Some(changed) = contacts::changed(list.as_ref(), person, follow, Timestamp::now()) else {
1812            return Ok(unchanged());
1813        };
1814        let sent = self.sign_and_publish(signer, account, changed).await.map_err(FollowError::Publish)?;
1815        Ok(contacts::followed(&sent))
1816    }
1817
1818    /// The bookmarks of `account` that `list`, its newest bookmark list,
1819    /// keeps to itself, which `signer` decrypts.
1820    ///
1821    /// `known` is what was read before. If it was read from this very
1822    /// list, it is the answer, and nothing is decrypted again: a remote
1823    /// signer may ask a person about each request.
1824    async fn read_bookmarks(
1825        &self,
1826        signer: &Signer,
1827        account: PublicKey,
1828        list: Option<Event>,
1829        known: Option<Bookmarks>,
1830    ) -> Result<Bookmarks, ListError> {
1831        let Some(list) = list else {
1832            return Ok(Bookmarks::default());
1833        };
1834        if let Some(known) = known.filter(|known| known.list().is_some_and(|read| read.id == list.id)) {
1835            return Ok(known);
1836        }
1837        let private = Self::read_private(signer, account, &list).await?;
1838        Ok(Bookmarks::new(Some(list), private))
1839    }
1840
1841    /// The tags `list` keeps to itself (NIP-51), which `signer` decrypts.
1842    /// A list that keeps nothing to itself has no content, and is not
1843    /// taken to the signer.
1844    async fn read_private(signer: &Signer, account: PublicKey, list: &Event) -> Result<PrivateTags, ListError> {
1845        if list.content.trim().is_empty() {
1846            return Ok(Vec::new());
1847        }
1848        let json = signer.decrypt_from_self(account, &list.content).await.map_err(ListError::Unreadable)?;
1849        bookmarks::decode(&json).map_err(|e| ListError::Unreadable(SignError::Cipher(e)))
1850    }
1851
1852    /// `private`, the tags a list keeps to itself, as its content:
1853    /// encrypted by `signer` to `account` itself, or nothing at all when
1854    /// there are none.
1855    async fn written_private(signer: &Signer, account: PublicKey, private: &PrivateTags) -> Result<String, ListError> {
1856        if private.is_empty() {
1857            return Ok(String::new());
1858        }
1859        let sign_error = |e| ListError::Publish(PublishError::Sign(e));
1860        signer.encrypt_to_self(account, &bookmarks::encode(private)).await.map_err(sign_error)
1861    }
1862
1863    /// The bookmarks of `account`, as far as `source` knows: by the list
1864    /// in the store, or by the newest the relays have. An account with no
1865    /// list has none. See [`Self::read_bookmarks`] for `known`.
1866    pub async fn bookmarks(
1867        &self,
1868        source: Source,
1869        signer: &Signer,
1870        account: PublicKey,
1871        known: Option<Bookmarks>,
1872    ) -> Result<Bookmarks, ListError> {
1873        let list = match source {
1874            Source::Store => self.stored_list(Kind::Bookmarks, account).await,
1875            Source::Relays => self.newest_list(Kind::Bookmarks, account).await.map_err(ListError::Fetch)?,
1876        };
1877        self.read_bookmarks(signer, account, list, known).await
1878    }
1879
1880    /// Have `account` bookmark `note` (`bookmark`), privately, or take its
1881    /// bookmark off: its newest bookmark list, asked of the relays just
1882    /// now, with that one change to what it keeps to itself, encrypted
1883    /// anew, signed and sent out. What the list says to anyone goes out
1884    /// as it came. Returns the account's bookmarks after it. See
1885    /// [`Self::read_bookmarks`] for `known`.
1886    ///
1887    /// With no list anywhere, a first one is only written if `first_list`
1888    /// says so; otherwise that is the error, and nothing is sent. Nor is
1889    /// anything sent when what the list keeps to itself can't be read.
1890    pub async fn set_bookmarked(
1891        &self,
1892        signer: &Signer,
1893        account: PublicKey,
1894        note: EventId,
1895        bookmark: bool,
1896        first_list: bool,
1897        known: Option<Bookmarks>,
1898    ) -> Result<Bookmarks, ListError> {
1899        let list = self.list_to_change(Kind::Bookmarks, account).await.map_err(ListError::Fetch)?;
1900        if list.is_none() && bookmark && !first_list {
1901            return Err(ListError::NoList);
1902        }
1903        let current = self.read_bookmarks(signer, account, list, known).await?;
1904        // Where the note is, for whoever reads the list elsewhere.
1905        let hint = self.seen_on(&[note]).remove(&note).and_then(|relays| relays.into_iter().next());
1906        let Some(private) = current.changed(note, hint.as_ref(), bookmark) else {
1907            return Ok(current);
1908        };
1909        let content = Self::written_private(signer, account, &private).await?;
1910        let unsigned = bookmarks::list(current.list(), content, Timestamp::now());
1911        let sent = self.sign_and_publish(signer, account, unsigned).await.map_err(ListError::Publish)?;
1912        Ok(Bookmarks::new(Some(sent), private))
1913    }
1914
1915    // =========================================================================
1916    // Drafts
1917    // =========================================================================
1918
1919    /// Have the relay of this machine keep `text` as the draft of
1920    /// `account` for `target`: a draft wrap (see [`kept_drafts`]), which
1921    /// `signer` encrypts to the account itself and signs, in place of the
1922    /// one it had, with `said` for what it says of the files it links to.
1923    /// A blank `text` is a draft done with, and is kept as that. It goes
1924    /// to that relay and to no other.
1925    pub async fn keep_draft(
1926        &self,
1927        signer: &Signer,
1928        account: PublicKey,
1929        target: Target,
1930        text: &str,
1931        said: &[Tag],
1932    ) -> Result<(), String> {
1933        let which = Filter::new().kind(DRAFT_KIND).author(account).identifier(kept_drafts::identifier(target));
1934        let earlier = newest(self.private.ask(which).await?);
1935        let now = Timestamp::now();
1936        let content = if text.trim().is_empty() {
1937            String::new()
1938        } else {
1939            let written = kept_drafts::written(account, text, said, now);
1940            signer.encrypt_to_self(account, &written).await.map_err(|e| format!("{e:?}"))?
1941        };
1942        let unsigned = kept_drafts::wrap(target, content, earlier.as_ref(), now);
1943        let event = signer.sign(account, unsigned).await.map_err(|e| format!("{e:?}"))?;
1944        self.private.send(&event).await
1945    }
1946
1947    /// The drafts of `account` that the relay of this machine keeps, each
1948    /// with what it is a draft of and what it says of the files it links
1949    /// to: those of this client's that are not done with, which `signer`
1950    /// decrypts. One that can't be read is left out.
1951    pub async fn kept_drafts(&self, signer: &Signer, account: PublicKey) -> Result<Vec<(Target, String, Vec<Tag>)>, String> {
1952        let wraps = self.private.ask(Filter::new().kind(DRAFT_KIND).author(account)).await?;
1953        let mut drafts = Vec::new();
1954        for wrap in &wraps {
1955            let Some((target, content)) = kept_drafts::kept(wrap).filter(|(_, content)| !content.trim().is_empty()) else {
1956                continue;
1957            };
1958            match signer.decrypt_from_self(account, content).await {
1959                Ok(json) => drafts.extend(kept_drafts::text_of(&json).map(|text| (target, text, kept_drafts::said_of(&json)))),
1960                Err(e) => tracing::warn!("a draft could not be read: {e:?}"),
1961            }
1962        }
1963        Ok(drafts)
1964    }
1965
1966    // =========================================================================
1967    // Searching
1968    // =========================================================================
1969
1970    /// What `relays`, the account's search relays, find of `what` for
1971    /// `words` (NIP-50), the best matches first, as each relay had them
1972    /// (see [`search::ranked`]).
1973    ///
1974    /// The relays are the account's own word, and any it names is asked:
1975    /// where it is, if it is one of the account's own, and otherwise among
1976    /// other people's relays, where it is let go of when it is not used.
1977    /// What was searched for goes to those relays and nowhere else: it is
1978    /// not logged, and not kept.
1979    async fn search_events(&self, relays: &[RelayUrl], words: &str, what: SearchFor) -> Result<Vec<Event>, FetchError> {
1980        Ok(search::ranked(self.ask_named(relays, search::filter(words, what)).await?))
1981    }
1982
1983    /// What each of `relays`, which the account itself named, sends for
1984    /// `filter`: one answer for each that gave one, as it gave it. That
1985    /// none of them is reached, or that none answers, is the error.
1986    async fn ask_named(&self, relays: &[RelayUrl], filter: Filter) -> Result<Vec<Vec<Event>>, FetchError> {
1987        let home: HashSet<RelayUrl> = self.reachable_relays().await.into_iter().collect();
1988        let (own, others): (Vec<RelayUrl>, Vec<RelayUrl>) = relays.iter().cloned().partition(|relay| home.contains(relay));
1989        let others = self.connected(others.into_iter().map(|relay| (relay, ())).collect()).await;
1990        let asks: Vec<(Pool, RelayUrl)> = own
1991            .into_iter()
1992            .map(|relay| (Pool::Home, relay))
1993            .chain(others.into_iter().map(|(relay, ())| (Pool::Others, relay)))
1994            .collect();
1995        if asks.is_empty() {
1996            return Err(FetchError::NoRelayReachable);
1997        }
1998        let asking = asks.iter().map(|(pool, relay)| self.ask(*pool, relay, vec![filter.clone()], SEARCH_TIMEOUT));
1999        let answers = join_all(asking).await;
2000
2001        let mut found = Vec::new();
2002        let mut failure = None;
2003        {
2004            let mut sightings = self.sightings();
2005            for ((_, relay), answer) in asks.iter().zip(answers) {
2006                match answer {
2007                    Ok(asked) => {
2008                        for event in asked.events.iter().filter(|event| FEED_KINDS.contains(&event.kind)) {
2009                            sightings.record(event.id, relay);
2010                        }
2011                        found.push(asked.events);
2012                    }
2013                    Err(e) => {
2014                        tracing::warn!("{relay} could not be searched: {e}");
2015                        failure = Some(e);
2016                    }
2017                }
2018            }
2019        }
2020        if found.is_empty() {
2021            return Err(FetchError::Failed(failure.unwrap_or_default()));
2022        }
2023        tracing::debug!("{} relay(s) the account named were asked: {} answered", asks.len(), found.len());
2024        Ok(found)
2025    }
2026
2027    /// The notes `relay` got last, as rows show them, the newest first:
2028    /// what a relay is like, for whoever typed its address. The account's
2029    /// own word, as its search relays are; and as with those, a relay it
2030    /// has blocked is not connected to.
2031    pub async fn relay_notes(&self, relay: &RelayUrl) -> Result<Vec<Note>, FetchError> {
2032        let answers = self.ask_named(std::slice::from_ref(relay), search::latest_notes()).await?;
2033        let mut events: Vec<Event> = answers.into_iter().flatten().filter(|event| FEED_KINDS.contains(&event.kind)).collect();
2034        events.sort_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| a.id.cmp(&b.id)));
2035        let notes = events.into_iter().map(Note::from).collect();
2036        Ok(self.with_quotes(notes, Source::Relays).await)
2037    }
2038
2039    /// What the account's search relays `relays` find of `what` for
2040    /// `words`: people with their profiles, or notes as rows show them,
2041    /// with the notes they quote. See [`Self::search_events`].
2042    pub async fn search(&self, relays: &[RelayUrl], words: &str, what: SearchFor) -> Result<Found, FetchError> {
2043        let events = self.search_events(relays, words, what).await?;
2044        match what {
2045            SearchFor::People => {
2046                // Each person once, where they first came; with their
2047                // profile as it stands now, which the store knows.
2048                let mut seen = HashSet::new();
2049                let ranked: Vec<PublicKey> = events
2050                    .iter()
2051                    .filter(|event| event.kind == Kind::Metadata)
2052                    .map(|event| event.pubkey)
2053                    .filter(|person| seen.insert(*person))
2054                    .collect();
2055                let mut profiles: HashMap<PublicKey, Profile> = newest_profiles(events).into_iter().collect();
2056                profiles.extend(self.cached_profiles(ranked.clone()).await);
2057                let people = ranked.into_iter().filter_map(|person| profiles.remove(&person).map(|profile| (person, profile)));
2058                Ok(Found::People(people.collect()))
2059            }
2060            SearchFor::Notes => {
2061                let notes = events.into_iter().filter(|event| FEED_KINDS.contains(&event.kind)).map(Note::from).collect();
2062                Ok(Found::Notes(self.with_quotes(notes, Source::Relays).await))
2063            }
2064        }
2065    }
2066
2067    // =========================================================================
2068    // The account's relays
2069    // =========================================================================
2070
2071    /// The relays of `account` that `list`, its newest list of one kind,
2072    /// names, with those it keeps to itself if `open` says to read them:
2073    /// that takes the signer, which may ask a person about each request.
2074    /// A list with no content keeps nothing, and is not taken to the
2075    /// signer. If `known` was read from this very list, it is the answer,
2076    /// and nothing is decrypted again.
2077    async fn read_listed(
2078        signer: &Signer,
2079        account: PublicKey,
2080        list: Option<Event>,
2081        known: Option<&ListedRelays>,
2082        open: bool,
2083    ) -> ListedRelays {
2084        let Some(list) = list else {
2085            return ListedRelays::default();
2086        };
2087        let same = |known: &&ListedRelays| known.list().is_some_and(|read| read.id == list.id);
2088        // Unless it left unread what is now to be read.
2089        if let Some(known) = known.filter(same).filter(|known| !open || *known.kept() != Kept::Unread) {
2090            return known.clone();
2091        }
2092        if !open && !list.content.trim().is_empty() {
2093            return ListedRelays::new(Some(list), Kept::Unread);
2094        }
2095        let kept = match Self::read_private(signer, account, &list).await {
2096            Ok(private) => Kept::Read(private),
2097            Err(ListError::Unreadable(why)) => {
2098                tracing::warn!("what a list (kind {}) keeps to itself could not be read: {why:?}", list.kind.as_u16());
2099                Kept::Unreadable(why)
2100            }
2101            // Reading asks no relay and sends nothing.
2102            Err(_) => Kept::Unread,
2103        };
2104        ListedRelays::new(Some(list), kept)
2105    }
2106
2107    /// The newest list of each of `kinds` that `account` wrote, after
2108    /// asking the relays for them in one question. As
2109    /// [`Self::newest_list`], for several.
2110    async fn newest_lists(&self, kinds: &[Kind], account: PublicKey) -> Result<HashMap<Kind, Event>, FetchError> {
2111        let filter = Filter::new().kinds(kinds.iter().copied()).author(account);
2112        let (fetched, _) = self.fetch_from_each(vec![filter], FETCH_TIMEOUT).await?;
2113        let mut lists: HashMap<Kind, Event> = HashMap::new();
2114        let mut take = |list: Event| match lists.get(&list.kind) {
2115            Some(known) if known.created_at >= list.created_at => {}
2116            _ => {
2117                lists.insert(list.kind, list);
2118            }
2119        };
2120        fetched.into_iter().for_each(&mut take);
2121        for kind in kinds {
2122            self.stored_list(*kind, account).await.into_iter().for_each(&mut take);
2123        }
2124        Ok(lists)
2125    }
2126
2127    /// The relay lists of `account`, as far as `source` knows: its relay
2128    /// list (NIP-65) and its other lists of relays (see
2129    /// [`relay_lists`]), by the lists in the store or by the newest the
2130    /// relays have. What the lists of `open` keep to themselves is read,
2131    /// and the others' is left unread. `known` is what was read before:
2132    /// nothing is decrypted twice.
2133    ///
2134    /// A list whose private part can't be read is no error: the relays it
2135    /// names for anyone are there, with why the others aren't.
2136    pub async fn relay_lists(
2137        &self,
2138        source: Source,
2139        signer: &Signer,
2140        account: PublicKey,
2141        known: Option<RelayLists>,
2142        open: &[Section],
2143    ) -> Result<RelayLists, FetchError> {
2144        let kinds: Vec<Kind> =
2145            std::iter::once(Kind::RelayList).chain(Section::LISTS.iter().map(|section| section.kind())).collect();
2146        let mut lists = match source {
2147            Source::Store => {
2148                let mut lists = HashMap::new();
2149                for kind in &kinds {
2150                    lists.extend(self.stored_list(*kind, account).await.map(|list| (*kind, list)));
2151                }
2152                lists
2153            }
2154            Source::Relays => self.newest_lists(&kinds, account).await?,
2155        };
2156        let advertised = lists.remove(&Kind::RelayList);
2157        let mut listed = HashMap::new();
2158        for section in Section::LISTS {
2159            let known = known.as_ref().and_then(|known| known.listed.get(&section));
2160            let read = Self::read_listed(signer, account, lists.remove(&section.kind()), known, open.contains(&section)).await;
2161            listed.insert(section, read);
2162        }
2163        Ok(RelayLists { advertised, listed })
2164    }
2165
2166    /// Have the relay list (NIP-65) of `account` name `outbox` for the
2167    /// relays it writes to and `inbox` for those it reads: its newest
2168    /// list, asked of the relays just now, with its relays replaced and
2169    /// the rest as it was, signed and sent out, to the relays it wrote to
2170    /// before and to those it writes to now, which are its own from then
2171    /// on. Returns the list after it; nothing is sent when it says so
2172    /// already.
2173    ///
2174    /// With no list anywhere, a first one is only written if `first_list`
2175    /// says so; otherwise that is the error, and nothing is sent.
2176    pub async fn set_advertised_relays(
2177        &self,
2178        signer: &Signer,
2179        account: PublicKey,
2180        outbox: &[RelayUrl],
2181        inbox: &[RelayUrl],
2182        first_list: bool,
2183    ) -> Result<Option<Event>, ListError> {
2184        let list = self.list_to_change(Kind::RelayList, account).await.map_err(ListError::Fetch)?;
2185        let Some(unsigned) = relay_lists::advertised_list(list.as_ref(), outbox, inbox, Timestamp::now()) else {
2186            return Ok(list);
2187        };
2188        if list.is_none() && !first_list {
2189            return Err(ListError::NoList);
2190        }
2191        let event = signer.sign(account, unsigned).await.map_err(|e| ListError::Publish(PublishError::Sign(e)))?;
2192        // Told to the relays it leaves as well as to those it joins:
2193        // whoever asks either finds where the account is now.
2194        let before = self.own().listed.clone();
2195        let both = outbox.iter().chain(&before).cloned().collect();
2196        self.join_account_relays(both).await;
2197        let published = self.publish(&event).await;
2198        self.join_account_relays(outbox.to_vec()).await;
2199        let accepted = published.map_err(ListError::Publish)?;
2200        tracing::info!("published the relay list {} to {accepted} relay(s)", event.id);
2201        Ok(Some(event))
2202    }
2203
2204    /// Have the relays of `section`, one of the lists of `relay` tags of
2205    /// `account`, be `relays`: its newest list of that kind, asked of the
2206    /// relays just now, with that change (see [`ListedRelays::changed`]),
2207    /// what it keeps to itself encrypted anew, signed and sent out.
2208    /// Returns the list's relays after it. See [`Self::read_listed`] for
2209    /// `known`.
2210    ///
2211    /// With no list anywhere, a first one is only written if `first_list`
2212    /// says so; otherwise that is the error, and nothing is sent. Nor is
2213    /// anything sent when what the list keeps to itself can't be read.
2214    pub async fn set_listed_relays(
2215        &self,
2216        signer: &Signer,
2217        account: PublicKey,
2218        section: Section,
2219        relays: &[RelayUrl],
2220        first_list: bool,
2221        known: Option<ListedRelays>,
2222    ) -> Result<ListedRelays, ListError> {
2223        let list = self.list_to_change(section.kind(), account).await.map_err(ListError::Fetch)?;
2224        let current = Self::read_listed(signer, account, list, known.as_ref(), true).await;
2225        if let Kept::Unreadable(why) = current.kept() {
2226            return Err(ListError::Unreadable(why.clone()));
2227        }
2228        let Some((tags, private)) = current.changed(section, relays) else {
2229            return Ok(current);
2230        };
2231        if current.list().is_none() && !first_list {
2232            return Err(ListError::NoList);
2233        }
2234        let content = Self::written_private(signer, account, &private).await?;
2235        let unsigned = relay_lists::listed(section, current.list(), tags, content, Timestamp::now());
2236        let sent = self.sign_and_publish(signer, account, unsigned).await.map_err(ListError::Publish)?;
2237        Ok(ListedRelays::new(Some(sent), Kept::Read(private)))
2238    }
2239
2240    /// The media server list of `account` (BUD-03, kind 10063), as far as
2241    /// `source` knows: its newest. `None` if it has none there.
2242    pub async fn media_server_list(&self, source: Source, account: PublicKey) -> Result<Option<Event>, FetchError> {
2243        match source {
2244            Source::Store => Ok(self.stored_list(Kind::BlossomServerList, account).await),
2245            Source::Relays => self.newest_list(Kind::BlossomServerList, account).await,
2246        }
2247    }
2248
2249    /// Have the media servers of `account` be `servers`, the one files
2250    /// are sent to first at the head: its newest server list, asked of
2251    /// the relays just now, with its servers replaced and the rest as it
2252    /// was, signed and sent out. Returns the list after it; nothing is
2253    /// sent when it says so already.
2254    ///
2255    /// With no list anywhere, a first one is only written if `first_list`
2256    /// says so; otherwise that is the error, and nothing is sent.
2257    pub async fn set_media_servers(
2258        &self,
2259        signer: &Signer,
2260        account: PublicKey,
2261        servers: &[Url],
2262        first_list: bool,
2263    ) -> Result<Option<Event>, ListError> {
2264        let list = self.list_to_change(Kind::BlossomServerList, account).await.map_err(ListError::Fetch)?;
2265        let Some(unsigned) = blossom::server_list(list.as_ref(), servers, Timestamp::now()) else {
2266            return Ok(list);
2267        };
2268        if list.is_none() && !first_list {
2269            return Err(ListError::NoList);
2270        }
2271        let sent = self.sign_and_publish(signer, account, unsigned).await.map_err(ListError::Publish)?;
2272        Ok(Some(sent))
2273    }
2274
2275    /// How every relay this is connected to has been doing: the account's
2276    /// own, and other people's that are in their pool now. A relay that
2277    /// is in both counts as the account's own.
2278    pub async fn relay_use(&self) -> HashMap<RelayUrl, RelayUse> {
2279        let mut in_use = HashMap::new();
2280        for pool in [&self.others, &self.client] {
2281            for (url, relay) in pool.relays().await {
2282                let stats = relay.stats();
2283                let doing = RelayUse {
2284                    connected: matches!(relay.status(), RelayStatus::Connected | RelayStatus::Sleeping),
2285                    received: stats.bytes_received(),
2286                    sent: stats.bytes_sent(),
2287                    attempts: stats.attempts(),
2288                    succeeded: stats.success(),
2289                    latency: stats.latency(),
2290                };
2291                in_use.insert(url, doing);
2292            }
2293        }
2294        in_use
2295    }
2296
2297    /// Go by these of the account's relays from now on: `lookup`, where
2298    /// profiles and relay lists that its own relays don't have are looked
2299    /// up, and `blocked`, which are never connected to on anyone's word.
2300    /// Relay lists are looked for again when there are other relays to
2301    /// look on.
2302    pub fn use_listed(&self, lookup: Vec<RelayUrl>, blocked: Vec<RelayUrl>) {
2303        let mut reached = self.reached();
2304        if reached.lookup != lookup {
2305            reached.lists_asked.clear();
2306            reached.lookup = lookup;
2307        }
2308        reached.blocked = blocked.into_iter().collect();
2309    }
2310
2311    /// What the relays that look things up send for `filters`, beside
2312    /// what the account's own have: those of them that are not its own,
2313    /// which were asked. Nothing, and never an error, when there are
2314    /// none, or none answers.
2315    async fn ask_lookup(&self, filters: Vec<Filter>) -> Vec<Event> {
2316        let in_use = self.in_use();
2317        let relays: Vec<RelayUrl> = self.reached().lookup.iter().filter(|relay| !in_use.contains(relay)).cloned().collect();
2318        if relays.is_empty() || filters.is_empty() {
2319            return Vec::new();
2320        }
2321        let asks = self.connected(relays.into_iter().map(|relay| (relay, filters.clone())).collect()).await;
2322        if asks.is_empty() {
2323            return Vec::new();
2324        }
2325        let asked = asks.len();
2326        let (events, answered, _) = self.gather(Pool::Others, asks, REACH_TIMEOUT).await;
2327        tracing::debug!("{} event(s) looked up on {answered} of {asked} relay(s)", events.len());
2328        events
2329    }
2330
2331    /// The profiles of `authors` that are already in the store.
2332    pub async fn cached_profiles(&self, authors: Vec<PublicKey>) -> Vec<(PublicKey, Profile)> {
2333        let filter = Filter::new().kind(Kind::Metadata).authors(authors);
2334        match self.client.database().query(filter).await {
2335            Ok(events) => newest_profiles(events),
2336            Err(e) => {
2337                tracing::warn!("profiles could not be read from the store: {e}");
2338                Vec::new()
2339            }
2340        }
2341    }
2342
2343    /// The profiles of `authors`, after asking the relays for them. As with
2344    /// a contact list, what the relays send is kept in the store, which only
2345    /// ever keeps the newest, and the answer is read back from there: a
2346    /// relay that is behind doesn't undo a newer profile already seen.
2347    pub async fn fetch_profiles(&self, authors: Vec<PublicKey>) -> Vec<(PublicKey, Profile)> {
2348        let fetched = match self.fetch(vec![Filter::new().kind(Kind::Metadata).authors(authors.clone())]).await {
2349            Ok(events) => newest_profiles(events),
2350            Err(e) => {
2351                tracing::warn!("profiles could not be fetched: {e:?}");
2352                return Vec::new();
2353            }
2354        };
2355        let mut profiles: HashMap<PublicKey, Profile> = fetched.into_iter().collect();
2356        profiles.extend(self.cached_profiles(authors).await);
2357        profiles.into_iter().collect()
2358    }
2359
2360    /// The profiles of those of `people` that the account's own relays
2361    /// don't have, after asking the relays those people write to. Asked
2362    /// for beside [`Self::fetch_profiles`], which answers sooner for most:
2363    /// who is still missing is seen once the relay lists are known, by
2364    /// when the account's own relays have had their say.
2365    pub async fn fetch_profiles_where_written(&self, people: Vec<PublicKey>) -> Vec<(PublicKey, Profile)> {
2366        self.relays_of(&people, Listed::Write, true).await;
2367        let known: HashSet<PublicKey> =
2368            self.cached_profiles(people.clone()).await.into_iter().map(|(person, _)| person).collect();
2369        let missing: Vec<PublicKey> = people.into_iter().filter(|person| !known.contains(person)).collect();
2370        let profiles_of = |people: &[PublicKey]| -> Vec<Filter> {
2371            let asking = |chunk: &[PublicKey]| Filter::new().kind(Kind::Metadata).authors(chunk.iter().copied());
2372            people.chunks(AUTHORS_PER_FILTER).map(asking).collect()
2373        };
2374        // Where they write, and where everyone's profile is looked up.
2375        let theirs = self.ask_their_relays(&missing, Listed::Write, true, profiles_of);
2376        let (theirs, looked_up) = join(theirs, self.ask_lookup(profiles_of(&missing))).await;
2377        if theirs.is_empty() && looked_up.is_empty() {
2378            return Vec::new();
2379        }
2380        self.cached_profiles(missing).await
2381    }
2382}
2383
2384#[cfg(test)]
2385mod tests {
2386    use super::{
2387        AUTHORS_PER_FILTER, FetchError, FollowError, ListError, NostrService, PublishError, Reach, Source, feed_filters, newest,
2388        newest_profiles,
2389    };
2390    use crate::nostr::account::testing::{Approves, with_remote_signer_for};
2391    use crate::nostr::account::{SignError, Signer};
2392    use crate::nostr::blossom;
2393    use crate::nostr::bookmarks::{self, Bookmarks, PrivateTags};
2394    use crate::nostr::compose;
2395    use crate::nostr::compose::Target;
2396    use crate::nostr::content::FEED_NOTE_MAX_CHARS;
2397    use crate::nostr::engagement::{self, Engagement, Reaction};
2398    use crate::nostr::kept_drafts::DRAFT_KIND;
2399    use crate::nostr::models::Note;
2400    use crate::nostr::outbox::Whereabouts;
2401    use crate::nostr::relay_lists::{Kept, RelayLists, Section};
2402    use crate::nostr::search::{Found, SearchFor};
2403    use nostr_connect::prelude::{Nip04, Nip44};
2404    use nostr_sdk::prelude::{
2405        Event, EventBuilder, EventId, Filter, FinalizeEvent, Keys, Kind, LocalRelay, MachineReadablePrefix, Nip19Event,
2406        PublicKey, RelayUrl, Tag, Timestamp, ToBech32, Url, WritePolicy, WritePolicyResult,
2407    };
2408    use std::collections::HashMap;
2409    use std::future::Future;
2410    use std::net::SocketAddr;
2411    use std::pin::Pin;
2412    use std::time::{Duration, Instant};
2413
2414    fn people(count: usize) -> Vec<PublicKey> {
2415        (0..count).map(|_| Keys::generate().public_key()).collect()
2416    }
2417
2418    /// A note saying `text`, written at `at`, with the `e` tags `(id,
2419    /// marker)`, an empty marker being none.
2420    fn note(text: &str, at: u64, tags: &[(EventId, &str)]) -> Event {
2421        let tags = tags.iter().map(|(id, marker)| match *marker {
2422            "" => Tag::parse(["e", &id.to_hex()]).unwrap(),
2423            marker => Tag::parse(["e", &id.to_hex(), "", marker]).unwrap(),
2424        });
2425        EventBuilder::new(Kind::TextNote, text)
2426            .tags(tags)
2427            .custom_created_at(Timestamp::from_secs(at))
2428            .finalize(&Keys::generate())
2429            .unwrap()
2430    }
2431
2432    /// What the store knows of the thread of `focused` when it holds
2433    /// `events`: the ids, sorted, and how many characters the focused note
2434    /// shows.
2435    fn thread_in_store(name: &str, events: &[Event], focused: EventId) -> (Vec<EventId>, usize) {
2436        let path = std::env::temp_dir().join(format!("avestruz-test-{}-{name}", std::process::id()));
2437        let _ = std::fs::remove_dir_all(&path);
2438        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2439        let notes = runtime.block_on(async {
2440            let service = NostrService::open(path.clone(), Vec::new()).await.unwrap();
2441            for event in events {
2442                service.client.database().save_event(event).await.unwrap();
2443            }
2444            service.thread(Source::Store, focused, &Whereabouts::default()).await.unwrap()
2445        });
2446        drop(runtime);
2447        let _ = std::fs::remove_dir_all(&path);
2448
2449        let shown = notes.iter().find(|note| note.id == focused).map_or(0, |note| note.content.line_chars.iter().sum::<usize>());
2450        let mut ids: Vec<EventId> = notes.iter().map(|note| note.id).collect();
2451        ids.sort();
2452        (ids, shown)
2453    }
2454
2455    fn sorted(mut ids: Vec<EventId>) -> Vec<EventId> {
2456        ids.sort();
2457        ids
2458    }
2459
2460    #[test]
2461    fn a_thread_is_the_root_what_names_it_and_what_names_those() {
2462        let long = "word ".repeat(FEED_NOTE_MAX_CHARS);
2463        let root = note("it starts", 100, &[]);
2464        let first = note("an answer", 200, &[(root.id, "root")]);
2465        let focused = note(&long, 300, &[(root.id, "root"), (first.id, "reply")]);
2466        // Tags only the note it answers, as some clients do.
2467        let deeper = note("an answer to the answer", 400, &[(focused.id, "")]);
2468        // Cites a note of the thread without answering anything.
2469        let citing = note("look at this", 450, &[(first.id, "mention")]);
2470        let elsewhere = note("another conversation", 500, &[]);
2471        let events = [root.clone(), first.clone(), focused.clone(), deeper.clone(), citing, elsewhere];
2472
2473        let (ids, shown) = thread_in_store("thread", &events, focused.id);
2474
2475        assert_eq!(ids, sorted(vec![root.id, first.id, focused.id, deeper.id]));
2476        assert_eq!(shown, long.trim().chars().count(), "the note the thread is for shows in full");
2477    }
2478
2479    #[test]
2480    fn a_thread_reaches_for_the_parents_that_nothing_else_brought() {
2481        // The parent names a root of its own, which nobody has; the focused
2482        // note names another. Only the walk up from the note finds the parent.
2483        let (lost_root, other_root) = (EventId::from_byte_array([1; 32]), EventId::from_byte_array([2; 32]));
2484        let parent = note("the parent", 100, &[(lost_root, "root")]);
2485        let focused = note("the note", 200, &[(other_root, "root"), (parent.id, "reply")]);
2486
2487        let (ids, _) = thread_in_store("parents", &[parent.clone(), focused.clone()], focused.id);
2488
2489        assert_eq!(ids, sorted(vec![parent.id, focused.id]));
2490    }
2491
2492    #[test]
2493    fn a_thread_of_comments_is_what_they_are_about_and_the_comments_under_it() {
2494        let keys = Keys::generate();
2495        let at = |builder: EventBuilder, at: u64| builder.custom_created_at(Timestamp::from_secs(at)).finalize(&keys).unwrap();
2496        let comment = |text: &str, on: &Event, when: u64| at(compose::build(text, Some(on), keys.public_key()), when);
2497
2498        let picture = at(EventBuilder::new(Kind::Custom(20), "a heron"), 100);
2499        let first = comment("what a bird", &picture, 200);
2500        let answer = comment("isn't it", &first, 300);
2501        let other = comment("lovely", &picture, 400);
2502        let elsewhere = note("another conversation", 500, &[]);
2503        let events = [picture.clone(), first.clone(), answer.clone(), other.clone(), elsewhere];
2504
2505        // Opened for the answer to a comment: the picture, both comments on
2506        // it, and the answer.
2507        let (ids, _) = thread_in_store("comments", &events, answer.id);
2508        assert_eq!(ids, sorted(vec![picture.id, first.id, answer.id, other.id]));
2509    }
2510
2511    /// A relay that takes nothing.
2512    #[derive(Debug)]
2513    struct TakesNothing;
2514
2515    impl WritePolicy for TakesNothing {
2516        fn admit_event<'a>(
2517            &'a self,
2518            _event: &'a Event,
2519            _addr: &'a SocketAddr,
2520        ) -> Pin<Box<dyn Future<Output = WritePolicyResult> + Send + 'a>> {
2521            Box::pin(async { WritePolicyResult::reject(MachineReadablePrefix::Blocked, "not here") })
2522        }
2523    }
2524
2525    /// Publish a note to a relay in this process, which takes it or (with
2526    /// `refusing`) doesn't. Returns what publishing said, and whether the
2527    /// store has the note afterwards.
2528    fn publish_to_a_relay(name: &str, refusing: bool) -> (Result<usize, PublishError>, bool) {
2529        let path = std::env::temp_dir().join(format!("avestruz-test-{}-{name}", std::process::id()));
2530        let _ = std::fs::remove_dir_all(&path);
2531        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2532        let outcome = runtime.block_on(async {
2533            let builder = LocalRelay::builder();
2534            let relay = if refusing { builder.write_policy(TakesNothing).build() } else { builder.build() };
2535            relay.run().await.unwrap();
2536            let service = NostrService::open(path.clone(), vec![relay.url().await.to_string()]).await.unwrap();
2537
2538            let event = note("hello", 100, &[]);
2539            let result = service.publish(&event).await;
2540            let stored = service.stored_event(event.id).await.is_some();
2541            relay.shutdown();
2542            (result, stored)
2543        });
2544        drop(runtime);
2545        let _ = std::fs::remove_dir_all(&path);
2546        outcome
2547    }
2548
2549    #[test]
2550    fn what_was_made_of_a_note_is_counted_from_the_store_which_the_relays_fill() {
2551        let path = std::env::temp_dir().join(format!("avestruz-test-{}-engagement", std::process::id()));
2552        let _ = std::fs::remove_dir_all(&path);
2553        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2554        let (me, about) = (Keys::generate(), note("it starts", 100, &[]));
2555        let (before, after) = runtime.block_on(async {
2556            let relay = LocalRelay::builder().build();
2557            relay.run().await.unwrap();
2558            let like = |keys: &Keys| EventBuilder::new(Kind::Reaction, "+").tag(Tag::event(about.id)).finalize(keys).unwrap();
2559            let repost = engagement::repost(&about, None).finalize(&me).unwrap();
2560            for event in
2561                [about.clone(), note("an answer", 200, &[(about.id, "root")]), like(&me), like(&Keys::generate()), repost]
2562            {
2563                relay.add_event(event).await.unwrap();
2564            }
2565            let service = NostrService::open(path.clone(), vec![relay.url().await.to_string()]).await.unwrap();
2566
2567            let url = relay.url().await;
2568            let ask = |source| service.standing(source, vec![about.id], Some(me.public_key()));
2569            let before = ask(Source::Store).await.unwrap();
2570            let after = ask(Source::Relays).await.unwrap();
2571            assert_eq!(ask(Source::Store).await.unwrap(), after, "what the relays sent is the store's now");
2572            relay.shutdown();
2573            assert_eq!(after.seen_on, HashMap::from([(about.id, vec![url])]), "the relay that has the note said so");
2574            (before, after)
2575        });
2576        drop(runtime);
2577        let _ = std::fs::remove_dir_all(&path);
2578
2579        assert_eq!(before.engagement.get(&about.id), Some(&Engagement::default()), "nothing known yet");
2580        assert!(before.seen_on.is_empty(), "and seen nowhere: no relay was asked");
2581        assert_eq!(
2582            after.engagement.get(&about.id),
2583            Some(&Engagement { replies: 1, reposts: 1, reposted: true, likes: 2, reaction: Some(Reaction::Like), zap_sats: 0 })
2584        );
2585    }
2586
2587    #[test]
2588    fn a_page_comes_with_the_notes_its_notes_quote_and_the_store_keeps_them() {
2589        let path = std::env::temp_dir().join(format!("avestruz-test-{}-quotes", std::process::id()));
2590        let _ = std::fs::remove_dir_all(&path);
2591        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2592        let (me, them) = (Keys::generate(), Keys::generate());
2593        let at = |builder: EventBuilder, keys: &Keys, at: u64| {
2594            builder.custom_created_at(Timestamp::from_secs(at)).finalize(keys).unwrap()
2595        };
2596        let address = |event: &Event| format!("nostr:{}", event.id.to_bech32().unwrap());
2597        // A chain of quotes, three notes long under the note of mine: the
2598        // custom, the note that passed it on, and the one that did so again.
2599        let innermost = at(EventBuilder::new(Kind::TextNote, "where it started"), &them, 70);
2600        let inner = at(EventBuilder::new(Kind::TextNote, format!("the custom {}", address(&innermost))), &them, 80);
2601        // A note, a picture (which is no note a row shows), and a note
2602        // nobody has; and a note of mine that quotes all three.
2603        let quoted = at(EventBuilder::new(Kind::TextNote, format!("worth a second look {}", address(&inner))), &them, 100);
2604        let picture = at(EventBuilder::new(Kind::Custom(20), "a heron"), &them, 110);
2605        let lost = at(EventBuilder::new(Kind::TextNote, "nobody kept this"), &them, 120);
2606        let text = format!("look {} {} {}", address(&quoted), address(&picture), address(&lost));
2607        let quoting = at(EventBuilder::new(Kind::TextNote, text), &me, 200);
2608
2609        let (before, fetched, cached, thread) = runtime.block_on(async {
2610            let relay = LocalRelay::builder().build();
2611            relay.run().await.unwrap();
2612            for event in [innermost.clone(), inner.clone(), quoted.clone(), picture.clone(), quoting.clone()] {
2613                relay.add_event(event).await.unwrap();
2614            }
2615            let service = NostrService::open(path.clone(), vec![relay.url().await.to_string()]).await.unwrap();
2616            let authors = [me.public_key()];
2617
2618            // The store has the note already, and not what it quotes.
2619            service.client.database().save_event(&quoting).await.unwrap();
2620            let before = service.cached_feed(&authors, 50).await.unwrap();
2621            let fetched = service.fetch_feed(&authors, None, 50).await.unwrap();
2622            // The relays are gone: what they sent is the store's now.
2623            relay.shutdown();
2624            let cached = service.cached_feed(&authors, 50).await.unwrap();
2625            let thread = service.thread(Source::Store, quoting.id, &Whereabouts::default()).await.unwrap();
2626            (before, fetched, cached, thread)
2627        });
2628        drop(runtime);
2629        let _ = std::fs::remove_dir_all(&path);
2630
2631        let quoted_by = |notes: &[Note]| -> Vec<EventId> {
2632            assert_eq!(notes.iter().map(|note| note.id).collect::<Vec<_>>(), [quoting.id]);
2633            notes[0].quoted.iter().map(|note| note.id).collect()
2634        };
2635        assert!(quoted_by(&before).is_empty(), "the store alone has nothing to show for them");
2636        assert_eq!(quoted_by(&fetched), [quoted.id], "the note; not the picture, and not what nobody has");
2637        assert_eq!(quoted_by(&cached), [quoted.id]);
2638        assert_eq!(quoted_by(&thread), [quoted.id]);
2639        assert_eq!(fetched[0].content.quotes.len(), 3, "all three are named, and two show as links");
2640
2641        // The note quoted comes with the note it quotes, and that one
2642        // without: two notes deep, and the third is a link.
2643        for notes in [&fetched, &cached, &thread] {
2644            let first = &notes[0].quoted[0];
2645            assert_eq!(first.quoted.iter().map(|note| note.id).collect::<Vec<_>>(), [inner.id]);
2646            assert!(first.quoted[0].quoted.is_empty(), "no deeper");
2647            assert_eq!(first.quoted[0].content.quotes.iter().map(|quote| quote.id).collect::<Vec<_>>(), [innermost.id]);
2648        }
2649    }
2650
2651    #[test]
2652    fn a_note_is_seen_on_the_relays_that_have_it_and_on_those_that_took_it() {
2653        let path = std::env::temp_dir().join(format!("avestruz-test-{}-seen", std::process::id()));
2654        let _ = std::fs::remove_dir_all(&path);
2655        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2656        let keys = Keys::generate();
2657        let at = |text: &str, at: u64| {
2658            EventBuilder::new(Kind::TextNote, text).custom_created_at(Timestamp::from_secs(at)).finalize(&keys).unwrap()
2659        };
2660        let (everywhere, on_one, mine) = (at("on both", 300), at("on the first", 200), at("just written", 400));
2661        let (first, second, feed, seen) = runtime.block_on(async {
2662            let (first, second) = (LocalRelay::builder().build(), LocalRelay::builder().build());
2663            first.run().await.unwrap();
2664            second.run().await.unwrap();
2665            first.add_event(everywhere.clone()).await.unwrap();
2666            first.add_event(on_one.clone()).await.unwrap();
2667            second.add_event(everywhere.clone()).await.unwrap();
2668            let urls = (first.url().await, second.url().await);
2669            let service = NostrService::open(path.clone(), vec![urls.0.to_string(), urls.1.to_string()]).await.unwrap();
2670
2671            // A page of the feed says where its notes are; and publishing
2672            // a note, which relays took it.
2673            let feed = service.fetch_feed(&[keys.public_key()], None, 50).await.unwrap();
2674            service.publish(&mine).await.unwrap();
2675            let seen = service.seen_on(&[everywhere.id, on_one.id, mine.id, EventId::from_byte_array([9; 32])]);
2676            first.shutdown();
2677            second.shutdown();
2678            (urls.0, urls.1, feed, seen)
2679        });
2680        drop(runtime);
2681        let _ = std::fs::remove_dir_all(&path);
2682
2683        let ids: Vec<EventId> = feed.iter().map(|note| note.id).collect();
2684        assert_eq!(ids, [everywhere.id, on_one.id], "each note once, newest first, whoever sent it");
2685        let on = |id: EventId| {
2686            let mut relays = seen.get(&id).cloned().unwrap_or_default();
2687            relays.sort();
2688            relays
2689        };
2690        let mut both = vec![first.clone(), second];
2691        both.sort();
2692        assert_eq!(on(everywhere.id), both);
2693        assert_eq!(on(on_one.id), [first]);
2694        assert_eq!(on(mine.id), both);
2695        assert_eq!(seen.len(), 3, "a note nobody sent is seen nowhere");
2696    }
2697
2698    #[test]
2699    fn the_relay_that_has_an_event_is_the_one_pointed_at() {
2700        let path = std::env::temp_dir().join(format!("avestruz-test-{}-holder", std::process::id()));
2701        let _ = std::fs::remove_dir_all(&path);
2702        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2703        let (held, missing) = (note("here", 100, &[]), note("nowhere", 200, &[]));
2704        let (with, without, holder, nobody) = runtime.block_on(async {
2705            let (with, without) = (LocalRelay::builder().build(), LocalRelay::builder().build());
2706            with.run().await.unwrap();
2707            without.run().await.unwrap();
2708            with.add_event(held.clone()).await.unwrap();
2709            let urls = (with.url().await, without.url().await);
2710            let service = NostrService::open(path.clone(), vec![urls.1.to_string(), urls.0.to_string()]).await.unwrap();
2711
2712            let found = (service.relay_holding(held.id).await, service.relay_holding(missing.id).await);
2713            with.shutdown();
2714            without.shutdown();
2715            (urls.0, urls.1, found.0, found.1)
2716        });
2717        drop(runtime);
2718        let _ = std::fs::remove_dir_all(&path);
2719
2720        assert_ne!(with, without);
2721        assert_eq!(holder, Some(with));
2722        assert_eq!(nobody, None);
2723    }
2724
2725    #[test]
2726    fn the_receipt_of_a_zap_is_waited_for_and_then_counted() {
2727        let path = std::env::temp_dir().join(format!("avestruz-test-{}-receipt", std::process::id()));
2728        let _ = std::fs::remove_dir_all(&path);
2729        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2730        let about = note("it starts", 100, &[]);
2731        let receipt = |invoice: &str| {
2732            EventBuilder::new(Kind::ZapReceipt, "")
2733                .tags([Tag::event(about.id), Tag::custom("bolt11", [invoice])])
2734                .finalize(&Keys::generate())
2735                .unwrap()
2736        };
2737        let (paid, counted) = runtime.block_on(async {
2738            let relay = LocalRelay::builder().build();
2739            relay.run().await.unwrap();
2740            // Someone else's zap of the same note is there already.
2741            relay.add_event(receipt("lnbc10u1theirs")).await.unwrap();
2742            let service = NostrService::open(path.clone(), vec![relay.url().await.to_string()]).await.unwrap();
2743
2744            let waiting =
2745                tokio::time::timeout(Duration::from_secs(10), service.await_zap_receipt(about.id, "lnbc210n1mine".into()));
2746            let paying = async {
2747                tokio::time::sleep(Duration::from_millis(500)).await;
2748                // As a wallet service may write it: in capitals.
2749                assert!(relay.notify_event(receipt("LNBC210N1MINE")));
2750            };
2751            let (paid, ()) = tokio::join!(waiting, paying);
2752            let counted = service.standing(Source::Store, vec![about.id], None).await.unwrap().engagement;
2753            relay.shutdown();
2754            (paid, counted)
2755        });
2756        drop(runtime);
2757        let _ = std::fs::remove_dir_all(&path);
2758
2759        assert_eq!(paid, Ok(true), "the receipt for this invoice, not the one that was there");
2760        assert_eq!(counted.get(&about.id).map(|engagement| engagement.zap_sats), Some(1_021), "both are in the store");
2761    }
2762
2763    #[test]
2764    fn a_published_event_is_kept_once_a_relay_took_it() {
2765        assert_eq!(publish_to_a_relay("published", false), (Ok(1), true));
2766    }
2767
2768    #[test]
2769    fn an_event_no_relay_took_is_not_kept_and_says_why() {
2770        let (result, stored) = publish_to_a_relay("refused", true);
2771        match result {
2772            Err(PublishError::Refused(reason)) => assert!(reason.contains("not here"), "{reason}"),
2773            other => panic!("refused, not {other:?}"),
2774        }
2775        assert!(!stored, "nobody else can see it: the store doesn't show it either");
2776    }
2777
2778    #[test]
2779    fn notes_named_by_id_come_in_the_order_they_were_named_from_the_store_or_the_relays() {
2780        let path = std::env::temp_dir().join(format!("avestruz-test-{}-listed", std::process::id()));
2781        let _ = std::fs::remove_dir_all(&path);
2782        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2783        let address = |event: &Event| format!("nostr:{}", event.id.to_bech32().unwrap());
2784        let (kept, far) = (note("in the store", 100, &[]), note("on the relay", 200, &[]));
2785        let quoting = EventBuilder::new(Kind::TextNote, format!("on the relay too, quoting {}", address(&far)))
2786            .custom_created_at(Timestamp::from_secs(300))
2787            .finalize(&Keys::generate())
2788            .unwrap();
2789        let picture = EventBuilder::new(Kind::Custom(20), "a heron").finalize(&Keys::generate()).unwrap();
2790        let lost = note("nobody kept this", 400, &[]);
2791
2792        let (listed, again) = runtime.block_on(async {
2793            let relay = LocalRelay::builder().build();
2794            relay.run().await.unwrap();
2795            for event in [far.clone(), quoting.clone(), picture.clone()] {
2796                relay.add_event(event).await.unwrap();
2797            }
2798            let service = NostrService::open(path.clone(), vec![relay.url().await.to_string()]).await.unwrap();
2799            service.client.database().save_event(&kept).await.unwrap();
2800
2801            let ids: Vec<(EventId, Whereabouts)> =
2802                [quoting.id, lost.id, kept.id, picture.id, far.id].map(|id| (id, Whereabouts::default())).to_vec();
2803            let listed = service.notes_listed(ids.clone()).await;
2804            // The relay is gone: what it sent is the store's now.
2805            relay.shutdown();
2806            (listed, service.notes_listed(ids).await)
2807        });
2808        drop(runtime);
2809        let _ = std::fs::remove_dir_all(&path);
2810
2811        // The one nobody has and the one that is no note are left out.
2812        let ids = |notes: &[Note]| notes.iter().map(|note| note.id).collect::<Vec<_>>();
2813        assert_eq!(ids(&listed), [quoting.id, kept.id, far.id]);
2814        assert_eq!(ids(&listed[0].quoted), [far.id], "with what it quotes");
2815        assert_eq!(ids(&again), ids(&listed));
2816    }
2817
2818    /// Run `test` with `count` relays in this process and a client whose
2819    /// own relay is the first of them. It takes anyone's word for a relay,
2820    /// since none of these is on the open internet, and reaches for `cap`
2821    /// of other people's at a time.
2822    fn with_relays<F: Future<Output = ()>>(
2823        name: &str,
2824        count: usize,
2825        cap: usize,
2826        test: impl FnOnce(NostrService, Vec<LocalRelay>, Vec<RelayUrl>) -> F,
2827    ) {
2828        with_relays_reaching(name, count, Reach { cap, accepts: |_| true, ..Reach::default() }, test);
2829    }
2830
2831    /// As [`with_relays`], reaching as far as `reach` says.
2832    fn with_relays_reaching<F: Future<Output = ()>>(
2833        name: &str,
2834        count: usize,
2835        reach: Reach,
2836        test: impl FnOnce(NostrService, Vec<LocalRelay>, Vec<RelayUrl>) -> F,
2837    ) {
2838        let path = std::env::temp_dir().join(format!("avestruz-test-{}-{name}", std::process::id()));
2839        let _ = std::fs::remove_dir_all(&path);
2840        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2841        runtime.block_on(async {
2842            let mut relays = Vec::new();
2843            let mut urls = Vec::new();
2844            for _ in 0..count {
2845                let relay = LocalRelay::builder().build();
2846                relay.run().await.unwrap();
2847                urls.push(relay.url().await);
2848                relays.push(relay);
2849            }
2850            let service = NostrService::open_reaching(path.clone(), vec![urls[0].to_string()], reach).await.unwrap();
2851            tokio::time::timeout(Duration::from_secs(60), test(service, relays.clone(), urls)).await.unwrap();
2852            for relay in relays {
2853                relay.shutdown();
2854            }
2855        });
2856        drop(runtime);
2857        let _ = std::fs::remove_dir_all(&path);
2858    }
2859
2860    /// The relay list of `keys`: the relays it writes to, and those it reads.
2861    fn relay_list(keys: &Keys, write: &[&RelayUrl], read: &[&RelayUrl]) -> Event {
2862        let marked = |relays: &[&RelayUrl], marker: &str| -> Vec<Tag> {
2863            relays.iter().map(|relay| Tag::parse(["r", relay.as_str(), marker]).unwrap()).collect()
2864        };
2865        EventBuilder::new(Kind::RelayList, "")
2866            .tags(marked(write, "write").into_iter().chain(marked(read, "read")))
2867            .finalize(keys)
2868            .unwrap()
2869    }
2870
2871    /// A note by `keys`, written at `at`, with `tags`.
2872    fn note_by(keys: &Keys, text: &str, at: u64, tags: Vec<Tag>) -> Event {
2873        EventBuilder::new(Kind::TextNote, text).tags(tags).custom_created_at(Timestamp::from_secs(at)).finalize(keys).unwrap()
2874    }
2875
2876    /// Whether the relay at `relay` has the event `id`, asked by a client
2877    /// of its own.
2878    async fn holds(relay: &RelayUrl, id: EventId) -> bool {
2879        let path = std::env::temp_dir().join(format!("avestruz-test-{}-holds-{}", std::process::id(), id.to_hex()));
2880        let _ = std::fs::remove_dir_all(&path);
2881        let asking = NostrService::open(path.clone(), vec![relay.to_string()]).await.unwrap();
2882        let held = asking.events(Source::Relays, vec![Filter::new().id(id)]).await.is_ok_and(|events| !events.is_empty());
2883        let _ = std::fs::remove_dir_all(&path);
2884        held
2885    }
2886
2887    fn ids(notes: &[Note]) -> Vec<EventId> {
2888        notes.iter().map(|note| note.id).collect()
2889    }
2890
2891    #[test]
2892    fn a_note_the_store_let_go_of_is_asked_of_the_relays_again() {
2893        with_relays("swept-note", 2, 20, async |service, relays, urls| {
2894            let (me, near, far) = (Keys::generate(), Keys::generate(), Keys::generate());
2895            let here = note_by(&near, "on my relay", 300, vec![]);
2896            let there = note_by(&far, "on theirs", 200, vec![]);
2897            relays[0].add_event(relay_list(&far, &[&urls[1]], &[])).await.unwrap();
2898            relays[0].add_event(here.clone()).await.unwrap();
2899            relays[1].add_event(there.clone()).await.unwrap();
2900            let authors = [near.public_key(), far.public_key()];
2901            assert_eq!(service.fetch_feed(&authors, None, 50).await.unwrap().len(), 2);
2902
2903            // Swept, neither is in the store, and each is found again
2904            // where it is: on the account's relay, and where its author
2905            // writes.
2906            let swept = service.sweep(me.public_key(), &std::collections::HashSet::new(), Timestamp::from_secs(1_000)).await;
2907            assert_eq!(swept, Ok(2));
2908            assert!(service.stored_event(here.id).await.is_none() && service.stored_event(there.id).await.is_none());
2909            assert_eq!(service.event(here.id, near.public_key()).await, Some(here));
2910            assert_eq!(service.event(there.id, far.public_key()).await, Some(there.clone()));
2911            // What the relays sent is the store's again.
2912            assert_eq!(service.stored_event(there.id).await, Some(there));
2913            assert_eq!(service.event(id(9), far.public_key()).await, None);
2914        });
2915    }
2916
2917    #[test]
2918    fn notes_are_read_from_the_relays_their_authors_write_to() {
2919        with_relays("outbox-feed", 3, 20, async |service, relays, urls| {
2920            let (near, far, nowhere) = (Keys::generate(), Keys::generate(), Keys::generate());
2921            // One writes to the account's own relay, one elsewhere, and
2922            // one has no relay list: all three lists are on the own relay.
2923            let here = note_by(&near, "on my relay", 300, vec![]);
2924            let there = note_by(&far, "on theirs", 200, vec![]);
2925            let older = note_by(&far, "on theirs, long ago", 100, vec![]);
2926            let lost = note_by(&nowhere, "on a relay nobody names", 250, vec![]);
2927            relays[0].add_event(relay_list(&near, &[&urls[0]], &[])).await.unwrap();
2928            relays[0].add_event(relay_list(&far, &[&urls[1]], &[])).await.unwrap();
2929            relays[0].add_event(here.clone()).await.unwrap();
2930            relays[1].add_event(there.clone()).await.unwrap();
2931            relays[1].add_event(older.clone()).await.unwrap();
2932            relays[2].add_event(lost.clone()).await.unwrap();
2933
2934            let authors = [near.public_key(), far.public_key(), nowhere.public_key()];
2935            let page = service.fetch_feed(&authors, None, 50).await.unwrap();
2936            assert_eq!(ids(&page), [here.id, there.id, older.id], "newest first, from wherever they are");
2937            // Each was seen on the relay that sent it.
2938            let seen = service.seen_on(&[here.id, there.id]);
2939            assert_eq!(seen.get(&here.id), Some(&vec![urls[0].clone()]));
2940            assert_eq!(seen.get(&there.id), Some(&vec![urls[1].clone()]));
2941            // Only the relay someone writes to is in the pool of other
2942            // people's, and the account's own pool is as it was.
2943            assert_eq!(service.others.relays().await.into_keys().collect::<Vec<_>>(), [urls[1].clone()]);
2944            assert_eq!(service.client.relays().await.len(), 1);
2945
2946            // A page further back comes from there as well, and what came
2947            // is in the store.
2948            let before = service.fetch_feed(&authors, Some(150), 50).await.unwrap();
2949            assert_eq!(ids(&before), [older.id]);
2950            assert!(service.stored_event(there.id).await.is_some());
2951
2952            // With the own relay gone, their relays still answer: the
2953            // lists are in the store.
2954            relays[0].shutdown();
2955            tokio::time::sleep(Duration::from_millis(300)).await;
2956            let without = service.fetch_feed(&[far.public_key()], None, 50).await.unwrap();
2957            assert_eq!(ids(&without), [there.id, older.id]);
2958        });
2959    }
2960
2961    #[test]
2962    fn no_more_of_other_peoples_relays_are_reached_for_than_may_be() {
2963        // Two authors on two relays, and room for one.
2964        with_relays("outbox-cap", 3, 1, async |service, relays, urls| {
2965            let (one, other) = (Keys::generate(), Keys::generate());
2966            relays[0].add_event(relay_list(&one, &[&urls[1]], &[])).await.unwrap();
2967            relays[0].add_event(relay_list(&other, &[&urls[2]], &[])).await.unwrap();
2968            relays[1].add_event(note_by(&one, "on one", 100, vec![])).await.unwrap();
2969            relays[2].add_event(note_by(&other, "on the other", 200, vec![])).await.unwrap();
2970
2971            let page = service.fetch_feed(&[one.public_key(), other.public_key()], None, 50).await.unwrap();
2972            assert_eq!(page.len(), 1, "one relay was asked, and not the other");
2973            assert_eq!(service.others.relays().await.len(), 1);
2974        });
2975        // And none at all when none may be.
2976        with_relays("outbox-none", 2, 0, async |service, relays, urls| {
2977            let far = Keys::generate();
2978            relays[0].add_event(relay_list(&far, &[&urls[1]], &[])).await.unwrap();
2979            relays[1].add_event(note_by(&far, "on theirs", 100, vec![])).await.unwrap();
2980            assert!(service.fetch_feed(&[far.public_key()], None, 50).await.unwrap().is_empty());
2981            assert!(service.others.relays().await.is_empty());
2982        });
2983    }
2984
2985    #[test]
2986    fn a_relay_on_this_machine_is_not_connected_to_on_somebody_elses_word() {
2987        let path = std::env::temp_dir().join(format!("avestruz-test-{}-outbox-word", std::process::id()));
2988        let _ = std::fs::remove_dir_all(&path);
2989        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
2990        runtime.block_on(async {
2991            let (mine, theirs) = (LocalRelay::builder().build(), LocalRelay::builder().build());
2992            mine.run().await.unwrap();
2993            theirs.run().await.unwrap();
2994            let far = Keys::generate();
2995            mine.add_event(relay_list(&far, &[&theirs.url().await], &[])).await.unwrap();
2996            theirs.add_event(note_by(&far, "on theirs", 100, vec![])).await.unwrap();
2997
2998            // As the applet opens it: what a list names has to be public.
2999            let service = NostrService::open(path.clone(), vec![mine.url().await.to_string()]).await.unwrap();
3000            assert!(service.fetch_feed(&[far.public_key()], None, 50).await.unwrap().is_empty());
3001            assert!(service.others.relays().await.is_empty());
3002            mine.shutdown();
3003            theirs.shutdown();
3004        });
3005        drop(runtime);
3006        let _ = std::fs::remove_dir_all(&path);
3007    }
3008
3009    #[test]
3010    fn a_relay_that_does_not_connect_is_left_alone_and_the_others_still_asked() {
3011        with_relays("outbox-dead", 2, 20, async |service, relays, urls| {
3012            let far = Keys::generate();
3013            // Nothing listens at the first relay they name.
3014            let dead = RelayUrl::parse("ws://127.0.0.1:9").unwrap();
3015            let there = note_by(&far, "on theirs", 100, vec![]);
3016            relays[0].add_event(relay_list(&far, &[&dead, &urls[1]], &[])).await.unwrap();
3017            relays[1].add_event(there.clone()).await.unwrap();
3018
3019            let page = service.fetch_feed(&[far.public_key()], None, 50).await.unwrap();
3020            assert_eq!(ids(&page), [there.id]);
3021            assert_eq!(service.others.relays().await.into_keys().collect::<Vec<_>>(), [urls[1].clone()]);
3022            assert!(service.reached().failed.contains_key(&dead));
3023
3024            // Asked again, it is not tried again: nothing waits for it.
3025            let asked = Instant::now();
3026            assert_eq!(ids(&service.fetch_feed(&[far.public_key()], None, 50).await.unwrap()), [there.id]);
3027            assert!(asked.elapsed() < Duration::from_secs(2), "{:?}", asked.elapsed());
3028        });
3029    }
3030
3031    #[test]
3032    fn a_profile_the_accounts_relays_do_not_have_is_asked_of_where_its_person_writes() {
3033        with_relays("outbox-profiles", 2, 20, async |service, relays, urls| {
3034            let (near, far, unlisted) = (Keys::generate(), Keys::generate(), Keys::generate());
3035            let profile = |keys: &Keys, name: &str| {
3036                EventBuilder::new(Kind::Metadata, format!(r#"{{"name":"{name}"}}"#)).finalize(keys).unwrap()
3037            };
3038            relays[0].add_event(profile(&near, "Near")).await.unwrap();
3039            relays[0].add_event(relay_list(&far, &[&urls[1]], &[])).await.unwrap();
3040            relays[1].add_event(profile(&far, "Far")).await.unwrap();
3041            // On their relay too, which nothing says.
3042            relays[1].add_event(profile(&unlisted, "Unlisted")).await.unwrap();
3043
3044            let people = vec![near.public_key(), far.public_key(), unlisted.public_key()];
3045            let own = service.fetch_profiles(people.clone()).await;
3046            assert_eq!(own.iter().map(|(person, _)| *person).collect::<Vec<_>>(), [near.public_key()]);
3047
3048            let theirs = service.fetch_profiles_where_written(people.clone()).await;
3049            assert_eq!(theirs.len(), 1);
3050            assert_eq!(theirs[0].0, far.public_key());
3051            assert_eq!(theirs[0].1.name.as_deref(), Some("Far"));
3052            // Known by now: nobody is asked about again.
3053            assert!(service.fetch_profiles_where_written(vec![near.public_key(), far.public_key()]).await.is_empty());
3054        });
3055    }
3056
3057    #[test]
3058    fn a_quoted_note_is_asked_of_where_its_address_says_it_is() {
3059        with_relays("outbox-quotes", 3, 20, async |service, relays, urls| {
3060            let (me, far, quiet) = (Keys::generate(), Keys::generate(), Keys::generate());
3061            let quoted = note_by(&far, "said elsewhere", 100, vec![]);
3062            let unsigned = note_by(&far, "said elsewhere too", 110, vec![]);
3063            let hinted = note_by(&quiet, "on a relay the address names", 120, vec![]);
3064            relays[0].add_event(relay_list(&far, &[&urls[1]], &[])).await.unwrap();
3065            relays[1].add_event(quoted.clone()).await.unwrap();
3066            relays[1].add_event(unsigned.clone()).await.unwrap();
3067            // Nobody's relay list names this one.
3068            relays[2].add_event(hinted.clone()).await.unwrap();
3069
3070            // One address says who wrote the note, one says nothing, and
3071            // one says which relay has it.
3072            let with_author = Nip19Event::new(quoted.id).author(far.public_key()).to_bech32().unwrap();
3073            let bare = unsigned.id.to_bech32().unwrap();
3074            let with_relay = Nip19Event::new(hinted.id).relays([urls[2].clone()]).to_bech32().unwrap();
3075            let text = format!("look nostr:{with_author} and nostr:{bare} and nostr:{with_relay}");
3076            let quoting = note_by(&me, &text, 200, vec![]);
3077            relays[0].add_event(quoting.clone()).await.unwrap();
3078
3079            let page = service.fetch_feed(&[me.public_key()], None, 50).await.unwrap();
3080            assert_eq!(ids(&page), [quoting.id]);
3081            assert_eq!(
3082                ids(&page[0].quoted),
3083                [quoted.id, hinted.id],
3084                "found where its author writes, and on the relay its address names"
3085            );
3086            assert_eq!(service.seen_on(&[hinted.id]).get(&hinted.id), Some(&vec![urls[2].clone()]));
3087        });
3088    }
3089
3090    #[test]
3091    fn a_search_asks_the_accounts_search_relays_and_no_others() {
3092        with_relays("search", 3, 20, async |service, relays, urls| {
3093            let (author, other) = (Keys::generate(), Keys::generate());
3094            let profile = |keys: &Keys, name: &str| {
3095                EventBuilder::new(Kind::Metadata, format!(r#"{{"name":"{name}"}}"#)).finalize(keys).unwrap()
3096            };
3097            let wanted = note_by(&author, "tokens for friends", 100, vec![]);
3098            relays[1].add_event(wanted.clone()).await.unwrap();
3099            relays[1].add_event(note_by(&author, "something else", 200, vec![])).await.unwrap();
3100            relays[1].add_event(profile(&author, "Karnage")).await.unwrap();
3101            relays[1].add_event(profile(&other, "Somebody")).await.unwrap();
3102            // A relay that is not searched has a match nobody finds.
3103            relays[2].add_event(note_by(&other, "tokens elsewhere", 300, vec![])).await.unwrap();
3104
3105            let searched = [urls[1].clone()];
3106            let Found::Notes(notes) = service.search(&searched, "tokens", SearchFor::Notes).await.unwrap() else {
3107                panic!("notes were searched for");
3108            };
3109            assert_eq!(ids(&notes), [wanted.id]);
3110            assert_eq!(service.seen_on(&[wanted.id]).get(&wanted.id), Some(&vec![urls[1].clone()]));
3111            let Found::People(people) = service.search(&searched, "karnage", SearchFor::People).await.unwrap() else {
3112                panic!("people were searched for");
3113            };
3114            assert_eq!(people.len(), 1);
3115            assert_eq!((people[0].0, people[0].1.name.as_deref()), (author.public_key(), Some("Karnage")));
3116            assert_eq!(service.others.relays().await.into_keys().collect::<Vec<_>>(), searched);
3117
3118            // One of the account's own relays that searches is asked where it is.
3119            let at_home = note_by(&other, "tokens at home", 400, vec![]);
3120            relays[0].add_event(at_home.clone()).await.unwrap();
3121            let both = [urls[0].clone(), urls[1].clone()];
3122            let Found::Notes(notes) = service.search(&both, "tokens", SearchFor::Notes).await.unwrap() else {
3123                panic!("notes were searched for");
3124            };
3125            assert_eq!(sorted(ids(&notes)), sorted(vec![wanted.id, at_home.id]));
3126            assert_eq!(service.others.relays().await.len(), 1);
3127
3128            // Two searches at once, as a search page makes them, reach
3129            // for the same relay and both get its answer.
3130            let newly = [urls[2].clone()];
3131            let (one, other) = futures_util::future::join(
3132                service.search(&newly, "tokens", SearchFor::Notes),
3133                service.search(&newly, "tokens", SearchFor::People),
3134            )
3135            .await;
3136            assert!(matches!(one, Ok(Found::Notes(notes)) if notes.len() == 1));
3137            assert!(matches!(other, Ok(Found::People(people)) if people.is_empty()));
3138
3139            // A relay's own notes, for whoever names it: the newest first.
3140            let later = note_by(&author, "later, on the same relay", 500, vec![]);
3141            relays[2].add_event(later.clone()).await.unwrap();
3142            let on_relay = service.relay_notes(&urls[2]).await.unwrap();
3143            assert_eq!(ids(&on_relay).first(), Some(&later.id));
3144            assert_eq!(on_relay.len(), 2);
3145
3146            // Nothing found is no error; nobody to ask is.
3147            let Found::Notes(none) = service.search(&searched, "nothing says this", SearchFor::Notes).await.unwrap() else {
3148                panic!("notes were searched for");
3149            };
3150            assert!(none.is_empty());
3151            let dead = [RelayUrl::parse("ws://127.0.0.1:9").unwrap()];
3152            assert!(matches!(service.search(&dead, "tokens", SearchFor::Notes).await, Err(FetchError::NoRelayReachable)));
3153            assert!(matches!(service.search(&[], "tokens", SearchFor::Notes).await, Err(FetchError::NoRelayReachable)));
3154        });
3155    }
3156
3157    #[test]
3158    fn a_thread_opens_on_a_note_that_is_only_where_its_address_says() {
3159        with_relays("outbox-thread-hint", 3, 20, async |service, relays, urls| {
3160            let (far, quiet) = (Keys::generate(), Keys::generate());
3161            let hinted = note_by(&quiet, "on a relay the address names", 100, vec![]);
3162            let written = note_by(&far, "where its author writes", 200, vec![]);
3163            relays[0].add_event(relay_list(&far, &[&urls[2]], &[])).await.unwrap();
3164            relays[1].add_event(hinted.clone()).await.unwrap();
3165            relays[2].add_event(written.clone()).await.unwrap();
3166
3167            // With nothing said of where it is, it is not found.
3168            let nowhere = Whereabouts::default();
3169            assert!(service.thread(Source::Relays, hinted.id, &nowhere).await.unwrap().is_empty());
3170            assert!(service.others.relays().await.is_empty());
3171
3172            let on = Whereabouts { author: None, relay: Some(urls[1].clone()) };
3173            assert_eq!(ids(&service.thread(Source::Relays, hinted.id, &on).await.unwrap()), [hinted.id]);
3174            let by = Whereabouts { author: Some(far.public_key()), relay: None };
3175            assert_eq!(ids(&service.thread(Source::Relays, written.id, &by).await.unwrap()), [written.id]);
3176            // The store's turn asks nobody, wherever the note is said to be.
3177            let unseen = note_by(&quiet, "another, there too", 300, vec![]);
3178            relays[1].add_event(unseen.clone()).await.unwrap();
3179            assert!(service.thread(Source::Store, unseen.id, &on).await.unwrap().is_empty());
3180        });
3181    }
3182
3183    #[test]
3184    fn a_listed_note_is_asked_of_the_relay_it_is_said_to_be_on_and_of_where_its_author_writes() {
3185        with_relays("outbox-listed", 4, 20, async |service, relays, urls| {
3186            let (far, quiet) = (Keys::generate(), Keys::generate());
3187            let said = note_by(&quiet, "on the relay the list names", 100, vec![]);
3188            let written = note_by(&far, "where its author writes", 200, vec![]);
3189            let unsaid = note_by(&quiet, "on a relay nothing names", 300, vec![]);
3190            relays[0].add_event(relay_list(&far, &[&urls[2]], &[])).await.unwrap();
3191            relays[1].add_event(said.clone()).await.unwrap();
3192            relays[2].add_event(written.clone()).await.unwrap();
3193            relays[3].add_event(unsaid.clone()).await.unwrap();
3194
3195            let on = |relay: &RelayUrl| Whereabouts { author: None, relay: Some(relay.clone()) };
3196            let by = |author: &Keys| Whereabouts { author: Some(author.public_key()), relay: None };
3197            let listed = vec![(said.id, on(&urls[1])), (written.id, by(&far)), (unsaid.id, Whereabouts::default())];
3198            let found = service.notes_listed(listed.clone()).await;
3199            assert_eq!(ids(&found), [said.id, written.id]);
3200            assert_eq!(service.seen_on(&[said.id]).get(&said.id), Some(&vec![urls[1].clone()]));
3201
3202            // Said to be where it isn't: not found, and nothing fails.
3203            assert!(service.notes_listed(vec![(unsaid.id, on(&urls[1]))]).await.is_empty());
3204        });
3205        // Nothing is reached for when nothing may be.
3206        with_relays("outbox-listed-none", 2, 0, async |service, relays, urls| {
3207            let said = note_by(&Keys::generate(), "on the relay the list names", 100, vec![]);
3208            relays[1].add_event(said.clone()).await.unwrap();
3209            let listed = vec![(said.id, Whereabouts { author: None, relay: Some(urls[1].clone()) })];
3210            assert!(service.notes_listed(listed).await.is_empty());
3211            assert!(service.others.relays().await.is_empty());
3212        });
3213    }
3214
3215    #[test]
3216    fn a_thread_is_asked_of_the_relays_of_those_whose_conversation_it_is() {
3217        with_relays("outbox-thread", 4, 20, async |service, relays, urls| {
3218            let (asker, answerer, third) = (Keys::generate(), Keys::generate(), Keys::generate());
3219            // The root is where its author writes; the answer, which is
3220            // the note opened, is on the account's own relay; and an
3221            // answer to that is where the answerer reads.
3222            let root = note_by(&asker, "a question", 100, vec![]);
3223            let naming = |parent: &Event, marker: &str| Tag::parse(["e", &parent.id.to_hex(), "", marker]).unwrap();
3224            let answer = note_by(&answerer, "an answer", 200, vec![naming(&root, "root"), Tag::public_key(asker.public_key())]);
3225            let reply = note_by(
3226                &third,
3227                "a reply to the answer",
3228                300,
3229                vec![naming(&root, "root"), naming(&answer, "reply"), Tag::public_key(answerer.public_key())],
3230            );
3231            relays[0].add_event(relay_list(&asker, &[&urls[1]], &[])).await.unwrap();
3232            relays[0].add_event(relay_list(&answerer, &[&urls[0]], &[&urls[2]])).await.unwrap();
3233            relays[0].add_event(answer.clone()).await.unwrap();
3234            relays[1].add_event(root.clone()).await.unwrap();
3235            relays[2].add_event(reply.clone()).await.unwrap();
3236            // A relay nobody names has an answer nobody will find.
3237            relays[3].add_event(note_by(&third, "unheard", 400, vec![naming(&root, "root")])).await.unwrap();
3238
3239            let thread = service.thread(Source::Relays, answer.id, &Whereabouts::default()).await.unwrap();
3240            assert_eq!(sorted(ids(&thread)), sorted(vec![root.id, answer.id, reply.id]));
3241        });
3242    }
3243
3244    #[test]
3245    fn the_configs_relays_stand_down_once_the_account_says_where_it_writes() {
3246        // The config's relay counts as one on the open internet here: one
3247        // on this machine stays in use, as in every other test.
3248        let reach = Reach { cap: 20, accepts: |_| true, local: |_| false };
3249        with_relays_reaching("own-stand-down", 2, reach, async |service, relays, urls| {
3250            let (me, other) = (Keys::generate(), Keys::generate());
3251            relays[0].add_event(relay_list(&me, &[&urls[1]], &[])).await.unwrap();
3252            let elsewhere = note_by(&other, "on the config's relay alone", 50, vec![]);
3253            relays[0].add_event(elsewhere.clone()).await.unwrap();
3254
3255            // With no account, the config's relay is where things are.
3256            let before = note_by(&me, "before", 100, vec![]);
3257            assert_eq!(service.publish(&before).await, Ok(1));
3258            assert!(holds(&urls[0], before.id).await);
3259            assert_eq!(ids(&service.fetch_feed(&[other.public_key()], None, 50).await.unwrap()), [elsewhere.id]);
3260
3261            // The account writes to another relay: that one is its own,
3262            // and the config's is neither written to nor asked.
3263            assert_eq!(service.use_relays_of(Some(me.public_key())).await, 1);
3264            assert_eq!(service.reachable_relays().await, [urls[1].clone()]);
3265            let after = note_by(&me, "after", 200, vec![]);
3266            assert_eq!(service.publish(&after).await, Ok(1));
3267            assert!(holds(&urls[1], after.id).await && !holds(&urls[0], after.id).await);
3268            let unseen = note_by(&other, "on the config's relay, later", 300, vec![]);
3269            relays[0].add_event(unseen.clone()).await.unwrap();
3270            assert!(
3271                service.fetch_feed(&[other.public_key()], Some(350), 50).await.unwrap().iter().all(|note| note.id != unseen.id)
3272            );
3273
3274            // Signed out, the config's relay is back in use.
3275            assert_eq!(service.use_relays_of(None).await, 0);
3276            assert_eq!(service.reachable_relays().await, [urls[0].clone()]);
3277            assert!(ids(&service.fetch_feed(&[other.public_key()], None, 50).await.unwrap()).contains(&unseen.id));
3278        });
3279        // A relay list that names nowhere that answers changes nothing.
3280        with_relays_reaching("own-no-stand-down", 1, reach, async |service, relays, urls| {
3281            let me = Keys::generate();
3282            let dead = RelayUrl::parse("ws://127.0.0.1:9").unwrap();
3283            relays[0].add_event(relay_list(&me, &[&dead], &[])).await.unwrap();
3284            service.use_relays_of(Some(me.public_key())).await;
3285            assert_eq!(service.reachable_relays().await, [urls[0].clone()]);
3286            assert_eq!(service.publish(&note_by(&me, "still here", 100, vec![])).await, Ok(1));
3287        });
3288    }
3289
3290    #[test]
3291    fn what_the_account_writes_goes_to_the_relays_its_list_names_and_to_those_it_is_meant_for() {
3292        with_relays("outbox-publish", 4, 20, async |service, relays, urls| {
3293            let (me, friend) = (Keys::generate(), Keys::generate());
3294            // The account writes to a relay the config doesn't name, and
3295            // to one it does; a friend reads a third.
3296            relays[0].add_event(relay_list(&me, &[&urls[0], &urls[1]], &[&urls[3]])).await.unwrap();
3297            relays[0].add_event(relay_list(&friend, &[&urls[3]], &[&urls[2]])).await.unwrap();
3298            assert_eq!(service.use_relays_of(Some(me.public_key())).await, 1);
3299            assert_eq!(service.client.relays().await.len(), 2);
3300            tokio::time::sleep(Duration::from_millis(300)).await;
3301
3302            // A note that names nobody: the account's own relays, both.
3303            let alone = note_by(&me, "to nobody", 100, vec![]);
3304            assert_eq!(service.publish(&alone).await, Ok(2));
3305            assert!(holds(&urls[1], alone.id).await);
3306            assert!(!holds(&urls[2], alone.id).await);
3307
3308            // A note that names the friend: their relay too, the one they
3309            // read and not the one they write to.
3310            let said = note_by(&me, "to a friend", 200, vec![Tag::public_key(friend.public_key())]);
3311            assert_eq!(service.publish(&said).await, Ok(3));
3312            assert!(holds(&urls[0], said.id).await && holds(&urls[1], said.id).await && holds(&urls[2], said.id).await);
3313            assert!(!holds(&urls[3], said.id).await);
3314            assert_eq!(service.seen_on(&[said.id]).get(&said.id).map(Vec::len), Some(3));
3315
3316            // A contact list names the friend, and is not meant for them.
3317            let follows =
3318                EventBuilder::new(Kind::ContactList, "").tag(Tag::public_key(friend.public_key())).finalize(&me).unwrap();
3319            assert_eq!(service.publish(&follows).await, Ok(2));
3320            assert!(holds(&urls[1], follows.id).await);
3321            assert!(!holds(&urls[2], follows.id).await);
3322
3323            // Signed out, the relays the list named are nobody's.
3324            assert_eq!(service.use_relays_of(None).await, 0);
3325            assert_eq!(service.client.relays().await.into_keys().collect::<Vec<_>>(), [urls[0].clone()]);
3326            let after = note_by(&me, "after", 300, vec![]);
3327            assert_eq!(service.publish(&after).await, Ok(1));
3328            assert!(!holds(&urls[1], after.id).await);
3329        });
3330    }
3331
3332    #[test]
3333    fn the_newest_list_is_the_one_that_counts() {
3334        let keys = Keys::generate();
3335        let list =
3336            |at: u64| EventBuilder::new(Kind::Bookmarks, "").custom_created_at(Timestamp::from_secs(at)).finalize(&keys).unwrap();
3337        let (older, newer) = (list(1_000), list(2_000));
3338        assert_eq!(newest([older.clone(), newer.clone()]).map(|list| list.id), Some(newer.id));
3339        assert_eq!(newest([newer.clone(), older]).map(|list| list.id), Some(newer.id), "whichever order they arrive in");
3340        assert!(newest([]).is_none(), "no list at all");
3341    }
3342
3343    fn id(byte: u8) -> EventId {
3344        EventId::from_byte_array([byte; 32])
3345    }
3346
3347    fn e(note: EventId) -> Vec<String> {
3348        vec!["e".to_string(), note.to_hex()]
3349    }
3350
3351    fn fields(tags: &[&[&str]]) -> PrivateTags {
3352        tags.iter().map(|tag| tag.iter().map(ToString::to_string).collect()).collect()
3353    }
3354
3355    /// The bookmark list another client would have written for the account
3356    /// `keys`: `tags` for anyone to read, and `content`, as it stands.
3357    fn list_of(keys: &Keys, tags: &PrivateTags, content: &str, at: u64) -> Event {
3358        EventBuilder::new(Kind::Bookmarks, content)
3359            .tags(tags.iter().map(|tag| Tag::parse(tag).unwrap()))
3360            .custom_created_at(Timestamp::from_secs(at))
3361            .finalize(keys)
3362            .unwrap()
3363    }
3364
3365    /// What `keys` encrypts to itself the new way: `private`, as a
3366    /// bookmark list's content.
3367    fn kept(keys: &Keys, private: &PrivateTags) -> String {
3368        keys.nip44_encrypt(&keys.public_key(), &bookmarks::encode(private)).unwrap()
3369    }
3370
3371    /// What the bookmark list `list` of `keys` keeps to itself, read with
3372    /// the key itself, as another client would.
3373    fn kept_in(keys: &Keys, list: &Event) -> PrivateTags {
3374        bookmarks::decode(&keys.nip44_decrypt(&keys.public_key(), &list.content).unwrap()).unwrap()
3375    }
3376
3377    fn tags_of(list: &Event) -> PrivateTags {
3378        list.tags.iter().map(|tag| tag.as_slice().to_vec()).collect()
3379    }
3380
3381    /// Run `test` for an account whose key a remote signer keeps, which
3382    /// decrypts for it (`decrypting`) or won't, against a relay in this
3383    /// process, and `other_relays` beside it: the client, what signs for
3384    /// the account, and the account's key, with which another client would
3385    /// have written its lists.
3386    fn with_bookmarking_account<F: Future<Output = ()>>(
3387        name: &str,
3388        decrypting: bool,
3389        other_relays: &[&str],
3390        test: impl FnOnce(NostrService, Signer, Keys) -> F,
3391    ) {
3392        let path = std::env::temp_dir().join(format!("avestruz-test-{}-{name}", std::process::id()));
3393        let _ = std::fs::remove_dir_all(&path);
3394        let keys = Keys::generate();
3395        let approves = Approves { signing: true, decrypting };
3396        with_remote_signer_for(keys.clone(), None, approves, async |bunker| {
3397            let relay = bunker.relays().first().unwrap().to_string();
3398            let relays = std::iter::once(relay).chain(other_relays.iter().map(ToString::to_string)).collect();
3399            let service = NostrService::open(path.clone(), relays).await.unwrap();
3400            let signer = Signer::connected_to(bunker).await;
3401            test(service, signer, keys).await;
3402        });
3403        let _ = std::fs::remove_dir_all(&path);
3404    }
3405
3406    /// A list of `kind` by `keys` with `tags` and `content`, written at `at`.
3407    fn a_list(keys: &Keys, kind: Kind, tags: &PrivateTags, content: &str, at: u64) -> Event {
3408        EventBuilder::new(kind, content)
3409            .tags(tags.iter().map(|tag| Tag::parse(tag).unwrap()))
3410            .custom_created_at(Timestamp::from_secs(at))
3411            .finalize(keys)
3412            .unwrap()
3413    }
3414
3415    fn url(relay: &str) -> RelayUrl {
3416        RelayUrl::parse(relay).unwrap()
3417    }
3418
3419    #[test]
3420    fn the_accounts_relays_are_read_from_its_lists_and_changed_as_another_client_left_them() {
3421        with_bookmarking_account("relays-change", true, &[], async |service, signer, keys| {
3422            let account = keys.public_key();
3423            let (home, open, kept_relay) = ("wss://home.example.com/", "wss://open.example.com/", "wss://kept.example.com/");
3424            // As Amethyst leaves them: unmarked relays, a tag of its own,
3425            // and search relays said to anyone and kept private.
3426            let advertised = a_list(&keys, Kind::RelayList, &fields(&[&["r", home], &["client", "Amethyst"]]), "", 1_000);
3427            let private = fields(&[&["relay", kept_relay]]);
3428            let public = fields(&[&["client", "Amethyst"], &["relay", open]]);
3429            let search = a_list(&keys, Kind::SearchRelays, &public, &kept(&keys, &private), 1_000);
3430            service.publish(&advertised).await.unwrap();
3431            service.publish(&search).await.unwrap();
3432
3433            // Not asked to be read, what a list keeps to itself is left
3434            // alone: only what anyone can read is there.
3435            let closed = service.relay_lists(Source::Relays, &signer, account, None, &[]).await.unwrap();
3436            assert_eq!(closed.sets().of(Section::Search), [url(open)]);
3437            assert_eq!(*closed.of(Section::Search).kept(), Kept::Unread);
3438
3439            let read = service.relay_lists(Source::Relays, &signer, account, Some(closed), &Section::LISTS).await.unwrap();
3440            let sets = read.sets();
3441            assert_eq!((sets.of(Section::Outbox), sets.of(Section::Inbox)), (&[url(home)][..], &[url(home)][..]));
3442            assert_eq!(sets.of(Section::Search), [url(open), url(kept_relay)]);
3443            assert!(matches!(read.of(Section::Search).kept(), Kept::Read(_)));
3444            assert!(sets.of(Section::Blocked).is_empty());
3445            let again = service.relay_lists(Source::Store, &signer, account, Some(read.clone()), &Section::LISTS).await;
3446            assert_eq!(again, Ok(read.clone()));
3447
3448            // A relay the account now writes to is one of its own, and is
3449            // told so; the list is otherwise as it was.
3450            let joining = LocalRelay::builder().build();
3451            joining.run().await.unwrap();
3452            let joined = joining.url().await;
3453            let (outbox, inbox) = ([url(home), joined.clone()], [url(home)]);
3454            let changed = service.set_advertised_relays(&signer, account, &outbox, &inbox, false).await.unwrap().unwrap();
3455            assert!(changed.created_at > advertised.created_at && changed.verify().is_ok());
3456            assert_eq!(tags_of(&changed), fields(&[&["client", "Amethyst"], &["r", home], &["r", joined.as_str(), "write"]]));
3457            // The config's relay, and the two the list says it writes to.
3458            assert_eq!(service.client.relays().await.len(), 3);
3459            assert!(holds(&joined, changed.id).await);
3460            assert_eq!(service.stored_list(Kind::RelayList, account).await.map(|list| list.id), Some(changed.id));
3461            // The same relays again: nothing goes out.
3462            let same = service.set_advertised_relays(&signer, account, &outbox, &inbox, false).await.unwrap();
3463            assert_eq!(same.map(|list| list.id), Some(changed.id));
3464            // Left again: the relay is told that too, and is no longer one
3465            // of the account's.
3466            let left = service.set_advertised_relays(&signer, account, &[url(home)], &[], false).await.unwrap().unwrap();
3467            assert_eq!(tags_of(&left), fields(&[&["client", "Amethyst"], &["r", home, "write"]]));
3468            assert!(holds(&joined, left.id).await);
3469            assert_eq!(service.client.relays().await.len(), 2);
3470            joining.shutdown();
3471
3472            // A new search relay goes where the list keeps them, to itself;
3473            // the others stay where they were.
3474            let new = "wss://new.example.com/";
3475            let wanted = [url(open), url(kept_relay), url(new)];
3476            let known = Some(read.of(Section::Search));
3477            let added = service.set_listed_relays(&signer, account, Section::Search, &wanted, false, known).await.unwrap();
3478            assert_eq!(added.relays(), wanted);
3479            let ours = added.list().unwrap().clone();
3480            assert!(ours.created_at > search.created_at && ours.verify().is_ok());
3481            assert_eq!(tags_of(&ours), public);
3482            assert_eq!(kept_in(&keys, &ours), fields(&[&["relay", kept_relay], &["relay", new]]));
3483            // The same again: nothing goes out. In another order, it does.
3484            let same = service.set_listed_relays(&signer, account, Section::Search, &wanted, false, Some(added.clone())).await;
3485            assert_eq!(same.unwrap().list().map(|list| list.id), Some(ours.id));
3486            let moved = [url(open), url(new), url(kept_relay)];
3487            let moved_list =
3488                service.set_listed_relays(&signer, account, Section::Search, &moved, false, Some(added)).await.unwrap();
3489            assert_eq!(moved_list.relays(), moved);
3490            // One said to anyone is taken out of what is said to anyone.
3491            let fewer = [url(kept_relay), url(new)];
3492            let fewer_list =
3493                service.set_listed_relays(&signer, account, Section::Search, &fewer, false, Some(moved_list)).await.unwrap();
3494            assert_eq!(tags_of(fewer_list.list().unwrap()), fields(&[&["client", "Amethyst"]]));
3495            let again = service.relay_lists(Source::Relays, &signer, account, None, &[Section::Search]).await.unwrap();
3496            assert_eq!(again.sets().of(Section::Search), fewer);
3497        });
3498    }
3499
3500    #[test]
3501    fn a_first_relay_list_is_only_written_after_saying_so() {
3502        with_bookmarking_account("relays-first", true, &[], async |service, signer, keys| {
3503            let account = keys.public_key();
3504            let none = service.relay_lists(Source::Relays, &signer, account, None, &Section::LISTS).await.unwrap();
3505            assert_eq!(none.sets(), RelayLists::default().sets());
3506            assert_eq!(none.advertised, None);
3507
3508            // The relay it will write to is there to answer: a first list
3509            // is not written while one of the account's relays doesn't.
3510            let writing = LocalRelay::builder().build();
3511            writing.run().await.unwrap();
3512            let (outbox, search) = ([writing.url().await], [url("wss://search.example.com")]);
3513            // Nothing to write is nothing to refuse.
3514            assert_eq!(service.set_advertised_relays(&signer, account, &[], &[], false).await, Ok(None));
3515            assert_eq!(service.set_advertised_relays(&signer, account, &outbox, &[], false).await, Err(ListError::NoList));
3516            let refused = service.set_listed_relays(&signer, account, Section::Search, &search, false, None).await;
3517            assert_eq!(refused, Err(ListError::NoList));
3518            assert_eq!(service.stored_list(Kind::RelayList, account).await, None);
3519            assert_eq!(service.stored_list(Kind::SearchRelays, account).await, None);
3520
3521            let first = service.set_advertised_relays(&signer, account, &outbox, &[], true).await.unwrap().unwrap();
3522            assert_eq!(tags_of(&first), fields(&[&["r", outbox[0].as_str(), "write"]]));
3523            // A first search relay list says its relays to anyone, and a
3524            // first list of blocked relays keeps them to itself.
3525            let first = service.set_listed_relays(&signer, account, Section::Search, &search, true, None).await.unwrap();
3526            let list = first.list().unwrap();
3527            assert_eq!(tags_of(list), fields(&[&["relay", search[0].as_str()]]));
3528            assert_eq!(list.content, "");
3529            let blocked = [url("wss://blocked.example.com")];
3530            let first = service.set_listed_relays(&signer, account, Section::Blocked, &blocked, true, None).await.unwrap();
3531            let list = first.list().unwrap();
3532            assert_eq!((list.kind.as_u16(), list.tags.len()), (10006, 0));
3533            assert_eq!(kept_in(&keys, list), fields(&[&["relay", blocked[0].as_str()]]));
3534            let read = service.relay_lists(Source::Relays, &signer, account, None, &Section::LISTS).await.unwrap();
3535            assert_eq!(read.sets().of(Section::Blocked), blocked);
3536            writing.shutdown();
3537        });
3538    }
3539
3540    #[test]
3541    fn the_accounts_media_servers_are_its_list_and_a_first_one_is_only_written_after_saying_so() {
3542        with_bookmarking_account("media-servers", true, &[], async |service, signer, keys| {
3543            let account = keys.public_key();
3544            let server = |name: &str| Url::parse(name).unwrap();
3545            let (first, second) = (server("https://one.example.com/"), server("https://two.example.com/"));
3546            assert_eq!(service.media_server_list(Source::Relays, account).await, Ok(None));
3547
3548            let wanted = [first.clone()];
3549            assert_eq!(service.set_media_servers(&signer, account, &wanted, false).await, Err(ListError::NoList));
3550            assert_eq!(service.stored_list(Kind::BlossomServerList, account).await, None);
3551            let written = service.set_media_servers(&signer, account, &wanted, true).await.unwrap().unwrap();
3552            assert_eq!(tags_of(&written), fields(&[&["server", "https://one.example.com"]]));
3553            assert_eq!(written.pubkey, account);
3554            // The store has it at once, and the relays when asked.
3555            assert_eq!(service.media_server_list(Source::Store, account).await, Ok(Some(written.clone())));
3556            assert_eq!(service.media_server_list(Source::Relays, account).await, Ok(Some(written.clone())));
3557            // What it says already is not written again.
3558            assert_eq!(service.set_media_servers(&signer, account, &wanted, false).await, Ok(Some(written.clone())));
3559
3560            // Another put first: the list that replaces it is the newer.
3561            let changed =
3562                service.set_media_servers(&signer, account, &[second.clone(), first.clone()], false).await.unwrap().unwrap();
3563            assert_eq!(blossom::servers(Some(&changed)), [second, first]);
3564            assert!(changed.created_at > written.created_at);
3565            assert_eq!(service.media_server_list(Source::Relays, account).await, Ok(Some(changed)));
3566        });
3567    }
3568
3569    #[test]
3570    fn listed_relays_that_cannot_be_read_are_not_written_over() {
3571        with_bookmarking_account("relays-closed", false, &[], async |service, signer, keys| {
3572            let account = keys.public_key();
3573            let (open, kept_relay) = ("wss://open.example.com/", "wss://kept.example.com/");
3574            let private = fields(&[&["relay", kept_relay]]);
3575            let search = a_list(&keys, Kind::SearchRelays, &fields(&[&["relay", open]]), &kept(&keys, &private), 1_000);
3576            service.publish(&search).await.unwrap();
3577
3578            // What anyone can read is read, and that the rest wasn't is said.
3579            let read = service.relay_lists(Source::Relays, &signer, account, None, &Section::LISTS).await.unwrap();
3580            assert_eq!(read.sets().of(Section::Search), [url(open)]);
3581            assert!(matches!(read.of(Section::Search).kept(), Kept::Unreadable(_)));
3582
3583            let wanted = [url(open), url("wss://new.example.com")];
3584            let refused = service.set_listed_relays(&signer, account, Section::Search, &wanted, true, None).await;
3585            assert!(matches!(refused, Err(ListError::Unreadable(_))), "{refused:?}");
3586            assert_eq!(service.stored_list(Kind::SearchRelays, account).await.map(|list| list.id), Some(search.id));
3587            // The relay list keeps nothing to itself, and is changed all the same.
3588            let outbox = [url("wss://out.example.com")];
3589            assert!(service.set_advertised_relays(&signer, account, &outbox, &[], true).await.unwrap().is_some());
3590        });
3591    }
3592
3593    #[test]
3594    fn what_the_accounts_relays_do_not_have_is_looked_up_where_its_list_says() {
3595        with_relays("lookup", 3, 20, async |service, relays, urls| {
3596            let far = Keys::generate();
3597            let profile = EventBuilder::new(Kind::Metadata, r#"{"name":"Far"}"#).finalize(&far).unwrap();
3598            let there = note_by(&far, "on theirs", 100, vec![]);
3599            // Their relay list and their profile are on the indexer alone,
3600            // and their notes where the list says.
3601            relays[1].add_event(relay_list(&far, &[&urls[2]], &[])).await.unwrap();
3602            relays[1].add_event(profile).await.unwrap();
3603            relays[2].add_event(there.clone()).await.unwrap();
3604
3605            // With nowhere to look things up, they are not found.
3606            assert!(service.fetch_feed(&[far.public_key()], None, 50).await.unwrap().is_empty());
3607            assert!(service.fetch_profiles_where_written(vec![far.public_key()]).await.is_empty());
3608
3609            // With the indexer, they are, and asked for again at once.
3610            service.use_listed(vec![urls[1].clone()], Vec::new());
3611            assert_eq!(ids(&service.fetch_feed(&[far.public_key()], None, 50).await.unwrap()), [there.id]);
3612            let found = service.fetch_profiles_where_written(vec![far.public_key()]).await;
3613            assert_eq!(found.iter().map(|(_, profile)| profile.name.as_deref()).collect::<Vec<_>>(), [Some("Far")]);
3614        });
3615    }
3616
3617    #[test]
3618    fn a_blocked_relay_is_never_connected_to_on_anyones_word() {
3619        with_relays("blocked", 3, 20, async |service, relays, urls| {
3620            let far = Keys::generate();
3621            let (blocked_note, other_note) =
3622                (note_by(&far, "on the blocked one", 100, vec![]), note_by(&far, "elsewhere", 200, vec![]));
3623            relays[0].add_event(relay_list(&far, &[&urls[1], &urls[2]], &[])).await.unwrap();
3624            relays[1].add_event(blocked_note.clone()).await.unwrap();
3625            relays[2].add_event(other_note.clone()).await.unwrap();
3626            service.use_listed(Vec::new(), vec![urls[1].clone()]);
3627
3628            // Not for someone's notes, not for a note said to be there,
3629            // and not to search.
3630            assert_eq!(ids(&service.fetch_feed(&[far.public_key()], None, 50).await.unwrap()), [other_note.id]);
3631            let said = vec![(blocked_note.id, Whereabouts { author: None, relay: Some(urls[1].clone()) })];
3632            assert!(service.notes_listed(said).await.is_empty());
3633            let searched = service.search(&[urls[1].clone()], "blocked", SearchFor::Notes).await;
3634            assert!(matches!(searched, Err(FetchError::NoRelayReachable)));
3635            assert_eq!(service.others.relays().await.into_keys().collect::<Vec<_>>(), [urls[2].clone()]);
3636        });
3637    }
3638
3639    #[test]
3640    fn a_draft_is_kept_on_the_relay_of_this_machine_and_on_no_other() {
3641        with_bookmarking_account("drafts", true, &[], async |service, signer, keys| {
3642            let account = keys.public_key();
3643            let reply = Target::Reply(id(1));
3644            // With nobody signed in, the relay of this machine takes nothing.
3645            assert!(service.keep_draft(&signer, account, Target::Note, "too soon", &[]).await.is_err());
3646            service.use_relays_of(Some(account)).await;
3647
3648            service.keep_draft(&signer, account, Target::Note, "half a thought", &[]).await.unwrap();
3649            let said = Tag::parse(["imeta", "url https://cdn.example.com/abc.png", "m image/png"]).unwrap();
3650            service.keep_draft(&signer, account, reply, "an answer", std::slice::from_ref(&said)).await.unwrap();
3651            // Written again within the second, it replaces what was there.
3652            service.keep_draft(&signer, account, Target::Note, "a whole thought", &[]).await.unwrap();
3653            let kept = service.kept_drafts(&signer, account).await.unwrap();
3654            assert_eq!(kept.len(), 2, "{kept:?}");
3655            assert!(kept.contains(&(Target::Note, "a whole thought".to_string(), Vec::new())));
3656            // With what it says of the file it links to.
3657            assert!(kept.contains(&(reply, "an answer".to_string(), vec![said.clone()])));
3658
3659            // They are in the store, where nobody else can read them, and
3660            // on none of the account's other relays.
3661            let wraps = service.events(Source::Store, vec![Filter::new().kind(DRAFT_KIND).author(account)]).await.unwrap();
3662            assert_eq!(wraps.len(), 2);
3663            let elsewhere = service.client.relays().await.into_keys().next().unwrap();
3664            for wrap in &wraps {
3665                assert!(wrap.verify().is_ok() && !wrap.content.contains("thought") && !wrap.content.contains("answer"));
3666                assert!(!holds(&elsewhere, wrap.id).await);
3667            }
3668
3669            // Done with, it is kept as that, and is no draft any more.
3670            service.keep_draft(&signer, account, Target::Note, "  ", &[]).await.unwrap();
3671            assert_eq!(service.kept_drafts(&signer, account).await.unwrap(), [(reply, "an answer".to_string(), vec![said])]);
3672            // Signed out, the relay takes nothing again.
3673            service.use_relays_of(None).await;
3674            assert!(service.keep_draft(&signer, account, reply, "later", &[]).await.is_err());
3675        });
3676    }
3677
3678    #[test]
3679    fn a_bookmark_is_one_change_to_the_list_another_client_wrote() {
3680        with_bookmarking_account("bookmark-change", true, &[], async |service, signer, keys| {
3681            let account = keys.public_key();
3682            let public = fields(&[&["e", &id(1).to_hex()], &["t", "nostr"], &["title", "Mine"]]);
3683            let private = fields(&[&["e", &id(2).to_hex(), "wss://relay.example.com/"], &["a", "30023:abc:post"]]);
3684            let theirs = list_of(&keys, &public, &kept(&keys, &private), 1_000);
3685            service.publish(&theirs).await.unwrap();
3686
3687            // Read: what only the account can see. What anyone can is no
3688            // bookmark here.
3689            let read = service.bookmarks(Source::Relays, &signer, account, None).await.unwrap();
3690            assert_eq!(read.list().map(|list| list.id), Some(theirs.id));
3691            assert!(read.has(&id(2)) && !read.has(&id(1)) && !read.has(&id(3)));
3692            assert_eq!(service.bookmarks(Source::Store, &signer, account, None).await.as_ref(), Ok(&read));
3693
3694            // A note that is on the relay is bookmarked with where it is.
3695            let found = note("worth finding again", 500, &[]);
3696            service.publish(&found).await.unwrap();
3697            let added = service.set_bookmarked(&signer, account, found.id, true, false, Some(read)).await.unwrap();
3698            assert!(added.has(&found.id) && added.has(&id(2)));
3699            let ours = added.list().unwrap().clone();
3700            assert_eq!(service.stored_list(Kind::Bookmarks, account).await.map(|list| list.id), Some(ours.id));
3701            assert_eq!((ours.kind, ours.pubkey), (Kind::Bookmarks, account));
3702            assert!(ours.created_at > theirs.created_at && ours.verify().is_ok());
3703            assert_eq!(tags_of(&ours), public, "what anyone can read is as it was");
3704            let hinted = kept_in(&keys, &ours);
3705            assert_eq!(hinted[..2], private[..], "and so is what was kept private");
3706            assert_eq!(hinted[2][..2], e(found.id)[..]);
3707            assert!(hinted[2][2].starts_with("ws://"), "{:?}", hinted[2]);
3708            assert_eq!(hinted.len(), 3);
3709
3710            // Bookmarked already: nothing goes out.
3711            let again = service.set_bookmarked(&signer, account, found.id, true, false, Some(added.clone())).await.unwrap();
3712            assert_eq!(again.list().map(|list| list.id), Some(ours.id));
3713
3714            // A note that anyone can see in the list has no bookmark here
3715            // to take off: nothing goes out, and it stays where it is.
3716            let same = service.set_bookmarked(&signer, account, id(1), false, false, Some(again)).await.unwrap();
3717            assert_eq!(same.list().map(|list| list.id), Some(ours.id));
3718            // Bookmarked here, it is kept private as any other note is.
3719            let both = service.set_bookmarked(&signer, account, id(1), true, false, Some(same)).await.unwrap();
3720            assert!(both.has(&id(1)));
3721            assert_eq!(tags_of(both.list().unwrap()), public);
3722            assert_eq!(kept_in(&keys, both.list().unwrap()).last(), Some(&e(id(1))));
3723
3724            // Taken off a note kept private, read anew from the relays.
3725            let least = service.set_bookmarked(&signer, account, id(2), false, false, None).await.unwrap();
3726            assert!(!least.has(&id(2)) && least.has(&found.id) && least.has(&id(1)));
3727            let list = least.list().unwrap();
3728            assert_eq!(tags_of(list), public, "what anyone can read is still as it was");
3729            assert_eq!(kept_in(&keys, list), [private[1].clone(), hinted[2].clone(), e(id(1))]);
3730            // The relay has the last one, and no other.
3731            let on_relay = service.bookmarks(Source::Relays, &signer, account, None).await.unwrap();
3732            assert_eq!(on_relay.list().map(|list| list.id), Some(list.id));
3733        });
3734    }
3735
3736    #[test]
3737    fn the_first_bookmark_list_is_only_written_when_the_account_says_so() {
3738        with_bookmarking_account("bookmark-first", true, &[], async |service, signer, keys| {
3739            let account = keys.public_key();
3740            let none = service.bookmarks(Source::Relays, &signer, account, None).await.unwrap();
3741            assert_eq!(none, Bookmarks::default());
3742
3743            let refused = service.set_bookmarked(&signer, account, id(1), true, false, Some(none.clone())).await;
3744            assert_eq!(refused, Err(ListError::NoList));
3745            assert!(service.stored_list(Kind::Bookmarks, account).await.is_none(), "nothing was written");
3746            // Taking off what isn't there needs no list either.
3747            assert_eq!(service.set_bookmarked(&signer, account, id(1), false, false, None).await, Ok(none));
3748
3749            let first = service.set_bookmarked(&signer, account, id(1), true, true, None).await.unwrap();
3750            let list = first.list().unwrap();
3751            assert!(first.has(&id(1)) && list.tags.is_empty());
3752            assert_eq!(kept_in(&keys, list), [e(id(1))], "as another client reads it");
3753
3754            // With nothing left to keep, the list has no content.
3755            let emptied = service.set_bookmarked(&signer, account, id(1), false, false, Some(first)).await.unwrap();
3756            let list = emptied.list().unwrap();
3757            assert!(!emptied.has(&id(1)) && list.tags.is_empty() && list.content.is_empty());
3758            // Which is read without decrypting anything, and added to.
3759            let read = service.bookmarks(Source::Relays, &signer, account, None).await.unwrap();
3760            assert_eq!(read, emptied);
3761            let refilled = service.set_bookmarked(&signer, account, id(2), true, false, None).await.unwrap();
3762            assert_eq!(kept_in(&keys, refilled.list().unwrap()), [e(id(2))]);
3763        });
3764    }
3765
3766    #[test]
3767    fn no_first_list_is_written_while_a_relay_that_may_have_one_does_not_answer() {
3768        // Nothing listens at the second relay.
3769        with_bookmarking_account("bookmark-incomplete", true, &["ws://127.0.0.1:9"], async |service, signer, keys| {
3770            let account = keys.public_key();
3771            // To read, the relay that answers is enough.
3772            let none = service.bookmarks(Source::Relays, &signer, account, None).await.unwrap();
3773            assert_eq!(none, Bookmarks::default());
3774
3775            // To write a first list, it isn't, whatever the account says.
3776            for first_list in [false, true] {
3777                let unsure = service.set_bookmarked(&signer, account, id(1), true, first_list, None).await;
3778                assert_eq!(unsure, Err(ListError::Fetch(FetchError::Incomplete)));
3779            }
3780            assert!(service.stored_list(Kind::Bookmarks, account).await.is_none(), "nothing was written");
3781            let person = Keys::generate().public_key();
3782            let unsure = service.set_following(&signer, account, person, true, true).await;
3783            assert_eq!(unsure, Err(FollowError::Fetch(FetchError::Incomplete)), "nor a first contact list");
3784
3785            // A list that is found is changed, wherever it was found.
3786            service.publish(&list_of(&keys, &PrivateTags::new(), "", 1_000)).await.unwrap();
3787            let added = service.set_bookmarked(&signer, account, id(1), true, false, None).await.unwrap();
3788            assert_eq!(kept_in(&keys, added.list().unwrap()), [e(id(1))]);
3789        });
3790    }
3791
3792    #[test]
3793    fn a_list_from_an_older_client_is_read_and_written_back_the_new_way() {
3794        with_bookmarking_account("bookmark-old", true, &[], async |service, signer, keys| {
3795            let account = keys.public_key();
3796            let private = fields(&[&["e", &id(2).to_hex()]]);
3797            let old_way = keys.nip04_encrypt(&account, &bookmarks::encode(&private)).unwrap();
3798            service.publish(&list_of(&keys, &PrivateTags::new(), &old_way, 1_000)).await.unwrap();
3799
3800            let read = service.bookmarks(Source::Relays, &signer, account, None).await.unwrap();
3801            assert!(read.has(&id(2)));
3802            let added = service.set_bookmarked(&signer, account, id(3), true, false, Some(read)).await.unwrap();
3803            let list = added.list().unwrap();
3804            assert!(!list.content.contains("?iv="), "{}", list.content);
3805            assert_eq!(kept_in(&keys, list), [e(id(2)), e(id(3))]);
3806        });
3807    }
3808
3809    #[test]
3810    fn a_list_that_cannot_be_read_is_not_written_over() {
3811        // The remote signer signs, and decrypts nothing.
3812        with_bookmarking_account("bookmark-unreadable", false, &[], async |service, signer, keys| {
3813            let account = keys.public_key();
3814            let private = fields(&[&["e", &id(2).to_hex()]]);
3815            let public = fields(&[&["e", &id(1).to_hex()]]);
3816            let theirs = list_of(&keys, &public, &kept(&keys, &private), 1_000);
3817            service.publish(&theirs).await.unwrap();
3818
3819            let unread = service.bookmarks(Source::Relays, &signer, account, None).await;
3820            assert!(matches!(unread, Err(ListError::Unreadable(SignError::Remote(_)))), "{unread:?}");
3821            for bookmark in [true, false] {
3822                let unchanged = service.set_bookmarked(&signer, account, id(1), bookmark, true, None).await;
3823                assert!(matches!(unchanged, Err(ListError::Unreadable(_))), "{unchanged:?}");
3824            }
3825            assert_eq!(service.stored_list(Kind::Bookmarks, account).await.map(|list| list.id), Some(theirs.id));
3826
3827            // A list read before is not decrypted again: nothing is asked
3828            // of the signer but to encrypt and to sign.
3829            let known = Bookmarks::new(Some(theirs.clone()), private.clone());
3830            assert_eq!(service.bookmarks(Source::Relays, &signer, account, Some(known.clone())).await.as_ref(), Ok(&known));
3831            let added = service.set_bookmarked(&signer, account, id(3), true, false, Some(known)).await.unwrap();
3832            assert_eq!(kept_in(&keys, added.list().unwrap()), [e(id(2)), e(id(3))]);
3833        });
3834    }
3835
3836    #[test]
3837    fn what_decrypts_to_something_else_than_tags_is_not_a_list_to_change() {
3838        with_bookmarking_account("bookmark-not-tags", true, &[], async |service, signer, keys| {
3839            let account = keys.public_key();
3840            let words = keys.nip44_encrypt(&account, "secret words").unwrap();
3841            let theirs = list_of(&keys, &PrivateTags::new(), &words, 1_000);
3842            service.publish(&theirs).await.unwrap();
3843
3844            let unread = service.bookmarks(Source::Relays, &signer, account, None).await;
3845            match unread {
3846                Err(ListError::Unreadable(SignError::Cipher(why))) => assert!(!why.contains("secret"), "{why}"),
3847                other => panic!("unreadable, not {other:?}"),
3848            }
3849            let unchanged = service.set_bookmarked(&signer, account, id(1), true, false, None).await;
3850            assert!(matches!(unchanged, Err(ListError::Unreadable(_))), "{unchanged:?}");
3851            assert_eq!(service.stored_list(Kind::Bookmarks, account).await.map(|list| list.id), Some(theirs.id));
3852        });
3853    }
3854
3855    #[test]
3856    fn a_note_nobody_has_has_no_thread() {
3857        let (ids, _) = thread_in_store("nothing", &[note("something else", 100, &[])], EventId::from_byte_array([9; 32]));
3858        assert!(ids.is_empty());
3859    }
3860
3861    #[test]
3862    fn a_list_of_authors_is_asked_about_in_one_filter_for_every_so_many_of_them() {
3863        assert_eq!(feed_filters(&people(3), None, 50).len(), 1);
3864        assert_eq!(feed_filters(&people(AUTHORS_PER_FILTER + 1), None, 50).len(), 2);
3865        assert!(feed_filters(&[], None, 50).is_empty(), "nobody followed, nothing to ask");
3866    }
3867
3868    #[test]
3869    fn a_feed_filter_names_its_authors_its_page_and_only_notes_and_comments() {
3870        let authors = people(2);
3871        let filters = feed_filters(&authors, Some(1_000), 50);
3872        let filter = &filters[0];
3873        assert_eq!(filter.limit, Some(50));
3874        assert_eq!(filter.until, Some(Timestamp::from_secs(1_000)));
3875        assert_eq!(
3876            filter.kinds.as_ref().map(|kinds| kinds.iter().copied().collect::<Vec<_>>()),
3877            Some(vec![Kind::TextNote, Kind::Comment])
3878        );
3879        let named = filter.authors.as_ref().unwrap();
3880        assert!(authors.iter().all(|author| named.contains(author)) && named.len() == 2);
3881    }
3882
3883    #[test]
3884    fn an_author_who_published_twice_is_known_by_the_later_profile() {
3885        let keys = Keys::generate();
3886        let profile = |name: &str, at: u64| {
3887            EventBuilder::new(Kind::Metadata, format!(r#"{{"name":"{name}"}}"#))
3888                .custom_created_at(Timestamp::from_secs(at))
3889                .finalize(&keys)
3890                .unwrap()
3891        };
3892
3893        for events in [[profile("old", 100), profile("new", 200)], [profile("new", 200), profile("old", 100)]] {
3894            let profiles = newest_profiles(events);
3895            assert_eq!(profiles.len(), 1);
3896            assert_eq!(profiles[0].0, keys.public_key());
3897            assert_eq!(profiles[0].1.name.as_deref(), Some("new"));
3898        }
3899    }
3900}