1use std::collections::{HashMap, HashSet};
60use std::fmt;
61
62use nostr_sdk::prelude::{Event, EventBuilder, Kind, RelayUrl, Tag, Timestamp};
63
64use crate::nostr::account::SignError;
65use crate::nostr::bookmarks::PrivateTags;
66use crate::nostr::outbox::{self, Listed};
67use crate::nostr::relay_info::RelayInfo;
68
69const ADVERTISED_TAG: &str = "r";
72const RELAY_TAG: &str = "relay";
73
74pub const NIP_SEARCH: u16 = 50;
77pub const NIP_AUTH: u16 = 42;
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum Hindrance {
83 Lacks(u16),
86 RestrictedWrites,
88 PaymentRequired,
90 AuthToWrite,
93 AuthToRead,
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
100pub enum Section {
101 Outbox,
103 Inbox,
105 Messages,
107 Search,
109 Indexer,
112 Trusted,
114 Blocked,
116}
117
118impl Section {
119 pub const ALL: [Self; 7] =
121 [Self::Outbox, Self::Inbox, Self::Messages, Self::Search, Self::Indexer, Self::Trusted, Self::Blocked];
122
123 pub const LISTS: [Self; 5] = [Self::Messages, Self::Search, Self::Indexer, Self::Trusted, Self::Blocked];
126
127 pub fn kind(self) -> Kind {
129 match self {
130 Self::Outbox | Self::Inbox => Kind::RelayList,
131 Self::Messages => Kind::InboxRelays,
132 Self::Search => Kind::SearchRelays,
133 Self::Indexer => Kind::Custom(10086),
134 Self::Trusted => Kind::Custom(10089),
135 Self::Blocked => Kind::BlockedRelays,
136 }
137 }
138
139 pub fn needs(self) -> Option<u16> {
146 match self {
147 Self::Search => Some(NIP_SEARCH),
148 Self::Messages => Some(NIP_AUTH),
149 Self::Outbox | Self::Inbox | Self::Indexer | Self::Trusted | Self::Blocked => None,
150 }
151 }
152
153 fn written_to_by_others(self) -> bool {
156 matches!(self, Self::Inbox | Self::Messages)
157 }
158
159 fn read_by_others(self) -> bool {
162 self == Self::Outbox
163 }
164
165 pub fn asks_of_relays(self) -> bool {
168 self.needs().is_some() || self.written_to_by_others() || self.read_by_others()
169 }
170
171 pub fn hindrances(self, info: &RelayInfo) -> Vec<Hindrance> {
180 let mut found = Vec::new();
181 if let Some(nip) = self.needs()
182 && info.supports(nip) == Some(false)
183 {
184 found.push(Hindrance::Lacks(nip));
185 }
186 if self.written_to_by_others() {
187 let limits = info.limits;
188 found.extend(limits.restricted_writes.then_some(Hindrance::RestrictedWrites));
189 found.extend(limits.payment_required.then_some(Hindrance::PaymentRequired));
190 found.extend((limits.auth_required && self.needs() != Some(NIP_AUTH)).then_some(Hindrance::AuthToWrite));
191 }
192 if self.read_by_others() {
193 found.extend(info.limits.auth_required.then_some(Hindrance::AuthToRead));
194 }
195 found
196 }
197
198 fn always_public(self) -> bool {
201 self == Self::Messages
202 }
203
204 fn first_is_public(self) -> bool {
207 matches!(self, Self::Messages | Self::Search)
208 }
209}
210
211#[derive(Debug, Clone, Default, PartialEq, Eq)]
213pub struct RelaySets(HashMap<Section, Vec<RelayUrl>>);
214
215impl RelaySets {
216 pub fn of(&self, section: Section) -> &[RelayUrl] {
218 self.0.get(§ion).map_or(&[], Vec::as_slice)
219 }
220
221 pub fn set(&mut self, section: Section, relays: Vec<RelayUrl>) {
223 self.0.insert(section, relays);
224 }
225
226 pub fn add(&mut self, section: Section, relay: RelayUrl) -> bool {
229 let relays = self.0.entry(section).or_default();
230 let new = !relays.contains(&relay);
231 if new {
232 relays.push(relay);
233 }
234 new
235 }
236
237 pub fn remove(&mut self, section: Section, relay: &RelayUrl) {
239 self.0.entry(section).or_default().retain(|listed| listed != relay);
240 }
241
242 pub fn shift(&mut self, section: Section, relay: &RelayUrl, up: bool) {
245 let relays = self.0.entry(section).or_default();
246 let Some(place) = relays.iter().position(|listed| listed == relay) else {
247 return;
248 };
249 let other = if up { place.checked_sub(1) } else { Some(place + 1).filter(|next| *next < relays.len()) };
250 if let Some(other) = other {
251 relays.swap(place, other);
252 }
253 }
254
255 pub fn same_as(&self, other: &Self) -> bool {
258 Section::ALL.iter().all(|section| self.of(*section) == other.of(*section))
259 }
260}
261
262pub fn typed_relay(typed: &str) -> Option<RelayUrl> {
265 let typed = typed.trim();
266 if typed.is_empty() || typed.contains(char::is_whitespace) {
267 return None;
268 }
269 let address = if typed.contains("://") { typed.to_string() } else { format!("wss://{typed}") };
270 RelayUrl::parse(&address).ok()
271}
272
273fn replacing(earlier: Option<&Event>, now: Timestamp) -> Timestamp {
277 earlier.map_or(now, |earlier| now.max(Timestamp::from_secs(earlier.created_at.as_secs() + 1)))
278}
279
280fn names_relay(fields: &[String], name: &str) -> bool {
282 matches!(fields, [called, relay, ..] if called == name && RelayUrl::parse(relay).is_ok())
283}
284
285fn relays_named<'a>(tags: impl IntoIterator<Item = &'a [String]>, name: &str) -> Vec<RelayUrl> {
287 let mut seen = HashSet::new();
288 tags.into_iter()
289 .filter(|fields| fields.first().is_some_and(|called| called == name))
290 .filter_map(|fields| fields.get(1).and_then(|relay| RelayUrl::parse(relay).ok()))
291 .filter(|relay| seen.insert(relay.clone()))
292 .collect()
293}
294
295pub fn advertised(list: Option<&Event>) -> (Vec<RelayUrl>, Vec<RelayUrl>) {
298 list.map(|list| (outbox::relays(list, Listed::Write), outbox::relays(list, Listed::Read))).unwrap_or_default()
299}
300
301pub fn advertised_list(earlier: Option<&Event>, outbox: &[RelayUrl], inbox: &[RelayUrl], now: Timestamp) -> Option<EventBuilder> {
311 let names = |tag: &&Tag| names_relay(tag.as_slice(), ADVERTISED_TAG);
312 let naming = |relay: &RelayUrl, marker: Option<&str>| {
313 let fields = [ADVERTISED_TAG, relay.as_str()].into_iter().chain(marker);
314 Tag::parse(fields).ok()
315 };
316 let written = outbox.iter().filter_map(|relay| naming(relay, (!inbox.contains(relay)).then_some("write")));
317 let read = inbox.iter().filter(|relay| !outbox.contains(relay)).filter_map(|relay| naming(relay, Some("read")));
318 let relays: Vec<Tag> = written.chain(read).collect();
319
320 let said = |tags: &[Tag]| -> Vec<(Option<RelayUrl>, Option<String>)> {
322 tags.iter()
323 .map(|tag| (tag.as_slice().get(1).and_then(|relay| RelayUrl::parse(relay).ok()), tag.as_slice().get(2).cloned()))
324 .collect()
325 };
326 let before: Vec<Tag> = earlier.into_iter().flat_map(|earlier| earlier.tags.iter()).filter(names).cloned().collect();
327 if said(&before) == said(&relays) {
328 return None;
329 }
330 let kept = earlier.into_iter().flat_map(|earlier| earlier.tags.iter()).filter(|tag| !names(tag));
331 let tags: Vec<Tag> = kept.cloned().chain(relays).collect();
332 let content = earlier.map(|earlier| earlier.content.clone()).unwrap_or_default();
333 Some(EventBuilder::new(Kind::RelayList, content).tags(tags).custom_created_at(replacing(earlier, now)))
334}
335
336#[derive(Clone, PartialEq, Eq)]
338pub enum Kept {
339 Read(PrivateTags),
341 Unread,
344 Unreadable(SignError),
346}
347
348impl fmt::Debug for Kept {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 match self {
353 Self::Read(private) => write!(f, "Read({} tag(s))", private.len()),
354 Self::Unread => f.write_str("Unread"),
355 Self::Unreadable(why) => write!(f, "Unreadable({why:?})"),
356 }
357 }
358}
359
360#[derive(Clone, PartialEq, Eq)]
364pub struct ListedRelays {
365 list: Option<Event>,
367 kept: Kept,
369}
370
371impl Default for ListedRelays {
372 fn default() -> Self {
373 Self { list: None, kept: Kept::Read(Vec::new()) }
374 }
375}
376
377impl fmt::Debug for ListedRelays {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 f.debug_struct("ListedRelays")
382 .field("list", &self.list.as_ref().map(|list| list.id))
383 .field("relays", &self.relays().len())
384 .finish_non_exhaustive()
385 }
386}
387
388impl ListedRelays {
389 pub fn new(list: Option<Event>, kept: Kept) -> Self {
391 Self { list, kept }
392 }
393
394 pub fn list(&self) -> Option<&Event> {
396 self.list.as_ref()
397 }
398
399 pub fn kept(&self) -> &Kept {
401 &self.kept
402 }
403
404 fn public(&self) -> Vec<RelayUrl> {
406 relays_named(self.list.iter().flat_map(|list| list.tags.iter()).map(Tag::as_slice), RELAY_TAG)
407 }
408
409 fn private(&self) -> Vec<RelayUrl> {
411 match &self.kept {
412 Kept::Read(private) => relays_named(private.iter().map(Vec::as_slice), RELAY_TAG),
413 Kept::Unread | Kept::Unreadable(_) => Vec::new(),
414 }
415 }
416
417 pub fn relays(&self) -> Vec<RelayUrl> {
420 let mut relays = self.public();
421 for relay in self.private() {
422 if !relays.contains(&relay) {
423 relays.push(relay);
424 }
425 }
426 relays
427 }
428
429 pub fn changed(&self, section: Section, relays: &[RelayUrl]) -> Option<(Vec<Tag>, PrivateTags)> {
438 let Kept::Read(kept) = &self.kept else {
439 return None;
440 };
441 let (was_public, was_private) = (self.public(), self.private());
442 let new_are_public = section.always_public()
443 || if self.list.is_none() { section.first_is_public() } else { !was_public.is_empty() && was_private.is_empty() };
444 let is_public = |relay: &&RelayUrl| {
445 section.always_public() || was_public.contains(relay) || (!was_private.contains(relay) && new_are_public)
446 };
447 let (public, private): (Vec<&RelayUrl>, Vec<&RelayUrl>) = relays.iter().partition(is_public);
448 let same =
449 |one: &[&RelayUrl], other: &[RelayUrl]| one.len() == other.len() && one.iter().zip(other).all(|(a, b)| *a == b);
450 let was_private_alone: Vec<RelayUrl> = was_private.iter().filter(|relay| !was_public.contains(relay)).cloned().collect();
452 if same(&public, &was_public) && same(&private, &was_private_alone) {
453 return None;
454 }
455 let naming = |relay: &RelayUrl| vec![RELAY_TAG.to_string(), relay.to_string()];
456 let others = self.list.iter().flat_map(|list| list.tags.iter()).filter(|tag| !names_relay(tag.as_slice(), RELAY_TAG));
457 let tags: Vec<Tag> =
458 others.cloned().chain(public.into_iter().filter_map(|relay| Tag::parse(naming(relay)).ok())).collect();
459 let mut private_tags: PrivateTags = kept.iter().filter(|fields| !names_relay(fields, RELAY_TAG)).cloned().collect();
460 private_tags.extend(private.into_iter().map(naming));
461 Some((tags, private_tags))
462 }
463}
464
465pub fn listed(section: Section, earlier: Option<&Event>, tags: Vec<Tag>, content: String, now: Timestamp) -> EventBuilder {
468 EventBuilder::new(section.kind(), content).tags(tags).custom_created_at(replacing(earlier, now))
469}
470
471#[derive(Debug, Clone, Default, PartialEq, Eq)]
473pub struct RelayLists {
474 pub advertised: Option<Event>,
476 pub listed: HashMap<Section, ListedRelays>,
478}
479
480impl RelayLists {
481 pub fn of(&self, section: Section) -> ListedRelays {
484 self.listed.get(§ion).cloned().unwrap_or_default()
485 }
486
487 pub fn sets(&self) -> RelaySets {
490 let (outbox, inbox) = advertised(self.advertised.as_ref());
491 let mut sets = RelaySets::default();
492 sets.set(Section::Outbox, outbox);
493 sets.set(Section::Inbox, inbox);
494 for section in Section::LISTS {
495 sets.set(section, self.listed.get(§ion).map(ListedRelays::relays).unwrap_or_default());
496 }
497 sets
498 }
499}
500
501#[cfg(test)]
502mod tests {
503 use super::{
504 Hindrance, Kept, ListedRelays, NIP_AUTH, NIP_SEARCH, RelayLists, RelaySets, Section, advertised, advertised_list, listed,
505 typed_relay,
506 };
507 use crate::nostr::account::SignError;
508 use crate::nostr::relay_info::{Limits, RelayInfo};
509 use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, Keys, Kind, RelayUrl, Tag, Timestamp};
510
511 fn relay(name: &str) -> RelayUrl {
512 RelayUrl::parse(&format!("wss://{name}.example.com")).unwrap()
513 }
514
515 fn tag(fields: &[&str]) -> Tag {
516 Tag::parse(fields.iter().copied()).unwrap()
517 }
518
519 fn a_list(kind: Kind, tags: Vec<Tag>, content: &str, at: u64) -> Event {
520 EventBuilder::new(kind, content)
521 .tags(tags)
522 .custom_created_at(Timestamp::from_secs(at))
523 .finalize(&Keys::generate())
524 .unwrap()
525 }
526
527 fn fields(event: &Event) -> Vec<Vec<String>> {
528 event.tags.iter().map(|tag| tag.as_slice().to_vec()).collect()
529 }
530
531 fn private(relays: &[&RelayUrl]) -> Vec<Vec<String>> {
532 relays.iter().map(|relay| vec!["relay".to_string(), relay.to_string()]).collect()
533 }
534
535 #[test]
536 fn what_a_relay_says_of_itself_gets_in_the_way_of_some_sets_and_not_of_others() {
537 let says = |nips: &[u16], limits: Limits| RelayInfo { nips: Some(nips.to_vec()), limits, ..RelayInfo::default() };
538 let open = Limits::default();
539 let closed = Limits { auth_required: true, payment_required: true, restricted_writes: true };
540
541 assert_eq!(Section::Search.hindrances(&says(&[1, 11], open)), [Hindrance::Lacks(NIP_SEARCH)]);
544 assert_eq!(Section::Search.hindrances(&says(&[1, 50], open)), []);
545 assert_eq!(Section::Search.hindrances(&RelayInfo::default()), []);
546 assert_eq!(Section::Messages.hindrances(&says(&[1], open)), [Hindrance::Lacks(NIP_AUTH)]);
547
548 let all = [Hindrance::RestrictedWrites, Hindrance::PaymentRequired, Hindrance::AuthToWrite];
551 assert_eq!(Section::Inbox.hindrances(&says(&[1], closed)), all);
552 assert_eq!(Section::Inbox.hindrances(&RelayInfo { limits: closed, ..RelayInfo::default() }), all);
553 assert_eq!(Section::Inbox.hindrances(&says(&[1], open)), []);
554 let asking = Limits { auth_required: true, ..open };
555 assert_eq!(Section::Inbox.hindrances(&says(&[1, 42], asking)), [Hindrance::AuthToWrite]);
556 assert_eq!(Section::Messages.hindrances(&says(&[1, 42], asking)), []);
558 assert_eq!(Section::Messages.hindrances(&says(&[1, 42], closed)), all[..2]);
559
560 assert_eq!(Section::Outbox.hindrances(&says(&[1, 42], closed)), [Hindrance::AuthToRead]);
564 let members = Limits { payment_required: true, restricted_writes: true, ..open };
565 assert_eq!(Section::Outbox.hindrances(&says(&[1], members)), []);
566 assert!(Section::Outbox.asks_of_relays());
567
568 for section in [Section::Indexer, Section::Trusted, Section::Blocked] {
570 assert_eq!(section.hindrances(&says(&[1], closed)), [], "{section:?}");
571 assert!(!section.asks_of_relays());
572 }
573 assert!(Section::Inbox.asks_of_relays() && Section::Messages.asks_of_relays() && Section::Search.asks_of_relays());
574 assert_eq!(Section::Search.hindrances(&says(&[1, 50], closed)), []);
575 }
576
577 #[test]
578 fn a_relay_is_typed_with_or_without_its_scheme() {
579 let ditto = RelayUrl::parse("wss://relay.ditto.pub").unwrap();
580 for typed in ["relay.ditto.pub", " wss://relay.ditto.pub/ ", "wss://relay.ditto.pub"] {
581 assert_eq!(typed_relay(typed), Some(ditto.clone()), "{typed}");
582 }
583 assert_eq!(typed_relay("ws://127.0.0.1:7777"), RelayUrl::parse("ws://127.0.0.1:7777").ok());
584 for not_a_relay in ["", " ", "https://example.com", "two words", "wss://"] {
585 assert_eq!(typed_relay(not_a_relay), None, "{not_a_relay:?}");
586 }
587 }
588
589 #[test]
590 fn relays_are_added_once_taken_out_and_moved() {
591 let mut sets = RelaySets::default();
592 assert!(sets.add(Section::Search, relay("one")));
593 assert!(sets.add(Section::Search, relay("two")));
594 assert!(!sets.add(Section::Search, relay("one")), "there already");
595 assert!(sets.add(Section::Outbox, relay("one")), "each set for itself");
596 assert_eq!(sets.of(Section::Search), [relay("one"), relay("two")]);
597 sets.remove(Section::Search, &relay("one"));
598 assert_eq!(sets.of(Section::Search), [relay("two")]);
599 assert_eq!(sets.of(Section::Outbox), [relay("one")]);
600 assert!(sets.of(Section::Inbox).is_empty());
601
602 let mut sets = RelaySets::default();
604 for name in ["a", "b", "c"] {
605 sets.add(Section::Outbox, relay(name));
606 }
607 sets.shift(Section::Outbox, &relay("c"), true);
608 assert_eq!(sets.of(Section::Outbox), [relay("a"), relay("c"), relay("b")]);
609 sets.shift(Section::Outbox, &relay("a"), true);
610 sets.shift(Section::Outbox, &relay("b"), false);
611 sets.shift(Section::Outbox, &relay("nowhere"), false);
612 assert_eq!(sets.of(Section::Outbox), [relay("a"), relay("c"), relay("b")]);
613 sets.shift(Section::Outbox, &relay("a"), false);
614 assert_eq!(sets.of(Section::Outbox), [relay("c"), relay("a"), relay("b")]);
615
616 let mut other = sets.clone();
618 assert!(sets.same_as(&other));
619 other.shift(Section::Outbox, &relay("b"), true);
620 assert!(!sets.same_as(&other));
621 }
622
623 #[test]
624 fn a_relay_list_is_written_with_each_relay_marked_for_what_it_is_for() {
625 let (both, out, into, new) = (relay("both"), relay("out"), relay("in"), relay("new"));
627 let tags = vec![
628 tag(&["r", both.as_str()]),
629 tag(&["r", out.as_str(), "write"]),
630 tag(&["r", into.as_str(), "read"]),
631 tag(&["client", "Amethyst"]),
632 ];
633 let earlier = a_list(Kind::RelayList, tags, "", 100);
634 assert_eq!(advertised(Some(&earlier)), (vec![both.clone(), out.clone()], vec![both.clone(), into.clone()]));
635 assert_eq!(advertised(None), (vec![], vec![]));
636
637 let keys = Keys::generate();
639 let now = Timestamp::from_secs(200);
640 let (outbox, inbox) = (vec![both.clone(), new.clone(), into.clone()], vec![both.clone(), into.clone()]);
641 let changed = advertised_list(Some(&earlier), &outbox, &inbox, now).unwrap().finalize(&keys).unwrap();
642 assert_eq!(
643 fields(&changed),
644 [vec!["client", "Amethyst"], vec!["r", both.as_str()], vec!["r", new.as_str(), "write"], vec!["r", into.as_str()],]
645 );
646 assert_eq!(changed.created_at, now);
647 assert_eq!(advertised(Some(&changed)), (outbox.clone(), inbox.clone()));
648
649 assert!(advertised_list(Some(&changed), &outbox, &inbox, now).is_none());
652 let reordered = vec![new.clone(), both.clone(), into.clone()];
653 let moved = advertised_list(Some(&changed), &reordered, &inbox, now).unwrap().finalize(&keys).unwrap();
654 assert_eq!(advertised(Some(&moved)).0, reordered);
655
656 let first = advertised_list(None, &[out.clone()], &[into.clone()], now).unwrap().finalize(&keys).unwrap();
658 assert_eq!(fields(&first), [vec!["r", out.as_str(), "write"], vec!["r", into.as_str(), "read"]]);
659 assert!(advertised_list(None, &[], &[], now).is_none(), "no relays and no list");
660 let ahead = a_list(Kind::RelayList, vec![tag(&["r", out.as_str()])], "", 500);
661 assert_eq!(advertised_list(Some(&ahead), &[], &[], now).unwrap().finalize(&keys).unwrap().created_at.as_secs(), 501);
662 }
663
664 #[test]
665 fn listed_relays_are_those_said_to_anyone_and_those_kept_private() {
666 let (open, kept, twice) = (relay("open"), relay("kept"), relay("twice"));
667 let list = a_list(Kind::SearchRelays, vec![tag(&["relay", open.as_str()]), tag(&["relay", twice.as_str()])], "x", 100);
668 let search = ListedRelays::new(Some(list.clone()), Kept::Read(private(&[&kept, &twice])));
669 assert_eq!(search.relays(), [open.clone(), twice.clone(), kept.clone()]);
670 assert_eq!(search.list(), Some(&list));
671 assert!(ListedRelays::default().relays().is_empty());
672 assert!(!format!("{search:?}").contains("kept"));
674
675 for unread in [Kept::Unread, Kept::Unreadable(SignError::Cipher("no".to_string()))] {
678 let closed = ListedRelays::new(Some(list.clone()), unread);
679 assert_eq!(closed.relays(), [open.clone(), twice.clone()]);
680 assert!(closed.changed(Section::Search, &[open.clone()]).is_none());
681 }
682
683 let lists = RelayLists { advertised: None, listed: [(Section::Search, search.clone())].into() };
684 assert_eq!(lists.sets().of(Section::Search), search.relays());
685 assert_eq!(lists.of(Section::Blocked), ListedRelays::default());
686 }
687
688 #[test]
689 fn a_listed_relay_stays_where_it_was_and_a_new_one_goes_where_the_list_keeps_them() {
690 let (open, kept, new) = (relay("open"), relay("kept"), relay("new"));
691 let other = vec!["t".to_string(), "nostr".to_string()];
692 let said = |tags: &[Tag]| -> Vec<Vec<String>> { tags.iter().map(|tag| tag.as_slice().to_vec()).collect() };
693
694 let list = a_list(Kind::SearchRelays, vec![tag(&["client", "Amethyst"]), tag(&["relay", open.as_str()])], "x", 100);
696 let mut kept_private = private(&[&kept]);
697 kept_private.push(other.clone());
698 let search = ListedRelays::new(Some(list), Kept::Read(kept_private));
699 assert!(search.changed(Section::Search, &[open.clone(), kept.clone()]).is_none(), "as it is");
700
701 let (tags, private_tags) = search.changed(Section::Search, &[open.clone(), kept.clone(), new.clone()]).unwrap();
702 assert_eq!(said(&tags), [vec!["client", "Amethyst"], vec!["relay", open.as_str()]]);
703 assert_eq!(private_tags, [other.clone(), private(&[&kept])[0].clone(), private(&[&new])[0].clone()]);
704 let (_, private_tags) = search.changed(Section::Search, &[new.clone(), open.clone(), kept.clone()]).unwrap();
706 assert_eq!(private_tags, [other.clone(), private(&[&new])[0].clone(), private(&[&kept])[0].clone()]);
707
708 let (tags, private_tags) = search.changed(Section::Search, &[open.clone()]).unwrap();
710 assert_eq!(tags.len(), 2);
711 assert_eq!(private_tags, [other]);
712
713 let public = a_list(Kind::SearchRelays, vec![tag(&["relay", open.as_str()])], "", 100);
715 let public = ListedRelays::new(Some(public), Kept::Read(vec![]));
716 let (tags, private_tags) = public.changed(Section::Search, &[open.clone(), new.clone()]).unwrap();
717 assert_eq!(tags.len(), 2);
718 assert!(private_tags.is_empty());
719
720 let empty = ListedRelays::new(Some(a_list(Kind::SearchRelays, vec![], "", 100)), Kept::Read(vec![]));
722 let (tags, private_tags) = empty.changed(Section::Search, &[new.clone()]).unwrap();
723 assert!(tags.is_empty());
724 assert_eq!(private_tags, private(&[&new]));
725 assert!(ListedRelays::default().changed(Section::Search, &[]).is_none());
726 }
727
728 #[test]
729 fn a_first_list_says_its_relays_or_keeps_them_as_its_kind_does() {
730 let new = relay("new");
731 let none = ListedRelays::default();
732 for section in [Section::Search, Section::Messages] {
734 let (tags, private_tags) = none.changed(section, &[new.clone()]).unwrap();
735 assert_eq!(tags, [tag(&["relay", new.as_str()])], "{section:?}");
736 assert!(private_tags.is_empty());
737 }
738 for section in [Section::Indexer, Section::Trusted, Section::Blocked] {
740 let (tags, private_tags) = none.changed(section, &[new.clone()]).unwrap();
741 assert!(tags.is_empty(), "{section:?}");
742 assert_eq!(private_tags, private(&[&new]));
743 }
744 let empty = ListedRelays::new(Some(a_list(Kind::InboxRelays, vec![], "", 100)), Kept::Read(vec![]));
746 let (tags, private_tags) = empty.changed(Section::Messages, &[new.clone()]).unwrap();
747 assert_eq!(tags.len(), 1);
748 assert!(private_tags.is_empty());
749
750 assert_eq!(Section::Blocked.kind().as_u16(), 10006);
751 assert_eq!(Section::Search.kind().as_u16(), 10007);
752 assert!(Section::ALL.iter().all(|section| section.kind().as_u16() != 10013));
754 assert_eq!(Section::Messages.kind().as_u16(), 10050);
755 assert_eq!(Section::Indexer.kind().as_u16(), 10086);
756 assert_eq!(Section::Trusted.kind().as_u16(), 10089);
757 let ahead = a_list(Kind::SearchRelays, vec![], "", 500);
758 let written = listed(Section::Blocked, Some(&ahead), vec![], String::new(), Timestamp::from_secs(200));
759 let written = written.finalize(&Keys::generate()).unwrap();
760 assert_eq!((written.kind.as_u16(), written.created_at.as_secs()), (10006, 501));
761 }
762}