Skip to main content

vector_core/
badges.rs

1//! Profile badges — fetch, validate, and cache.
2//!
3//! Badges are not loaded during the critical boot path. The cache is filled
4//! once after initial sync (see `refresh_own_badges`) so badge-gated perks
5//! (e.g. raised emoji-pack limits) resolve without an on-demand network
6//! round-trip. `has_vector_badge` is the cheap synchronous reader used by
7//! those gates.
8
9use nostr_sdk::prelude::*;
10use std::collections::HashSet;
11use std::sync::LazyLock;
12
13// Guy Fawkes Day 2025 — V for Vector badge claim window.
14const FAWKES_DAY_START: u64 = 1762300800; // 2025-11-05 00:00:00 UTC
15const FAWKES_DAY_END: u64 = 1762387200; // 2025-11-06 00:00:00 UTC
16
17/// Per-account settings key: "true" once we've confirmed the Vector badge.
18const BADGE_VECTOR_KEY: &str = "badge_vector";
19/// Per-account settings key: unix-secs of the last unsuccessful resolve pass.
20/// Throttles re-checking for accounts that don't (yet) hold the badge.
21const BADGE_CHECK_TS_KEY: &str = "badge_check_ts";
22/// Don't re-run the full retry loop more than this often for an account we've
23/// already checked without success. The claim window is permanently closed, so
24/// a non-holder can never become a holder — frequent restarts shouldn't each
25/// trigger a fresh relay sweep.
26const RECHECK_COOLDOWN_SECS: u64 = 6 * 3600;
27
28fn unix_now() -> u64 {
29    crate::clock::now_secs()
30}
31
32/// Whether a kind-30078 event is a valid Fawkes badge claim: right content and
33/// a timestamp inside the (half-open) event window. Pure so it's unit-testable.
34fn is_valid_fawkes_claim(content: &str, created_at: u64) -> bool {
35    content == "fawkes_badge_claimed"
36        && (FAWKES_DAY_START..FAWKES_DAY_END).contains(&created_at)
37}
38
39/// Fetch + validate whether `pubkey` holds the V for Vector (Guy Fawkes 2025)
40/// badge: a kind-30078 `d=fawkes_2025` claim published within the event window.
41///
42/// Queries the full relay pool rather than only the trusted relays: the claim
43/// was published during the event to whatever relays the holder used, and any
44/// single relay (including a trusted one) can be transiently down. Broadest
45/// net gives the best chance of locating the permanent claim.
46pub async fn has_fawkes_badge(pubkey: &PublicKey) -> Result<bool, String> {
47    let client = crate::state::nostr_client().ok_or("Nostr client not initialized")?;
48    let filter = Filter::new()
49        .author(*pubkey)
50        .kind(Kind::ApplicationSpecificData)
51        .custom_tag(SingleLetterTag::LOWERCASE_D, "fawkes_2025")
52        // > 1 to tolerate relays serving superseded copies of the replaceable
53        // event alongside the current one.
54        .limit(10);
55    let mut events = client
56        .stream_events(filter)
57        .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(10)))
58        .await
59        .map_err(|e| e.to_string())?;
60    // 0.45 streams (relay, Result<Event>) so callers can attribute per-relay failures.
61    while let Some((_relay, res)) = events.next().await {
62        let Ok(event) = res else { continue };
63        if is_valid_fawkes_claim(&event.content, event.created_at.as_secs()) {
64            return Ok(true);
65        }
66    }
67    if !any_relay_connected(&client).await {
68        return Err("no relay connected".into());
69    }
70    Ok(false)
71}
72
73// ── V for Vector 2026 (self-claimed in the 24 hours from v0.5.0's release; closed) ─────────
74
75/// The claim window, unix seconds, half-open: 16:00 UTC on 2026-11-05 to the next day's 16:00.
76const V2026_START: u64 = 1793894400;
77const V2026_END: u64 = 1793980800;
78
79const V2026_D: &str = "vector_2026";
80const V2026_CONTENT: &str = "vector_2026_badge_claimed";
81/// Per-account settings key: "true" once the badge is ours.
82const BADGE_V2026_KEY: &str = "badge_vector_2026";
83
84fn is_valid_v2026_claim(content: &str, created_at: u64) -> bool {
85    content == V2026_CONTENT && (V2026_START..V2026_END).contains(&created_at)
86}
87
88/// Fetch whether `pubkey` holds V for Vector 2026: its own kind-30078 `d=vector_2026` claim,
89/// published inside the window.
90pub async fn has_v2026_badge(pubkey: &PublicKey) -> Result<bool, String> {
91    let client = crate::state::nostr_client().ok_or("Nostr client not initialized")?;
92    let filter = Filter::new()
93        .author(*pubkey)
94        .kind(Kind::ApplicationSpecificData)
95        .custom_tag(SingleLetterTag::LOWERCASE_D, V2026_D)
96        .limit(10);
97    let mut events = client
98        .stream_events(filter)
99        .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(10)))
100        .await
101        .map_err(|e| e.to_string())?;
102    while let Some((_relay, res)) = events.next().await {
103        let Ok(event) = res else { continue };
104        if is_valid_v2026_claim(&event.content, event.created_at.as_secs()) && !event.is_expired() {
105            return Ok(true);
106        }
107    }
108    if !any_relay_connected(&client).await {
109        return Err("no relay connected".into());
110    }
111    Ok(false)
112}
113
114/// Cached: whether this account holds V for Vector 2026.
115pub fn has_vector_2026_badge() -> bool {
116    match crate::db::settings::get_sql_setting_strict(BADGE_V2026_KEY) {
117        Ok(v) => {
118            let held = v.as_deref() == Some("true");
119            with_last(|l| l.vector_2026 = Some(held));
120            held
121        }
122        Err(_) => with_last(|l| l.vector_2026).unwrap_or(false),
123    }
124}
125
126fn store_v2026_badge() {
127    with_last(|l| l.vector_2026 = Some(true));
128    let _ = crate::db::set_sql_setting(BADGE_V2026_KEY.to_string(), "true".to_string());
129}
130
131/// Someone's V for Vector 2026, looked up on demand (a profile). Our own, when found, is held,
132/// as the post-sync refresh would.
133pub async fn check_v2026(pubkey: &PublicKey) -> Result<bool, String> {
134    let has = has_v2026_badge(pubkey).await?;
135    if has && !has_vector_2026_badge() && crate::state::my_public_key().as_ref() == Some(pubkey) {
136        store_v2026_badge();
137        emit_badges();
138    }
139    Ok(has)
140}
141
142/// This account's badges and perk tier, for the UI.
143pub fn own_summary() -> serde_json::Value {
144    serde_json::json!({
145        "vector": has_vector_badge(),
146        "vector_2026": has_vector_2026_badge(),
147        "tier": effective_tier(),
148        "bug_hunter": bug_hunter_tier(),
149    })
150}
151
152/// Our own claim, made on another device (or before a reinstall): found and kept, as the 2025
153/// badge is.
154async fn refresh_own_v2026(pk: PublicKey) {
155    if has_vector_2026_badge() {
156        return;
157    }
158    if let Ok(true) = has_v2026_badge(&pk).await {
159        store_v2026_badge();
160        emit_badges();
161    }
162}
163
164/// An empty answer means "none" only if some relay was there to give it.
165async fn any_relay_connected(client: &Client) -> bool {
166    client.relays().await.values().any(|r| r.status() == RelayStatus::Connected)
167}
168
169/// The last badge state this session read from or wrote to its database. A failed
170/// read answers from here, never as "no badge": a busy or unbound connection must
171/// not take an account's perks away.
172#[derive(Default)]
173struct LastRead {
174    vector: Option<bool>,
175    vector_2026: Option<bool>,
176    bug_hunter: Option<u8>,
177}
178struct LastReadKey;
179
180fn last_read() -> std::sync::Arc<std::sync::Mutex<LastRead>> {
181    crate::db::current_session().scoped::<LastReadKey, _>()
182}
183
184fn with_last<T>(f: impl FnOnce(&mut LastRead) -> T) -> T {
185    f(&mut last_read().lock().unwrap_or_else(|e| e.into_inner()))
186}
187
188/// Cached flag for whether we hold the Vector badge. Cheap + synchronous, so
189/// safe to call from limit checks. Defaults to false when unset — badge perks
190/// stay off until the cache is filled post-sync.
191pub fn has_vector_badge() -> bool {
192    match crate::db::settings::get_sql_setting_strict(BADGE_VECTOR_KEY) {
193        Ok(v) => {
194            let held = v.as_deref() == Some("true");
195            with_last(|l| l.vector = Some(held));
196            held
197        }
198        Err(_) => with_last(|l| l.vector).unwrap_or(false),
199    }
200}
201
202fn store_vector_badge() {
203    with_last(|l| l.vector = Some(true));
204    let _ = crate::db::set_sql_setting(BADGE_VECTOR_KEY.to_string(), "true".to_string());
205}
206
207/// Per-account settings key: cached Bug Hunter NIP-58 tier (0-3). Filled by the
208/// award fetch; downgraded only on a seen issuer revocation, never on absence.
209const BADGE_BUG_HUNTER_TIER_KEY: &str = "badge_bug_hunter_tier";
210
211/// Per-account settings key: comma-separated hex ids of the award events backing
212/// the cached tier, so a revocation still resolves after the relays purge the award.
213const BADGE_BUG_HUNTER_AWARD_IDS_KEY: &str = "badge_bug_hunter_award_ids";
214
215/// Cached Bug Hunter tier (0-3) for the current account. Cheap + synchronous;
216/// 0 until the award fetch fills it.
217pub fn bug_hunter_tier() -> u8 {
218    match crate::db::settings::get_sql_setting_strict(BADGE_BUG_HUNTER_TIER_KEY) {
219        Ok(v) => {
220            let tier = v.and_then(|v| v.parse::<u8>().ok()).map(|t| t.min(3)).unwrap_or(0);
221            with_last(|l| l.bug_hunter = Some(tier));
222            tier
223        }
224        Err(_) => with_last(|l| l.bug_hunter).unwrap_or(0),
225    }
226}
227
228fn store_bug_hunter_tier(tier: u8) {
229    with_last(|l| l.bug_hunter = Some(tier));
230    let _ = crate::db::set_sql_setting(BADGE_BUG_HUNTER_TIER_KEY.to_string(), tier.to_string());
231}
232
233/// Tell the UI what the account's perks are now.
234fn emit_badges() {
235    crate::traits::emit_event_json("badges_updated", own_summary());
236}
237
238/// The account's effective premium tier (0-3): the highest its badges grant. V for Vector
239/// 2025 is full premium (3); 2026 grants what Bug Hunter's first tier does (1). Per-account
240/// perks (emoji limits, pins, Text Effects) read this.
241pub fn effective_tier() -> u8 {
242    if is_bot() { return 3; }
243    badge_tier(bug_hunter_tier(), has_vector_badge(), has_vector_2026_badge())
244}
245
246fn badge_tier(bug_hunter: u8, vector: bool, vector_2026: bool) -> u8 {
247    bug_hunter.max(if vector { 3 } else { 0 }).max(if vector_2026 { 1 } else { 0 })
248}
249
250/// Text Effects (coloured text, gradients, rainbows) are a perk of any badge: tier 1 and up.
251/// Others' coloured messages always render; only sending colour is gated.
252pub fn has_text_effects() -> bool {
253    effective_tier() >= 1
254}
255
256/// A process role, not account state: the SDK runs one bot per process.
257static BOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
258
259/// Run this process as a bot: every tiered perk at its top tier, and emoji packs
260/// uncapped (any number equipped, every emoji in each). Fixed protocol ceilings,
261/// like a message's reaction groups and the 64 KB event, still apply.
262pub fn set_bot(on: bool) {
263    BOT.store(on, std::sync::atomic::Ordering::Relaxed);
264}
265
266pub fn is_bot() -> bool {
267    BOT.load(std::sync::atomic::Ordering::Relaxed)
268}
269
270/// Per-effective-tier cap on NEW reaction groups one user may open on a single
271/// message. Joining an existing reaction (+1) is never gated — only introducing
272/// an emoji the message doesn't yet carry spends this allowance.
273pub const NEW_REACTIONS_PER_POST_BY_TIER: [usize; 4] = [6, 6, 9, 12];
274
275/// The current account's fresh-reaction allowance per message.
276pub fn effective_max_new_reactions_per_post() -> usize {
277    NEW_REACTIONS_PER_POST_BY_TIER[effective_tier() as usize]
278}
279
280/// Sender-side gate for reacting to `reference_id` with `emoji`: joining an
281/// existing group always passes; opening a new group checks the message-wide
282/// group ceiling, then the per-tier allowance. "Groups I opened" is judged by
283/// insertion order in our own view — the earliest held reaction per emoji.
284/// `Ok(())` when the send may proceed.
285pub async fn check_new_reaction_allowance(reference_id: &str, emoji: &str) -> Result<(), String> {
286    use nostr_sdk::prelude::ToBech32;
287    let me = match crate::state::my_public_key().and_then(|pk| pk.to_bech32().ok()) {
288        Some(npub) => npub,
289        None => return Err("Not logged in".to_string()),
290    };
291    let st = crate::state::STATE.lock().await;
292    let Some((_, message)) = st.find_message(reference_id) else { return Ok(()) };
293    if message.reactions.iter().any(|r| r.emoji == emoji) {
294        return Ok(());
295    }
296    let mut first_by_emoji: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
297    for r in &message.reactions {
298        first_by_emoji.entry(r.emoji.as_str()).or_insert(r.author_id.as_str());
299    }
300    if first_by_emoji.len() >= crate::compact::MAX_REACTION_GROUPS {
301        return Err("This message has reached its reaction limit".to_string());
302    }
303    let spent = first_by_emoji.values().filter(|a| **a == me).count();
304    if spent >= effective_max_new_reactions_per_post() {
305        return Err("You've used all your new reactions on this message".to_string());
306    }
307    Ok(())
308}
309
310/// The highest effective tier across ALL accounts on this install. The
311/// multi-account cap is device-level (adding a profile spans accounts), so it
312/// must not drop when you switch to an un-badged account — unlike the per-account
313/// perks. Reads each account's badge state straight from its vector.db.
314pub fn max_account_tier() -> u8 {
315    let mut max = effective_tier();
316    if let Ok(accounts) = crate::db::get_accounts() {
317        for npub in accounts {
318            max = max.max(read_account_tier(&npub).unwrap_or(0));
319        }
320    }
321    max
322}
323
324/// A (possibly non-active) account's effective tier, read read-only from its
325/// vector.db settings (plaintext KV). None if the DB/keys are absent or locked.
326fn read_account_tier(npub: &str) -> Option<u8> {
327    let path = crate::db::account_dir(npub).ok()?.join("vector.db");
328    let conn = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).ok()?;
329    let get = |key: &str| -> Option<String> {
330        conn.query_row("SELECT value FROM settings WHERE key = ?1", rusqlite::params![key], |r| r.get(0)).ok()
331    };
332    let bug = get(BADGE_BUG_HUNTER_TIER_KEY).and_then(|v| v.parse::<u8>().ok()).map(|t| t.min(3)).unwrap_or(0);
333    let vector = get(BADGE_VECTOR_KEY).map(|v| v == "true").unwrap_or(false);
334    let vector_2026 = get(BADGE_V2026_KEY).as_deref() == Some("true");
335    Some(badge_tier(bug, vector, vector_2026))
336}
337
338/// Record the result of an on-demand badge check. When the checked key is our
339/// own and the badge is present, persist it (sticky) and emit `badges_updated`
340/// so badge-gated perks (raised emoji-pack limits) turn on immediately — this is
341/// the safety net for a post-sync `refresh_own_badges` that missed the claim
342/// (the holding relay is often flaky during the saturated sync window) and is now
343/// sitting in its multi-hour re-check cooldown. An on-demand check runs at a
344/// quiet moment, so it lands where the sync-time sweep didn't.
345///
346/// No-op for other users, a negative result, or an account swap mid-check (the
347/// own-key comparison re-reads the *current* account, so a stale key never
348/// writes the wrong DB). No awaits, so the read + write stay on one account.
349pub fn note_own_badge_confirmed(pubkey: &PublicKey, has_badge: bool) {
350    if !has_badge || has_vector_badge() {
351        return;
352    }
353    if crate::state::my_public_key().as_ref() != Some(pubkey) {
354        return;
355    }
356    store_vector_badge();
357    crate::log_info!("[Badges] vector badge confirmed via on-demand check");
358    emit_badges();
359}
360
361/// Resolve the account's badges once its sync has settled, on every login and on
362/// every client, then tell the UI. The relay holding a claim is often the one the
363/// sync just saturated.
364pub async fn refresh_own() {
365    crate::rt::time::sleep(std::time::Duration::from_secs(30)).await;
366    let v2026 = async {
367        if let Some(pk) = crate::state::my_public_key() {
368            crate::db::scoped(refresh_own_v2026(pk)).await;
369        }
370    };
371    futures_util::join!(refresh_own_badges(), refresh_own_bug_hunter(), v2026);
372    emit_badges();
373}
374
375/// Fetch our own badges and persist to the per-account cache. Called once
376/// after initial sync. The std::sync::Arc<crate::db::Session> straddles the network fetch so a
377/// mid-fetch account swap can't write account A's badge into account B's DB.
378async fn refresh_own_badges() {
379    crate::db::scoped(async move {
380        let Some(pk) = crate::state::my_public_key() else {
381            crate::log_warn!("[Badges] refresh skipped — no public key");
382            return;
383        };
384
385        // Sticky: the badge is a permanent achievement, so once confirmed we never
386        // re-query (avoids a flaky relay later flipping it off) and never downgrade.
387        if has_vector_badge() {
388            crate::log_info!("[Badges] vector badge already cached — skipping refresh");
389            return;
390        }
391
392        // Throttle: skip the relay sweep if we already checked recently without
393        // success. The window is closed, so a miss now will still be a miss in an
394        // hour — no need to re-sweep on every restart.
395        let now = unix_now();
396        if let Some(last) = crate::db::get_sql_setting(BADGE_CHECK_TS_KEY.to_string())
397            .ok()
398            .flatten()
399            .and_then(|v| v.parse::<u64>().ok())
400        {
401            if now.saturating_sub(last) < RECHECK_COOLDOWN_SECS {
402                return;
403            }
404        }
405
406        crate::log_info!(
407            "[Badges] resolving own badges for {}…",
408            pk.to_bech32().unwrap_or_default()
409        );
410
411        // The holding relay (often the user's own) is flaky/overloaded during the
412        // heavy sync window, so retry a few times to catch it during a quiet
413        // moment. A miss leaves the badge cache untouched (records only the check
414        // time for the cooldown); the next boot past the cooldown tries again until
415        // it lands once (then sticky-cached forever).
416        const ATTEMPTS: u8 = 3;
417        let mut answered = false;
418        for attempt in 1..=ATTEMPTS {
419            match has_fawkes_badge(&pk).await {
420                Ok(true) => {
421                    crate::log_info!("[Badges] vector badge confirmed (attempt {})", attempt);
422                    store_vector_badge();
423                    emit_badges();
424                    return;
425                }
426                Ok(false) => {
427                    answered = true;
428                    crate::log_info!("[Badges] vector badge not found (attempt {}/{})", attempt, ATTEMPTS);
429                }
430                Err(e) => {
431                    crate::log_warn!("[Badges] refresh attempt {}/{} failed: {}", attempt, ATTEMPTS, e);
432                }
433            }
434            if attempt < ATTEMPTS {
435                crate::rt::time::sleep(std::time::Duration::from_secs(20)).await;
436            }
437        }
438        // The cooldown starts only once a relay answered: an offline boot checked nothing.
439        if answered {
440            let _ = crate::db::set_sql_setting(BADGE_CHECK_TS_KEY.to_string(), now.to_string());
441            crate::log_info!("[Badges] vector badge not resolved this boot — will retry after cooldown");
442        } else {
443            crate::log_info!("[Badges] no relay answered — will retry next login");
444        }
445    })
446    .await
447}
448
449// ── Bug Hunter (NIP-58 tiered, team-awarded) ───────────────────────────────
450
451/// The Vector Team issuer key — the NIP-58 trust root for Bug Hunter badges.
452/// Only awards (kind 8) and revocations (kind 5) signed by this key are honored,
453/// so a forged award from any other key grants nothing.
454const BUG_HUNTER_ISSUER_NPUB: &str =
455    "npub1hrujuc08r4zcdtn0u6ts7u7apldcjqgftz0z7stmaaz9hwaf9jxs66f3yh";
456
457static BUG_HUNTER_ISSUER: LazyLock<PublicKey> = LazyLock::new(|| {
458    PublicKey::from_bech32(BUG_HUNTER_ISSUER_NPUB)
459        .expect("hardcoded Bug Hunter issuer npub must be valid")
460});
461
462/// Map a badge-definition `d` identifier to its tier. The display `name` can
463/// change freely; the `d` slug is the permanent identity.
464fn tier_from_slug(d: &str) -> Option<u8> {
465    match d {
466        "bug-hunter-tier-1" => Some(1),
467        "bug-hunter-tier-2" => Some(2),
468        "bug-hunter-tier-3" => Some(3),
469        _ => None,
470    }
471}
472
473/// Parse a NIP-58 `a`-tag coordinate (`30009:<issuer-hex>:<d>`) into a tier, but
474/// only when the kind is 30009 AND the author is our trusted issuer — an award
475/// pointing at a definition minted under any other key is ignored.
476fn tier_from_coord(coord: &str, issuer_hex: &str) -> Option<u8> {
477    let mut parts = coord.splitn(3, ':');
478    let kind = parts.next()?;
479    let author = parts.next()?;
480    let d = parts.next()?;
481    if kind != "30009" || author != issuer_hex {
482        return None;
483    }
484    tier_from_slug(d)
485}
486
487/// Fold awards (event id + tier) and the set of revoked award ids into the tier
488/// seen this fetch, plus whether a revocation actually applied to one of our
489/// awards. Pure so it's unit-testable. `saw_revocation` is the positive signal
490/// that justifies a downgrade (vs. a flaky-relay absence, which must not).
491fn fold_bug_hunter(awards: &[(EventId, u8)], revoked: &HashSet<EventId>) -> (u8, bool) {
492    let mut seen_tier = 0u8;
493    let mut saw_revocation = false;
494    for (id, tier) in awards {
495        if revoked.contains(id) {
496            saw_revocation = true;
497        } else {
498            seen_tier = seen_tier.max(*tier);
499        }
500    }
501    (seen_tier, saw_revocation)
502}
503
504/// Fetch `pubkey`'s raw Bug Hunter standing from the issuer: the seen kind-8
505/// awards (id + tier) whose `a` points at one of our tier definitions, plus the
506/// set of award ids the issuer has revoked (kind-5). Queries the full pool.
507async fn fetch_bug_hunter_raw(pubkey: &PublicKey) -> Result<(Vec<(EventId, u8)>, HashSet<EventId>), String> {
508    let client = crate::state::nostr_client().ok_or("Nostr client not initialized")?;
509    let issuer = *BUG_HUNTER_ISSUER;
510    let issuer_hex = issuer.to_hex();
511
512    // Awards: kind 8 signed by the issuer, p-tagging this user.
513    let award_filter = Filter::new()
514        .author(issuer)
515        .kind(Kind::Custom(8))
516        .custom_tag(SingleLetterTag::LOWERCASE_P, pubkey.to_hex())
517        .limit(64);
518    let mut awards: Vec<(EventId, u8)> = Vec::new();
519    let mut stream = client
520        .stream_events(award_filter)
521        .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(10)))
522        .await
523        .map_err(|e| e.to_string())?;
524    while let Some((_relay, res)) = stream.next().await {
525        let Ok(ev) = res else { continue };
526        let coord = ev.tags.iter().find_map(|t| {
527            let s = t.as_slice();
528            if s.first().map(|k| k == "a").unwrap_or(false) {
529                s.get(1).cloned()
530            } else {
531                None
532            }
533        });
534        if let Some(c) = coord {
535            if let Some(tier) = tier_from_coord(&c, &issuer_hex) {
536                awards.push((ev.id, tier));
537            }
538        }
539    }
540
541    // Revocations: kind 5 from the issuer (NIP-09); each `e` tag names a revoked award.
542    let revoke_filter = Filter::new()
543        .author(issuer)
544        .kind(Kind::Custom(5))
545        .limit(256);
546    let mut revoked: HashSet<EventId> = HashSet::new();
547    let mut rstream = client
548        .stream_events(revoke_filter)
549        .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(10)))
550        .await
551        .map_err(|e| e.to_string())?;
552    while let Some((_relay, res)) = rstream.next().await {
553        let Ok(ev) = res else { continue };
554        for t in ev.tags.iter() {
555            let s = t.as_slice();
556            if s.first().map(|k| k == "e").unwrap_or(false) {
557                if let Some(id) = s.get(1).and_then(|h| EventId::from_hex(h).ok()) {
558                    revoked.insert(id);
559                }
560            }
561        }
562    }
563
564    if awards.is_empty() && !any_relay_connected(&client).await {
565        return Err("no relay connected".into());
566    }
567    Ok((awards, revoked))
568}
569
570/// Highest non-revoked tier + whether a seen award was revoked, for displaying
571/// another user's badge. Our own status goes through `refresh_own_bug_hunter`,
572/// which also catches revocation of a since-purged award.
573pub async fn fetch_bug_hunter_tier(pubkey: &PublicKey) -> Result<(u8, bool), String> {
574    let (awards, revoked) = fetch_bug_hunter_raw(pubkey).await?;
575    let (tier, revoked_seen) = fold_bug_hunter(&awards, &revoked);
576    note_own_bug_hunter(pubkey, tier);
577    Ok((tier, revoked_seen))
578}
579
580/// A live look at our own Bug Hunter awards raises the cached tier at once, so a
581/// badge the profile shows always carries its perks. Only ever upward: a lower
582/// result is a relay that missed the award, and downgrades go through
583/// `refresh_own_bug_hunter`'s revocation check.
584fn note_own_bug_hunter(pubkey: &PublicKey, tier: u8) {
585    if crate::state::my_public_key().as_ref() != Some(pubkey) || tier <= bug_hunter_tier() {
586        return;
587    }
588    store_bug_hunter_tier(tier);
589    crate::log_info!("[Badges] bug hunter tier {} confirmed via on-demand check", tier);
590    emit_badges();
591}
592
593fn read_cached_award_ids() -> Vec<EventId> {
594    crate::db::get_sql_setting(BADGE_BUG_HUNTER_AWARD_IDS_KEY.to_string())
595        .ok()
596        .flatten()
597        .map(|s| s.split(',').filter_map(|h| EventId::from_hex(h.trim()).ok()).collect())
598        .unwrap_or_default()
599}
600
601fn write_cached_award_ids(ids: &[EventId]) {
602    let csv = ids.iter().map(|id| id.to_hex()).collect::<Vec<_>>().join(",");
603    let _ = crate::db::set_sql_setting(BADGE_BUG_HUNTER_AWARD_IDS_KEY.to_string(), csv);
604}
605
606/// The tier to hold after a fetch: a higher award applies at once, a lower view only
607/// when the issuer's revocation was seen, since a missing award is a relay that missed it.
608fn next_tier(cached: u8, seen: u8, saw_revocation: bool) -> u8 {
609    if seen > cached || (seen < cached && saw_revocation) { seen } else { cached }
610}
611
612/// Resolve + persist our own Bug Hunter tier (called post-sync). Sticky cache:
613/// upgrades apply immediately; a downgrade is honored ONLY on a seen revocation,
614/// never a mere absent award (flaky relay). The ids of the awards backing the
615/// current tier are cached so a revocation still resolves after the relays purge
616/// the award itself (NIP-09 deletion).
617async fn refresh_own_bug_hunter() {
618    let Some(pk) = crate::state::my_public_key() else {
619        return;
620    };
621
622    // A failed fetch, or an empty one for an account with nothing cached yet, is
623    // most often a relay still busy with the sync: ask again before settling.
624    const ATTEMPTS: u8 = 3;
625    let mut attempt = 0;
626    let (awards, revoked) = loop {
627        attempt += 1;
628        match fetch_bug_hunter_raw(&pk).await {
629            Ok((awards, revoked)) if !awards.is_empty() || bug_hunter_tier() > 0 || attempt >= ATTEMPTS => {
630                break (awards, revoked);
631            }
632            Ok(_) => crate::log_info!("[Badges] no bug hunter award found (attempt {attempt}/{ATTEMPTS})"),
633            Err(e) if attempt >= ATTEMPTS => {
634                crate::log_warn!("[Badges] bug hunter fetch failed: {}", e);
635                return;
636            }
637            Err(e) => crate::log_warn!("[Badges] bug hunter fetch attempt {attempt}/{ATTEMPTS} failed: {e}"),
638        }
639        crate::rt::time::sleep(std::time::Duration::from_secs(20)).await;
640    };
641
642    // Highest non-revoked seen tier + the award ids backing it.
643    let mut seen_tier = 0u8;
644    let mut active_ids: Vec<EventId> = Vec::new();
645    let mut seen_revoked = false;
646    for (id, tier) in &awards {
647        if revoked.contains(id) {
648            seen_revoked = true;
649        } else {
650            seen_tier = seen_tier.max(*tier);
651            active_ids.push(*id);
652        }
653    }
654    // Also honor a revocation of an award we previously cached but that the relays
655    // have since purged (so it's no longer in `awards` to match directly).
656    let cached_revoked = read_cached_award_ids().iter().any(|id| revoked.contains(id));
657    let saw_revocation = seen_revoked || cached_revoked;
658
659    // Re-read the current account before any write: never persist A's state into B.
660    if crate::state::my_public_key().as_ref() != Some(&pk) {
661        return;
662    }
663
664    let cached = bug_hunter_tier();
665    let new_tier = next_tier(cached, seen_tier, saw_revocation);
666
667    // Remember the awards behind the current tier — but only when we actually saw
668    // awards, so a flaky empty fetch never wipes the memory we need for revocation.
669    if !awards.is_empty() {
670        write_cached_award_ids(&active_ids);
671    }
672    if new_tier == cached {
673        return;
674    }
675    store_bug_hunter_tier(new_tier);
676    crate::log_info!("[Badges] bug hunter tier {} -> {}", cached, new_tier);
677    emit_badges();
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683
684    #[test]
685    fn fawkes_claim_window_boundaries() {
686        // Correct content, inside the window.
687        assert!(is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_START));
688        assert!(is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_END - 1));
689        // End is exclusive.
690        assert!(!is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_END));
691        // Before the window.
692        assert!(!is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_START - 1));
693        // Wrong / empty content, even inside the window.
694        assert!(!is_valid_fawkes_claim("", FAWKES_DAY_START));
695        assert!(!is_valid_fawkes_claim("something_else", FAWKES_DAY_START));
696    }
697
698    #[test]
699    fn bug_hunter_issuer_npub_is_valid() {
700        // A malformed hardcoded issuer would panic when the LazyLock forces.
701        let _ = *BUG_HUNTER_ISSUER;
702        assert!(PublicKey::from_bech32(BUG_HUNTER_ISSUER_NPUB).is_ok());
703    }
704
705    #[test]
706    fn tier_from_coord_trusts_only_issuer_kind_and_slug() {
707        let issuer = "abc123";
708        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-1", issuer), Some(1));
709        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-2", issuer), Some(2));
710        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-3", issuer), Some(3));
711        // Forged: a definition minted under another key.
712        assert_eq!(tier_from_coord("30009:evil:bug-hunter-tier-3", issuer), None);
713        // Wrong kind.
714        assert_eq!(tier_from_coord("30008:abc123:bug-hunter-tier-3", issuer), None);
715        // Unknown slug.
716        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-9", issuer), None);
717    }
718
719    #[test]
720    fn fold_bug_hunter_highest_non_revoked_with_revocation_flag() {
721        let id = |b: u8| EventId::from_hex(&format!("{:02x}", b).repeat(32)).unwrap();
722        // No revocations: highest tier, flag clear.
723        assert_eq!(fold_bug_hunter(&[(id(1), 1), (id(3), 3), (id(2), 2)], &HashSet::new()), (3, false));
724        // Revoke the tier-3 award: tier drops to 2, flag set.
725        let revoked: HashSet<EventId> = [id(3)].into_iter().collect();
726        assert_eq!(fold_bug_hunter(&[(id(1), 1), (id(3), 3), (id(2), 2)], &revoked), (2, true));
727        // No awards: tier 0, no revocation.
728        assert_eq!(fold_bug_hunter(&[], &HashSet::new()), (0, false));
729    }
730
731    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
732        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
733        crate::db::close_database();
734        crate::db::clear_id_caches();
735        let tmp = tempfile::tempdir().unwrap();
736        let me = Keys::generate();
737        let account = me.public_key().to_bech32().unwrap();
738        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
739        crate::db::set_current_account(account.clone()).unwrap();
740        crate::db::init_database(&account).unwrap();
741        crate::state::set_my_public_key(me.public_key());
742        (tmp, guard, me)
743    }
744
745    fn rename_settings(from: &str, to: &str) {
746        let conn = crate::db::get_write_connection_guard_static().unwrap();
747        conn.execute(&format!("ALTER TABLE {from} RENAME TO {to}"), []).unwrap();
748    }
749
750    #[test]
751    fn a_missing_award_never_lowers_the_tier_and_a_revocation_does() {
752        assert_eq!(next_tier(0, 2, false), 2, "a new award applies at once");
753        assert_eq!(next_tier(2, 3, false), 3, "an upgrade applies at once");
754        assert_eq!(next_tier(2, 0, false), 2, "a relay that missed the award changes nothing");
755        assert_eq!(next_tier(3, 1, false), 3, "nor does one that only holds an older award");
756        assert_eq!(next_tier(2, 0, true), 0, "a seen revocation takes it away");
757        assert_eq!(next_tier(3, 2, true), 2, "or down to what remains");
758    }
759
760    #[test]
761    fn a_failed_settings_read_keeps_the_perks_it_last_saw() {
762        let (_tmp, _guard, _me) = init_test_db();
763        store_bug_hunter_tier(2);
764        assert_eq!(effective_tier(), 2);
765
766        rename_settings("settings", "settings_away");
767        assert_eq!(bug_hunter_tier(), 2, "an unreadable cache is not an absent badge");
768        assert_eq!(effective_tier(), 2);
769        assert_eq!(crate::emoji_packs::effective_max_emojis_per_pack(), 60);
770        assert_eq!(crate::emoji_packs::effective_max_equipped_packs(), 9);
771        assert_eq!(crate::pinned_chats::effective_max_pinned(), 9);
772        rename_settings("settings_away", "settings");
773
774        store_vector_badge();
775        rename_settings("settings", "settings_away");
776        assert!(has_vector_badge());
777        assert_eq!(effective_tier(), 3);
778        rename_settings("settings_away", "settings");
779    }
780
781    #[test]
782    fn v2026_claims_count_inside_the_window() {
783        assert!(is_valid_v2026_claim(V2026_CONTENT, V2026_START));
784        assert!(is_valid_v2026_claim(V2026_CONTENT, V2026_END - 1));
785        assert!(!is_valid_v2026_claim(V2026_CONTENT, V2026_START - 1), "before the window");
786        assert!(!is_valid_v2026_claim(V2026_CONTENT, V2026_END), "the window is half-open");
787        assert!(!is_valid_v2026_claim("fawkes_badge_claimed", V2026_START), "another badge's claim");
788
789    }
790
791    #[test]
792    fn v2026_grants_the_first_tier_and_no_more() {
793        assert_eq!(badge_tier(0, false, true), 1);
794        assert_eq!(badge_tier(2, false, true), 2, "a higher Bug Hunter tier wins");
795        assert_eq!(badge_tier(0, true, true), 3, "and 2025's full premium");
796        assert_eq!(badge_tier(0, false, false), 0);
797    }
798
799    #[test]
800    fn colour_only_sends_with_a_badge() {
801        let (_tmp, _guard, _me) = init_test_db();
802        let colours = |text: &str| {
803            let (plain, spans) = crate::text_spans::extract_own(text);
804            (plain, spans.iter().filter(|s| matches!(s, crate::text_spans::TextSpan::Color(_))).count())
805        };
806        assert!(!has_text_effects());
807        assert_eq!(colours("I <rainbow>love</rainbow> it"), ("I love it".into(), 0), "the markup goes, its colour with it");
808        store_bug_hunter_tier(1);
809        assert!(has_text_effects());
810        assert_eq!(colours("I <rainbow>love</rainbow> it"), ("I love it".into(), 1));
811    }
812
813    #[test]
814    fn perks_hold_across_a_restart_with_no_network() {
815        let (_tmp, _guard, me) = init_test_db();
816        store_bug_hunter_tier(3);
817        let account = me.public_key().to_bech32().unwrap();
818
819        // A relaunch: a new session over the same database, nothing fetched.
820        crate::db::close_database();
821        crate::db::set_current_account(account.clone()).unwrap();
822        crate::db::init_database(&account).unwrap();
823        crate::state::set_my_public_key(me.public_key());
824        assert_eq!(bug_hunter_tier(), 3);
825        assert_eq!(effective_tier(), 3);
826        assert_eq!(crate::emoji_packs::effective_max_emojis_per_pack(), 90);
827        assert_eq!(crate::emoji_packs::effective_max_equipped_packs(), usize::MAX);
828    }
829
830    #[test]
831    fn a_live_look_at_our_own_awards_raises_the_cache_and_never_lowers_it() {
832        let (_tmp, _guard, me) = init_test_db();
833        assert_eq!(effective_tier(), 0);
834
835        note_own_bug_hunter(&me.public_key(), 2);
836        assert_eq!(bug_hunter_tier(), 2, "the badge the profile shows carries its perks");
837        assert_eq!(crate::emoji_packs::effective_max_emojis_per_pack(), 60);
838
839        note_own_bug_hunter(&me.public_key(), 1);
840        note_own_bug_hunter(&me.public_key(), 0);
841        assert_eq!(bug_hunter_tier(), 2, "a lower live view is a relay that missed the award");
842
843        note_own_bug_hunter(&Keys::generate().public_key(), 3);
844        assert_eq!(bug_hunter_tier(), 2, "someone else's awards are not ours");
845    }
846
847    #[test]
848    fn perks_stay_with_their_account_across_a_swap() {
849        let (_tmp, _guard, a) = init_test_db();
850        store_bug_hunter_tier(3);
851        store_vector_badge();
852        assert_eq!(effective_tier(), 3);
853
854        let b = Keys::generate();
855        let b_npub = b.public_key().to_bech32().unwrap();
856        crate::db::close_database();
857        crate::db::set_current_account(b_npub.clone()).unwrap();
858        crate::db::init_database(&b_npub).unwrap();
859        crate::state::set_my_public_key(b.public_key());
860        assert_eq!(effective_tier(), 0, "another account's badges never carry over");
861        assert!(!has_vector_badge());
862        assert_eq!(crate::emoji_packs::effective_max_emojis_per_pack(), 30);
863
864        let a_npub = a.public_key().to_bech32().unwrap();
865        crate::db::close_database();
866        crate::db::set_current_account(a_npub.clone()).unwrap();
867        crate::db::init_database(&a_npub).unwrap();
868        crate::state::set_my_public_key(a.public_key());
869        assert_eq!(effective_tier(), 3, "and swapping back finds them where they were");
870    }
871}