Skip to main content

vector_core/profile/
mod.rs

1//! Profile types and sync — compact internal representation + relay fetching.
2//!
3//! The `id` field is a u16 interner handle — the canonical npub string lives
4//! in `NpubInterner` (single source of truth). Use `SlimProfile` at
5//! serialization boundaries (frontend, DB).
6//!
7//! The `sync` submodule has the priority queue, background processor,
8//! and `load_profile` relay fetch logic.
9
10pub mod sync;
11
12pub use sync::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
13
14use nostr_sdk::prelude::Metadata;
15
16use crate::compact::NO_NPUB;
17
18// ============================================================================
19// ProfileFlags — 4 bools packed into 1 byte
20// ============================================================================
21
22/// Kind-0 content key by which a user consents to being shown on someone's stream.
23pub const STREAM_CONSENT_KEY: &str = "stream_consent";
24
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26pub struct ProfileFlags(u8);
27
28impl ProfileFlags {
29    const MINE:           u8 = 0b0001;
30    const BLOCKED:        u8 = 0b0010;
31    const BOT:            u8 = 0b0100;
32    const STREAM_CONSENT: u8 = 0b1000;
33
34    #[inline] pub fn is_mine(self) -> bool    { self.0 & Self::MINE != 0 }
35    #[inline] pub fn is_blocked(self) -> bool  { self.0 & Self::BLOCKED != 0 }
36    #[inline] pub fn is_bot(self) -> bool      { self.0 & Self::BOT != 0 }
37    #[inline] pub fn is_stream_consent(self) -> bool { self.0 & Self::STREAM_CONSENT != 0 }
38
39    #[inline] pub fn set_mine(&mut self, v: bool)    { if v { self.0 |= Self::MINE } else { self.0 &= !Self::MINE } }
40    #[inline] pub fn set_blocked(&mut self, v: bool)  { if v { self.0 |= Self::BLOCKED } else { self.0 &= !Self::BLOCKED } }
41    #[inline] pub fn set_bot(&mut self, v: bool)      { if v { self.0 |= Self::BOT } else { self.0 &= !Self::BOT } }
42    #[inline] pub fn set_stream_consent(&mut self, v: bool) { if v { self.0 |= Self::STREAM_CONSENT } else { self.0 &= !Self::STREAM_CONSENT } }
43}
44
45/// Whether a kind-0's content opts in to streams: `true` or the string `"true"`.
46pub fn metadata_stream_consent(meta: &Metadata) -> bool {
47    meta.custom.get(STREAM_CONSENT_KEY).is_some_and(|v| match v.as_bool() {
48        Some(b) => b,
49        None => v.as_str().is_some_and(|s| s.eq_ignore_ascii_case("true")),
50    })
51}
52
53/// `meta` with the consent key set when `on`, and absent otherwise.
54pub fn with_stream_consent(mut meta: Metadata, on: bool) -> Metadata {
55    meta.custom.remove(STREAM_CONSENT_KEY);
56    if on {
57        meta.custom.insert(STREAM_CONSENT_KEY.to_string(), serde_json::Value::Bool(true));
58    }
59    meta
60}
61
62// ============================================================================
63// Profile — compact internal representation
64// ============================================================================
65
66const NAME: usize = 0;
67const DISPLAY_NAME: usize = 1;
68const BANNER: usize = 2;
69const AVATAR: usize = 3;
70const ABOUT: usize = 4;
71const AVATAR_CACHED: usize = 5;
72const BANNER_CACHED: usize = 6;
73const NICKNAME: usize = 7;
74const LUD06: usize = 8;
75const LUD16: usize = 9;
76const NIP05: usize = 10;
77const WEBSITE: usize = 11;
78const STATUS_TITLE: usize = 12;
79const STATUS_PURPOSE: usize = 13;
80const STATUS_URL: usize = 14;
81const FIELDS: usize = 15;
82
83const WIDE: u16 = 1 << 15;
84const FIELD_BITS: u16 = WIDE - 1;
85const HEADER: usize = 4;
86
87/// Every string of a profile in one heap block; `None` when all of them are empty.
88///
89/// `[mask u16][emoji count u16][end offset × slots][utf8]`: mask bit `i` marks field `i`
90/// present, bit 15 widens the offsets from u16 to u32. The slots are the present fields in
91/// field order, then each status emoji tag's shortcode and url; an offset is a slot's end.
92#[derive(Clone, Default, PartialEq, Eq)]
93struct ProfileText(Option<Box<[u8]>>);
94
95impl ProfileText {
96    fn build(fields: &[&str; FIELDS], emoji: &[(&str, &str)]) -> Self {
97        let emoji = &emoji[..emoji.len().min(u16::MAX as usize)];
98        let mut mask = 0u16;
99        for (i, f) in fields.iter().enumerate() {
100            if !f.is_empty() {
101                mask |= 1 << i;
102            }
103        }
104        if mask == 0 && emoji.is_empty() {
105            return Self(None);
106        }
107        let slots = || fields.iter().copied().filter(|f| !f.is_empty()).chain(emoji.iter().flat_map(|&(s, u)| [s, u]));
108        let count = mask.count_ones() as usize + 2 * emoji.len();
109        let total: usize = slots().map(str::len).sum();
110        assert!(total <= u32::MAX as usize, "profile text over 4 GiB");
111        let wide = total > u16::MAX as usize;
112        let width = if wide { 4 } else { 2 };
113
114        let mut out = Vec::with_capacity(HEADER + width * count + total);
115        out.extend_from_slice(&(mask | if wide { WIDE } else { 0 }).to_le_bytes());
116        out.extend_from_slice(&(emoji.len() as u16).to_le_bytes());
117        let mut end = 0;
118        for s in slots() {
119            end += s.len();
120            if wide {
121                out.extend_from_slice(&(end as u32).to_le_bytes());
122            } else {
123                out.extend_from_slice(&(end as u16).to_le_bytes());
124            }
125        }
126        for s in slots() {
127            out.extend_from_slice(s.as_bytes());
128        }
129        Self(Some(out.into_boxed_slice()))
130    }
131
132    #[inline]
133    fn get(&self, field: usize) -> &str {
134        let Some(b) = self.0.as_deref() else { return "" };
135        let mask = u16::from_le_bytes([b[0], b[1]]);
136        let bit = 1u16 << field;
137        if mask & bit == 0 {
138            return "";
139        }
140        Self::slot(b, (mask & FIELD_BITS & (bit - 1)).count_ones() as usize)
141    }
142
143    #[inline]
144    fn slot(b: &[u8], k: usize) -> &str {
145        let mask = u16::from_le_bytes([b[0], b[1]]);
146        let count = (mask & FIELD_BITS).count_ones() as usize + 2 * u16::from_le_bytes([b[2], b[3]]) as usize;
147        let width = if mask & WIDE != 0 { 4 } else { 2 };
148        let end = |j: usize| {
149            let at = HEADER + width * j;
150            if width == 4 {
151                u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) as usize
152            } else {
153                u16::from_le_bytes([b[at], b[at + 1]]) as usize
154            }
155        };
156        let data = HEADER + width * count;
157        let start = if k == 0 { 0 } else { end(k - 1) };
158        let bytes = &b[data + start..data + end(k)];
159        debug_assert!(std::str::from_utf8(bytes).is_ok(), "profile slot {k} split a character");
160        // SAFETY: `build` copied every slot whole from a `&str`, and a block is never written after.
161        unsafe { std::str::from_utf8_unchecked(bytes) }
162    }
163
164    fn fields(&self) -> [&str; FIELDS] {
165        std::array::from_fn(|i| self.get(i))
166    }
167
168    fn emoji(&self) -> impl ExactSizeIterator<Item = (&str, &str)> + '_ {
169        let (b, first, n) = match self.0.as_deref() {
170            Some(b) => (
171                b,
172                (u16::from_le_bytes([b[0], b[1]]) & FIELD_BITS).count_ones() as usize,
173                u16::from_le_bytes([b[2], b[3]]) as usize,
174            ),
175            None => (&[][..], 0, 0),
176        };
177        (0..n).map(move |j| (Self::slot(b, first + 2 * j), Self::slot(b, first + 2 * j + 1)))
178    }
179
180    fn heap_bytes(&self) -> usize {
181        self.0.as_ref().map_or(0, |b| b.len())
182    }
183}
184
185const AVATAR_IN_CACHE: u8 = 1;
186const BANNER_IN_CACHE: u8 = 2;
187
188/// `{app_data}/cache/avatars` and `…/banners`, spelled as the image cache spells its paths.
189fn image_cache_dirs() -> Option<&'static [String; 2]> {
190    static DIRS: std::sync::OnceLock<[String; 2]> = std::sync::OnceLock::new();
191    if let Some(dirs) = DIRS.get() {
192        return Some(dirs);
193    }
194    let app = crate::db::get_app_data_dir().ok()?;
195    Some(DIRS.get_or_init(|| ["avatars", "banners"].map(|sub| app.join("cache").join(sub).to_string_lossy().into_owned())))
196}
197
198/// `path`'s file name when the path is exactly `dir`, one separator, then that name.
199fn cached_file_name<'a>(path: &'a str, dir: &str) -> Option<&'a str> {
200    let name = path.strip_prefix(dir)?.strip_prefix(std::path::MAIN_SEPARATOR)?;
201    (!name.is_empty() && !name.contains(['/', std::path::MAIN_SEPARATOR])).then_some(name)
202}
203
204fn expand_cached(name: &str, dir: &str) -> String {
205    let mut path = String::with_capacity(dir.len() + 1 + name.len());
206    path.push_str(dir);
207    path.push(std::path::MAIN_SEPARATOR);
208    path.push_str(name);
209    path
210}
211
212/// What a cached path is stored as (`kind` 0 = avatar, 1 = banner), and whether it was shortened.
213fn store_cached(path: &str, kind: usize) -> (&str, bool) {
214    match image_cache_dirs().and_then(|dirs| cached_file_name(path, &dirs[kind])) {
215        Some(name) => (name, true),
216        None => (path, false),
217    }
218}
219
220/// Internal profile: a u16 interner handle, flags, and every string in one packed block.
221///
222/// A cached image path inside the image cache dir is held as its file name and rebuilt
223/// on read, so [`SlimProfile`] and the DB still see the full path.
224#[derive(Clone)]
225pub struct Profile {
226    pub id: u16,
227    pub flags: ProfileFlags,
228    in_cache: u8,
229    pub last_updated: u32,
230    text: ProfileText,
231}
232
233impl Default for Profile {
234    fn default() -> Self {
235        Self::new()
236    }
237}
238
239impl PartialEq for Profile {
240    fn eq(&self, other: &Self) -> bool {
241        self.id == other.id
242            && self.last_updated == other.last_updated
243            && self.flags == other.flags
244            && if self.in_cache == other.in_cache {
245                self.text == other.text
246            } else {
247                (0..FIELDS).all(|i| i == AVATAR_CACHED || i == BANNER_CACHED || self.text.get(i) == other.text.get(i))
248                    && self.avatar_cached() == other.avatar_cached()
249                    && self.banner_cached() == other.banner_cached()
250                    && self.text.emoji().eq(other.text.emoji())
251            }
252    }
253}
254
255impl std::fmt::Debug for Profile {
256    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257        f.debug_struct("Profile")
258            .field("id", &self.id)
259            .field("name", &self.name())
260            .field("display_name", &self.display_name())
261            .field("nickname", &self.nickname())
262            .field("about", &self.about())
263            .field("avatar", &self.avatar())
264            .field("banner", &self.banner())
265            .field("avatar_cached", &self.avatar_cached())
266            .field("banner_cached", &self.banner_cached())
267            .field("lud06", &self.lud06())
268            .field("lud16", &self.lud16())
269            .field("nip05", &self.nip05())
270            .field("website", &self.website())
271            .field("status_title", &self.status_title())
272            .field("status_purpose", &self.status_purpose())
273            .field("status_url", &self.status_url())
274            .field("status_emoji_tags", &self.text.emoji().collect::<Vec<_>>())
275            .field("last_updated", &self.last_updated)
276            .field("flags", &self.flags)
277            .finish()
278    }
279}
280
281/// A profile picture held on disk: the URL it was fetched from and the file holding it.
282#[derive(Debug, Clone, PartialEq)]
283pub struct CachedImage {
284    pub url: String,
285    pub path: String,
286    /// The banner rather than the avatar.
287    pub banner: bool,
288}
289
290impl Profile {
291    pub fn new() -> Self {
292        Self { id: NO_NPUB, flags: ProfileFlags::default(), in_cache: 0, last_updated: 0, text: ProfileText(None) }
293    }
294
295    #[inline] pub fn name(&self) -> &str { self.text.get(NAME) }
296    #[inline] pub fn display_name(&self) -> &str { self.text.get(DISPLAY_NAME) }
297    #[inline] pub fn banner(&self) -> &str { self.text.get(BANNER) }
298    #[inline] pub fn avatar(&self) -> &str { self.text.get(AVATAR) }
299    #[inline] pub fn about(&self) -> &str { self.text.get(ABOUT) }
300    #[inline] pub fn nickname(&self) -> &str { self.text.get(NICKNAME) }
301    #[inline] pub fn lud06(&self) -> &str { self.text.get(LUD06) }
302    #[inline] pub fn lud16(&self) -> &str { self.text.get(LUD16) }
303    #[inline] pub fn nip05(&self) -> &str { self.text.get(NIP05) }
304    #[inline] pub fn website(&self) -> &str { self.text.get(WEBSITE) }
305    #[inline] pub fn status_title(&self) -> &str { self.text.get(STATUS_TITLE) }
306    #[inline] pub fn status_purpose(&self) -> &str { self.text.get(STATUS_PURPOSE) }
307    #[inline] pub fn status_url(&self) -> &str { self.text.get(STATUS_URL) }
308
309    /// NIP-30 tags from the status event, so `:shortcode:` in it renders.
310    pub fn status_emoji_tags(&self) -> Vec<crate::types::EmojiTag> {
311        self.text.emoji().map(|(s, u)| crate::types::EmojiTag { shortcode: s.to_string(), url: u.to_string() }).collect()
312    }
313
314    pub fn avatar_cached(&self) -> std::borrow::Cow<'_, str> { self.cached(AVATAR_CACHED, AVATAR_IN_CACHE, 0) }
315    pub fn banner_cached(&self) -> std::borrow::Cow<'_, str> { self.cached(BANNER_CACHED, BANNER_IN_CACHE, 1) }
316    #[inline] pub fn has_avatar_cached(&self) -> bool { !self.text.get(AVATAR_CACHED).is_empty() }
317    #[inline] pub fn has_banner_cached(&self) -> bool { !self.text.get(BANNER_CACHED).is_empty() }
318
319    fn cached(&self, field: usize, bit: u8, kind: usize) -> std::borrow::Cow<'_, str> {
320        let stored = self.text.get(field);
321        match image_cache_dirs() {
322            Some(dirs) if self.in_cache & bit != 0 && !stored.is_empty() => expand_cached(stored, &dirs[kind]).into(),
323            _ => stored.into(),
324        }
325    }
326
327    pub fn set_name(&mut self, v: &str) { self.write(&[(NAME, v)], None); }
328    pub fn set_display_name(&mut self, v: &str) { self.write(&[(DISPLAY_NAME, v)], None); }
329    pub fn set_banner(&mut self, v: &str) { self.write(&[(BANNER, v)], None); }
330    pub fn set_avatar(&mut self, v: &str) { self.write(&[(AVATAR, v)], None); }
331    pub fn set_about(&mut self, v: &str) { self.write(&[(ABOUT, v)], None); }
332    pub fn set_nickname(&mut self, v: &str) { self.write(&[(NICKNAME, v)], None); }
333    pub fn set_lud06(&mut self, v: &str) { self.write(&[(LUD06, v)], None); }
334    pub fn set_lud16(&mut self, v: &str) { self.write(&[(LUD16, v)], None); }
335    pub fn set_nip05(&mut self, v: &str) { self.write(&[(NIP05, v)], None); }
336    pub fn set_website(&mut self, v: &str) { self.write(&[(WEBSITE, v)], None); }
337    pub fn set_status_title(&mut self, v: &str) { self.write(&[(STATUS_TITLE, v)], None); }
338    pub fn set_status_purpose(&mut self, v: &str) { self.write(&[(STATUS_PURPOSE, v)], None); }
339    pub fn set_status_url(&mut self, v: &str) { self.write(&[(STATUS_URL, v)], None); }
340    pub fn set_status_emoji_tags(&mut self, tags: &[crate::types::EmojiTag]) { self.write(&[], Some(tags)); }
341
342    /// Every status part in one rebuild.
343    pub fn set_status(&mut self, title: &str, purpose: &str, url: &str, tags: &[crate::types::EmojiTag]) {
344        self.write(&[(STATUS_TITLE, title), (STATUS_PURPOSE, purpose), (STATUS_URL, url)], Some(tags));
345    }
346
347    /// Drop the avatar and banner, URLs and cached copies alike; returns the copies to delete.
348    pub fn forget_imagery(&mut self) -> Vec<CachedImage> {
349        let images = [
350            (self.avatar(), self.avatar_cached(), false),
351            (self.banner(), self.banner_cached(), true),
352        ]
353        .into_iter()
354        .filter(|(_, path, _)| !path.is_empty())
355        .map(|(url, path, banner)| CachedImage { url: url.to_string(), path: path.into_owned(), banner })
356        .collect();
357        self.write(&[(AVATAR, ""), (BANNER, ""), (AVATAR_CACHED, ""), (BANNER_CACHED, "")], None);
358        images
359    }
360
361    #[inline] pub fn has_imagery(&self) -> bool {
362        !self.avatar().is_empty() || !self.banner().is_empty() || self.has_avatar_cached() || self.has_banner_cached()
363    }
364
365    pub fn set_avatar_cached(&mut self, path: &str) { self.set_cached(AVATAR_CACHED, AVATAR_IN_CACHE, 0, path); }
366    pub fn set_banner_cached(&mut self, path: &str) { self.set_cached(BANNER_CACHED, BANNER_IN_CACHE, 1, path); }
367
368    fn set_cached(&mut self, field: usize, bit: u8, kind: usize, path: &str) {
369        let (stored, short) = store_cached(path, kind);
370        self.write(&[(field, stored)], None);
371        if short { self.in_cache |= bit } else { self.in_cache &= !bit }
372    }
373
374    /// Rebuild the block with `updates` (and `tags`, when given) applied; nothing when none differ.
375    fn write(&mut self, updates: &[(usize, &str)], tags: Option<&[crate::types::EmojiTag]>) -> bool {
376        fn pair(t: &crate::types::EmojiTag) -> (&str, &str) {
377            (t.shortcode.as_str(), t.url.as_str())
378        }
379        let mut fields = self.text.fields();
380        let mut changed = false;
381        for &(i, v) in updates {
382            if fields[i] != v {
383                fields[i] = v;
384                changed = true;
385            }
386        }
387        changed |= tags.is_some_and(|t| !self.text.emoji().eq(t.iter().map(pair)));
388        if !changed {
389            return false;
390        }
391        let emoji: Vec<(&str, &str)> = match tags {
392            Some(t) => t.iter().map(pair).collect(),
393            None => self.text.emoji().collect(),
394        };
395        let cleared = if fields[AVATAR_CACHED].is_empty() { AVATAR_IN_CACHE } else { 0 }
396            | if fields[BANNER_CACHED].is_empty() { BANNER_IN_CACHE } else { 0 };
397        self.text = ProfileText::build(&fields, &emoji);
398        self.in_cache &= !cleared;
399        true
400    }
401
402    /// Heap bytes held by the packed strings.
403    pub fn heap_bytes(&self) -> usize {
404        self.text.heap_bytes()
405    }
406
407    /// Merge Nostr Metadata into this Profile. Returns `true` if any fields changed.
408    pub fn from_metadata(&mut self, meta: Metadata) -> bool {
409        // Absence revokes: every caller passes a whole kind-0, so a missing key is an opt-out.
410        let consent = metadata_stream_consent(&meta);
411
412        let mut fields = self.text.fields();
413        let mut in_cache = self.in_cache;
414        let mut changed = false;
415        // A blocked profile takes no pictures: nothing of theirs is fetched, cached or shown.
416        let blocked = self.flags.is_blocked();
417        for (i, value) in [
418            (NAME, &meta.name),
419            (DISPLAY_NAME, &meta.display_name),
420            (LUD06, &meta.lud06),
421            (LUD16, &meta.lud16),
422            (BANNER, &meta.banner),
423            (AVATAR, &meta.picture),
424            (ABOUT, &meta.about),
425            (WEBSITE, &meta.website),
426            (NIP05, &meta.nip05),
427        ] {
428            // A picture the kind-0 no longer names was removed; other fields keep their last value.
429            let value = match value.as_deref() {
430                Some(value) => value,
431                None if i == AVATAR || i == BANNER => "",
432                None => continue,
433            };
434            if blocked && (i == AVATAR || i == BANNER) {
435                continue;
436            }
437            if fields[i] == value {
438                continue;
439            }
440            fields[i] = value;
441            changed = true;
442            // A new image URL invalidates the file cached for the old one.
443            if i == BANNER {
444                fields[BANNER_CACHED] = "";
445                in_cache &= !BANNER_IN_CACHE;
446            } else if i == AVATAR {
447                fields[AVATAR_CACHED] = "";
448                in_cache &= !AVATAR_IN_CACHE;
449            }
450        }
451        if changed {
452            let emoji: Vec<(&str, &str)> = self.text.emoji().collect();
453            self.text = ProfileText::build(&fields, &emoji);
454            self.in_cache = in_cache;
455        }
456
457        if let Some(custom) = meta.custom.get("bot") {
458            let bot_value = match custom.as_bool() {
459                Some(b) => b,
460                None => custom.as_str().map(|s| s.to_lowercase() == "true").unwrap_or(false),
461            };
462            if self.flags.is_bot() != bot_value {
463                self.flags.set_bot(bot_value);
464                changed = true;
465            }
466        }
467        if self.flags.is_stream_consent() != consent {
468            self.flags.set_stream_consent(consent);
469            changed = true;
470        }
471
472        changed
473    }
474}
475
476// ============================================================================
477// SlimProfile — serialization boundary (frontend, DB)
478// ============================================================================
479
480/// Profile with npub string instead of interner handle. Used for:
481/// - Sending to frontend (JSON serializable)
482/// - Persisting to database
483/// - IPC between processes
484#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Default)]
485pub struct SlimProfile {
486    pub id: String,
487    pub name: String,
488    pub display_name: String,
489    pub nickname: String,
490    pub lud06: String,
491    pub lud16: String,
492    pub banner: String,
493    pub avatar: String,
494    pub about: String,
495    pub website: String,
496    pub nip05: String,
497    pub status: Status,
498    pub last_updated: u64,
499    pub mine: bool,
500    pub bot: bool,
501    pub is_blocked: bool,
502    pub avatar_cached: String,
503    pub banner_cached: String,
504    #[serde(default)]
505    pub stream_consent: bool,
506}
507
508impl SlimProfile {
509    /// Convert from internal Profile, resolving interner handle to npub.
510    pub fn from_profile(profile: &Profile, interner: &crate::compact::NpubInterner) -> Self {
511        Self {
512            id: interner.resolve(profile.id).unwrap_or("").to_string(),
513            name: profile.name().to_string(),
514            display_name: profile.display_name().to_string(),
515            nickname: profile.nickname().to_string(),
516            lud06: profile.lud06().to_string(),
517            lud16: profile.lud16().to_string(),
518            banner: profile.banner().to_string(),
519            avatar: profile.avatar().to_string(),
520            about: profile.about().to_string(),
521            website: profile.website().to_string(),
522            nip05: profile.nip05().to_string(),
523            status: Status {
524                title: profile.status_title().to_string(),
525                purpose: profile.status_purpose().to_string(),
526                url: profile.status_url().to_string(),
527                emoji_tags: profile.status_emoji_tags(),
528            },
529            last_updated: crate::compact::secs_from_compact(profile.last_updated),
530            mine: profile.flags.is_mine(),
531            bot: profile.flags.is_bot(),
532            is_blocked: profile.flags.is_blocked(),
533            avatar_cached: profile.avatar_cached().into_owned(),
534            banner_cached: profile.banner_cached().into_owned(),
535            stream_consent: profile.flags.is_stream_consent(),
536        }
537    }
538
539    /// Convert to internal Profile (for loading from DB).
540    pub fn to_profile(&self) -> Profile {
541        let (avatar_cached, avatar_short) = store_cached(&self.avatar_cached, 0);
542        let (banner_cached, banner_short) = store_cached(&self.banner_cached, 1);
543        let mut fields = [""; FIELDS];
544        fields[NAME] = &self.name;
545        fields[DISPLAY_NAME] = &self.display_name;
546        fields[BANNER] = &self.banner;
547        fields[AVATAR] = &self.avatar;
548        fields[ABOUT] = &self.about;
549        fields[AVATAR_CACHED] = avatar_cached;
550        fields[BANNER_CACHED] = banner_cached;
551        fields[NICKNAME] = &self.nickname;
552        fields[LUD06] = &self.lud06;
553        fields[LUD16] = &self.lud16;
554        fields[NIP05] = &self.nip05;
555        fields[WEBSITE] = &self.website;
556        fields[STATUS_TITLE] = &self.status.title;
557        fields[STATUS_PURPOSE] = &self.status.purpose;
558        fields[STATUS_URL] = &self.status.url;
559        let emoji: Vec<(&str, &str)> =
560            self.status.emoji_tags.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
561
562        let mut flags = ProfileFlags::default();
563        flags.set_mine(self.mine);
564        flags.set_bot(self.bot);
565        flags.set_blocked(self.is_blocked);
566        flags.set_stream_consent(self.stream_consent);
567        Profile {
568            id: NO_NPUB,
569            flags,
570            in_cache: if avatar_short { AVATAR_IN_CACHE } else { 0 } | if banner_short { BANNER_IN_CACHE } else { 0 },
571            last_updated: crate::compact::secs_to_compact(self.last_updated),
572            text: ProfileText::build(&fields, &emoji),
573        }
574    }
575}
576
577#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
578pub struct Status {
579    pub title: String,
580    pub purpose: String,
581    pub url: String,
582    /// NIP-30 tags from the status event; absent in DB rows (memory-only).
583    #[serde(default)]
584    pub emoji_tags: Vec<crate::types::EmojiTag>,
585}
586
587impl Status {
588    pub fn new() -> Self {
589        Self { title: String::new(), purpose: String::new(), url: String::new(), emoji_tags: Vec::new() }
590    }
591}
592
593impl Default for Status {
594    fn default() -> Self {
595        Self::new()
596    }
597}
598
599// ============================================================================
600// Npub keys
601// ============================================================================
602
603/// The 32 key bytes of a canonical npub: lowercase, `npub1`, valid bech32 checksum, zero padding.
604///
605/// Exactly one string decodes to each key, so a map keyed by it never merges two npubs.
606pub(crate) fn npub_bytes(npub: &str) -> Option<[u8; 32]> {
607    let s = npub.as_bytes();
608    if s.len() != 63 || !s.starts_with(b"npub1") {
609        return None;
610    }
611    let mut chk = NPUB_HRP_CHECKSUM;
612    let mut out = [0u8; 32];
613    let (mut acc, mut bits, mut n) = (0u32, 0u32, 0usize);
614    for (i, &c) in s[5..].iter().enumerate() {
615        let v = bech32_value(c)?;
616        chk = bech32_step(chk, v);
617        if i < 52 {
618            acc = (acc << 5) | v as u32;
619            bits += 5;
620            if bits >= 8 {
621                bits -= 8;
622                out[n] = (acc >> bits) as u8;
623                n += 1;
624                acc &= (1 << bits) - 1;
625            }
626        }
627    }
628    (chk == 1 && bits == 4 && acc == 0).then_some(out)
629}
630
631const BECH32_CHARSET: &[u8; 32] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
632
633const BECH32_VALUES: [u8; 128] = {
634    let mut table = [u8::MAX; 128];
635    let mut i = 0;
636    while i < 32 {
637        table[BECH32_CHARSET[i] as usize] = i as u8;
638        i += 1;
639    }
640    table
641};
642
643/// The BCH generator terms XORed in for each value of the checksum's top five bits.
644const BECH32_GEN: [u32; 32] = {
645    const GEN: [u32; 5] = [0x3b6a_57b2, 0x2650_8e6d, 0x1ea1_19fa, 0x3d42_33dd, 0x2a14_62b3];
646    let mut table = [0u32; 32];
647    let mut top = 0;
648    while top < 32 {
649        let mut i = 0;
650        while i < 5 {
651            if (top >> i) & 1 == 1 {
652                table[top] ^= GEN[i];
653            }
654            i += 1;
655        }
656        top += 1;
657    }
658    table
659};
660
661const fn bech32_step(chk: u32, v: u8) -> u32 {
662    ((chk & 0x01ff_ffff) << 5) ^ v as u32 ^ BECH32_GEN[(chk >> 25) as usize]
663}
664
665/// A lowercase bech32 character's 5-bit value.
666fn bech32_value(c: u8) -> Option<u8> {
667    BECH32_VALUES.get(c as usize).copied().filter(|&v| v != u8::MAX)
668}
669
670/// The checksum state after the expanded `npub` prefix.
671const NPUB_HRP_CHECKSUM: u32 = {
672    let hrp = b"npub";
673    let mut chk = 1;
674    let mut i = 0;
675    while i < hrp.len() {
676        chk = bech32_step(chk, hrp[i] >> 5);
677        i += 1;
678    }
679    chk = bech32_step(chk, 0);
680    i = 0;
681    while i < hrp.len() {
682        chk = bech32_step(chk, hrp[i] & 31);
683        i += 1;
684    }
685    chk
686};
687
688/// A map keyed by npub, holding a canonical npub as its 32 key bytes and anything else as given.
689#[derive(Debug)]
690pub(crate) struct NpubMap<V> {
691    keys: std::collections::HashMap<[u8; 32], V>,
692    other: std::collections::HashMap<Box<str>, V>,
693}
694
695impl<V> Default for NpubMap<V> {
696    fn default() -> Self {
697        Self { keys: Default::default(), other: Default::default() }
698    }
699}
700
701impl<V> NpubMap<V> {
702    pub(crate) fn get(&self, npub: &str) -> Option<&V> {
703        match npub_bytes(npub) {
704            Some(key) => self.keys.get(&key),
705            None => self.other.get(npub),
706        }
707    }
708
709    #[cfg(test)]
710    pub(crate) fn contains(&self, npub: &str) -> bool {
711        self.get(npub).is_some()
712    }
713
714    pub(crate) fn insert(&mut self, npub: &str, value: V) {
715        match npub_bytes(npub) {
716            Some(key) => {
717                self.keys.insert(key, value);
718            }
719            None => {
720                self.other.insert(npub.into(), value);
721            }
722        }
723    }
724
725    pub(crate) fn retain(&mut self, mut keep: impl FnMut(&V) -> bool) {
726        self.keys.retain(|_, v| keep(v));
727        self.other.retain(|_, v| keep(v));
728    }
729
730    pub(crate) fn clear(&mut self) {
731        self.keys.clear();
732        self.other.clear();
733    }
734
735    #[cfg(test)]
736    pub(crate) fn len(&self) -> usize {
737        self.keys.len() + self.other.len()
738    }
739}
740
741#[cfg(test)]
742mod stream_consent_tests {
743    use super::*;
744
745    fn kind0(json: &str) -> Metadata {
746        Metadata::from_json(json).unwrap()
747    }
748
749    #[test]
750    fn a_kind0_opts_in_with_a_bool_or_a_true_string() {
751        for json in [r#"{"name":"a","stream_consent":true}"#, r#"{"name":"a","stream_consent":"true"}"#, r#"{"stream_consent":"TRUE"}"#] {
752            let mut p = Profile::new();
753            assert!(p.from_metadata(kind0(json)), "{json} changes the profile");
754            assert!(p.flags.is_stream_consent(), "{json} opts in");
755        }
756        for json in [r#"{"name":"a","stream_consent":false}"#, r#"{"stream_consent":"yes"}"#, r#"{"stream_consent":1}"#, r#"{"name":"a"}"#] {
757            let mut p = Profile::new();
758            p.from_metadata(kind0(json));
759            assert!(!p.flags.is_stream_consent(), "{json} does not opt in");
760        }
761    }
762
763    #[test]
764    fn a_newer_kind0_without_the_key_revokes_consent() {
765        let mut p = Profile::new();
766        p.flags.set_bot(true);
767        p.from_metadata(kind0(r#"{"name":"a","stream_consent":true}"#));
768        assert!(p.flags.is_stream_consent());
769
770        assert!(p.from_metadata(kind0(r#"{"name":"a"}"#)), "dropping the key is a change");
771        assert!(!p.flags.is_stream_consent(), "absence means no consent");
772        assert!(p.flags.is_bot(), "the other flags are untouched");
773
774        assert!(!p.from_metadata(kind0(r#"{"name":"a"}"#)), "an unchanged kind-0 is no change");
775    }
776
777    #[test]
778    fn the_consent_bit_is_independent_of_the_others() {
779        let mut f = ProfileFlags::default();
780        f.set_mine(true);
781        f.set_blocked(true);
782        f.set_bot(true);
783        assert!(!f.is_stream_consent());
784        f.set_stream_consent(true);
785        assert!(f.is_mine() && f.is_blocked() && f.is_bot() && f.is_stream_consent());
786        f.set_stream_consent(false);
787        assert!(f.is_mine() && f.is_blocked() && f.is_bot() && !f.is_stream_consent());
788    }
789
790    #[test]
791    fn with_stream_consent_sets_or_omits_the_key_and_keeps_the_rest() {
792        let meta = kind0(r#"{"name":"a","pronouns":"they","stream_consent":"true"}"#);
793        let on = with_stream_consent(meta.clone(), true);
794        assert_eq!(on.custom.get(STREAM_CONSENT_KEY), Some(&serde_json::Value::Bool(true)));
795        assert_eq!(on.custom.get("pronouns").and_then(|v| v.as_str()), Some("they"));
796
797        let off = with_stream_consent(meta, false);
798        let json = off.as_json();
799        assert!(!json.contains(STREAM_CONSENT_KEY), "off publishes no key at all: {json}");
800        assert!(json.contains("pronouns") && off.name.as_deref() == Some("a"));
801    }
802
803    #[test]
804    fn slim_profile_round_trips_consent() {
805        let mut interner = crate::compact::NpubInterner::new();
806        let mut p = Profile::new();
807        p.id = interner.intern("npub1consent");
808        p.flags.set_stream_consent(true);
809
810        let slim = SlimProfile::from_profile(&p, &interner);
811        assert!(slim.stream_consent);
812        assert!(slim.to_profile().flags.is_stream_consent());
813
814        let wire = serde_json::to_value(&slim).unwrap();
815        assert_eq!(wire["stream_consent"], serde_json::Value::Bool(true));
816        let back: SlimProfile = serde_json::from_value(wire.clone()).unwrap();
817        assert_eq!(back, slim);
818
819        let mut legacy = wire;
820        legacy.as_object_mut().unwrap().remove("stream_consent");
821        let old: SlimProfile = serde_json::from_value(legacy).unwrap();
822        assert!(!old.stream_consent, "a payload without the field reads as no consent");
823    }
824}
825
826#[cfg(test)]
827mod packed_tests {
828    use super::*;
829    use crate::types::EmojiTag;
830
831    fn tag(s: &str, u: &str) -> EmojiTag {
832        EmojiTag { shortcode: s.into(), url: u.into() }
833    }
834
835    /// Every string field distinct, so a slot read from the wrong offset shows.
836    fn full_slim(about: String) -> SlimProfile {
837        SlimProfile {
838            id: "npub1packed".into(),
839            name: "alice".into(),
840            display_name: "Alice 🐈 Wonderland".into(),
841            nickname: "ally".into(),
842            lud06: "lnurl1dp68gurn8ghj7".into(),
843            lud16: "alice@getalby.com".into(),
844            banner: "https://image.nostr.build/banner.png".into(),
845            avatar: "https://image.nostr.build/avatar.jpg".into(),
846            about,
847            website: "https://alice.example".into(),
848            nip05: "alice@nostrplebs.com".into(),
849            status: Status {
850                title: "Listening to :cat: 猫".into(),
851                purpose: "general".into(),
852                url: "https://status.example/now".into(),
853                emoji_tags: vec![tag("cat", "https://e.example/cat.png"), tag("", ""), tag("dog", "https://e.example/dog.gif")],
854            },
855            last_updated: 1_790_000_123,
856            mine: true,
857            bot: false,
858            is_blocked: true,
859            avatar_cached: "/elsewhere/a.webp".into(),
860            banner_cached: "/elsewhere/b.webp".into(),
861            stream_consent: true,
862        }
863    }
864
865    fn round_trip(slim: &SlimProfile) -> SlimProfile {
866        let mut interner = crate::compact::NpubInterner::new();
867        let mut p = slim.to_profile();
868        p.id = interner.intern(&slim.id);
869        SlimProfile::from_profile(&p, &interner)
870    }
871
872    #[test]
873    fn profile_is_three_words() {
874        assert!(std::mem::size_of::<Profile>() <= 24, "Profile grew to {}B", std::mem::size_of::<Profile>());
875    }
876
877    #[test]
878    fn every_field_round_trips() {
879        let slim = full_slim("a short bio".into());
880        assert_eq!(round_trip(&slim), slim);
881        let p = slim.to_profile();
882        assert_eq!(p.name(), "alice");
883        assert_eq!(p.display_name(), "Alice 🐈 Wonderland");
884        assert_eq!(p.nickname(), "ally");
885        assert_eq!(p.lud06(), "lnurl1dp68gurn8ghj7");
886        assert_eq!(p.lud16(), "alice@getalby.com");
887        assert_eq!(p.banner(), "https://image.nostr.build/banner.png");
888        assert_eq!(p.avatar(), "https://image.nostr.build/avatar.jpg");
889        assert_eq!(p.about(), "a short bio");
890        assert_eq!(p.website(), "https://alice.example");
891        assert_eq!(p.nip05(), "alice@nostrplebs.com");
892        assert_eq!(p.status_title(), "Listening to :cat: 猫");
893        assert_eq!(p.status_purpose(), "general");
894        assert_eq!(p.status_url(), "https://status.example/now");
895        assert_eq!(p.status_emoji_tags(), slim.status.emoji_tags);
896        assert_eq!(p.avatar_cached(), "/elsewhere/a.webp");
897        assert_eq!(p.banner_cached(), "/elsewhere/b.webp");
898    }
899
900    #[test]
901    fn the_frontend_json_is_unchanged() {
902        let slim = full_slim("bio".into());
903        assert_eq!(serde_json::to_string(&round_trip(&slim)).unwrap(), serde_json::to_string(&slim).unwrap());
904    }
905
906    #[test]
907    fn a_long_about_widens_the_offsets() {
908        let about = "ab🐈".repeat(20_000);
909        assert!(about.len() > u16::MAX as usize);
910        let slim = full_slim(about.clone());
911        let p = slim.to_profile();
912        let block = p.text.0.as_deref().unwrap();
913        assert_ne!(u16::from_le_bytes([block[0], block[1]]) & WIDE, 0, "past 64 KiB the offsets are u32");
914        assert_eq!(p.about(), about);
915        assert_eq!(round_trip(&slim), slim);
916    }
917
918    #[test]
919    fn a_short_block_keeps_narrow_offsets() {
920        let p = full_slim("bio".into()).to_profile();
921        let block = p.text.0.as_deref().unwrap();
922        assert_eq!(u16::from_le_bytes([block[0], block[1]]) & WIDE, 0);
923    }
924
925    #[test]
926    fn any_mix_of_empty_fields_round_trips() {
927        let values: Vec<String> = (0..FIELDS).map(|i| format!("v{i}-{}", "x".repeat(i))).collect();
928        for skip in 0..FIELDS {
929            let mut fields = [""; FIELDS];
930            for i in 0..FIELDS {
931                if i != skip && (i + skip) % 3 != 0 {
932                    fields[i] = &values[i];
933                }
934            }
935            let text = ProfileText::build(&fields, &[("s", "u")]);
936            assert_eq!(text.fields(), fields, "mask {skip}");
937            assert_eq!(text.emoji().collect::<Vec<_>>(), [("s", "u")]);
938        }
939    }
940
941    #[test]
942    fn nothing_set_holds_no_block() {
943        assert_eq!(Profile::new().heap_bytes(), 0);
944        let slim = SlimProfile { id: "npub1empty".into(), ..Default::default() };
945        let p = slim.to_profile();
946        assert!(p.text.0.is_none(), "a seen-but-unfetched placeholder allocates nothing");
947        assert_eq!(round_trip(&slim), slim);
948
949        let mut q = Profile::new();
950        q.set_name("x");
951        q.set_name("");
952        assert!(q.text.0.is_none(), "clearing the last field frees the block");
953    }
954
955    #[test]
956    fn the_block_is_one_exact_allocation() {
957        let p = full_slim("bio".into()).to_profile();
958        let strings: usize = p.text.fields().iter().map(|f| f.len()).sum::<usize>()
959            + p.text.emoji().map(|(s, u)| s.len() + u.len()).sum::<usize>();
960        let slots = (0..FIELDS).filter(|&i| !p.text.get(i).is_empty()).count() + 2 * p.text.emoji().len();
961        assert_eq!(p.heap_bytes(), HEADER + 2 * slots + strings);
962    }
963
964    #[test]
965    fn each_setter_writes_only_its_field() {
966        type Get = fn(&Profile) -> String;
967        type Set = fn(&mut Profile, &str);
968        let cases: [(Get, Set); 15] = [
969            (|p| p.name().into(), |p, v| p.set_name(v)),
970            (|p| p.display_name().into(), |p, v| p.set_display_name(v)),
971            (|p| p.banner().into(), |p, v| p.set_banner(v)),
972            (|p| p.avatar().into(), |p, v| p.set_avatar(v)),
973            (|p| p.about().into(), |p, v| p.set_about(v)),
974            (|p| p.avatar_cached().into(), |p, v| p.set_avatar_cached(v)),
975            (|p| p.banner_cached().into(), |p, v| p.set_banner_cached(v)),
976            (|p| p.nickname().into(), |p, v| p.set_nickname(v)),
977            (|p| p.lud06().into(), |p, v| p.set_lud06(v)),
978            (|p| p.lud16().into(), |p, v| p.set_lud16(v)),
979            (|p| p.nip05().into(), |p, v| p.set_nip05(v)),
980            (|p| p.website().into(), |p, v| p.set_website(v)),
981            (|p| p.status_title().into(), |p, v| p.set_status_title(v)),
982            (|p| p.status_purpose().into(), |p, v| p.set_status_purpose(v)),
983            (|p| p.status_url().into(), |p, v| p.set_status_url(v)),
984        ];
985        let base = full_slim("bio".into()).to_profile();
986        let long = "long".repeat(5000);
987        for (i, (get, set)) in cases.iter().enumerate() {
988            for value in ["", "changed ✓", long.as_str()] {
989                let mut p = base.clone();
990                set(&mut p, value);
991                assert_eq!(get(&p), value, "field {i}");
992                for (j, (other, _)) in cases.iter().enumerate() {
993                    if j != i {
994                        assert_eq!(other(&p), other(&base), "setting field {i} moved field {j}");
995                    }
996                }
997                assert_eq!(p.status_emoji_tags(), base.status_emoji_tags(), "field {i} kept the emoji");
998            }
999        }
1000    }
1001
1002    #[test]
1003    fn an_unchanged_write_keeps_the_block() {
1004        let mut p = full_slim("bio".into()).to_profile();
1005        let before = p.text.0.as_deref().unwrap().as_ptr();
1006        p.set_name("alice");
1007        let tags = p.status_emoji_tags();
1008        p.set_status_emoji_tags(&tags);
1009        assert_eq!(p.text.0.as_deref().unwrap().as_ptr(), before);
1010    }
1011
1012    #[test]
1013    fn status_writes_replace_title_purpose_url_and_tags() {
1014        let mut p = full_slim("bio".into()).to_profile();
1015        p.set_status("new", "music", "", &[tag("x", "https://x")]);
1016        assert_eq!((p.status_title(), p.status_purpose(), p.status_url()), ("new", "music", ""));
1017        assert_eq!(p.status_emoji_tags(), [tag("x", "https://x")]);
1018        assert_eq!(p.name(), "alice");
1019        p.set_status_emoji_tags(&[]);
1020        assert!(p.status_emoji_tags().is_empty());
1021        assert_eq!(p.status_title(), "new");
1022    }
1023
1024    #[test]
1025    fn metadata_merges_like_the_field_by_field_version() {
1026        let mut p = full_slim("bio".into()).to_profile();
1027        let meta = Metadata::new().name("alice").display_name("New Name").about("bio");
1028        assert!(p.from_metadata(meta.clone().custom_field(STREAM_CONSENT_KEY, true)), "a new display name is a change");
1029        assert_eq!(p.display_name(), "New Name");
1030        assert_eq!(p.avatar_cached(), "/elsewhere/a.webp", "an unchanged picture keeps its cache");
1031        assert_eq!(p.status_emoji_tags().len(), 3, "metadata never touches the status");
1032        assert_eq!(p.nickname(), "ally");
1033        assert!(!p.from_metadata(meta.custom_field(STREAM_CONSENT_KEY, true)), "the same kind-0 changes nothing");
1034
1035        let mut q = p.clone();
1036        q.flags.set_blocked(false); // the fixture sets every flag, and a blocked profile takes no pictures
1037        q.from_metadata(Metadata::from_json(r#"{"picture":"https://new/a.png","banner":"https://new/b.png"}"#).unwrap());
1038        assert_eq!(q.avatar(), "https://new/a.png");
1039        assert!(!q.has_avatar_cached() && !q.has_banner_cached(), "a new image drops the old cached file");
1040        assert_eq!(q.name(), "alice", "absent keys keep their field");
1041    }
1042
1043    #[test]
1044    fn debug_shows_the_fields() {
1045        let s = format!("{:?}", full_slim("bio".into()).to_profile());
1046        assert!(s.contains("\"alice\"") && s.contains("\"https://status.example/now\""), "{s}");
1047    }
1048
1049    // ------------------------------------------------------------------
1050    // Cached image paths
1051    // ------------------------------------------------------------------
1052
1053    fn sep() -> char {
1054        std::path::MAIN_SEPARATOR
1055    }
1056
1057    #[test]
1058    fn a_path_in_the_cache_dir_keeps_only_its_file_name() {
1059        let dir = format!("{s}data{s}cache{s}avatars", s = sep());
1060        let path = format!("{dir}{}0123abcd.webp", sep());
1061        assert_eq!(cached_file_name(&path, &dir), Some("0123abcd.webp"));
1062        assert_eq!(expand_cached("0123abcd.webp", &dir), path);
1063    }
1064
1065    #[test]
1066    fn a_path_outside_the_cache_dir_is_kept_whole() {
1067        let s = sep();
1068        let dir = format!("{s}data{s}cache{s}avatars");
1069        for path in [
1070            format!("{s}data{s}cache{s}banners{s}x.webp"),
1071            format!("{dir}x.webp"),
1072            format!("{dir}{s}nested{s}x.webp"),
1073            format!("{dir}{s}nested/x.webp"),
1074            format!("{dir}{s}"),
1075            dir.clone(),
1076            format!("{s}other{dir}{s}x.webp"),
1077            "x.webp".to_string(),
1078            String::new(),
1079        ] {
1080            assert_eq!(cached_file_name(&path, &dir), None, "{path}");
1081        }
1082    }
1083
1084    fn test_cache_dir(sub: &str) -> String {
1085        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
1086        crate::db::get_app_data_dir().unwrap().join("cache").join(sub).to_string_lossy().into_owned()
1087    }
1088
1089    #[test]
1090    fn a_cached_path_in_the_app_cache_is_stored_short_and_read_whole() {
1091        let avatars = test_cache_dir("avatars");
1092        let banners = test_cache_dir("banners");
1093        let avatar = format!("{avatars}{}0123456789abcdef0123456789abcdef.webp", sep());
1094        let banner = format!("{banners}{}fedcba9876543210fedcba9876543210.png", sep());
1095
1096        let mut p = Profile::new();
1097        p.set_avatar_cached(&avatar);
1098        p.set_banner_cached(&banner);
1099        assert_eq!(p.text.get(AVATAR_CACHED), "0123456789abcdef0123456789abcdef.webp");
1100        assert_eq!(p.text.get(BANNER_CACHED), "fedcba9876543210fedcba9876543210.png");
1101        assert_eq!(p.avatar_cached(), avatar);
1102        assert_eq!(p.banner_cached(), banner);
1103
1104        let mut slim = full_slim("bio".into());
1105        slim.avatar_cached = avatar.clone();
1106        slim.banner_cached = banner.clone();
1107        assert_eq!(slim.to_profile().text.get(AVATAR_CACHED).len(), 37);
1108        assert_eq!(round_trip(&slim), slim, "the DB and the frontend still get full paths");
1109
1110        let mut crossed = slim.clone();
1111        crossed.avatar_cached = banner.clone();
1112        crossed.banner_cached = avatar.clone();
1113        assert_eq!(round_trip(&crossed), crossed, "a path in the other kind's dir stays whole");
1114        assert_eq!(crossed.to_profile().text.get(AVATAR_CACHED), banner);
1115    }
1116
1117    #[test]
1118    fn a_cached_path_elsewhere_is_stored_whole() {
1119        let avatars = test_cache_dir("avatars");
1120        let mut p = Profile::new();
1121        for path in [format!("{avatars}{s}nested{s}x.webp", s = sep()), "/tmp/x.webp".into(), "x.webp".into()] {
1122            p.set_avatar_cached(&path);
1123            assert_eq!(p.text.get(AVATAR_CACHED), path);
1124            assert_eq!(p.avatar_cached(), path);
1125        }
1126    }
1127
1128    #[test]
1129    fn a_short_cached_path_follows_every_rewrite() {
1130        let avatars = test_cache_dir("avatars");
1131        let short = format!("{avatars}{}a.webp", sep());
1132        let mut p = Profile::new();
1133        p.set_avatar_cached(&short);
1134        p.set_avatar_cached("a.webp");
1135        assert_eq!(p.avatar_cached(), "a.webp", "a bare name stored as given reads back bare");
1136        p.set_avatar_cached(&short);
1137        assert_eq!(p.avatar_cached(), short);
1138        p.set_name("x");
1139        assert_eq!(p.avatar_cached(), short, "rebuilding for another field keeps it short");
1140        p.set_avatar_cached("");
1141        assert_eq!(p.avatar_cached(), "");
1142        assert!(!p.has_avatar_cached());
1143
1144        p.set_avatar_cached(&short);
1145        p.from_metadata(Metadata::from_json(r#"{"picture":"https://new/a.png"}"#).unwrap());
1146        assert_eq!(p.avatar_cached(), "", "a new picture drops the short path too");
1147        p.set_avatar_cached("/tmp/b.webp");
1148        assert_eq!(p.avatar_cached(), "/tmp/b.webp");
1149    }
1150
1151    #[test]
1152    fn equality_reads_through_the_short_form() {
1153        let avatars = test_cache_dir("avatars");
1154        let path = format!("{avatars}{}a.webp", sep());
1155        let mut short = Profile::new();
1156        short.set_avatar_cached(&path);
1157        let mut whole = Profile::new();
1158        whole.text = ProfileText::build(&std::array::from_fn(|i| if i == AVATAR_CACHED { path.as_str() } else { "" }), &[]);
1159        assert_eq!(short, whole);
1160        whole.set_name("y");
1161        assert_ne!(short, whole);
1162    }
1163
1164    // ------------------------------------------------------------------
1165    // Npub keys
1166    // ------------------------------------------------------------------
1167
1168    /// Test-only bech32 encoder over the decoder's own tables.
1169    fn encode_npub(data: &[u8]) -> String {
1170        let mut chk = NPUB_HRP_CHECKSUM;
1171        for &v in data {
1172            chk = bech32_step(chk, v);
1173        }
1174        for _ in 0..6 {
1175            chk = bech32_step(chk, 0);
1176        }
1177        chk ^= 1;
1178        let mut s = String::from("npub1");
1179        s.extend(data.iter().map(|&v| BECH32_CHARSET[v as usize] as char));
1180        s.extend((0..6).map(|i| BECH32_CHARSET[((chk >> (5 * (5 - i))) & 31) as usize] as char));
1181        s
1182    }
1183
1184    fn five_bit(bytes: &[u8; 32], padding: u8) -> Vec<u8> {
1185        let mut out = Vec::new();
1186        let (mut acc, mut bits) = (0u32, 0);
1187        for &b in bytes {
1188            acc = ((acc << 8) | b as u32) & 0xffff;
1189            bits += 8;
1190            while bits >= 5 {
1191                bits -= 5;
1192                out.push(((acc >> bits) & 31) as u8);
1193            }
1194        }
1195        out.push((((acc << (5 - bits)) & 31) as u8) | padding);
1196        out
1197    }
1198
1199    #[test]
1200    fn npub_bytes_matches_nostr() {
1201        use nostr_sdk::prelude::{Keys, ToBech32};
1202        for _ in 0..64 {
1203            let pk = Keys::generate().public_key();
1204            let npub = pk.to_bech32().unwrap();
1205            assert_eq!(npub_bytes(&npub), Some(pk.to_bytes()), "{npub}");
1206            assert_eq!(encode_npub(&five_bit(&pk.to_bytes(), 0)), npub);
1207        }
1208    }
1209
1210    #[test]
1211    fn npub_bytes_refuses_every_other_spelling() {
1212        use nostr_sdk::prelude::{Keys, ToBech32};
1213        let pk = Keys::generate().public_key();
1214        let npub = pk.to_bech32().unwrap();
1215        let mut last = npub.clone().into_bytes();
1216        let i = last.len() - 1;
1217        last[i] = if last[i] == b'q' { b'p' } else { b'q' };
1218        for bad in [
1219            npub.to_uppercase(),
1220            String::from_utf8(last).unwrap(),
1221            npub.replacen("npub1", "nsec1", 1),
1222            npub[..62].to_string(),
1223            format!("{npub}q"),
1224            encode_npub(&five_bit(&pk.to_bytes(), 1)),
1225            "npub1alice".to_string(),
1226            String::new(),
1227        ] {
1228            assert_eq!(npub_bytes(&bad), None, "{bad}");
1229        }
1230    }
1231
1232    #[test]
1233    fn npub_map_keys_npubs_by_bytes_and_keeps_the_rest() {
1234        use nostr_sdk::prelude::{Keys, ToBech32};
1235        let mut map = NpubMap::default();
1236        let npubs: Vec<String> = (0..50).map(|_| Keys::generate().public_key().to_bech32().unwrap()).collect();
1237        for (i, n) in npubs.iter().enumerate() {
1238            map.insert(n, i);
1239        }
1240        map.insert("npub1alice", 100);
1241        map.insert(&npubs[0].to_uppercase(), 101);
1242        assert_eq!(map.keys.len(), 50);
1243        assert_eq!(map.other.len(), 2);
1244        for (i, n) in npubs.iter().enumerate() {
1245            assert_eq!(map.get(n), Some(&i));
1246        }
1247        assert_eq!(map.get("npub1alice"), Some(&100));
1248        assert_eq!(map.get(&npubs[0].to_uppercase()), Some(&101), "a non-canonical spelling is its own key");
1249        map.retain(|&v| v % 2 == 0);
1250        assert_eq!(map.len(), 26);
1251        assert!(map.contains(&npubs[2]) && !map.contains(&npubs[1]));
1252        map.clear();
1253        assert_eq!(map.len(), 0);
1254    }
1255}
1256
1257#[cfg(test)]
1258mod blocked_imagery_tests {
1259    use super::*;
1260
1261    fn pictured(avatar: &str, banner: &str) -> Profile {
1262        let mut p = Profile::new();
1263        p.from_metadata(Metadata::from_json(&format!(r#"{{"name":"a","picture":"{avatar}","banner":"{banner}"}}"#)).unwrap());
1264        p
1265    }
1266
1267    #[test]
1268    fn a_blocked_profile_takes_no_pictures_from_its_kind0() {
1269        let mut p = Profile::new();
1270        p.flags.set_blocked(true);
1271        assert!(p.from_metadata(Metadata::from_json(r#"{"name":"a","picture":"https://x/a.png","banner":"https://x/b.png"}"#).unwrap()));
1272        assert_eq!(p.name(), "a", "the rest of the kind-0 still lands");
1273        assert!(p.avatar().is_empty() && p.banner().is_empty());
1274        assert!(!p.has_imagery());
1275    }
1276
1277    #[test]
1278    fn forgetting_drops_both_pictures_and_hands_back_their_files() {
1279        let mut p = pictured("https://x/a.png", "https://x/b.png");
1280        p.set_avatar_cached("/elsewhere/a.png");
1281        p.set_banner_cached("/elsewhere/b.png");
1282        let files = p.forget_imagery();
1283        assert_eq!(files, vec![
1284            CachedImage { url: "https://x/a.png".into(), path: "/elsewhere/a.png".into(), banner: false },
1285            CachedImage { url: "https://x/b.png".into(), path: "/elsewhere/b.png".into(), banner: true },
1286        ]);
1287        assert!(!p.has_imagery(), "URLs and cached paths are all gone");
1288        assert!(pictured("https://x/a.png", "").forget_imagery().is_empty(), "nothing on disk, nothing to delete");
1289    }
1290}