Skip to main content

vector_core/community/v2/
realtime.rs

1//! v2 realtime — the `authors`-based live subscription + dispatch.
2//!
3//! v2 addresses planes by their group pubkey (CORD-01), not v1's `#z` tag, so
4//! the subscription is `{kinds:[1059,21059], authors:[…plane pubkeys…]}`. A
5//! received event is routed to the owning community and handed to the shared
6//! [`inbound::dispatch_wrap`], which fires the protocol-agnostic
7//! `InboundEventHandler` the SDK's `on_message` consumes.
8//!
9//! The kind-1059 dispatch rule (CLAUDE.md A4): the listen loop tries this v2
10//! path for events on the v2 subscription; DM gift wraps and 3313 Direct Invites
11//! (both `#p=me`) stay on the DM subscription — the author-set here never
12//! includes an identity key, so the two never collide.
13
14use std::collections::HashSet;
15use std::sync::{Arc, LazyLock, Mutex as StdMutex};
16
17use nostr_sdk::prelude::{Client, Event, Filter, Kind, PublicKey, RelayStatus, RelayUrl, SubscriptionId};
18use tokio::sync::mpsc::UnboundedSender;
19use tokio::sync::Mutex;
20
21use super::community::CommunityV2;
22use super::stream;
23use super::{derive, inbound};
24use crate::community::{CommunityId, ConcordProtocol, Epoch};
25use crate::event_handler::InboundEventHandler;
26use crate::state::SessionGuard;
27use crate::ClientRelayExt;
28
29/// The targeted subscription id (streams on desktop).
30static V2_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
31/// The pool-wide subscription id (the path that streams on Android).
32static V2_POOLWIDE_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
33/// The current author-set (sorted hex) — an unchanged set skips a churny
34/// unsubscribe+resubscribe, exactly like v1's `COMMUNITY_SUB_SET`.
35static V2_SUB_SET: LazyLock<Mutex<Vec<String>>> = LazyLock::new(|| Mutex::new(Vec::new()));
36
37/// Session generation of the last COMPLETED [`refresh_subscription`] pass, or
38/// `u64::MAX` before any. Generation-keyed rather than a bare bool so an account
39/// swap invalidates it automatically — a per-account global that survived a swap
40/// would report account A's readiness for account B.
41static V2_SUB_READY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
42
43#[inline]
44fn mark_subscription_ready() {
45    V2_SUB_READY_GEN.store(
46        crate::state::SessionGuard::capture().generation(),
47        std::sync::atomic::Ordering::Release,
48    );
49}
50
51/// Whether the v2 Community subscription pass has COMPLETED for the active
52/// session: live channel events are being delivered (or there is genuinely
53/// nothing to subscribe to). `false` during the cold-start window where the
54/// relay-connect wait + stream-auth priming are still running — the state a
55/// health-checking bot could previously not distinguish from "subscribed to
56/// nothing".
57pub fn subscription_ready() -> bool {
58    V2_SUB_READY_GEN.load(std::sync::atomic::Ordering::Acquire)
59        == crate::state::SessionGuard::capture().generation()
60}
61/// Outer-wrap ids already dispatched, so the handler fires EXACTLY ONCE per
62/// message. The relay pool delivers the same wrap under both the targeted and
63/// pool-wide subs and from every relay independently, so without this a bot's
64/// `on_message` (and its reply) would run several times per message — the v1
65/// community path and the DM path dedup by outer id for the same reason. Cleared
66/// on session swap; coarsely bounded (a message's duplicates all arrive within a
67/// short window, so a recent-set suffices).
68static V2_SEEN_WRAPS: LazyLock<Mutex<HashSet<[u8; 32]>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
69/// Bound on [`V2_SEEN_WRAPS`] before a coarse flush.
70const SEEN_WRAPS_CAP: usize = 8192;
71/// The per-community follow QUEUE. dispatch, boot catch-up, reconnect, and manual
72/// sync all just [`enqueue_follow`] — non-blocking + coalesced. A single spawned
73/// worker ([`spawn_follow_worker`]) drains it and runs one combined rekey+control
74/// follow per community at a time, so two triggers can never concurrently
75/// whole-row-save and clobber each other. This replaces the old gate/rerun/
76/// spawn-vs-await machinery: an enqueue never blocks its caller, and a junk-wrap
77/// flood coalesces to at most one queued + one running follow per community.
78/// Reset on session swap (the worker exits when its `SessionGuard` invalidates or
79/// its channel closes).
80static V2_FOLLOW_TX: LazyLock<StdMutex<Option<UnboundedSender<CommunityId>>>> = LazyLock::new(|| StdMutex::new(None));
81/// Community ids currently queued or processing — coalesces a burst to one follow.
82static V2_FOLLOW_PENDING: LazyLock<StdMutex<HashSet<[u8; 32]>>> = LazyLock::new(|| StdMutex::new(HashSet::new()));
83/// Per-community follow serialization, shared by the queue worker AND the inline
84/// (headless) follow path. The worker-vs-inline CHOICE is a benign race
85/// (`follow_worker_running` is check-then-act; a worker can spawn right after a
86/// `false`), so correctness can't ride on it: whichever path runs, the follow body
87/// executes under this lock and two follows of one community can never interleave
88/// their whole-row saves. Bounded by the held-community count; reset on swap.
89static V2_FOLLOW_LOCKS: LazyLock<StdMutex<std::collections::HashMap<[u8; 32], Arc<Mutex<()>>>>> =
90    LazyLock::new(|| StdMutex::new(std::collections::HashMap::new()));
91
92/// The follow lock for one community (created on first use).
93pub(crate) fn follow_lock(id: &CommunityId) -> Arc<Mutex<()>> {
94    V2_FOLLOW_LOCKS.lock().unwrap().entry(id.0).or_default().clone()
95}
96
97/// The author set the live v2 subscription CURRENTLY carries (sorted hex).
98/// Diagnostics: comparing this against the freshly-derived plane authors is the
99/// one-glance test for "did a rotation leave this client subscribed to a dead
100/// epoch" — the failure that otherwise only shows up as silent missing events.
101pub async fn subscribed_author_set() -> Vec<String> {
102    V2_SUB_SET.lock().await.clone()
103}
104
105/// Diagnostics: run the three follow stages once for `id` UNDER the follow lock
106/// (so it can't race the worker into a whole-row clobber) and return each
107/// stage's outcome as a display string. Reloads freshly-persisted state between
108/// stages, exactly like [`follow_community`]. Mutating — same writes a live
109/// follow makes; the lock serializes it against the worker.
110#[cfg(debug_assertions)]
111pub async fn debug_run_follow_stages(id: &CommunityId, session: &SessionGuard) -> (String, String, String) {
112    let lock = follow_lock(id);
113    let _guard = lock.lock().await;
114    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
115
116    let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
117        return ("community gone".into(), "-".into(), "-".into());
118    };
119    let rekeys = match super::service::follow_rekeys(&transport, &c, session).await {
120        Ok(f) => format!(
121            "Ok(updated={} self_removed={} dissolved={})",
122            f.updated.as_ref().map(|u| format!("root_e{}", u.root_epoch.0)).unwrap_or_else(|| "no".into()),
123            f.self_removed, f.dissolved
124        ),
125        Err(e) => format!("ERR: {e}"),
126    };
127    let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
128        return (rekeys, "community gone".into(), "-".into());
129    };
130    let control = match super::service::follow_control(&transport, &c, session).await {
131        Ok(v) => format!("Ok(changed={})", v.is_some()),
132        Err(e) => format!("ERR: {e}"),
133    };
134    let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
135        return (rekeys, control, "community gone".into());
136    };
137    let guestbook = match super::service::sync_guestbook(&transport, &c, session).await {
138        Ok(fresh) => format!("Ok(fresh={})", fresh.len()),
139        Err(e) => format!("ERR: {e}"),
140    };
141    (rekeys, control, guestbook)
142}
143
144pub async fn subscription_id() -> Option<SubscriptionId> {
145    V2_SUB_ID.lock().await.clone()
146}
147
148pub async fn poolwide_subscription_id() -> Option<SubscriptionId> {
149    V2_POOLWIDE_SUB_ID.lock().await.clone()
150}
151
152/// Clear the v2 realtime state on a session reset (called from `swap_session`
153/// alongside v1's clear), so a stale sub id / author-set can't leak across accounts.
154pub async fn clear() {
155    *V2_SUB_ID.lock().await = None;
156    *V2_POOLWIDE_SUB_ID.lock().await = None;
157    V2_SUB_SET.lock().await.clear();
158    V2_SEEN_WRAPS.lock().await.clear();
159    // Drop the queue sender so the worker's channel closes and it exits (its
160    // SessionGuard also invalidates); the next login spawns a fresh worker.
161    *V2_FOLLOW_TX.lock().unwrap() = None;
162    V2_FOLLOW_PENDING.lock().unwrap().clear();
163    V2_FOLLOW_LOCKS.lock().unwrap().clear();
164    // Account A's stream keys must not keep authenticating (or answering relay
165    // challenges) once account B is live.
166    super::streamauth::clear();
167}
168
169/// Every plane pubkey a set of v2 communities publishes under that
170/// [`inbound::dispatch_wrap`] handles — the subscription author-set. Per
171/// community: the guestbook, the control plane, and each channel's current
172/// Chat-Plane address. Pure + deterministic (deduped, sorted) — the testable core.
173///
174/// The **control plane** rides here so a long-running bot follows metadata +
175/// public-channel edits live ([`super::service::follow_control`] re-folds on a
176/// recognized wrap), and the next-epoch rekey planes ride via [`rekey_authors`]
177/// (each subscribed author has its `dispatch_wrap` arm — never one without the
178/// other).
179pub fn plane_authors(communities: &[CommunityV2]) -> Vec<PublicKey> {
180    let mut out = Vec::new();
181    for c in communities {
182        out.push(derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).pk());
183        out.push(control_author(c));
184        // The dissolved plane (CORD-02 §9) — so a mid-session dissolution seals live.
185        out.push(super::derive::dissolved_group_key(c.id()).pk());
186        for ch in &c.channels {
187            // A KEYLESS private channel has no readable chat plane — channel_secret's
188            // root fallback would subscribe the PUBLIC plane for it. Its rekey plane
189            // (below) is still watched, which is how its key arrives.
190            if ch.private && ch.key.is_none() {
191                continue;
192            }
193            let (secret, epoch) = c.channel_secret(ch);
194            out.push(derive::channel_group_key(&secret, &ch.id, epoch).pk());
195        }
196        out.extend(rekey_authors(c));
197    }
198    out.sort_by_key(|p| p.to_hex());
199    out.dedup();
200    out
201}
202
203/// This community's Control Plane address at the current root epoch — the single
204/// source of truth shared by [`plane_authors`] (subscribe) and
205/// [`inbound::dispatch_wrap`] (recognize) so the two can't drift.
206pub(crate) fn control_author(c: &CommunityV2) -> PublicKey {
207    derive::control_group_key(&c.community_root, c.id(), c.root_epoch).pk()
208}
209
210/// The next-epoch rekey plane addresses for a community: the base rotation
211/// (`root_epoch + 1`) and each Private channel's rotation (`channel epoch + 1`),
212/// both under the CURRENT community_root. This is the single source of truth for
213/// which rekey wraps we subscribe AND recognize (`inbound::dispatch_wrap` calls
214/// it), so the two can never drift. A Public channel has no independent rotation
215/// (it rides the base), so only Private channels contribute a channel address.
216pub(crate) fn rekey_authors(c: &CommunityV2) -> Vec<PublicKey> {
217    // saturating: a bundle's epoch isn't covered by the community_id commitment, so
218    // it's attacker-influenced — never let `epoch + 1` overflow (a u64::MAX epoch
219    // just yields a dead address, never a panic).
220    let mut out = vec![derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(c.root_epoch.0.saturating_add(1))).pk()];
221    for ch in &c.channels {
222        if ch.private {
223            out.push(derive::channel_rekey_group_key(&c.community_root, &ch.id, Epoch(ch.epoch.0.saturating_add(1))).pk());
224        }
225    }
226    out
227}
228
229/// Load every locally-held, LIVE **v2** community (dispatching each id by its
230/// stored protocol). The realtime layer folds these into the subscription +
231/// routing, so excluding a DISSOLVED community here is what enforces CORD-02 §9
232/// on the receive side: its chat/control/rekey planes stop being subscribed and
233/// an arriving wrap for it is `NotOurs` (dropped, never honored). Held keys still
234/// open old history through the explicit read paths — this only stops NEW events.
235pub fn load_held_v2() -> Vec<CommunityV2> {
236    let ids = crate::db::community::list_community_ids().unwrap_or_default();
237    ids.iter()
238        .filter(|id| matches!(crate::db::community::community_protocol(id).ok().flatten(), Some(ConcordProtocol::V2)))
239        .filter(|id| !crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false))
240        .filter_map(|id| crate::db::community::load_community_v2(id).ok().flatten())
241        .collect()
242}
243
244/// Refresh the v2 subscription for the held communities: register
245/// `{kinds:[1059,21059], authors:[…]}` on their relays (targeted + pool-wide,
246/// mirroring v1). Idempotent on an unchanged author-set.
247pub async fn refresh_subscription(client: &Client) {
248    // Phase 1, LOCK-FREE: make sure the community relays are added + connected —
249    // the slow part (a connect wait of up to ~6s). Holding the sub locks across
250    // this stalled every concurrent dispatch/refresh behind one caller's connect.
251    {
252        let communities = load_held_v2();
253        let mut relays: Vec<String> = communities.iter().flat_map(|c| c.relays.iter().cloned()).collect();
254        relays.sort();
255        relays.dedup();
256        if !relays.is_empty() {
257            // Community relays ride GOSSIP|PING (warm but excluded from pool-wide DM ops).
258            for r in &relays {
259                let _ = client.add_managed_relay(r.as_str()).capabilities(crate::community_relay_capabilities()).await;
260            }
261            client.connect().await;
262            // Wait briefly for at least one relay to actually connect (a subscribe
263            // against a still-connecting relay silently fails to register — same
264            // trap as v1).
265            let wanted: Vec<RelayUrl> = relays.iter().filter_map(|r| RelayUrl::parse(r).ok()).collect();
266            for _ in 0..24 {
267                let pool = client.relays().all().await;
268                if wanted.iter().any(|u| pool.get(u).map(|r| r.status() == RelayStatus::Connected).unwrap_or(false)) {
269                    break;
270                }
271                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
272            }
273            // Register every held plane's key BEFORE subscribing, so the responder
274            // can answer any NIP-42 challenge our REQs trigger. Cheap + local.
275            for c in &communities {
276                super::streamauth::register_community(c);
277            }
278        }
279    }
280
281    // Phase 2, LOCKED + bounded (no connect waits): RE-snapshot the held state
282    // INSIDE the sub locks — the follow worker runs concurrently and may have just
283    // adopted a rotation, so the LAST locker must read the freshest persisted
284    // authors. An out-of-lock read lets a stale caller commit an old author-set
285    // over a fresh one and silently mute a rotated community. (A community whose
286    // relays appeared between the phases subscribes now and connects on the next
287    // refresh — the follow that discovers it always triggers one.)
288    let mut sub_guard = V2_SUB_ID.lock().await;
289    let mut set_guard = V2_SUB_SET.lock().await;
290
291    let communities = load_held_v2();
292    let authors = plane_authors(&communities);
293    let mut relays: Vec<String> = communities.iter().flat_map(|c| c.relays.iter().cloned()).collect();
294    relays.sort();
295    relays.dedup();
296
297    let mut new_set: Vec<String> = authors.iter().map(|p| p.to_hex()).collect();
298    new_set.sort();
299
300    // Unchanged-set fast path — but only when BOTH subs actually registered (a
301    // failed pool-wide subscribe would otherwise stay absent until the author-set
302    // changes, and Android streams via the pool-wide path).
303    if sub_guard.is_some() && *set_guard == new_set && (authors.is_empty() || V2_POOLWIDE_SUB_ID.lock().await.is_some()) {
304        mark_subscription_ready(); // an unchanged live sub is a completed pass
305        return; // the pool re-applies the live subs across reconnects.
306    }
307    if let Some(old) = sub_guard.take() {
308        let _ = client.unsubscribe(&old).await;
309    }
310    *set_guard = new_set;
311
312    if authors.is_empty() {
313        if let Some(old_pw) = V2_POOLWIDE_SUB_ID.lock().await.take() {
314            let _ = client.unsubscribe(&old_pw).await;
315        }
316        // Completed with nothing to hear: READY with zero planes, which is a
317        // different observable state from "still connecting".
318        mark_subscription_ready();
319        return;
320    }
321
322    let filter = Filter::new()
323        .kinds([Kind::Custom(stream::KIND_WRAP), Kind::Custom(stream::KIND_WRAP_EPHEMERAL)])
324        .authors(authors)
325        .limit(0);
326
327    {
328        let mut pw = V2_POOLWIDE_SUB_ID.lock().await;
329        if let Some(old) = pw.take() {
330            let _ = client.unsubscribe(&old).await;
331        }
332        if let Ok(out) = client.subscribe(filter.clone()).await {
333            *pw = Some(out.value);
334        }
335    }
336    if let Ok(out) = client
337        .subscribe(nostr_sdk::prelude::ReqTarget::manual(
338            relays.iter().cloned().map(|u| (u, vec![filter.clone()])),
339        ))
340        .await
341    {
342        *sub_guard = Some(out.value);
343    }
344    mark_subscription_ready();
345    drop(set_guard);
346    drop(sub_guard);
347
348    // AUTH-gating relays serve the planes only to a stream-authenticated
349    // connection, and a live subscription isn't auto-retried after the gate. The
350    // priming used to run BEFORE the subscribe, which gated the whole registration
351    // on the slowest relay: a set with dead or auth-refusing members left the
352    // client deaf for a minute while healthy relays sat idle. Prime in the
353    // BACKGROUND instead — healthy relays stream from the registration above, and
354    // each gating relay's auth completion re-sends the subs (`resubscribe_relay`
355    // via the responder), so it joins the moment IT is ready, gating nobody else.
356    prime_auth_in_background(client, relays);
357}
358
359/// In-flight coalescer for the background auth prime: boot fires many refreshes
360/// (dispatch, absorb, reconnect) and each spawning its own prime would stampede
361/// the gating relays with duplicate auth fetches.
362static PRIME_IN_FLIGHT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
363
364fn prime_auth_in_background(client: &Client, relays: Vec<String>) {
365    use std::sync::atomic::Ordering;
366    if relays.is_empty() || PRIME_IN_FLIGHT.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
367        return;
368    }
369    let client = client.clone();
370    let session = crate::state::SessionGuard::capture();
371    tokio::spawn(async move {
372        if session.is_valid() {
373            super::streamauth::prime_auth(&client, &relays).await;
374        }
375        PRIME_IN_FLIGHT.store(false, Ordering::Release);
376    });
377}
378
379/// Re-send the CURRENT v2 subscriptions (same ids) to ONE relay. An AUTH-gating
380/// relay CLOSEs a sub REQ that raced ahead of the stream AUTHs on a fresh
381/// connection, and it never re-challenges once the connection is authenticated —
382/// so the moment the streams finish authenticating is exactly when the subs must
383/// be re-sent. nostr-sdk re-sends them only when ITS OWN auth completes (it
384/// can't see ours), which usually wins by socket ordering; this makes the heal
385/// deterministic and independent of that internal. Same-id REQs are idempotent.
386pub(crate) async fn resubscribe_relay(client: &Client, relay: &RelayUrl) {
387    let targeted = V2_SUB_ID.lock().await.clone();
388    let poolwide = V2_POOLWIDE_SUB_ID.lock().await.clone();
389    if targeted.is_none() && poolwide.is_none() {
390        return; // nothing subscribed yet — the first refresh registers on an authed socket.
391    }
392    let communities = load_held_v2();
393    let authors = plane_authors(&communities);
394    if authors.is_empty() {
395        return;
396    }
397    let filter = Filter::new()
398        .kinds([Kind::Custom(stream::KIND_WRAP), Kind::Custom(stream::KIND_WRAP_EPHEMERAL)])
399        .authors(authors)
400        .limit(0);
401    for id in [targeted, poolwide].into_iter().flatten() {
402        let _ = client
403            .subscribe(nostr_sdk::prelude::ReqTarget::single(relay.clone(), [filter.clone()]))
404            .with_id(id)
405            .await;
406    }
407}
408
409/// Route an arriving v2 wrap: find the held community whose plane it opens under
410/// and fire the matching handler callback (via the shared bridge). Persistence to
411/// the local DB is deferred (bots deliver via the callback; GUI history is v1 for
412/// now). `session` gates against a mid-flight account swap.
413pub async fn dispatch_event(session: &SessionGuard, event: Event, handler: Arc<dyn InboundEventHandler>) {
414    let Some(my_pk) = crate::my_public_key() else {
415        return;
416    };
417    if !session.is_valid() {
418        return;
419    }
420    // Fire EXACTLY ONCE per wrap: the pool re-delivers the same event under both
421    // subs and from every relay. `insert` returns false if already dispatched.
422    {
423        let mut seen = V2_SEEN_WRAPS.lock().await;
424        if !seen.insert(event.id.to_bytes()) {
425            return;
426        }
427        if seen.len() > SEEN_WRAPS_CAP {
428            let keep = event.id.to_bytes();
429            seen.clear();
430            seen.insert(keep);
431        }
432    }
433    let communities = load_held_v2();
434    for c in &communities {
435        match inbound::dispatch_wrap(&event, c, &my_pk, &*handler) {
436            inbound::DispatchedV2::NotOurs => continue,
437            // A control OR a rekey wrap: just enqueue a follow for this community.
438            // Non-blocking + coalesced — the single follow worker serializes control
439            // and rekey per community (no concurrent whole-row clobber) off this hot
440            // path, so a junk-wrap flood can't head-of-line-block the notification loop.
441            inbound::DispatchedV2::Control { .. } | inbound::DispatchedV2::Rekey { .. } => {
442                enqueue_follow(c.id());
443                return;
444            }
445            inbound::DispatchedV2::Dissolved { community_id } => {
446                // Death wins (CORD-02 §9): seal read-only + surface the grave, ONCE
447                // (a re-wrapped tombstone with a fresh outer id must not re-fire the
448                // handler). The next load_held_v2 excludes it, so its planes also
449                // stop being subscribed + routed.
450                if crate::db::community::set_community_dissolved(&community_id).unwrap_or(false) {
451                    handler.on_community_dissolved(&community_id);
452                    if let Some(client) = crate::state::nostr_client() {
453                        refresh_subscription(&client).await;
454                    }
455                }
456                return;
457            }
458            // A chat event, opened but NOT yet applied: persist first (dedup by inner
459            // id + the author-scoped edit/delete checks), then fire the callback from
460            // the outcome — v1's exact model. A re-wrapped duplicate (any keyholder
461            // can re-seal a signed rumor into a fresh 1059), the relay echo of our
462            // own send, or a forged edit/delete yields no outcome and re-fires
463            // nothing.
464            inbound::DispatchedV2::Chat { channel_id, event } => {
465                if !session.is_valid() {
466                    return;
467                }
468                match inbound::persist_chat_event(&event, &channel_id, &my_pk, session).await {
469                    Some(inbound::ChatPersist::New(message)) => handler.on_community_message(&channel_id, &message, true),
470                    // A reaction or an edit: the folded TARGET row (its id is the
471                    // target's) — the same payload v1 hands this callback. Both come
472                    // back out of STATE, whose compact form drops the quoted
473                    // attachment's extension, so re-resolve before rendering.
474                    Some(inbound::ChatPersist::Updated { mut message, .. }) => {
475                        let _ = crate::db::events::populate_reply_context(&mut message).await;
476                        handler.on_community_update(&channel_id, &message.id, &message);
477                    }
478                    // An un-react re-renders the PARENT (its chips changed) — the
479                    // same surface a landed reaction drives.
480                    Some(inbound::ChatPersist::ReactionRemoved { mut message, .. }) => {
481                        let _ = crate::db::events::populate_reply_context(&mut message).await;
482                        handler.on_community_update(&channel_id, &message.id, &message);
483                    }
484                    Some(inbound::ChatPersist::Removed(target_id)) => handler.on_community_removed(&channel_id, &target_id),
485                    None => {}
486                }
487                return;
488            }
489            inbound::DispatchedV2::Presence { .. } => {
490                // Live membership motion: fold it into the persisted Guestbook so
491                // the memberlist stays a local read (the presence callback already
492                // fired inline). Reopen here — the dispatcher stays pure — and
493                // refresh the overview when it lands.
494                if !session.is_valid() {
495                    return;
496                }
497                let gb = derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch);
498                if let Ok(opened) = super::stream::open_wrap(&event, &gb) {
499                    if let Ok(ev) = super::guestbook::parse_guestbook_event(&opened) {
500                        let changed = super::service::ingest_guestbook_event(c, ev, event.created_at.as_secs()).unwrap_or(false);
501                        if changed && session.is_valid() {
502                            handler.on_community_refreshed(&crate::simd::hex::bytes_to_hex_32(&c.id().0));
503                        }
504                    }
505                }
506                return;
507            }
508            inbound::DispatchedV2::Kick { target } => {
509                if !session.is_valid() {
510                    return;
511                }
512                let gb = derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch);
513                let Ok(opened) = super::stream::open_wrap(&event, &gb) else { return };
514                let Ok(ev) = super::guestbook::parse_guestbook_event(&opened) else { return };
515                if !super::service::ingest_guestbook_event(c, ev, event.created_at.as_secs()).unwrap_or(false) {
516                    return;
517                }
518                if !session.is_valid() {
519                    return;
520                }
521                let community_id = crate::simd::hex::bytes_to_hex_32(&c.id().0);
522                // Self-removal rides the AUTHORIZED fold, never the wrap: the store takes
523                // any Kick rumor, so acting on arrival would let any member evict anyone.
524                // Fail-closed — a kick our roster can't justify leaves us in place.
525                //
526                // The COALESCE verdict, not the memberlist: on a rejoin the store starts
527                // empty while the control fold has already re-derived our old ban mark, so
528                // the memberlist legitimately excludes us for the window before the
529                // Guestbook catches up. A stale Kick landing in that window would read as
530                // an authorized eviction. Coalescing asks only what our latest authorized
531                // entry is, so a fresh Join beats the old Kick and an empty store decides
532                // nothing.
533                let evicted = my_pk == target && super::service::stored_kick_verdict(c, &my_pk);
534                if evicted {
535                    // WARN, not info: `log_info!` is compiled out in release, and a
536                    // self-eviction is exactly the destructive, hard-to-diagnose event
537                    // that must leave a trace on a shipped build.
538                    crate::log_warn!(
539                        "[v2:teardown {}] KICK: the authorized guestbook fold rules us kicked",
540                        &community_id[..8.min(community_id.len())]
541                    );
542                    handler.on_community_self_removed(&community_id);
543                } else {
544                    crate::log_debug!(
545                        "[v2:kick {}] declined: target={} is not ruled kicked by the fold",
546                        &community_id[..8.min(community_id.len())], &target.to_hex()[..8]
547                    );
548                    handler.on_community_refreshed(&community_id);
549                }
550                return;
551            }
552            _ => return, // typing (and non-surfaced guestbook kinds) handled inline by the dispatcher.
553        }
554    }
555}
556
557/// Whether a live follow worker is draining the queue (a `listen()` is running).
558/// Headless callers use this to run a follow inline instead of enqueueing into
559/// the void.
560pub fn follow_worker_running() -> bool {
561    V2_FOLLOW_TX.lock().unwrap().as_ref().map(|tx| !tx.is_closed()).unwrap_or(false)
562}
563
564/// Queue a follow for `id` — NON-BLOCKING + coalesced. A burst (or a junk-wrap
565/// flood) collapses to at most one queued + one running follow per community. A
566/// no-op if no worker is running (no live `listen()`). Callers: dispatch,
567/// boot/reconnect catch-up, manual sync — none of them block or touch a lock for
568/// longer than the enqueue.
569pub fn enqueue_follow(id: &CommunityId) {
570    let mut pending = V2_FOLLOW_PENDING.lock().unwrap();
571    if !pending.insert(id.0) {
572        return; // already queued or processing — coalesce.
573    }
574    match V2_FOLLOW_TX.lock().unwrap().as_ref() {
575        Some(tx) if tx.send(*id).is_ok() => {}
576        _ => {
577            // No worker yet — PARK the id in the pending set instead of
578            // dropping it; spawn_follow_worker drains parked ids into its
579            // fresh queue. The boot sweep's enqueues race notifs' worker
580            // spawn (they fire the moment init completes), so a pre-worker
581            // enqueue must defer, never silently vanish — a dropped boot
582            // refold leaves an offline-rotated community wedged at its old
583            // epoch until some live event happens to trigger a dispatch.
584        }
585    }
586}
587
588/// Spawn the single follow worker for this session. Installs the queue sender and
589/// drains it, running one combined follow per community at a time. Replacing the
590/// sender (a re-`listen()`) or [`clear`] (a swap) closes the old channel so the old
591/// worker exits; the captured `SessionGuard` also stops it. Idempotent per session.
592pub fn spawn_follow_worker(handler: Arc<dyn InboundEventHandler>) {
593    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
594    // Re-send every pending id into the fresh queue: parked pre-worker
595    // enqueues AND anything a replaced worker's dropped channel still owed.
596    // Entries stay in the set — the worker removes each as it starts
597    // processing, preserving the coalescing invariant.
598    {
599        let pending = V2_FOLLOW_PENDING.lock().unwrap();
600        for id in pending.iter() {
601            let _ = tx.send(CommunityId(*id));
602        }
603    }
604    *V2_FOLLOW_TX.lock().unwrap() = Some(tx);
605    let session = SessionGuard::capture();
606    tokio::spawn(async move {
607        while let Some(id) = rx.recv().await {
608            if !session.is_valid() {
609                break;
610            }
611            // Remove from pending BEFORE running, so a trigger arriving DURING the
612            // follow re-enqueues (and is processed after) rather than being lost.
613            V2_FOLLOW_PENDING.lock().unwrap().remove(&id.0);
614            follow_community(&session, &id, &*handler).await;
615        }
616    });
617}
618
619/// One combined rekey-then-control follow for a community, each pass against the
620/// FRESHLY-RELOADED persisted state (never a stale clone, so the two planes can't
621/// lose each other's writes). Rekey runs first: a base adopt moves the control
622/// address, and a self-removal tears the community down (skipping control). No-op
623/// without a live client — unit tests drive `service::follow_control` /
624/// `follow_rekeys` directly.
625async fn follow_community(session: &SessionGuard, id: &CommunityId, handler: &dyn InboundEventHandler) {
626    let Some(client) = crate::state::nostr_client() else {
627        return;
628    };
629    // Serialize against an inline (headless) follow of the same community — the
630    // queue only serializes triggers routed THROUGH it.
631    let lock = follow_lock(id);
632    let _guard = lock.lock().await;
633    let community_id = crate::simd::hex::bytes_to_hex_32(&id.0);
634    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
635
636    // Rekey first (fresh DB state).
637    let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
638        return; // community gone (left / removed).
639    };
640    match super::service::follow_rekeys(&transport, &current, session).await {
641        // A tombstone surfaced during catch-up (an offline member learning of a
642        // death) — the flag is set; seal + surface, and stop following.
643        Ok(follow) if follow.dissolved => {
644            if !session.is_valid() {
645                return;
646            }
647            crate::log_warn!("[v2:teardown {}] DISSOLVED tombstone", &community_id[..8.min(community_id.len())]);
648            handler.on_community_dissolved(&community_id);
649            return;
650        }
651        Ok(follow) if follow.self_removed => {
652            if !session.is_valid() {
653                return;
654            }
655            crate::log_warn!("[v2:teardown {}] REKEY EXCLUSION: an authorized rotation left us out", &community_id[..8.min(community_id.len())]);
656            let _ = crate::db::community::delete_community(&community_id);
657            refresh_subscription(&client).await;
658            handler.on_community_self_removed(&community_id);
659            return;
660        }
661        Ok(follow) if follow.updated.is_some() => {
662            if !session.is_valid() {
663                return;
664            }
665            refresh_subscription(&client).await;
666            handler.on_community_refreshed(&community_id);
667        }
668        Ok(_) => {}
669        Err(e) => {
670            // Surfaced, not swallowed: with EOSE-verified fetches an AUTH-gated
671            // or dead rekey plane now reports here instead of masquerading as
672            // "no rotation" — the exact signature of an epoch wedge.
673            crate::log_warn!("[v2:follow {}] rekey follow failed (will retry on next trigger): {}", &community_id[..8.min(community_id.len())], e);
674            return;
675        }
676    }
677
678    // Control second, on the (possibly new-root) freshly-reloaded state.
679    let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
680        return;
681    };
682    let control_changed = matches!(
683        super::service::follow_control(&transport, &current, session).await,
684        Ok(Some(_))
685    );
686    if !session.is_valid() {
687        return;
688    }
689    // Re-judge parked key vends on EVERY pass, not only when the fold moved. A
690    // vend that lands AFTER its Grant folded has nothing left to change the
691    // control plane, so gating this on `changed` strands it until some unrelated
692    // edition happens by (CORD-03 "delivered on grant").
693    if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
694        let keyed = super::service::absorb_parked_channel_keys(&folded, session);
695        if !keyed.is_empty() {
696            crate::log_info!(
697                "[v2:follow {}] adopted {} vended private-channel key(s)",
698                &community_id[..8.min(community_id.len())],
699                keyed.len()
700            );
701            // A newly-keyed channel adds its chat plane to the readable set, and
702            // the live subscription is addressed BY that set — without a rebuild
703            // we hold the key and still never hear the channel. Independent of
704            // `control_changed`: adopting a parked vend changes no control state.
705            refresh_subscription(&client).await;
706        }
707        for ch in keyed {
708            let hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
709            // Read what was said while we were locked out. The live subscription
710            // only carries what arrives NEXT, so without this a member granted
711            // access walks into a room that looks empty. The count rides the hook:
712            // backfilled history is NOT dispatched as live messages, and without
713            // the number a handler cannot even tell there is history to go read.
714            let backfilled = crate::VectorCore::v2_backfill_channel(
715                id, &hex, 50, 2, None, None,
716                crate::community::transport::Evidence::Fast, 12,
717            )
718            .await;
719            if !session.is_valid() {
720                return;
721            }
722            handler.on_channel_keyed(&community_id, &hex, backfilled);
723        }
724    }
725    if control_changed {
726        refresh_subscription(&client).await;
727        handler.on_community_refreshed(&community_id);
728        // A control change can reveal rekey work that predates it — a just-announced
729        // private channel's key crate is already sitting on its rekey plane (the key
730        // ships BEFORE the vsk-2), and this pass's rekey walk ran before the channel
731        // existed. Queue one more pass; it coalesces and converges (an unchanged
732        // control fold doesn't re-queue).
733        enqueue_follow(id);
734    }
735
736    // Banned by the banlist we just folded → self-remove NOW, not when the Refounding
737    // eventually lands. A Ban composes three layers (CORD-04 §6) and their guarantees
738    // arrive at different speeds: the Banlist edition is instant, the Refounding is
739    // "heavy and asynchronous" by design. Waiting on the rotation to notice our own
740    // removal left the target sitting in a community that had already dropped them from
741    // its member count — silenced, still looking joined. Checked unconditionally: a
742    // banlist-only change folds no document, so `follow_control` returns None for it.
743    // v1 has done this since it shipped (`am_i_banned` in its own realtime refresh).
744    if let Some(me) = crate::my_public_key() {
745        if crate::db::community::is_author_banned(&community_id, &me) {
746            if !session.is_valid() {
747                return;
748            }
749            crate::log_warn!("[v2:teardown {}] SELF-BAN: our npub is in the folded banlist", &community_id[..8.min(community_id.len())]);
750            handler.on_community_self_removed(&community_id);
751            return;
752        }
753    }
754
755    // Guestbook third: catch the membership store up from its cursor. Boot and
756    // reconnect land here through this same queue, so the memberlist is a local
757    // read by the time any panel asks — and every join/leave the catch-up folds
758    // surfaces as a presence line (real-rumor-id keyed, so a line each path also
759    // saw live inserts exactly once).
760    let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
761        return;
762    };
763    if let Ok(fresh) = super::service::sync_guestbook(&transport, &current, session).await {
764        if fresh.is_empty() || !session.is_valid() {
765            return;
766        }
767        surface_presence(&current, &fresh, handler);
768        handler.on_community_refreshed(&community_id);
769    }
770}
771
772/// Fire the presence-line surface for freshly-folded guestbook events — the
773/// catch-up twin of the live dispatch (same handler, same real-id dedup key,
774/// same banned-author drop). Kicks/snapshots shape the memberlist, not the feed.
775fn surface_presence(
776    community: &CommunityV2,
777    fresh: &[super::guestbook::GuestbookEvent],
778    handler: &dyn InboundEventHandler,
779) {
780    use super::guestbook::GuestbookEntry;
781    use nostr_sdk::prelude::ToBech32;
782    let Some(primary) = community.primary_channel() else {
783        return;
784    };
785    let chat_id = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
786    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
787    let banned = crate::db::community::banned_set(&cid_hex);
788    for ev in fresh {
789        let (member, joined, at_ms, invited_by) = match &ev.entry {
790            GuestbookEntry::Join { member, at_ms, invited_by } => (member, true, *at_ms, invited_by.clone()),
791            GuestbookEntry::Leave { member, at_ms } => (member, false, *at_ms, None),
792            GuestbookEntry::Kick { .. } | GuestbookEntry::Snapshot { .. } => continue,
793        };
794        if banned.contains(&member.to_bytes()) {
795            continue;
796        }
797        let Ok(npub) = member.to_bech32();
798        let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
799        let (by, label) = match &invited_by {
800            Some((c, l)) => (Some(c.as_str()), Some(l.as_str())),
801            None => (None, None),
802        };
803        handler.on_community_presence(&chat_id, &npub, joined, &event_id, at_ms / 1000, by, label);
804    }
805}
806
807#[cfg(test)]
808mod tests {
809    use super::*;
810    use super::super::control::{genesis, CommunityMetadata};
811    use crate::community::Epoch;
812    use nostr_sdk::prelude::Keys;
813
814    fn a_community(name: &str) -> CommunityV2 {
815        let owner = Keys::generate();
816        let g = genesis(&owner, CommunityMetadata { name: name.into(), ..Default::default() }, 1_000).unwrap();
817        CommunityV2::from_genesis(&g, name, None, vec!["wss://r".into()], 0)
818    }
819
820    #[test]
821    fn subscription_readiness_is_scoped_to_the_session_that_marked_it() {
822        // Generation-keyed on purpose: a bare bool would survive an account swap
823        // and report account A's readiness for account B — the exact class of
824        // per-account-global bug the swap-cache sweep exists to prevent.
825        //
826        // Bumping the GLOBAL generation invalidates every live SessionGuard, so
827        // serialize with the swap-sensitive tests via the same guard they hold.
828        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
829        mark_subscription_ready();
830        assert!(subscription_ready(), "marked for the current session");
831        crate::state::bump_session_generation();
832        assert!(!subscription_ready(), "an account swap invalidates it");
833        mark_subscription_ready();
834        assert!(subscription_ready(), "the new session's own pass re-arms it");
835    }
836
837    #[test]
838    fn plane_authors_covers_the_dispatched_planes_only() {
839        let c = a_community("A");
840        let authors = plane_authors(std::slice::from_ref(&c));
841
842        // Subscribed: the guestbook, the control plane, and the one public channel
843        // (the planes dispatch_wrap handles). Exactly those three.
844        let gb = derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).pk();
845        let control = derive::control_group_key(&c.community_root, c.id(), c.root_epoch).pk();
846        let general = {
847            let (s, e) = c.channel_secret(&c.channels[0]);
848            derive::channel_group_key(&s, &c.channels[0].id, e).pk()
849        };
850        // Plus the next base-rekey address (rekey-follow). A public channel has no
851        // independent rotation, so #general contributes no channel-rekey address.
852        let next_base = derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(1)).pk();
853        // Plus the dissolved plane (CORD-02 §9), so a live dissolution is detected.
854        let dissolved = derive::dissolved_group_key(c.id()).pk();
855        assert!(
856            authors.contains(&gb)
857                && authors.contains(&control)
858                && authors.contains(&general)
859                && authors.contains(&next_base)
860                && authors.contains(&dissolved)
861        );
862        assert_eq!(authors.len(), 5, "guestbook + control + dissolved + chat + base-rekey planes are subscribed");
863    }
864
865    #[test]
866    fn plane_authors_is_deterministic_deduped_and_multi_community() {
867        let a = a_community("A");
868        let b = a_community("B");
869        let one = plane_authors(std::slice::from_ref(&a));
870        // Re-running over the same community is byte-identical (deterministic).
871        assert_eq!(plane_authors(std::slice::from_ref(&a)), one);
872        // Two distinct communities' planes are all present, none dropped.
873        let two = plane_authors(&[a.clone(), b.clone()]);
874        assert_eq!(two.len(), one.len() * 2);
875        // Order-independent: reversing the input yields the identical sorted set.
876        assert_eq!(plane_authors(&[b, a]), two);
877    }
878
879    #[tokio::test]
880    async fn dispatch_event_routes_a_v2_message_to_the_handler() {
881        use crate::community::transport::memory::MemoryRelay;
882        use crate::community::transport::{Query, Transport};
883        use crate::types::Message;
884        use std::sync::Mutex as StdMutex;
885
886        #[derive(Default)]
887        struct Recorder {
888            got: StdMutex<Vec<(String, String)>>,
889        }
890        impl InboundEventHandler for Recorder {
891            fn on_community_message(&self, chat_id: &str, msg: &Message, _new: bool) {
892                self.got.lock().unwrap().push((chat_id.to_string(), msg.content.clone()));
893            }
894        }
895
896        // Offline DB + identity.
897        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
898        crate::db::close_database();
899        crate::db::clear_id_caches();
900        let tmp = tempfile::tempdir().unwrap();
901        let acct = {
902            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
903            let mut s = String::from("npub1");
904            for i in 0..58 {
905                s.push(B[(i * 5 + 1) % 32] as char);
906            }
907            s
908        };
909        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
910        crate::db::set_app_data_dir(tmp.path().to_path_buf());
911        crate::db::set_current_account(acct.clone()).unwrap();
912        crate::db::init_database(&acct).unwrap();
913        let _ = crate::state::take_nostr_client();
914        let me = Keys::generate();
915        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
916        crate::state::set_my_public_key(me.public_key());
917
918        // Create a v2 community (persisted), then ANOTHER member (holds the root)
919        // posts — the incoming case a live sub delivers (an OWN send is echoed at
920        // send time, so its relay copy correctly dedups instead of firing).
921        let relay = MemoryRelay::new();
922        let community = super::super::service::create_community(&relay, "Live", vec!["wss://r".into()], None).await.unwrap();
923        let general = community.channels[0].id;
924        let member = Keys::generate();
925        let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
926        let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "live ping", None, &[], vec![], 5_000);
927        let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(5), false).unwrap();
928        let _ = relay.publish(&wrap, &community.relays).await;
929        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
930        let wrap = relay.fetch(&q, &community.relays).await.unwrap().into_iter().find(|w| w.pubkey == group.pk()).unwrap();
931
932        // The realtime dispatch (loading held v2 communities from the DB) routes it.
933        // Dispatch the SAME wrap TWICE — modelling the pool re-delivering it under
934        // the targeted + pool-wide subs (and from multiple relays). The handler
935        // must fire EXACTLY ONCE (no duplicate bot replies) — and only AFTER the
936        // persist outcome (the callbacks-from-persist model).
937        let rec = Arc::new(Recorder::default());
938        let session = SessionGuard::capture();
939        crate::community::v2::realtime::clear().await; // fresh seen-set for the test
940        dispatch_event(&session, wrap.clone(), rec.clone()).await;
941        dispatch_event(&session, wrap, rec.clone()).await;
942
943        let got = rec.got.lock().unwrap();
944        assert_eq!(got.len(), 1, "a re-delivered wrap fires the handler exactly once");
945        assert_eq!(got[0].1, "live ping");
946        assert_eq!(got[0].0, crate::simd::hex::bytes_to_hex_32(&general.0));
947    }
948
949    #[tokio::test]
950    async fn follow_queue_coalesces_a_burst_and_re_enqueues_after_processing() {
951        // Install a test channel in place of the worker's, so we can observe what the
952        // queue delivers without a live client.
953        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
954        *V2_FOLLOW_TX.lock().unwrap() = Some(tx);
955        V2_FOLLOW_PENDING.lock().unwrap().clear();
956
957        let id = CommunityId([0x11; 32]);
958        // A burst for one community collapses to a SINGLE queued follow (coalesced).
959        enqueue_follow(&id);
960        enqueue_follow(&id);
961        enqueue_follow(&id);
962        assert_eq!(rx.recv().await, Some(id), "first trigger queues a follow");
963        assert!(rx.try_recv().is_err(), "the burst coalesced to exactly one");
964
965        // The worker removes it from pending before running; a trigger AFTER that
966        // re-queues (so a change during a follow isn't lost).
967        V2_FOLLOW_PENDING.lock().unwrap().remove(&id.0);
968        enqueue_follow(&id);
969        assert_eq!(rx.recv().await, Some(id), "a trigger after processing re-queues");
970
971        // A different community is independent (not coalesced against the first).
972        let id2 = CommunityId([0x22; 32]);
973        enqueue_follow(&id2);
974        assert_eq!(rx.recv().await, Some(id2));
975
976        *V2_FOLLOW_TX.lock().unwrap() = None;
977        V2_FOLLOW_PENDING.lock().unwrap().clear();
978    }
979
980    #[tokio::test]
981    async fn a_dissolved_community_honors_no_new_events_and_fires_death_once() {
982        use super::super::service;
983        use crate::community::transport::memory::MemoryRelay;
984        use crate::community::transport::Transport;
985        use crate::types::Message;
986        use std::sync::Mutex as StdMutex;
987
988        #[derive(Default)]
989        struct Recorder {
990            messages: StdMutex<Vec<String>>,
991            deaths: StdMutex<Vec<String>>,
992        }
993        impl InboundEventHandler for Recorder {
994            fn on_community_message(&self, _chat: &str, msg: &Message, _new: bool) {
995                self.messages.lock().unwrap().push(msg.content.clone());
996            }
997            fn on_community_dissolved(&self, community_id: &str) {
998                self.deaths.lock().unwrap().push(community_id.to_string());
999            }
1000        }
1001
1002        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1003        crate::db::close_database();
1004        crate::db::clear_id_caches();
1005        let tmp = tempfile::tempdir().unwrap();
1006        let acct = {
1007            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
1008            let mut s = String::from("npub1");
1009            for i in 0..58 {
1010                s.push(B[(i * 3 + 2) % 32] as char);
1011            }
1012            s
1013        };
1014        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
1015        crate::db::set_app_data_dir(tmp.path().to_path_buf());
1016        crate::db::set_current_account(acct.clone()).unwrap();
1017        crate::db::init_database(&acct).unwrap();
1018        let _ = crate::state::take_nostr_client();
1019        let me = Keys::generate();
1020        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
1021        crate::state::set_my_public_key(me.public_key());
1022
1023        let relay = MemoryRelay::new();
1024        let community = service::create_community(&relay, "Doomed", vec!["wss://r".into()], None).await.unwrap();
1025        let general = community.channels[0].id;
1026
1027        // The owner's tombstone arrives as a MEMBER sees it (local flag still 0 —
1028        // build + publish it directly rather than via dissolve_community, which
1029        // would seal our own DB first and make it the owner-published case). `me`
1030        // is the owner, so the seal verifies.
1031        let rumor = super::super::dissolution::dissolved_tombstone_rumor(me.public_key(), community.id(), 8_000);
1032        let tombstone = super::super::dissolution::seal_dissolved(&rumor, community.id(), &me, nostr_sdk::prelude::Timestamp::from_secs(8_000)).unwrap();
1033        let _ = relay.publish(&tombstone, &community.relays).await;
1034        assert!(!crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap(), "not yet locally sealed");
1035
1036        let rec = Arc::new(Recorder::default());
1037        let session = SessionGuard::capture();
1038        clear().await;
1039        // Fire the SAME tombstone twice AND a fresh re-wrap of its verified seal
1040        // (distinct outer id) — death must be announced exactly once.
1041        dispatch_event(&session, tombstone.clone(), rec.clone()).await;
1042        dispatch_event(&session, tombstone, rec.clone()).await;
1043        assert!(crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap());
1044
1045        // A member posts a fresh message to #general AFTER the tombstone. It must
1046        // not be honored (the community is excluded from load_held_v2, so its
1047        // plane is NotOurs).
1048        let member = Keys::generate();
1049        let cgroup = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1050        let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "into the grave", None, &[], vec![], 9_000);
1051        let (mw, _) = super::super::chat::seal_chat_rumor(&rumor, &cgroup, &member, nostr_sdk::prelude::Timestamp::from_secs(9), false).unwrap();
1052        dispatch_event(&session, mw, rec.clone()).await;
1053
1054        assert_eq!(rec.deaths.lock().unwrap().len(), 1, "death is announced exactly once");
1055        assert!(rec.messages.lock().unwrap().is_empty(), "a post-tombstone message is never honored (CORD-02 §9)");
1056    }
1057
1058    #[test]
1059    fn a_private_channel_subscribes_to_its_own_chat_plane() {
1060        let mut c = a_community("Priv");
1061        c.channels.push(super::super::community::ChannelV2 {
1062            id: crate::community::ChannelId([0x33; 32]),
1063            name: "mods".into(),
1064            private: true,
1065            key: Some([0x44; 32]),
1066            epoch: Epoch(1),
1067            voice: None,
1068            meta_custom: None,
1069            meta_extra: Default::default(),
1070        });
1071        let authors = plane_authors(std::slice::from_ref(&c));
1072        // A private channel is read under its OWN key/epoch (not the root).
1073        let priv_chat = derive::channel_group_key(&[0x44; 32], &c.channels[1].id, Epoch(1)).pk();
1074        assert!(authors.contains(&priv_chat), "a private channel subscribes to its own chat plane");
1075        // Its next-rekey address IS subscribed (rekey-follow), keyed by the current
1076        // root at the channel's next epoch — so a rotation is delivered.
1077        let next_rekey = derive::channel_rekey_group_key(&c.community_root, &c.channels[1].id, Epoch(2)).pk();
1078        assert!(authors.contains(&next_rekey), "a private channel's next rekey plane is subscribed");
1079    }
1080}