Skip to main content

vector_core/db/
community.rs

1//! Persistence for Community protocol local state (GROUP_PROTOCOL.md).
2//!
3//! Stores the secrets this account *holds*: the server-root key and per-channel keys
4//! (epoch-tagged). The DB is already account-scoped (`account_dir(npub)/vector.db`), so
5//! there is no npub column — a row belongs to whichever account's DB it lives in.
6//!
7//! At-rest encryption: when Local Encryption is on, every secret BLOB and every identifying
8//! metadata field (names, relays, roles, banlist, owner attestation, invite material) is wrapped
9//! with the account's ENCRYPTION_KEY before it touches disk and unwrapped on read, via the
10//! `enc_*`/`dec_*` helpers below. A raw DB then reveals no WHO/WHERE/WHAT. The discriminators
11//! (32-byte raw key vs 60-byte ciphertext; `looks_encrypted` for text) let a half-migrated DB
12//! read back correctly, so the toggle/PIN-rekey flows and the one-time backfill are safe to re-run.
13
14use nostr_sdk::prelude::{Keys, PublicKey, SecretKey};
15use nostr_sdk::prelude::ToBech32;
16use rusqlite::{params, OptionalExtension};
17
18use crate::community::{ChannelId, CommunityId, Epoch};
19
20fn now_secs() -> i64 {
21    crate::clock::now_secs() as i64
22}
23
24fn to_32(bytes: &[u8]) -> Result<[u8; 32], String> {
25    bytes
26        .try_into()
27        .map_err(|_| format!("expected 32-byte key, got {} bytes", bytes.len()))
28}
29
30// At-rest wrappers (see module doc). `enc_*` for write binds, `dec_*` for read.
31fn enc_key(k: &[u8; 32]) -> Result<Vec<u8>, String> { crate::crypto::maybe_encrypt_blob(k) }
32fn dec_key(stored: &[u8]) -> Result<[u8; 32], String> { to_32(&crate::crypto::maybe_decrypt_blob(stored)) }
33fn enc_txt(s: &str) -> Result<String, String> { crate::crypto::maybe_encrypt_text(s) }
34fn dec_txt(s: &str) -> String { crate::crypto::maybe_decrypt_text(s) }
35/// Encrypt an optional text field, preserving NULL.
36fn enc_txt_opt(s: &Option<String>) -> Result<Option<String>, String> {
37    s.as_deref().map(enc_txt).transpose()
38}
39
40/// Decode a 64-char hex id to 32 bytes, REJECTING malformed input. Unlike
41/// `simd::hex::hex_to_bytes_32`, this never silently zero-fills or truncates — a
42/// corrupted id row must error, not reconstruct a wrong-but-self-consistent id.
43pub(crate) fn hex_id_to_32(hex: &str) -> Result<[u8; 32], String> {
44    crate::simd::hex::hex_to_bytes_32_checked(hex)
45        .ok_or_else(|| format!("corrupt or wrong-length 64-char hex id ({} chars)", hex.len()))
46}
47
48// ── Parked Private-Channel key vends (CORD-03 "delivered on grant") ──────────
49
50/// One parked key vend awaiting the control fold that proves its grant.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct PendingChannelKey {
53    /// Row id — the discharge handle, since several candidates may name one channel.
54    pub id: i64,
55    pub channel_id: String,
56    pub epoch: u64,
57    pub key: [u8; 32],
58    /// Seal author — judged as an entitled vendor before the key is accepted.
59    pub sender: String,
60    pub received_at: i64,
61}
62
63/// Most candidate vends retained per channel, and per community overall.
64///
65/// Parking is reachable by ANY npub that can gift-wrap us, so these bound what a
66/// stranger can make us store — and decrypt on every follow pass. Small, because
67/// more than a couple of live candidates for one channel is already pathological.
68const MAX_PARKED_PER_CHANNEL: usize = 4;
69const MAX_PARKED_PER_COMMUNITY: usize = 64;
70
71/// Park a vended channel key as a CANDIDATE.
72///
73/// Deliberately NOT a single slot keyed on (community, channel): parking is open
74/// to any sender, so a slot lets a stranger pre-empt the entitled vendor's key
75/// and silently suppress delivery. Every vend is its own row, the judge tries
76/// them all, and the caps evict oldest-first so an unprovable flood cannot push
77/// out a provable row indefinitely.
78///
79/// `sender` is encrypted at rest with a per-write nonce, so it can be neither a
80/// key nor a dedupe column — hence oldest-first eviction rather than per-sender
81/// replacement.
82pub fn park_channel_key(
83    community_id: &str,
84    channel_id: &str,
85    epoch: u64,
86    key: &[u8; 32],
87    sender: &str,
88) -> Result<(), String> {
89    let _seal = crate::crypto::gate::sealing();
90    let conn = super::get_write_connection_guard_static()?;
91    let tx = conn.unchecked_transaction().map_err(|e| format!("park channel key tx: {e}"))?;
92    let enc = enc_key(key)?;
93    let enc_sender = enc_txt(sender)?;
94    tx.execute(
95        "INSERT INTO pending_channel_keys
96            (community_id, channel_id, epoch, channel_key, sender, received_at)
97         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
98        params![community_id, channel_id, epoch as i64, &enc[..], enc_sender, now_secs()],
99    )
100    .map_err(|e| format!("park channel key: {e}"))?;
101    // Trim this channel's candidates, then the community's total. `id` is the
102    // arrival order (autoincrement), so this is oldest-first without trusting
103    // any attacker-supplied field.
104    tx.execute(
105        "DELETE FROM pending_channel_keys WHERE id IN (
106            SELECT id FROM pending_channel_keys
107             WHERE community_id = ?1 AND channel_id = ?2
108             ORDER BY id DESC LIMIT -1 OFFSET ?3)",
109        params![community_id, channel_id, MAX_PARKED_PER_CHANNEL as i64],
110    )
111    .map_err(|e| format!("trim parked channel keys: {e}"))?;
112    tx.execute(
113        "DELETE FROM pending_channel_keys WHERE id IN (
114            SELECT id FROM pending_channel_keys
115             WHERE community_id = ?1
116             ORDER BY id DESC LIMIT -1 OFFSET ?2)",
117        params![community_id, MAX_PARKED_PER_COMMUNITY as i64],
118    )
119    .map_err(|e| format!("trim parked community keys: {e}"))?;
120    tx.commit().map_err(|e| format!("park channel key commit: {e}"))?;
121    Ok(())
122}
123
124/// Every parked vend for a community, for the post-fold re-judge.
125pub fn get_pending_channel_keys(community_id: &str) -> Result<Vec<PendingChannelKey>, String> {
126    let conn = super::get_db_connection_guard_static()?;
127    // Newest first: the freshest candidate is the likeliest genuine vend, so a
128    // pile of stale squatters costs at most a few failed judgements.
129    let mut stmt = conn
130        .prepare("SELECT id, channel_id, epoch, channel_key, sender, received_at FROM pending_channel_keys WHERE community_id = ?1 ORDER BY id DESC")
131        .map_err(|e| e.to_string())?;
132    let rows = stmt
133        .query_map(params![community_id], |row| {
134            Ok((
135                row.get::<_, i64>(0)?,
136                row.get::<_, String>(1)?,
137                row.get::<_, i64>(2)?,
138                row.get::<_, Vec<u8>>(3)?,
139                row.get::<_, String>(4)?,
140                row.get::<_, i64>(5)?,
141            ))
142        })
143        .map_err(|e| e.to_string())?;
144    let mut out = Vec::new();
145    for row in rows {
146        let (id, channel_id, epoch, blob, sender, received_at) = row.map_err(|e| e.to_string())?;
147        // A key that won't decrypt is unusable — drop it rather than failing the
148        // whole re-judge for its sake.
149        let Ok(key) = dec_key(&blob) else { continue };
150        out.push(PendingChannelKey { id, channel_id, epoch: epoch as u64, key, sender: dec_txt(&sender), received_at });
151    }
152    Ok(out)
153}
154
155/// Seat a channel key on a channel that currently holds NONE, without the
156/// monotonic epoch guard.
157///
158/// [`advance_channel_epoch`] requires `new_epoch > current`, which is right for a
159/// rotation but wrong for first delivery: a keyless record parks at epoch 0 (the
160/// rekey-scan cursor) and a client that mints born-private channels at epoch 0
161/// vends exactly that epoch, so the guard would silently refuse the only key we
162/// will ever be offered. A keyless channel has no key to lose, so any authorized
163/// delivery is strictly an improvement.
164pub fn seat_channel_key(
165    community_id: &str,
166    channel_id: &str,
167    epoch: u64,
168    key: &[u8; 32],
169) -> Result<(), String> {
170    let _seal = crate::crypto::gate::sealing();
171    let conn = super::get_write_connection_guard_static()?;
172    let tx = conn.unchecked_transaction().map_err(|e| format!("seat channel key tx: {e}"))?;
173    // "Keyless" is the caller's read of a snapshot; re-establish it HERE, inside the
174    // transaction that writes. Seating over a real key is a downgrade to whatever a
175    // vend offered, and only lock discipline stands between this and that today.
176    // A keyless private channel stores the community_root as its placeholder.
177    let placeholder: Vec<u8> = tx
178        .query_row(
179            "SELECT server_root_key FROM communities WHERE community_id = ?1",
180            params![community_id],
181            |r| r.get(0),
182        )
183        .map_err(|e| format!("seat channel key root: {e}"))?;
184    let current: Vec<u8> = tx
185        .query_row(
186            "SELECT channel_key FROM community_channels WHERE community_id = ?1 AND channel_id = ?2",
187            params![community_id, channel_id],
188            |r| r.get(0),
189        )
190        .map_err(|e| format!("seat channel key read: {e}"))?;
191    // Ciphertext carries a per-write nonce, so the comparison has to be on plaintext.
192    if dec_key(&current)? != dec_key(&placeholder)? {
193        return Err("channel already holds a key — seating would downgrade it".to_string());
194    }
195    store_epoch_key_tx(&tx, community_id, channel_id, epoch, key)?;
196    let enc = enc_key(key)?;
197    tx.execute(
198        "UPDATE community_channels SET epoch = ?1, channel_key = ?2
199           WHERE community_id = ?3 AND channel_id = ?4",
200        params![epoch as i64, &enc[..], community_id, channel_id],
201    )
202    .map_err(|e| format!("seat channel key: {e}"))?;
203    tx.commit().map_err(|e| format!("seat channel key commit: {e}"))?;
204    crate::community::v2::realtime::invalidate_held_v2_community(community_id);
205    Ok(())
206}
207
208/// Discharge ONE candidate (refused, superseded, expired, or undecodable).
209pub fn drop_pending_channel_key(id: i64) -> Result<(), String> {
210    let conn = super::get_write_connection_guard_static()?;
211    conn.execute("DELETE FROM pending_channel_keys WHERE id = ?1", params![id])
212        .map_err(|e| format!("drop pending channel key: {e}"))?;
213    Ok(())
214}
215
216/// Discharge every candidate for a channel — a key landed, so the rest are moot.
217pub fn drop_pending_channel_keys_for(community_id: &str, channel_id: &str) -> Result<(), String> {
218    let conn = super::get_write_connection_guard_static()?;
219    conn.execute(
220        "DELETE FROM pending_channel_keys WHERE community_id = ?1 AND channel_id = ?2",
221        params![community_id, channel_id],
222    )
223    .map_err(|e| format!("drop pending channel keys: {e}"))?;
224    Ok(())
225}
226
227/// Store one held epoch key in the multi-held archive. `scope_id` is a channel_id hex or
228/// [`crate::community::SERVER_ROOT_SCOPE_HEX`]. The `(community, scope, epoch)` PK makes a write for
229/// one epoch unable to disturb another epoch's key — so retained history survives a rekey. Uses
230/// REPLACE on the exact coordinate so the fork-resolution apply path can commit the *winning*
231/// key for a contested epoch over a previously-stored loser (the only legitimate same-coordinate
232/// overwrite; an epoch key is otherwise immutable).
233pub fn store_epoch_key(community_id: &str, scope_id: &str, epoch: u64, key: &[u8; 32]) -> Result<(), String> {
234    let _seal = crate::crypto::gate::sealing();
235    let conn = super::get_write_connection_guard_static()?;
236    store_epoch_key_tx(&conn, community_id, scope_id, epoch, key)
237}
238
239/// Forget one held epoch key, as a device that never held it.
240#[cfg(test)]
241pub fn delete_epoch_key(community_id: &str, scope_id: &str, epoch: u64) -> Result<(), String> {
242    let conn = super::get_write_connection_guard_static()?;
243    conn.execute(
244        "DELETE FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2 AND epoch = ?3",
245        params![community_id, scope_id, epoch as i64],
246    )
247    .map_err(|e| format!("delete epoch key: {e}"))?;
248    Ok(())
249}
250
251/// Shared INSERT body so `save_community` can archive keys inside its own transaction and the
252/// standalone [`store_epoch_key`] can run on a borrowed connection. `C: Deref<Target=Connection>`
253/// covers both a `Connection` and a `Transaction`.
254fn store_epoch_key_tx<C: std::ops::Deref<Target = rusqlite::Connection>>(
255    conn: &C,
256    community_id: &str,
257    scope_id: &str,
258    epoch: u64,
259    key: &[u8; 32],
260) -> Result<(), String> {
261    let enc = enc_key(key)?;
262    conn.execute(
263        "INSERT OR REPLACE INTO community_epoch_keys
264            (community_id, scope_id, epoch, key, created_at)
265         VALUES (?1, ?2, ?3, ?4, ?5)",
266        // epoch reinterpreted u64->i64 (lossless); never ORDER BY / range-filter it in SQL (see save).
267        params![community_id, scope_id, epoch as i64, &enc[..], now_secs()],
268    )
269    .map_err(|e| format!("store epoch key: {e}"))?;
270    Ok(())
271}
272
273/// Apply a received channel rekey's new key — the atomic archive+head dual-write: in ONE transaction,
274/// ARCHIVE `(channel, new_epoch) -> new_key` in `community_epoch_keys` AND advance the channel's
275/// read-head (`community_channels.epoch` + `channel_key`) iff `new_epoch` exceeds the current head.
276/// A caught-up OLDER epoch is archived (its history stays decryptable) but never regresses the head.
277/// Atomic so a crash can't leave the archive ahead of the head or the reverse. Returns whether the
278/// head advanced. Epoch comparison is done in RUST (the u64-as-i64 ≥2^63 SQL mis-order trap).
279pub fn advance_channel_epoch(
280    community_id: &str,
281    channel_id: &str,
282    new_epoch: u64,
283    new_key: &[u8; 32],
284) -> Result<bool, String> {
285    let _seal = crate::crypto::gate::sealing();
286    let conn = super::get_write_connection_guard_static()?;
287    let tx = conn.unchecked_transaction().map_err(|e| format!("advance channel epoch tx: {e}"))?;
288    // Archive always (PK includes epoch → never clobbers another epoch's key).
289    store_epoch_key_tx(&tx, community_id, channel_id, new_epoch, new_key)?;
290    // Monotonic head advance, compared in Rust.
291    let cur: Option<i64> = tx
292        .query_row(
293            "SELECT epoch FROM community_channels WHERE community_id = ?1 AND channel_id = ?2",
294            params![community_id, channel_id],
295            |r| r.get(0),
296        )
297        .optional()
298        .map_err(|e| format!("read channel head: {e}"))?;
299    let advanced = matches!(cur, Some(c) if new_epoch > c as u64);
300    if advanced {
301        let enc = enc_key(new_key)?;
302        tx.execute(
303            "UPDATE community_channels SET epoch = ?1, channel_key = ?2
304               WHERE community_id = ?3 AND channel_id = ?4",
305            params![new_epoch as i64, &enc[..], community_id, channel_id],
306        )
307        .map_err(|e| format!("advance channel head: {e}"))?;
308    }
309    tx.commit().map_err(|e| format!("advance channel epoch commit: {e}"))?;
310    if advanced {
311        crate::community::v2::realtime::invalidate_held_v2_community(community_id);
312    }
313    Ok(advanced)
314}
315
316/// Apply a received SERVER-ROOT (base) rekey's new root — the base counterpart to
317/// [`advance_channel_epoch`], atomic: in ONE transaction, ARCHIVE `(server-root scope, new_epoch) ->
318/// new_root` in `community_epoch_keys` AND advance the base head (`communities.server_root_epoch` +
319/// `server_root_key`) iff `new_epoch` exceeds the current base epoch (monotonic, compared in RUST). A
320/// caught-up OLDER base epoch is archived (its control/base history stays decryptable) but never
321/// regresses the head. Returns whether the head advanced.
322/// The community row's CURRENT base epoch — the cheap freshness probe a
323/// root-derived write compares its in-hand struct against.
324pub fn get_server_root_epoch(community_id: &str) -> Result<Option<u64>, String> {
325    let conn = super::get_db_connection_guard_static()?;
326    conn.query_row(
327        "SELECT server_root_epoch FROM communities WHERE community_id = ?1",
328        params![community_id],
329        |r| r.get::<_, i64>(0),
330    )
331    .optional()
332    .map(|v| v.map(|e| e as u64))
333    .map_err(|e| format!("get server root epoch: {e}"))
334}
335
336pub fn advance_server_root_epoch(community_id: &str, new_epoch: u64, new_root: &[u8; 32]) -> Result<bool, String> {
337    let _seal = crate::crypto::gate::sealing();
338    let conn = super::get_write_connection_guard_static()?;
339    let tx = conn.unchecked_transaction().map_err(|e| format!("advance server root tx: {e}"))?;
340    // Archive always, under the all-zero server-root scope sentinel (PK includes epoch → never clobbers
341    // another epoch's root).
342    store_epoch_key_tx(&tx, community_id, crate::community::SERVER_ROOT_SCOPE_HEX, new_epoch, new_root)?;
343    let cur: Option<i64> = tx
344        .query_row(
345            "SELECT server_root_epoch FROM communities WHERE community_id = ?1",
346            params![community_id],
347            |r| r.get(0),
348        )
349        .optional()
350        .map_err(|e| format!("read server-root epoch: {e}"))?;
351    let advanced = matches!(cur, Some(c) if new_epoch > c as u64);
352    if advanced {
353        let enc = enc_key(new_root)?;
354        tx.execute(
355            "UPDATE communities SET server_root_epoch = ?1, server_root_key = ?2 WHERE community_id = ?3",
356            params![new_epoch as i64, &enc[..], community_id],
357        )
358        .map_err(|e| format!("advance server-root head: {e}"))?;
359    }
360    tx.commit().map_err(|e| format!("advance server root commit: {e}"))?;
361    if advanced {
362        crate::community::v2::realtime::invalidate_held_v2_community(community_id);
363    }
364    Ok(advanced)
365}
366
367/// SAME-EPOCH convergence for the server root (concurrent re-founding heal): two BAN-holders who
368/// re-founded at the same time each sit on their OWN root at the SAME epoch. `advance_server_root_epoch`
369/// refuses to switch (its guard is strictly monotonic), so this is the sibling that REPLACES the head root
370/// at `epoch` with the deterministic winner (lowest root bytes — the caller decides). Archives the new root +
371/// swaps the head, but ONLY while we're still AT `epoch` (a later real rotation must win over a stale
372/// converge). Returns whether it switched.
373pub fn converge_server_root_epoch(community_id: &str, epoch: u64, new_root: &[u8; 32]) -> Result<bool, String> {
374    let _seal = crate::crypto::gate::sealing();
375    let conn = super::get_write_connection_guard_static()?;
376    let tx = conn.unchecked_transaction().map_err(|e| format!("converge server root tx: {e}"))?;
377    store_epoch_key_tx(&tx, community_id, crate::community::SERVER_ROOT_SCOPE_HEX, epoch, new_root)?;
378    let enc = enc_key(new_root)?;
379    let switched = tx
380        .execute(
381            "UPDATE communities SET server_root_key = ?1 WHERE community_id = ?2 AND server_root_epoch = ?3",
382            params![&enc[..], community_id, epoch as i64],
383        )
384        .map_err(|e| format!("converge server-root head: {e}"))?
385        > 0;
386    tx.commit().map_err(|e| format!("converge server root commit: {e}"))?;
387    if switched {
388        crate::community::v2::realtime::invalidate_held_v2_community(community_id);
389    }
390    Ok(switched)
391}
392
393/// Every held `(epoch, key)` for a scope, ascending by epoch. The read paths derive a pseudonym per
394/// returned epoch (`#z` OR-set) so cross-epoch history isn't stranded. Sorted in Rust (not SQL):
395/// epoch is a u64 stored as i64, so a SQL `ORDER BY` would mis-order epochs >= 2^63.
396pub fn held_epoch_keys(community_id: &str, scope_id: &str) -> Result<Vec<(Epoch, [u8; 32])>, String> {
397    let conn = super::get_db_connection_guard_static()?;
398    let mut stmt = conn
399        .prepare("SELECT epoch, key FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2")
400        .map_err(|e| e.to_string())?;
401    let rows = stmt
402        .query_map(params![community_id, scope_id], |r| {
403            Ok((r.get::<_, i64>(0)?, r.get::<_, Vec<u8>>(1)?))
404        })
405        .map_err(|e| e.to_string())?;
406    let mut out: Vec<(Epoch, [u8; 32])> = Vec::new();
407    for row in rows {
408        let (epoch, key_blob) = row.map_err(|e| e.to_string())?;
409        out.push((Epoch(epoch as u64), dec_key(&key_blob)?));
410    }
411    out.sort_by_key(|(e, _)| e.0);
412    Ok(out)
413}
414
415/// Archive a past epoch's read view of a private channel (CORD-03 §5): its conversation key and
416/// address, under scopes of their own so neither is ever taken for a channel key.
417pub fn store_history_view(community_id: &str, channel_id: &str, epoch: u64, view: &crate::community::v2::rekey::HistoryView) -> Result<(), String> {
418    let _seal = crate::crypto::gate::sealing();
419    let conn = super::get_write_connection_guard_static()?;
420    let tx = conn.unchecked_transaction().map_err(|e| format!("store history view tx: {e}"))?;
421    store_epoch_key_tx(&tx, community_id, &format!("hist:{channel_id}"), epoch, &view.conv_key)?;
422    store_epoch_key_tx(&tx, community_id, &format!("hista:{channel_id}"), epoch, &view.address)?;
423    tx.commit().map_err(|e| format!("store history view commit: {e}"))
424}
425
426/// Every past epoch of a private channel held read-only, oldest first.
427pub fn history_views(community_id: &str, channel_id: &str) -> Result<Vec<(Epoch, crate::community::v2::rekey::HistoryView)>, String> {
428    let addresses: std::collections::HashMap<u64, [u8; 32]> =
429        held_epoch_keys(community_id, &format!("hista:{channel_id}"))?.into_iter().map(|(e, a)| (e.0, a)).collect();
430    Ok(held_epoch_keys(community_id, &format!("hist:{channel_id}"))?
431        .into_iter()
432        .filter_map(|(e, conv_key)| addresses.get(&e.0).map(|address| (e, crate::community::v2::rekey::HistoryView { address: *address, conv_key })))
433        .collect())
434}
435
436/// The held key for one specific `(scope, epoch)`, or `None` if not held. The open path uses this to
437/// select the decryption key by the inbound event's `epoch` tag.
438pub fn held_epoch_key(community_id: &str, scope_id: &str, epoch: u64) -> Result<Option<[u8; 32]>, String> {
439    let conn = super::get_db_connection_guard_static()?;
440    let blob: Option<Vec<u8>> = conn
441        .query_row(
442            "SELECT key FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2 AND epoch = ?3",
443            params![community_id, scope_id, epoch as i64],
444            |r| r.get(0),
445        )
446        .optional()
447        .map_err(|e| format!("held epoch key: {e}"))?;
448    blob.map(|b| dec_key(&b)).transpose()
449}
450
451/// Retain the ephemeral signing key of a message I published, so I can later
452/// NIP-09-delete it. `relays` is where the deletion must be sent.
453pub fn store_message_key(
454    message_id: &str,
455    outer_event_id: &str,
456    ephemeral: &Keys,
457    relays: &[String],
458) -> Result<(), String> {
459    let _seal = crate::crypto::gate::sealing();
460    let conn = super::get_write_connection_guard_static()?;
461    let relays_json = serde_json::to_string(relays).map_err(|e| e.to_string())?;
462    let sk_bytes = to_32(ephemeral.secret_key().as_secret_bytes())?;
463    let enc_secret = enc_key(&sk_bytes)?;
464    let enc_relays = enc_txt(&relays_json)?;
465    conn.execute(
466        "INSERT OR REPLACE INTO community_message_keys
467            (outer_event_id, message_id, ephemeral_secret, relays, created_at)
468         VALUES (?1, ?2, ?3, ?4, ?5)",
469        params![
470            outer_event_id,
471            message_id,
472            &enc_secret[..],
473            enc_relays,
474            now_secs(),
475        ],
476    )
477    .map_err(|e| format!("store message key: {e}"))?;
478    Ok(())
479}
480
481/// Read (WITHOUT removing) the retained key for a message by its INNER message id (what
482/// the UI holds). Returns the ephemeral signing `Keys`, the OUTER event id to
483/// NIP-09-delete, and the relay set — or `None` if not retained (someone else's message,
484/// or already deleted). Peek-only so the key survives a failed deletion publish; the
485/// caller removes it with [`delete_message_key`] only after the publish succeeds.
486pub fn get_message_key(message_id: &str) -> Result<Option<(Keys, String, Vec<String>)>, String> {
487    let conn = super::get_db_connection_guard_static()?;
488    let row = conn
489        .query_row(
490            "SELECT ephemeral_secret, outer_event_id, relays
491               FROM community_message_keys WHERE message_id = ?1",
492            params![message_id],
493            |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)),
494        )
495        .optional()
496        .map_err(|e| format!("get message key: {e}"))?;
497    let (secret_blob, outer_event_id, relays_json) = match row {
498        Some(t) => t,
499        None => return Ok(None),
500    };
501    let secret = SecretKey::from_slice(&dec_key(&secret_blob)?).map_err(|e| format!("ephemeral secret: {e}"))?;
502    let relays: Vec<String> = serde_json::from_str(&dec_txt(&relays_json)).map_err(|e| e.to_string())?;
503    Ok(Some((Keys::new(secret), outer_event_id, relays)))
504}
505
506/// Whether the plane key of a wrap of `message_id` is kept.
507pub fn has_message_key(message_id: &str) -> Result<bool, String> {
508    let conn = super::get_db_connection_guard_static()?;
509    conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM community_message_keys WHERE message_id = ?1)")
510        .and_then(|mut stmt| stmt.query_row(params![message_id], |r| r.get(0)))
511        .map_err(|e| format!("has message key: {e}"))
512}
513
514/// Remove a retained message key (after a successful deletion publish).
515pub fn delete_message_key(message_id: &str) -> Result<(), String> {
516    let conn = super::get_write_connection_guard_static()?;
517    conn.execute(
518        "DELETE FROM community_message_keys WHERE message_id = ?1",
519        params![message_id],
520    )
521    .map_err(|e| format!("remove message key: {e}"))?;
522    Ok(())
523}
524
525/// Peek + remove in one call. Prefer [`get_message_key`] + [`delete_message_key`] when a
526/// fallible step sits between, so a failure doesn't strand the key.
527pub fn take_message_key(message_id: &str) -> Result<Option<(Keys, String, Vec<String>)>, String> {
528    let r = get_message_key(message_id)?;
529    if r.is_some() {
530        delete_message_key(message_id)?;
531    }
532    Ok(r)
533}
534
535/// Keep the `p` key of a wrap I published or met: its holder may delete the wrap (CORD-01
536/// §Deletions) on every relay that refuses the plane key's deletions.
537pub fn store_wrap_owner(message_id: &str, outer_event_id: &str, owner: &Keys, relays: &[String]) -> Result<(), String> {
538    let _seal = crate::crypto::gate::sealing();
539    let conn = super::get_write_connection_guard_static()?;
540    let relays_json = serde_json::to_string(relays).map_err(|e| e.to_string())?;
541    let enc_secret = enc_key(&to_32(owner.secret_key().as_secret_bytes())?)?;
542    let enc_relays = enc_txt(&relays_json)?;
543    conn.execute(
544        "INSERT OR REPLACE INTO community_wrap_owners (outer_event_id, message_id, owner_secret, relays, created_at)
545         VALUES (?1, ?2, ?3, ?4, ?5)",
546        params![outer_event_id, message_id, &enc_secret[..], enc_relays, now_secs()],
547    )
548    .map_err(|e| format!("store wrap owner: {e}"))?;
549    Ok(())
550}
551
552/// Every wrap of `message_id` whose `p` key is kept: the key, the wrap's id, and the relays
553/// it was sent to.
554pub fn wrap_owners(message_id: &str) -> Result<Vec<(Keys, String, Vec<String>)>, String> {
555    let conn = super::get_db_connection_guard_static()?;
556    let mut stmt = conn
557        .prepare_cached("SELECT owner_secret, outer_event_id, relays FROM community_wrap_owners WHERE message_id = ?1")
558        .map_err(|e| format!("wrap owners: {e}"))?;
559    let rows = stmt
560        .query_map(params![message_id], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))
561        .map_err(|e| format!("wrap owners: {e}"))?;
562    let mut out = Vec::new();
563    for row in rows {
564        let (secret_blob, outer_event_id, relays_json) = row.map_err(|e| format!("wrap owners: {e}"))?;
565        let secret = SecretKey::from_slice(&dec_key(&secret_blob)?).map_err(|e| format!("wrap owner secret: {e}"))?;
566        let relays: Vec<String> = serde_json::from_str(&dec_txt(&relays_json)).map_err(|e| e.to_string())?;
567        out.push((Keys::new(secret), outer_event_id, relays));
568    }
569    Ok(out)
570}
571
572/// Whether a wrap of `message_id` can be deleted by its owner from here.
573pub fn has_wrap_owner(message_id: &str) -> Result<bool, String> {
574    let conn = super::get_db_connection_guard_static()?;
575    conn.prepare_cached("SELECT EXISTS(SELECT 1 FROM community_wrap_owners WHERE message_id = ?1)")
576        .and_then(|mut stmt| stmt.query_row(params![message_id], |r| r.get(0)))
577        .map_err(|e| format!("has wrap owner: {e}"))
578}
579
580/// Drop the kept `p` keys of `message_id`'s wraps, once their deletions went out.
581pub fn forget_wrap_owners(message_id: &str) -> Result<(), String> {
582    let conn = super::get_write_connection_guard_static()?;
583    conn.execute("DELETE FROM community_wrap_owners WHERE message_id = ?1", params![message_id])
584        .map_err(|e| format!("forget wrap owners: {e}"))?;
585    Ok(())
586}
587
588/// Queue my own `message_ids` of `community_id` to leave the relays, a wrap at a time.
589pub fn queue_wrap_scrubs(community_id: &str, message_ids: &[String]) -> Result<(), String> {
590    let mut conn = super::get_write_connection_guard_static()?;
591    let tx = conn.transaction().map_err(|e| format!("queue wrap scrubs: {e}"))?;
592    for id in message_ids {
593        tx.execute(
594            "INSERT OR IGNORE INTO community_wrap_scrubs (message_id, community_id, queued_at) VALUES (?1, ?2, ?3)",
595            params![id, community_id, now_secs()],
596        )
597        .map_err(|e| format!("queue wrap scrubs: {e}"))?;
598    }
599    tx.commit().map_err(|e| format!("queue wrap scrubs: {e}"))
600}
601
602/// The longest-waiting queued scrub: `(message_id, community_id)`.
603pub fn next_wrap_scrub() -> Result<Option<(String, String)>, String> {
604    let conn = super::get_db_connection_guard_static()?;
605    conn.query_row(
606        "SELECT message_id, community_id FROM community_wrap_scrubs ORDER BY queued_at, rowid LIMIT 1",
607        [],
608        |r| Ok((r.get(0)?, r.get(1)?)),
609    )
610    .optional()
611    .map_err(|e| format!("next wrap scrub: {e}"))
612}
613
614/// Settle a queued scrub: `retry` sends it to the back of the queue, otherwise it is done.
615pub fn settle_wrap_scrub(message_id: &str, retry: bool) -> Result<(), String> {
616    let conn = super::get_write_connection_guard_static()?;
617    let sql = if retry {
618        "UPDATE community_wrap_scrubs SET queued_at = ?2 WHERE message_id = ?1"
619    } else {
620        "DELETE FROM community_wrap_scrubs WHERE message_id = ?1"
621    };
622    let n = if retry { conn.execute(sql, params![message_id, now_secs()]) } else { conn.execute(sql, params![message_id]) };
623    n.map(|_| ()).map_err(|e| format!("settle wrap scrub: {e}"))
624}
625
626/// Drop what this device holds of a deleted Channel's Chat Plane: its chat, events and their
627/// attachment rows, and wraps held for a later judgment. Its keys stay (CORD-03 §2).
628/// Returns whether it held anything.
629pub fn forget_channel_chat(community_id: &str, channel_id: &str) -> Result<bool, String> {
630    let held = {
631        let conn = super::get_write_connection_guard_static()?;
632        let files = conn
633            .execute(
634                "DELETE FROM attachments WHERE event_id IN (SELECT e.id FROM events e JOIN chats c ON c.id = e.chat_id WHERE c.chat_identifier = ?1)",
635                params![channel_id],
636            )
637            .map_err(|e| format!("forget channel attachments: {e}"))?;
638        let wraps = conn
639            .execute("DELETE FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2", params![community_id, channel_id])
640            .map_err(|e| format!("forget channel held wraps: {e}"))?;
641        let chat: bool = conn
642            .query_row("SELECT EXISTS(SELECT 1 FROM chats WHERE chat_identifier = ?1)", params![channel_id], |r| r.get(0))
643            .map_err(|e| format!("forget channel chat: {e}"))?;
644        files + wraps > 0 || chat
645    };
646    if held {
647        super::chats::delete_chat(channel_id)?;
648    }
649    Ok(held)
650}
651
652/// Every event this device stores in `channel_id`'s chat, and whether it carries files.
653pub fn channel_events(channel_id: &str) -> Result<Vec<(String, bool)>, String> {
654    let conn = super::get_db_connection_guard_static()?;
655    let mut stmt = conn
656        .prepare(
657            "SELECT e.id, EXISTS(SELECT 1 FROM attachments a WHERE a.event_id = e.id)
658               FROM events e JOIN chats c ON c.id = e.chat_id WHERE c.chat_identifier = ?1",
659        )
660        .map_err(|e| format!("channel events: {e}"))?;
661    let rows = stmt
662        .query_map(params![channel_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)))
663        .map_err(|e| format!("channel events: {e}"))?;
664    rows.collect::<Result<_, _>>().map_err(|e| format!("channel events: {e}"))
665}
666
667/// The hex id of the Community that owns `channel_id`, if any is stored locally. Used to
668/// resolve a channel-addressed chat back to its Community for sending.
669// ── Channel → community cache ────────────────────────────────────────────────
670// The owning community of a channel is IMMUTABLE (a channel belongs to one community
671// for life; channel ids are random-32 and never reused — the save path refuses a
672// cross-community id claim), so a live entry is never wrong. It only needs eviction
673// when the channel row itself goes away: `delete_community_inner` (all rows) or a
674// `save_community_v2` prune (some rows); `save_community` is UPSERT-only and never
675// removes a channel, so it needs none. POSITIVES ONLY — a missing channel is never
676// cached, so a not-yet-synced channel resolves the moment its row lands and `None`
677// keeps meaning "gone" for delete-then-check callers. Per session: what is held is
678// the account's own. Keyed by bytes; an id not in canonical hex skips the cache.
679struct ChannelCommunityCache;
680type ChannelCommunityMap = std::sync::RwLock<std::collections::HashMap<[u8; 32], [u8; 32]>>;
681
682fn channel_community_cache() -> std::sync::Arc<ChannelCommunityMap> {
683    crate::db::current_session().scoped::<ChannelCommunityCache, ChannelCommunityMap>()
684}
685
686/// Drop every cached channel→community mapping.
687pub fn clear_channel_community_cache() {
688    *channel_community_cache().write().unwrap_or_else(|e| e.into_inner()) = Default::default();
689    crate::notify::invalidate_communities();
690}
691
692/// Forget a community's channel mappings — its rows were dropped or rewritten, so any
693/// pruned entry must stop resolving. Retained channels refill lazily on next lookup.
694fn forget_community_channels(community_id: &str) {
695    if let Some(cid) = crate::community::id32_from_hex(community_id) {
696        channel_community_cache().write().unwrap_or_else(|e| e.into_inner()).retain(|_, c| *c != cid);
697    }
698    // A prune here is how a channel stops being openable, which is what decides
699    // whether its unread may still badge.
700    crate::notify::invalidate_communities();
701}
702
703fn query_community_for_channel(channel_id: &str) -> Result<Option<String>, String> {
704    let conn = super::get_db_connection_guard_static()?;
705    conn.prepare_cached("SELECT community_id FROM community_channels WHERE channel_id = ?1")
706        .and_then(|mut stmt| stmt.query_row(params![channel_id], |r| r.get::<_, String>(0)))
707        .optional()
708        .map_err(|e| format!("community_id_for_channel: {e}"))
709}
710
711/// Whether a stored Channel is private, `None` when it isn't stored.
712pub fn channel_is_private(channel_id: &str) -> Result<Option<bool>, String> {
713    let conn = super::get_db_connection_guard_static()?;
714    conn.prepare_cached("SELECT private FROM community_channels WHERE channel_id = ?1")
715        .and_then(|mut stmt| stmt.query_row(params![channel_id], |r| r.get::<_, i64>(0)))
716        .optional()
717        .map(|p| p.map(|p| p != 0))
718        .map_err(|e| format!("channel_is_private: {e}"))
719}
720
721/// The id of the Community that owns `channel`, if one is stored locally.
722pub fn community_for_channel(channel: &[u8; 32]) -> Result<Option<[u8; 32]>, String> {
723    let cache = channel_community_cache();
724    if let Some(cid) = cache.read().unwrap_or_else(|e| e.into_inner()).get(channel) {
725        return Ok(Some(*cid));
726    }
727    let Some(cid_hex) = query_community_for_channel(&crate::simd::hex::bytes_to_hex_32(channel))? else {
728        return Ok(None);
729    };
730    let Some(cid) = crate::community::id32_from_hex(&cid_hex) else {
731        return Ok(None);
732    };
733    cache.write().unwrap_or_else(|e| e.into_inner()).insert(*channel, cid);
734    Ok(Some(cid))
735}
736
737/// [`community_for_channel`] over hex, returning the stored id verbatim.
738pub fn community_id_for_channel(channel_id: &str) -> Result<Option<String>, String> {
739    let channel = crate::community::id32_from_hex(channel_id);
740    if let Some(ch) = channel {
741        if let Some(cid) = channel_community_cache().read().unwrap_or_else(|e| e.into_inner()).get(&ch) {
742            return Ok(Some(crate::simd::hex::bytes_to_hex_32(cid)));
743        }
744    }
745    let cid = query_community_for_channel(channel_id)?;
746    if let (Some(ch), Some(c)) = (channel, cid.as_deref().and_then(crate::community::id32_from_hex)) {
747        channel_community_cache().write().unwrap_or_else(|e| e.into_inner()).insert(ch, c);
748    }
749    Ok(cid)
750}
751
752/// Whether a Community with this id is already stored locally (joined). Cheaper than
753/// `load_community` when only existence matters (e.g. inbound-invite dedup).
754pub fn community_exists(id: &CommunityId) -> Result<bool, String> {
755    let conn = super::get_db_connection_guard_static()?;
756    let found: Option<i64> = conn
757        .query_row(
758            "SELECT 1 FROM communities WHERE community_id = ?1",
759            params![id.to_hex()],
760            |r| r.get(0),
761        )
762        .optional()
763        .map_err(|e| format!("community_exists: {e}"))?;
764    Ok(found.is_some())
765}
766
767/// A parked invite awaiting the user's accept/decline decision.
768#[derive(Debug, Clone, serde::Serialize)]
769pub struct PendingCommunityInvite {
770    pub community_id: String,
771    pub bundle_json: String,
772    pub inviter_npub: String,
773    pub received_at: i64,
774    /// Sender-declared NIP-40 expiry (unix secs); 0 = none declared, so permanent.
775    pub expires_at: i64,
776    /// When it was sent (unix secs); 0 when parked before this was kept.
777    pub sent_at: i64,
778    /// When it leaves the list (unix secs): the sender's deadline or the recipient's lifetime,
779    /// whichever comes first.
780    pub ends_at: i64,
781}
782
783/// Park an inbound invite bundle for explicit user consent (the carrier never
784/// auto-joins). First-invite-wins: `INSERT OR IGNORE` means a later invite for the
785/// same `community_id` can't silently rewrite a parked bundle. Returns whether a new
786/// row was inserted (`false` = already pending, caller should not re-notify).
787pub fn save_pending_invite(
788    community_id: &str,
789    bundle_json: &str,
790    inviter_npub: &str,
791    expires_at: i64,
792) -> Result<bool, String> {
793    let _seal = crate::crypto::gate::sealing();
794    /// Cap on parked invites. Each row is one gift-wrapped invite from an arbitrary sender, so an
795    /// attacker fabricating unbounded community_ids could otherwise grow this table without limit
796    /// (#298). Newest-wins: a stale months-old park is the safe thing to shed.
797    const MAX_PENDING_INVITES: usize = 100;
798
799    let conn = super::get_write_connection_guard_static()?;
800    let enc_bundle = enc_txt(bundle_json)?;
801    let enc_inviter = enc_txt(inviter_npub)?;
802    // First-wins: a parked invite is never silently overwritten by a later different
803    // bundle (that would let an attacker replace a genuine parked invite). For v2, a
804    // pre-planted forged-root bundle sharing a real community_id is instead cleared on
805    // a failed accept (see `accept_pending_invite`), so a genuine re-invite can re-park.
806    let changed = conn
807        .execute(
808            "INSERT OR IGNORE INTO pending_community_invites
809                (community_id, bundle_json, inviter_npub, received_at, expires_at)
810             VALUES (?1, ?2, ?3, ?4, ?5)",
811            params![community_id, enc_bundle, enc_inviter, now_secs(), expires_at],
812        )
813        .map_err(|e| format!("save pending invite: {e}"))?;
814    // Only growth can breach the cap. Evict everything past the newest MAX rows
815    // (LIMIT -1 OFFSET cap = "all rows after the first cap"); community_id tie-breaks equal times.
816    if changed > 0 {
817        let _ = conn.execute(
818            "DELETE FROM pending_community_invites
819               WHERE community_id IN (
820                 SELECT community_id FROM pending_community_invites
821                 ORDER BY received_at DESC, community_id DESC
822                 LIMIT -1 OFFSET ?1
823               )",
824            params![MAX_PENDING_INVITES],
825        );
826    }
827    Ok(changed > 0)
828}
829
830/// Record a gift wrap that delivered `community_id`'s parked invite. A sender re-wrapping one
831/// invite without end adds nothing past the cap.
832pub fn note_pending_invite_wrap(community_id: &str, wrap_hex: &str) -> Result<(), String> {
833    const MAX_WRAPS: usize = 16;
834    let conn = super::get_write_connection_guard_static()?;
835    let held: Option<String> = conn
836        .query_row("SELECT wrap_ids FROM pending_community_invites WHERE community_id = ?1", params![community_id], |r| r.get(0))
837        .optional()
838        .map_err(|e| format!("read invite wraps: {e}"))?;
839    let Some(held) = held else { return Ok(()) };
840    let mut ids: Vec<&str> = held.split_whitespace().collect();
841    if ids.contains(&wrap_hex) || ids.len() >= MAX_WRAPS {
842        return Ok(());
843    }
844    ids.push(wrap_hex);
845    conn.execute("UPDATE pending_community_invites SET wrap_ids = ?2 WHERE community_id = ?1", params![community_id, ids.join(" ")])
846        .map_err(|e| format!("note invite wrap: {e}"))?;
847    Ok(())
848}
849
850/// Record when a parked invite was sent, once.
851pub fn set_pending_invite_sent(community_id: &str, sent_at: i64) -> Result<(), String> {
852    let conn = super::get_write_connection_guard_static()?;
853    conn.execute("UPDATE pending_community_invites SET sent_at = ?2 WHERE community_id = ?1 AND sent_at = 0", params![community_id, sent_at])
854        .map_err(|e| format!("set invite send time: {e}"))?;
855    Ok(())
856}
857
858/// When a parked invite's lifetime began, in SQL: its send time, or its park time when unknown.
859const INVITE_LIFETIME_FROM: &str = "CASE WHEN sent_at > 0 THEN sent_at ELSE received_at END";
860
861/// The gift wraps recorded for a parked invite.
862pub fn pending_invite_wraps(community_id: &str) -> Result<Vec<String>, String> {
863    let conn = super::get_db_connection_guard_static()?;
864    let held: Option<String> = conn
865        .query_row("SELECT wrap_ids FROM pending_community_invites WHERE community_id = ?1", params![community_id], |r| r.get(0))
866        .optional()
867        .map_err(|e| format!("read invite wraps: {e}"))?;
868    Ok(held.map(|s| s.split_whitespace().map(String::from).collect()).unwrap_or_default())
869}
870
871/// Drop every parked invite for a community we ALREADY hold — once joined on any device, the
872/// invite must never resurface. Ordering-independent: covers the cross-device case where the
873/// historical gift-wrapped invites are ingested BEFORE the synced membership list rehydrates
874/// those communities (so the ingest-time `community_exists` guard saw nothing yet). Returns the
875/// count purged.
876pub fn purge_pending_invites_for_held_communities() -> Result<usize, String> {
877    let conn = super::get_write_connection_guard_static()?;
878    let n = conn
879        .execute(
880            "DELETE FROM pending_community_invites
881               WHERE community_id IN (SELECT community_id FROM communities)",
882            [],
883        )
884        .map_err(|e| format!("purge held pending invites: {e}"))?;
885    Ok(n)
886}
887
888/// Drop parked invites past their sender-declared NIP-40 expiry OR past the
889/// recipient-enforced 24h lifetime (measured from park time — conservative,
890/// since parking postdates sending). The lifetime leg is what clears rows
891/// parked by builds that predate the ingest-time rule: a machine dormant for
892/// a month otherwise boots into a page of fossil invites no other culler can
893/// touch (no declared expiry, never held, never tombstoned). Returns the
894/// count purged.
895pub fn purge_expired_pending_invites() -> Result<usize, String> {
896    let conn = super::get_write_connection_guard_static()?;
897    let now = now_secs();
898    let n = conn
899        .execute(
900            &format!(
901                "DELETE FROM pending_community_invites
902                  WHERE (expires_at != 0 AND expires_at <= ?1)
903                     OR {INVITE_LIFETIME_FROM} <= ?2"
904            ),
905            params![now, now - crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64],
906        )
907        .map_err(|e| format!("purge expired pending invites: {e}"))?;
908    Ok(n)
909}
910
911/// All parked invites, newest first.
912pub fn list_pending_invites() -> Result<Vec<PendingCommunityInvite>, String> {
913    let now = now_secs();
914    let raw: Vec<(String, String, String, i64, i64, i64)> = {
915        let conn = super::get_db_connection_guard_static()?;
916        let mut stmt = conn
917            .prepare(&format!(
918                "SELECT community_id, bundle_json, inviter_npub, received_at, expires_at, sent_at
919                   FROM pending_community_invites
920                  WHERE (expires_at = 0 OR expires_at > ?1)
921                    AND {INVITE_LIFETIME_FROM} > ?2
922                  ORDER BY received_at DESC"
923            ))
924            .map_err(|e| e.to_string())?;
925        let rows = stmt
926            .query_map(params![now, now - crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64], |r| {
927                Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?))
928            })
929            .map_err(|e| e.to_string())?;
930        rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
931    };
932    Ok(raw
933        .into_iter()
934        .map(|(community_id, bundle, inviter, received_at, expires_at, sent_at)| {
935            let from = if sent_at > 0 { sent_at } else { received_at };
936            let lifetime_end = from + crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64;
937            PendingCommunityInvite {
938                community_id,
939                bundle_json: dec_txt(&bundle),
940                inviter_npub: dec_txt(&inviter),
941                received_at,
942                expires_at,
943                sent_at,
944                ends_at: if expires_at != 0 { expires_at.min(lifetime_end) } else { lifetime_end },
945            }
946        })
947        .collect())
948}
949
950/// Read a parked invite's bundle WITHOUT removing it. Accept is fallible (caps,
951/// owner/authority collision), so the row must survive a rejected accept — peek here,
952/// then [`delete_pending_invite`] only after the join succeeds.
953pub fn get_pending_invite(community_id: &str) -> Result<Option<String>, String> {
954    let conn = super::get_db_connection_guard_static()?;
955    let raw: Option<String> = conn
956        .query_row(
957            "SELECT bundle_json FROM pending_community_invites
958              WHERE community_id = ?1 AND (expires_at = 0 OR expires_at > ?2)",
959            params![community_id, now_secs()],
960            |r| r.get::<_, String>(0),
961        )
962        .optional()
963        .map_err(|e| format!("get pending invite: {e}"))?;
964    Ok(raw.map(|s| dec_txt(&s)))
965}
966
967/// Drop a parked invite without joining (the user declined).
968pub fn delete_pending_invite(community_id: &str) -> Result<(), String> {
969    let conn = super::get_write_connection_guard_static()?;
970    conn.execute(
971        "DELETE FROM pending_community_invites WHERE community_id = ?1",
972        params![community_id],
973    )
974    .map_err(|e| format!("delete pending invite: {e}"))?;
975    Ok(())
976}
977
978/// Drop every invite this person parked (they were blocked); the count dropped. The
979/// inviter is sealed at rest, so the rows are read to match it.
980pub fn delete_pending_invites_from(inviter_npub: &str) -> Result<usize, String> {
981    let mut dropped = 0;
982    for invite in list_pending_invites()? {
983        if invite.inviter_npub == inviter_npub {
984            delete_pending_invite(&invite.community_id)?;
985            dropped += 1;
986        }
987    }
988    Ok(dropped)
989}
990
991/// Whether an invite for this id is already parked (inbound dedup).
992/// When a parked invite ARRIVED (unix secs), or `None` if none is parked. The
993/// supersession key for the purge: an invite that arrived AFTER a removal is a genuine
994/// re-invite, not residue of the leave.
995pub fn pending_invite_received_at(community_id: &str) -> Result<Option<i64>, String> {
996    let conn = super::get_db_connection_guard_static()?;
997    conn.query_row(
998        "SELECT received_at FROM pending_community_invites WHERE community_id = ?1",
999        params![community_id],
1000        |r| r.get(0),
1001    )
1002    .optional()
1003    .map_err(|e| format!("pending_invite_received_at: {e}"))
1004}
1005
1006pub fn pending_invite_exists(community_id: &str) -> Result<bool, String> {
1007    let conn = super::get_db_connection_guard_static()?;
1008    let found: Option<i64> = conn
1009        .query_row(
1010            "SELECT 1 FROM pending_community_invites WHERE community_id = ?1",
1011            params![community_id],
1012            |r| r.get(0),
1013        )
1014        .optional()
1015        .map_err(|e| format!("pending_invite_exists: {e}"))?;
1016    Ok(found.is_some())
1017}
1018
1019/// A minted public-invite link the owner retains (to list + revoke).
1020#[derive(Debug, Clone, serde::Serialize)]
1021pub struct PublicInviteRecord {
1022    /// Hex token (the link's whole secret; lives only in the local account DB).
1023    pub token: String,
1024    pub community_id: String,
1025    pub url: String,
1026    pub expires_at: Option<i64>,
1027    pub created_at: i64,
1028    /// Optional human label set at mint time (e.g. "Twitter", "Discord"). None if unset.
1029    pub label: Option<String>,
1030    /// Distinct members who joined via this link (by label attribution). 0 if none/unknown.
1031    #[serde(default)]
1032    pub join_count: u64,
1033}
1034
1035/// Retain a minted public-invite token so the owner can later list + revoke it.
1036pub fn save_public_invite(
1037    token: &str,
1038    community_id: &str,
1039    url: &str,
1040    expires_at: Option<i64>,
1041    label: Option<&str>,
1042) -> Result<(), String> {
1043    let _seal = crate::crypto::gate::sealing();
1044    let conn = super::get_write_connection_guard_static()?;
1045    // token + url are the link's secret; encrypted, the token PK becomes per-write-unique (random
1046    // nonce) so this is effectively an INSERT — fine, mints generate a fresh token each time.
1047    let enc_token = enc_txt(token)?;
1048    let enc_url = enc_txt(url)?;
1049    // Encrypt the label at rest like the url; NULL when no label was set.
1050    let enc_label = label.map(enc_txt).transpose()?;
1051    conn.execute(
1052        "INSERT OR REPLACE INTO community_public_invites
1053            (token, community_id, url, expires_at, created_at, label)
1054         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1055        params![enc_token, community_id, enc_url, expires_at, now_secs(), enc_label],
1056    )
1057    .map_err(|e| format!("save public invite: {e}"))?;
1058    Ok(())
1059}
1060
1061/// Keep a public-invite link minted on another of this account's devices, dated as it was there.
1062pub fn adopt_public_invite(token: &str, community_id: &str, url: &str, expires_at: Option<i64>, label: Option<&str>, created_at: i64) -> Result<(), String> {
1063    let _seal = crate::crypto::gate::sealing();
1064    let conn = super::get_write_connection_guard_static()?;
1065    let enc_label = label.map(enc_txt).transpose()?;
1066    conn.execute(
1067        "INSERT INTO community_public_invites
1068            (token, community_id, url, expires_at, created_at, label)
1069         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1070        params![enc_txt(token)?, community_id, enc_txt(url)?, expires_at, created_at, enc_label],
1071    )
1072    .map_err(|e| format!("adopt public invite: {e}"))?;
1073    Ok(())
1074}
1075
1076/// All minted public-invite links for a Community, newest first.
1077pub fn list_public_invites(community_id: &str) -> Result<Vec<PublicInviteRecord>, String> {
1078    let conn = super::get_db_connection_guard_static()?;
1079    let mut stmt = conn
1080        .prepare(
1081            "SELECT token, community_id, url, expires_at, created_at, label
1082               FROM community_public_invites WHERE community_id = ?1 ORDER BY created_at DESC",
1083        )
1084        .map_err(|e| e.to_string())?;
1085    let rows = stmt
1086        .query_map(params![community_id], |r| {
1087            Ok(PublicInviteRecord {
1088                token: dec_txt(&r.get::<_, String>(0)?),
1089                community_id: r.get(1)?,
1090                url: dec_txt(&r.get::<_, String>(2)?),
1091                expires_at: r.get(3)?,
1092                created_at: r.get(4)?,
1093                label: r.get::<_, Option<String>>(5)?.map(|s| dec_txt(&s)),
1094                join_count: 0,
1095            })
1096        })
1097        .map_err(|e| e.to_string())?;
1098    let mut out = Vec::new();
1099    for row in rows {
1100        out.push(row.map_err(|e| e.to_string())?);
1101    }
1102    // Fill per-link join counts (distinct joiners via each label, attributed to me).
1103    if let Some(me) = crate::state::my_public_key() {
1104        if let Ok(counts) = community_invite_join_counts(community_id, &me) {
1105            // A v2 link minted without a label is joined as "": that bucket is only
1106            // its own while it is the one unlabeled link.
1107            let unlabeled = out.iter().filter(|r| r.label.as_deref().is_none_or(str::is_empty)).count();
1108            for rec in &mut out {
1109                match rec.label.as_deref() {
1110                    Some(l) if !l.is_empty() => rec.join_count = counts.get(l).copied().unwrap_or(0),
1111                    _ if unlabeled == 1 => rec.join_count = counts.get("").copied().unwrap_or(0),
1112                    _ => {}
1113                }
1114            }
1115        }
1116    }
1117    Ok(out)
1118}
1119
1120/// Forget a minted public-invite token (after revoking it on relays).
1121pub fn delete_public_invite(token: &str) -> Result<(), String> {
1122    let conn = super::get_write_connection_guard_static()?;
1123    // Stored tokens are encrypted (random nonce), so an equality DELETE can't match — scan,
1124    // decrypt, and delete the row whose plaintext token matches (by rowid). Few rows, owner-only.
1125    let rows: Vec<(i64, String)> = {
1126        let mut stmt = conn
1127            .prepare("SELECT rowid, token FROM community_public_invites")
1128            .map_err(|e| e.to_string())?;
1129        let mapped = stmt
1130            .query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)))
1131            .map_err(|e| e.to_string())?;
1132        mapped.filter_map(|r| r.ok()).collect()
1133    };
1134    for (rowid, stored) in rows {
1135        if dec_txt(&stored) == token {
1136            conn.execute("DELETE FROM community_public_invites WHERE rowid = ?1", params![rowid])
1137                .map_err(|e| format!("delete public invite: {e}"))?;
1138        }
1139    }
1140    Ok(())
1141}
1142
1143/// All minted public-invite links across ALL communities (backfill source for the synced Invite List).
1144pub fn list_all_public_invites() -> Result<Vec<PublicInviteRecord>, String> {
1145    let conn = super::get_db_connection_guard_static()?;
1146    let mut stmt = conn
1147        .prepare(
1148            "SELECT token, community_id, url, expires_at, created_at, label
1149               FROM community_public_invites ORDER BY created_at DESC",
1150        )
1151        .map_err(|e| e.to_string())?;
1152    let rows = stmt
1153        .query_map([], |r| {
1154            Ok(PublicInviteRecord {
1155                token: dec_txt(&r.get::<_, String>(0)?),
1156                community_id: r.get(1)?,
1157                url: dec_txt(&r.get::<_, String>(2)?),
1158                expires_at: r.get(3)?,
1159                created_at: r.get(4)?,
1160                label: r.get::<_, Option<String>>(5)?.map(|s| dec_txt(&s)),
1161                join_count: 0,
1162            })
1163        })
1164        .map_err(|e| e.to_string())?;
1165    let mut out = Vec::new();
1166    for row in rows {
1167        out.push(row.map_err(|e| e.to_string())?);
1168    }
1169    Ok(out)
1170}
1171
1172/// Remove a Community and all its local state (channels, retained message keys, parked
1173/// invites, minted public-invite tokens). Used when the user leaves a Community — there
1174/// is no protocol "leave" (membership is key possession), so leaving is purely local:
1175/// drop the keys + stop subscribing.
1176pub fn delete_community(community_id: &str) -> Result<(), String> {
1177    let out = delete_community_inner(community_id, false);
1178    crate::community::v2::realtime::invalidate_held_v2_community(community_id);
1179    out
1180}
1181
1182/// self-removal teardown: drop all local community state EXCEPT the held epoch keys
1183/// (`community_epoch_keys`). Read access to future epochs is already gone (the post-removal
1184/// keys are never delivered); retaining the OLD keys only preserves the ability to author a
1185/// `3305` self-delete of one's own past messages, each sealed under the epoch key it was sent
1186/// at. Used by every self-removal trigger (voluntary leave, kick of me, ban-rekey exclusion).
1187pub fn delete_community_retain_keys(community_id: &str) -> Result<(), String> {
1188    let out = delete_community_inner(community_id, true);
1189    crate::community::v2::realtime::invalidate_held_v2_community(community_id);
1190    out
1191}
1192
1193fn delete_community_inner(community_id: &str, retain_keys: bool) -> Result<(), String> {
1194    let conn = super::get_write_connection_guard_static()?;
1195    // Atomic: a crash/error mid-delete must not orphan channel/invite rows under a
1196    // now-missing parent (community_id_for_channel would still resolve them).
1197    let tx = conn.unchecked_transaction().map_err(|e| format!("delete community tx: {e}"))?;
1198    for sql in [
1199        Some("DELETE FROM communities WHERE community_id = ?1"),
1200        Some("DELETE FROM community_channels WHERE community_id = ?1"),
1201        // Multi-held epoch keys (base + per-channel, all epochs). RETAINED on a self-removal so a
1202        // later self-scrub of own past messages stays possible; dropped on an explicit delete/re-join reset
1203        // (else a re-join inherits stale rotated keys).
1204        (!retain_keys).then_some("DELETE FROM community_epoch_keys WHERE community_id = ?1"),
1205        // Writer and certifier secrets let their holder post and vouch; a self-scrub needs neither.
1206        Some("DELETE FROM community_epoch_keys WHERE community_id = ?1 AND (scope_id LIKE 'wr:%' OR scope_id LIKE 'wrmint:%' OR scope_id LIKE 'wrcert:%')"),
1207        Some("DELETE FROM community_public_invites WHERE community_id = ?1"),
1208        Some("DELETE FROM community_invite_link_sets WHERE community_id = ?1"),
1209        Some("DELETE FROM pending_community_invites WHERE community_id = ?1"),
1210        // Parked key vends. Dropped even under `retain_keys`: those are OUR held
1211        // epoch keys kept for a later self-scrub, whereas a parked vend is
1212        // undelivered key material for a community we no longer hold — nothing
1213        // re-judges it once the community is gone, and it would resurrect on
1214        // re-join to seat a stale epoch.
1215        Some("DELETE FROM pending_channel_keys WHERE community_id = ?1"),
1216        // Per-entity edition heads (keyless model) — else stale refuse-downgrade floors + self_hash
1217        // anchors survive a leave/re-join and reject a legitimately reset chain.
1218        Some("DELETE FROM community_edition_heads WHERE community_id = ?1"),
1219        Some("DELETE FROM community_bans WHERE community_id = ?1"),
1220        Some("DELETE FROM community_writers WHERE community_id = ?1"),
1221        Some("DELETE FROM community_held_wraps WHERE community_id = ?1"),
1222        // With the floors: a re-join reads the plane afresh, as its floors start afresh.
1223        Some("DELETE FROM community_control_wraps WHERE community_id = ?1"),
1224        Some("DELETE FROM settings WHERE key LIKE 'ctl_reads:' || ?1 || '%'"),
1225        Some("DELETE FROM settings WHERE key LIKE 'pln_reads:' || ?1 || '%'"),
1226        Some("DELETE FROM community_guestbook_wraps WHERE community_id = ?1"),
1227        Some("DELETE FROM settings WHERE key = 'gbk_reads:' || ?1"),
1228        Some("DELETE FROM settings WHERE key = 'gb_reads:' || ?1"),
1229        Some("DELETE FROM community_audit_local WHERE community_id = ?1"),
1230        Some("DELETE FROM settings WHERE key LIKE 'writer_postable:' || ?1 || ':%'"),
1231        Some("DELETE FROM settings WHERE key LIKE 'writer_cert:' || ?1 || ':%'"),
1232        Some("DELETE FROM settings WHERE key LIKE 'writer_retract:' || ?1 || ':%'"),
1233        Some("DELETE FROM settings WHERE key LIKE 'writer_retract_by:' || ?1 || ':%'"),
1234        Some("DELETE FROM community_owed_authors WHERE book IN (SELECT book FROM community_guestbook_books WHERE community_id = ?1)"),
1235        Some("DELETE FROM settings WHERE key = 'departures_seen:' || ?1"),
1236        Some("DELETE FROM community_departures_seen WHERE book IN (SELECT book FROM community_guestbook_books WHERE community_id = ?1)"),
1237    ]
1238    .into_iter()
1239    .flatten()
1240    {
1241        tx.execute(sql, params![community_id])
1242            .map_err(|e| format!("delete community: {e}"))?;
1243    }
1244    tx.commit().map_err(|e| format!("delete community commit: {e}"))?;
1245    roster_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
1246    departures_seen_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
1247    if let Some(cid) = crate::community::id32_from_hex(community_id) {
1248        banlist_cache().write().unwrap_or_else(|e| e.into_inner()).remove(&cid);
1249    }
1250    forget_community_channels(community_id);
1251    // `community_message_keys` and `community_wrap_owners` are INTENTIONALLY left intact: those are our OWN keys for
1252    // NIP-09-deleting our own messages. The right to erase our own content from relays outlives membership
1253    // — even after a ban or leave we must keep the ability to purge what we sent — so they survive a
1254    // community delete. (Keyed by message_id, no community_id; there is nothing community-scoped to drop.)
1255    Ok(())
1256}
1257
1258/// Observed participants: the best-effort member list of a Community, newest-active first.
1259/// Membership is NOT authoritative (a lurker who never posts and never announced won't appear).
1260/// A member is included when they have real activity — a posted message/reaction/edit, OR a
1261/// join presence (kind 3306) — UNLESS that is superseded by a more-recent leave, OR they are
1262/// banned. So a "leave" actually removes a member, and a leave-then-rejoin/post re-adds them.
1263/// `created_at` is in seconds. Result is capped (anti-flood); see `COMMUNITY_MEMBER_CAP`.
1264pub fn community_member_activity(community_id: &str) -> Result<Vec<(String, u64)>, String> {
1265    community_member_activity_capped(community_id, true)
1266}
1267
1268/// [`community_member_activity`] with the anti-flood display cap OPTIONAL. A roster seed
1269/// passes `capped = false` so EVERY member seeds — a silent truncation there would permanently
1270/// strand the dropped members (absent from the snapshot → absent from `memberlist()` → excluded
1271/// from every future rotation). Every other caller keeps the cap.
1272pub fn community_member_activity_capped(community_id: &str, capped: bool) -> Result<Vec<(String, u64)>, String> {
1273    member_activity(community_id, capped, false)
1274}
1275
1276/// [`community_member_activity`] for rules where leaving counts: a Grant holder is present only at
1277/// time 0, so any Leave or Kick of theirs outranks a Role that lingers. Uncapped.
1278pub fn community_member_activity_strict(community_id: &str) -> Result<Vec<(String, u64)>, String> {
1279    member_activity(community_id, false, true)
1280}
1281
1282/// Each author's newest post per Channel and kind: grouped in `idx_events_chat_kind_npub`'s
1283/// order, so it streams.
1284fn activity_sql(placeholders: &str) -> String {
1285    let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
1286    format!("SELECT npub, MAX(created_at) FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub IS NOT NULL AND npub != '' GROUP BY chat_id, kind, npub")
1287}
1288
1289/// The authors with a post that is no sign of membership, one indexed read per kind of sign.
1290/// Binds the Channel rows once per sign.
1291fn flagged_sql(placeholders: &str, strict: bool) -> String {
1292    let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
1293    let read = |sign: &str| format!("SELECT npub FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub IS NOT NULL AND {sign}");
1294    if strict { format!("{} UNION {}", read(HELD_POST), read(WRITER_POST)) } else { format!("SELECT DISTINCT npub FROM ({})", read(HELD_POST)) }
1295}
1296
1297/// A post its Channel's rules held, and a post at a writer address: each the predicate of a
1298/// partial index (migrations 122, 123), which the planner uses only for this very text.
1299pub(crate) const HELD_POST: &str = "instr(tags, '[\"unauthorized\"]') > 0";
1300pub(crate) const WRITER_POST: &str = "instr(tags, '[\"writer\"]') > 0";
1301
1302/// `strict`: Grants stamped 0 rather than now, and a post at a writer address no sign of
1303/// presence, since a writer who left still holds a key to post there.
1304fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result<Vec<(String, u64)>, String> {
1305    let grant_stamp = if strict { 0 } else { now_secs() as u64 };
1306    /// Cap on rendered members — bounds a presence-flood (fresh-identity 3306 spam) from
1307    /// growing the list / profile-fetch fan-out without limit.
1308    const COMMUNITY_MEMBER_CAP: usize = 500;
1309    use std::collections::HashMap;
1310
1311    // The owner is seeded by `fold_members`, which derives it from the community id.
1312    if !community_held(&CommunityId(hex_id_to_32(community_id)?))? {
1313        return Ok(Vec::new());
1314    }
1315
1316    let chat_ints = community_chat_row_ids(community_id)?;
1317
1318    // APPLICATION_SPECIFIC (30078) is the kind for presence/system events; everything else in a
1319    // community channel is real message activity. Inlined as a constant integer (no injection).
1320    let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
1321
1322    // active_at[npub] = newest real-activity time (any non-presence event), folded with joins below. The
1323    // proven owner + roster grant-holders are NOT seeded here — they're re-asserted AFTER the leave/ban
1324    // filter (else a stale message would overwrite the seed and a later `left` would wrongly cut a current
1325    // admin — the retain-set inversion). See the re-assert block below.
1326    let mut active: HashMap<String, u64> = HashMap::new();
1327    let mut left: HashMap<String, u64> = HashMap::new();
1328    // No channel has any events yet (e.g. fresh community) → skip the activity queries; the owner + roster
1329    // are still surfaced by the post-filter re-assert below.
1330    if !chat_ints.is_empty() {
1331    let conn = super::get_db_connection_guard_static()?;
1332    let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1333
1334    {
1335        // Each author's newest across Channels and kinds is taken here.
1336        let mut stmt = conn.prepare(&activity_sql(&placeholders)).map_err(|e| e.to_string())?;
1337        let rows = stmt
1338            .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1339                Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64))
1340            })
1341            .map_err(|e| e.to_string())?;
1342        for row in rows {
1343            let (npub, at) = row.map_err(|e| e.to_string())?;
1344            let newest = active.entry(npub).or_insert(at);
1345            *newest = (*newest).max(at);
1346        }
1347    }
1348
1349    // A post its Channel's rules held, kept marked on a manager's device, is no sign of membership;
1350    // for the writer rules, neither is one at a writer address.
1351    {
1352        let excluded = if strict { format!("({HELD_POST} OR {WRITER_POST})") } else { HELD_POST.to_string() };
1353        let mut stmt = conn.prepare(&flagged_sql(&placeholders, strict)).map_err(|e| e.to_string())?;
1354        let binds = chat_ints.iter().chain(chat_ints.iter().filter(|_| strict));
1355        let flagged: Vec<String> = stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get(0)).map_err(|e| e.to_string())?.flatten().collect();
1356        let sql = format!("SELECT MAX(created_at) FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub = ? AND NOT {excluded}");
1357        for npub in flagged {
1358            let mut args: Vec<rusqlite::types::Value> = chat_ints.iter().map(|i| rusqlite::types::Value::Integer(*i)).collect();
1359            args.push(npub.clone().into());
1360            let newest: Option<i64> = conn.query_row(&sql, rusqlite::params_from_iter(args), |r| r.get(0)).map_err(|e| e.to_string())?;
1361            match newest {
1362                Some(at) => active.insert(npub, at.max(0) as u64),
1363                None => active.remove(&npub),
1364            };
1365        }
1366    }
1367
1368    // Fold presence: a join (event-type "1") is activity; a leave (event-type "0") may remove.
1369    {
1370        let sql = format!(
1371            "SELECT npub, created_at, tags FROM events \
1372             WHERE chat_id IN ({placeholders}) AND kind = {sys} AND npub IS NOT NULL AND npub != ''"
1373        );
1374        let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1375        let rows = stmt
1376            .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1377                Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?))
1378            })
1379            .map_err(|e| e.to_string())?
1380            .collect::<Result<Vec<_>, _>>()
1381            .map_err(|e| e.to_string())?;
1382        // The reader goes back before every presence event's tags are parsed.
1383        drop(stmt);
1384        drop(conn);
1385        for (npub, at, tags_json) in rows {
1386            // SystemEventType: 1 = MemberJoined, 0 = MemberLeft (carried in an ["event-type", n] tag).
1387            let etype = serde_json::from_str::<Vec<Vec<String>>>(&tags_json)
1388                .ok()
1389                .and_then(|tags| {
1390                    tags.into_iter()
1391                        .find(|t| t.first().map(|s| s == "event-type").unwrap_or(false))
1392                        .and_then(|t| t.into_iter().nth(1))
1393                });
1394            match etype.as_deref() {
1395                Some("1") => {
1396                    let e = active.entry(npub).or_insert(0);
1397                    if at > *e { *e = at; }
1398                }
1399                Some("0") => {
1400                    let e = left.entry(npub).or_insert(0);
1401                    if at > *e { *e = at; }
1402                }
1403                _ => {}
1404            }
1405        }
1406    }
1407    }
1408
1409    // Events store bech32, so compare on bech32.
1410    let banned: std::collections::HashSet<String> = banned_set(community_id)
1411        .iter()
1412        .filter_map(|b| PublicKey::from_slice(b).ok())
1413        .filter_map(|pk| pk.to_bech32().ok())
1414        .collect();
1415
1416    // Member iff active, not banned, and last activity is at-or-after the last leave.
1417    let mut out: Vec<(String, u64)> = active
1418        .into_iter()
1419        .filter(|(npub, at)| !banned.contains(npub) && left.get(npub).is_none_or(|l| at >= l))
1420        .collect();
1421
1422    // RE-ASSERT authorized members AFTER the activity/leave filter: the proven owner + every
1423    // non-empty-grant roster holder is a member regardless of stale activity or a `left` — a privatize/ban
1424    // retain set must NEVER silently shed an authorized member (a leave or an old message must not drop a
1425    // current admin; that read-cut would lock a sitting admin out of their own community). Banned is the
1426    // only exclusion (a ban revokes the role anyway). Stamped `now_secs()` so they sort to the top and
1427    // survive the cap. Computed POST-filter so neither the leave filter nor a stale overwrite can cut them.
1428    {
1429        let mut present: std::collections::HashSet<String> = out.iter().map(|(n, _)| n.clone()).collect();
1430        let mut reassert = |npub: String| {
1431            if !banned.contains(&npub) && present.insert(npub.clone()) {
1432                out.push((npub, grant_stamp));
1433            }
1434        };
1435        if let Ok(roles) = get_community_roles(community_id) {
1436            for g in &roles.grants {
1437                if g.role_ids.is_empty() {
1438                    continue; // an empty grant is a revoked role, not a member
1439                }
1440                if let Some(b32) = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()) {
1441                    reassert(b32);
1442                }
1443            }
1444        }
1445    }
1446    out.sort_by_key(|m| std::cmp::Reverse(m.1));
1447    if capped {
1448        out.truncate(COMMUNITY_MEMBER_CAP);
1449    }
1450    Ok(out)
1451}
1452
1453/// Per-link join counts for the owner's public invites: `label -> distinct joiners` who joined
1454/// via a link minted by `inviter`. Distinct by joiner so a rejoin isn't double-counted. Labels are
1455/// unique per creator (random fallback ensures it), so (inviter, label) keys a single link.
1456///
1457/// Reads the attribution each joiner echoes into their Guestbook Join.
1458pub fn community_invite_join_counts(
1459    community_id: &str,
1460    inviter: &PublicKey,
1461) -> Result<std::collections::HashMap<String, u64>, String> {
1462    use std::collections::{HashMap, HashSet};
1463    hex_id_to_32(community_id)?;
1464    // Bundles name their creator in hex; older ones in bech32.
1465    let (hex, npub) = (inviter.to_hex(), inviter.to_bech32().unwrap_or_default());
1466    let (events, _) = get_guestbook(community_id)?;
1467    let mut per_label: HashMap<String, HashSet<PublicKey>> = HashMap::new();
1468    for e in &events {
1469        let crate::community::v2::guestbook::GuestbookEntry::Join { member, invited_by: Some((by, label)), .. } = &e.entry else {
1470            continue;
1471        };
1472        if by.eq_ignore_ascii_case(&hex) || *by == npub {
1473            per_label.entry(label.clone()).or_default().insert(*member);
1474        }
1475    }
1476    Ok(per_label.into_iter().map(|(k, v)| (k, v.len() as u64)).collect())
1477}
1478
1479/// One author's posting footprint in a Community, from the local store: how much
1480/// they have said and the window they said it in. Feeds the moderation panel's
1481/// tenure and volume signals ([`crate::community::raid`]). Times are seconds.
1482#[derive(Debug, Clone)]
1483pub struct AuthorFootprint {
1484    pub npub: String,
1485    pub messages: u64,
1486    pub first_secs: u64,
1487    pub last_secs: u64,
1488}
1489
1490/// The `chats` row ids of a Community's channels. Deliberately not `load_community`:
1491/// that decrypts every channel key and every retained epoch key, and all this needs is
1492/// the ids. A channel with no events yet has no row and is simply absent.
1493pub fn community_chat_row_ids(community_id: &str) -> Result<Vec<i64>, String> {
1494    let channel_ids = community_channel_ids(community_id)?;
1495    Ok(channel_ids.iter().filter_map(|c| super::id_cache::get_chat_id_by_identifier(c).ok()).collect())
1496}
1497
1498/// A community's channel ids, read from the rows alone (no key opened).
1499pub fn community_channel_ids(community_id: &str) -> Result<Vec<String>, String> {
1500    let conn = super::get_db_connection_guard_static()?;
1501    let mut stmt = conn
1502        .prepare("SELECT channel_id FROM community_channels WHERE community_id = ?1")
1503        .map_err(|e| e.to_string())?;
1504    let rows = stmt
1505        .query_map(params![community_id], |r| r.get::<_, String>(0))
1506        .map_err(|e| e.to_string())?;
1507    rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
1508}
1509
1510/// A stored policy: the exact bytes a community declared, plus what the engine
1511/// needs to use them.
1512#[derive(Debug, Clone)]
1513pub struct StoredPolicy {
1514    /// Stable local id. Once policies ride the control plane this becomes the
1515    /// edition's entity id.
1516    pub policy_id: String,
1517    /// The EXACT bytes, never a re-serialization — `policy_hash` is over these,
1518    /// and re-encoding them would change the only identity the wire has.
1519    pub bytes: String,
1520    pub hash: String,
1521    pub enabled: bool,
1522    pub updated_at: u64,
1523}
1524
1525/// Every policy a community holds, enabled or not, ordered by id so two clients
1526/// read them in the same order.
1527pub fn get_community_policies(community_id: &str) -> Result<Vec<StoredPolicy>, String> {
1528    let conn = super::get_db_connection_guard_static()?;
1529    let mut stmt = conn
1530        .prepare(
1531            "SELECT policy_id, bytes, hash, enabled, updated_at FROM community_policies \
1532             WHERE community_id = ?1 ORDER BY policy_id",
1533        )
1534        .map_err(|e| e.to_string())?;
1535    let rows = stmt
1536        .query_map(params![community_id], |r| {
1537            Ok(StoredPolicy {
1538                policy_id: r.get::<_, String>(0)?,
1539                bytes: dec_txt(&r.get::<_, String>(1)?),
1540                hash: r.get::<_, String>(2)?,
1541                enabled: r.get::<_, i64>(3)? != 0,
1542                updated_at: r.get::<_, i64>(4)?.max(0) as u64,
1543            })
1544        })
1545        .map_err(|e| e.to_string())?;
1546    rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
1547}
1548
1549/// Store one policy verbatim. The caller validates BEFORE calling: an invalid
1550/// policy is a rejected edit, not a stored one that evaluates to nothing.
1551pub fn set_community_policy(
1552    community_id: &str,
1553    policy_id: &str,
1554    bytes: &str,
1555    hash: &str,
1556    enabled: bool,
1557    updated_at: u64,
1558) -> Result<(), String> {
1559    let _seal = crate::crypto::gate::sealing();
1560    let conn = super::get_write_connection_guard_static()?;
1561    conn.execute(
1562        "INSERT INTO community_policies (community_id, policy_id, bytes, hash, enabled, updated_at)
1563         VALUES (?1, ?2, ?3, ?4, ?5, ?6)
1564         ON CONFLICT(community_id, policy_id) DO UPDATE SET bytes=?3, hash=?4, enabled=?5, updated_at=?6",
1565        params![community_id, policy_id, enc_txt(bytes)?, hash, enabled as i64, updated_at as i64],
1566    )
1567    .map_err(|e| format!("save policy: {e}"))?;
1568    Ok(())
1569}
1570
1571pub fn delete_community_policy(community_id: &str, policy_id: &str) -> Result<(), String> {
1572    let conn = super::get_write_connection_guard_static()?;
1573    conn.execute(
1574        "DELETE FROM community_policies WHERE community_id = ?1 AND policy_id = ?2",
1575        params![community_id, policy_id],
1576    )
1577    .map_err(|e| format!("delete policy: {e}"))?;
1578    Ok(())
1579}
1580
1581/// One message as the policy engine reads it: the identity, author, channel and
1582/// text a rule needs to cite what it convicted on.
1583#[derive(Debug, Clone)]
1584pub struct PolicyMessage {
1585    /// The inner rumor id, hex — a chunk-set wire event carries many messages,
1586    /// so only this names one.
1587    pub id: String,
1588    pub npub: String,
1589    /// Channel eid hex, so an exempt channel can be excluded by id.
1590    pub channel_id: String,
1591    /// Milliseconds: the engine clamps and orders on inner time.
1592    pub at_ms: u64,
1593    pub text: String,
1594    /// p-tags on the message — the only thing that counts as a mention.
1595    pub mentions: u32,
1596}
1597
1598/// The evaluation corpus: the newest `limit` messages a Community's channels
1599/// hold, with the identity and channel `community_recent_texts` discards.
1600/// Ordered oldest-first so the caller can clamp from the front.
1601pub fn community_policy_messages(community_id: &str, limit: usize) -> Result<Vec<PolicyMessage>, String> {
1602    let channel_ids: Vec<String> = {
1603        let conn = super::get_db_connection_guard_static()?;
1604        let mut stmt = conn
1605            .prepare("SELECT channel_id FROM community_channels WHERE community_id = ?1")
1606            .map_err(|e| e.to_string())?;
1607        let rows = stmt.query_map(params![community_id], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
1608        rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
1609    };
1610    if channel_ids.is_empty() || limit == 0 {
1611        return Ok(Vec::new());
1612    }
1613    // chat row id -> channel eid, so each message reports the channel it lives in.
1614    let mut chat_to_channel: std::collections::HashMap<i64, String> = std::collections::HashMap::new();
1615    for c in &channel_ids {
1616        if let Ok(row) = super::id_cache::get_chat_id_by_identifier(c) {
1617            chat_to_channel.insert(row, c.clone());
1618        }
1619    }
1620    if chat_to_channel.is_empty() {
1621        return Ok(Vec::new());
1622    }
1623    let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
1624    let chat_ints: Vec<i64> = chat_to_channel.keys().copied().collect();
1625    let rows: Vec<(String, String, i64, i64, String)> = {
1626        let conn = super::get_db_connection_guard_static()?;
1627        let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1628        let sql = format!(
1629            "SELECT id, npub, chat_id, created_at, content FROM events \
1630             WHERE chat_id IN ({placeholders}) AND kind = {text} \
1631               AND npub IS NOT NULL AND npub != '' \
1632             ORDER BY created_at DESC LIMIT {limit}"
1633        );
1634        let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1635        let mapped = stmt
1636            .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1637                Ok((
1638                    r.get::<_, String>(0)?,
1639                    r.get::<_, String>(1)?,
1640                    r.get::<_, i64>(2)?,
1641                    r.get::<_, i64>(3)?,
1642                    r.get::<_, String>(4)?,
1643                ))
1644            })
1645            .map_err(|e| e.to_string())?;
1646        mapped.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
1647    };
1648    let mut out: Vec<PolicyMessage> = crate::crypto::open_batch(|at_rest| rows
1649        .into_iter()
1650        .filter_map(|(id, npub, chat_id, created_at, content)| {
1651            let channel_id = chat_to_channel.get(&chat_id)?.clone();
1652            let content = at_rest.open_or_keep(content);
1653            // Vector has no mention tag: a mention is an npub in the body, which
1654            // the renderer turns into a pill. Counting `p` tags counted the reply
1655            // parent and the reaction target instead — 1 on an ordinary reply, 0
1656            // on a message that named fifteen people.
1657            let mentions = crate::community::policy::matchers::count_mentions(&content);
1658            Some(PolicyMessage {
1659                id,
1660                npub,
1661                channel_id,
1662                at_ms: (created_at.max(0) as u64).saturating_mul(1000),
1663                text: content,
1664                mentions,
1665            })
1666        })
1667        .collect());
1668    out.reverse(); // oldest-first
1669    Ok(out)
1670}
1671
1672/// Per-author message aggregates across a Community's channels. Counts only what a
1673/// person actually SAID — kinds 14/15 — so a reaction spammer doesn't read as a
1674/// conversationalist and an edit doesn't double-count its original.
1675pub fn community_author_footprints(community_id: &str) -> Result<Vec<AuthorFootprint>, String> {
1676    let chat_ints = community_chat_row_ids(community_id)?;
1677    if chat_ints.is_empty() {
1678        return Ok(Vec::new());
1679    }
1680    let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
1681    let file = crate::stored_event::event_kind::FILE_ATTACHMENT;
1682    let conn = super::get_db_connection_guard_static()?;
1683    let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1684    let sql = format!(
1685        "SELECT npub, COUNT(*), MIN(created_at), MAX(created_at) FROM events \
1686         WHERE chat_id IN ({placeholders}) AND kind IN ({text}, {file}) \
1687           AND npub IS NOT NULL AND npub != '' \
1688         GROUP BY npub"
1689    );
1690    let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1691    let rows = stmt
1692        .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1693            Ok(AuthorFootprint {
1694                npub: r.get::<_, String>(0)?,
1695                messages: r.get::<_, i64>(1)?.max(0) as u64,
1696                first_secs: r.get::<_, i64>(2)?.max(0) as u64,
1697                last_secs: r.get::<_, i64>(3)?.max(0) as u64,
1698            })
1699        })
1700        .map_err(|e| e.to_string())?;
1701    rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
1702}
1703
1704/// The newest `limit` message texts across a Community's channels, decrypted, as
1705/// `(npub, created_at_secs, text)`. Newest-first is the right window for raid work:
1706/// a wave is by definition recent, and reading the whole history would pay a vault
1707/// decrypt per row for messages that predate the attack.
1708pub fn community_recent_texts(community_id: &str, limit: usize) -> Result<Vec<(String, u64, String)>, String> {
1709    let chat_ints = community_chat_row_ids(community_id)?;
1710    if chat_ints.is_empty() || limit == 0 {
1711        return Ok(Vec::new());
1712    }
1713    let text = crate::stored_event::event_kind::PRIVATE_DIRECT_MESSAGE;
1714    let rows: Vec<(String, u64, String)> = {
1715        let conn = super::get_db_connection_guard_static()?;
1716        let placeholders = chat_ints.iter().map(|_| "?").collect::<Vec<_>>().join(",");
1717        let sql = format!(
1718            "SELECT npub, created_at, content FROM events \
1719             WHERE chat_id IN ({placeholders}) AND kind = {text} \
1720               AND npub IS NOT NULL AND npub != '' \
1721             ORDER BY created_at DESC LIMIT {limit}"
1722        );
1723        let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
1724        let mapped = stmt
1725            .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| {
1726                Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?))
1727            })
1728            .map_err(|e| e.to_string())?;
1729        mapped.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())?
1730    };
1731    Ok(crate::crypto::open_batch(|at_rest| {
1732        rows.into_iter().map(|(npub, at, content)| (npub, at, at_rest.open_or_keep(content))).collect()
1733    }))
1734}
1735
1736/// Replace a Community's stored banlist (JSON array of hex pubkeys) + the `created_at` (secs) of
1737/// the edition it came from. `at` is the version: the owner's own ban/unban writes its freshly
1738/// built event time, and `fetch_and_apply_banlist` only calls this with a strictly-newer edition,
1739/// so the stored banlist can never roll backwards.
1740// ── Banlist cache ────────────────────────────────────────────────────────────
1741// The inbound ban check runs per community event; uncached, each call costs a DB
1742// fetch + ChaCha20 vault decrypt + JSON parse, even though the banlist only changes
1743// on a fold. Cache the banned pubkeys as raw bytes, keyed by community id bytes —
1744// kept coherent by write-through in `set_community_banlist` and eviction in
1745// `delete_community_inner`, and held on the session, so a swap starts empty.
1746// Absent entry = not yet loaded (lazy-fills from DB on first read). An id not in
1747// canonical hex skips the cache and reads the DB.
1748type BanSet = std::sync::Arc<std::collections::HashSet<[u8; 32]>>;
1749struct BanlistCache;
1750type BanlistMap = std::sync::RwLock<std::collections::HashMap<[u8; 32], BanSet>>;
1751
1752fn banlist_cache() -> std::sync::Arc<BanlistMap> {
1753    crate::db::current_session().scoped::<BanlistCache, BanlistMap>()
1754}
1755
1756/// Most communities ban nobody; they all share this one empty set.
1757fn empty_ban_set() -> BanSet {
1758    static EMPTY: std::sync::LazyLock<BanSet> = std::sync::LazyLock::new(Default::default);
1759    std::sync::Arc::clone(&EMPTY)
1760}
1761
1762fn ban_set_from_hexes(hexes: &[String]) -> BanSet {
1763    let set: std::collections::HashSet<[u8; 32]> =
1764        hexes.iter().filter_map(|h| crate::simd::hex::hex_to_bytes_32_checked(h)).collect();
1765    if set.is_empty() { empty_ban_set() } else { std::sync::Arc::new(set) }
1766}
1767
1768/// Drop every cached banlist.
1769pub fn clear_banlist_cache() {
1770    *banlist_cache().write().unwrap_or_else(|e| e.into_inner()) = Default::default();
1771}
1772
1773/// [`banned_set`] by community id bytes — the inbound hot path's form.
1774pub fn banned_set_of(community: &[u8; 32]) -> BanSet {
1775    let cache = banlist_cache();
1776    if let Some(set) = cache.read().unwrap_or_else(|e| e.into_inner()).get(community) {
1777        return std::sync::Arc::clone(set);
1778    }
1779    let set = ban_set_from_hexes(&get_community_banlist(&crate::simd::hex::bytes_to_hex_32(community)).unwrap_or_default());
1780    cache.write().unwrap_or_else(|e| e.into_inner()).insert(*community, std::sync::Arc::clone(&set));
1781    set
1782}
1783
1784/// The banned-pubkey set for a community, lazily decrypted+parsed from DB on first
1785/// use and held (no further DB/decrypt) until a fold or delete invalidates it.
1786pub fn banned_set(community_id: &str) -> BanSet {
1787    match crate::community::id32_from_hex(community_id) {
1788        Some(cid) => banned_set_of(&cid),
1789        None => ban_set_from_hexes(&get_community_banlist(community_id).unwrap_or_default()),
1790    }
1791}
1792
1793/// Whether `author` is banned in this community. The per-event hot check: a HashSet
1794/// lookup once warm, no DB / decrypt / parse.
1795pub fn is_author_banned(community_id: &str, author: &PublicKey) -> bool {
1796    let set = banned_set(community_id);
1797    !set.is_empty() && set.contains(author.as_bytes())
1798}
1799
1800/// [`is_author_banned`] by community id bytes.
1801pub fn is_author_banned_in(community: &[u8; 32], author: &PublicKey) -> bool {
1802    let set = banned_set_of(community);
1803    !set.is_empty() && set.contains(author.as_bytes())
1804}
1805
1806/// Drop the moderation console's memoised verdict for this community. Called from
1807/// every write that changes who the console reports on, so an answer adopted from
1808/// ANOTHER admin's action invalidates it exactly like a local one: with a bot doing
1809/// the moderating, the stale console is the human admin's, and it is the only view
1810/// of the raid they have.
1811fn forget_console_verdict(community_id: &str) {
1812    crate::VectorCore::invalidate_raid_report(community_id);
1813}
1814
1815/// Whether the stored set changed: a ban hides what its target already posted, so a painted
1816/// timeline is stale only then.
1817pub fn set_community_banlist(community_id: &str, banned_hex: &[String], at: i64) -> Result<bool, String> {
1818    let before: std::collections::BTreeSet<String> = get_community_banlist(community_id).unwrap_or_default().into_iter().collect();
1819    let _seal = crate::crypto::gate::sealing();
1820    let conn = super::get_write_connection_guard_static()?;
1821    // MONOTONIC in the edition version. Un-banning is the fail-OPEN direction — the
1822    // un-banned party's rotations and messages start being honored again — so an
1823    // older edition must never overwrite a newer one, however it reached us. The
1824    // fold's floors already refuse a downgrade; this makes the storage layer refuse
1825    // it too, so no future folding change can reintroduce the hole. Checked before
1826    // writing so a refused downgrade touches neither the row nor the hot cache.
1827    let current_at: Option<i64> = conn
1828        .query_row("SELECT banlist_at FROM communities WHERE community_id = ?1", params![community_id], |r| r.get(0))
1829        .optional()
1830        .map_err(|e| format!("read banlist_at: {e}"))?
1831        .flatten();
1832    if current_at.is_some_and(|have| have > at) {
1833        crate::log_warn!(
1834            "[Banlist] refused a stale edition (v{at} behind held v{}) — un-banning is the fail-open direction",
1835            current_at.unwrap_or(0)
1836        );
1837        return Ok(false);
1838    }
1839    // The banlist lives in `community_bans`, not as a blob: SQL has to compare it
1840    // against `events.npub` to drop a banned author's rows BEFORE `LIMIT`, and a
1841    // filter applied after `LIMIT` returns short pages. Whole-set replace in one
1842    // transaction — the fold hands us the complete list every time, so there is no
1843    // partial state to reconcile and no second copy to drift.
1844    let tx = conn.unchecked_transaction().map_err(|e| format!("banlist tx: {e}"))?;
1845    tx.execute("DELETE FROM community_bans WHERE community_id = ?1", params![community_id])
1846        .map_err(|e| format!("clear banlist: {e}"))?;
1847    {
1848        let mut ins = tx
1849            .prepare("INSERT INTO community_bans (community_id, npub) VALUES (?1, ?2)")
1850            .map_err(|e| format!("prepare banlist insert: {e}"))?;
1851        // Stored as bech32, what `events.npub` holds, and sealed at rest: SQL is handed the
1852        // opened list (see `banned_npubs_json`). An unparseable entry is kept verbatim and
1853        // matches nothing. Sealed values never collide, so duplicates are dropped here.
1854        let joinable: std::collections::BTreeSet<String> = banned_hex
1855            .iter()
1856            .map(|hex| {
1857                PublicKey::from_hex(hex)
1858                    .ok()
1859                    .and_then(|pk| pk.to_bech32().ok())
1860                    .unwrap_or_else(|| hex.clone())
1861            })
1862            .collect();
1863        crate::crypto::seal_batch(|seal| {
1864            for npub in &joinable {
1865                ins.execute(params![community_id, seal.seal(npub)?])
1866                    .map_err(|e| format!("insert ban: {e}"))?;
1867            }
1868            Ok::<_, String>(())
1869        })?;
1870    }
1871    tx.execute(
1872        "UPDATE communities SET banlist_at = ?1 WHERE community_id = ?2",
1873        params![at, community_id],
1874    )
1875    .map_err(|e| format!("set banlist_at: {e}"))?;
1876    tx.commit().map_err(|e| format!("commit banlist: {e}"))?;
1877    forget_console_verdict(community_id);
1878    // Write-through: the hot-path cache must not lag a fold — a stale ban would wrongly
1879    // vanish a now-unbanned author's messages (fail-closed).
1880    if let Some(cid) = crate::community::id32_from_hex(community_id) {
1881        banlist_cache().write().unwrap_or_else(|e| e.into_inner()).insert(cid, ban_set_from_hexes(banned_hex));
1882    }
1883    Ok(before != banned_hex.iter().cloned().collect())
1884}
1885
1886/// Per-npub ban marks: lowercase-hex npub → `created_at` (secs) of the newest AUTHORIZED
1887/// banlist edition that named them. Retained past an un-ban on purpose — it is what stops a
1888/// pre-ban Join resurrecting a phantom member (CORD-02 §5 counts observation forward of the
1889/// latest Leave, Kick **or Ban**).
1890pub fn get_community_ban_marks(community_id: &str) -> Result<std::collections::BTreeMap<String, u64>, String> {
1891    let conn = super::get_db_connection_guard_static()?;
1892    let json: Option<String> = conn
1893        .query_row(
1894            "SELECT banlist_marks FROM communities WHERE community_id = ?1",
1895            params![community_id],
1896            |r| r.get(0),
1897        )
1898        .optional()
1899        .map_err(|e| format!("get ban marks: {e}"))?;
1900    Ok(json.and_then(|j| serde_json::from_str(&dec_txt(&j)).ok()).unwrap_or_default())
1901}
1902
1903/// MERGE fresh ban marks into the stored set, keeping the LATER time per npub and never
1904/// dropping an npub. A fold only sees the editions still in its window, so replacing
1905/// wholesale would forget every ban that has since aged out — precisely the history the
1906/// suppression depends on.
1907pub fn merge_community_ban_marks(community_id: &str, marks: &std::collections::BTreeMap<String, u64>) -> Result<bool, String> {
1908    let _seal = crate::crypto::gate::sealing();
1909    if marks.is_empty() {
1910        return Ok(false);
1911    }
1912    let mut stored = get_community_ban_marks(community_id)?;
1913    let mut changed = false;
1914    for (npub, at) in marks {
1915        let slot = stored.entry(npub.clone()).or_insert(0);
1916        if *at > *slot {
1917            *slot = *at;
1918            changed = true;
1919        }
1920    }
1921    if !changed {
1922        return Ok(false);
1923    }
1924    let json = enc_txt(&serde_json::to_string(&stored).map_err(|e| e.to_string())?)?;
1925    let conn = super::get_write_connection_guard_static()?;
1926    conn.execute(
1927        "UPDATE communities SET banlist_marks = ?1 WHERE community_id = ?2",
1928        params![json, community_id],
1929    )
1930    .map_err(|e| format!("set ban marks: {e}"))?;
1931    Ok(true)
1932}
1933
1934/// The `created_at` (secs) of the banlist edition currently stored, or 0 if none. The version
1935/// floor the rollback guard compares against.
1936pub fn get_community_banlist_at(community_id: &str) -> Result<i64, String> {
1937    let conn = super::get_db_connection_guard_static()?;
1938    let at: Option<i64> = conn
1939        .query_row(
1940            "SELECT banlist_at FROM communities WHERE community_id = ?1",
1941            params![community_id],
1942            |r| r.get(0),
1943        )
1944        .optional()
1945        .map_err(|e| format!("get banlist_at: {e}"))?;
1946    Ok(at.unwrap_or(0))
1947}
1948
1949/// Replace a Community's cached role graph (the aggregated `CommunityRoles`) + the `created_at`
1950/// (secs) of the newest per-entity edition it was built from. `at` is the version floor: the
1951/// fetch path only calls this with a strictly-newer aggregate, so the role graph can't roll
1952/// backwards (same guard as the banlist).
1953pub fn set_community_roles(
1954    community_id: &str,
1955    roles: &crate::community::roles::CommunityRoles,
1956    at: i64,
1957) -> Result<(), String> {
1958    let _seal = crate::crypto::gate::sealing();
1959    forget_console_verdict(community_id);
1960    let json = enc_txt(&serde_json::to_string(roles).map_err(|e| e.to_string())?)?;
1961    let conn = super::get_write_connection_guard_static()?;
1962    conn.execute(
1963        "UPDATE communities SET roles = ?1, roles_at = ?2 WHERE community_id = ?3",
1964        params![json, at, community_id],
1965    )
1966    .map_err(|e| format!("set roles: {e}"))?;
1967    roster_cache().lock().unwrap_or_else(|e| e.into_inner()).moved(community_id);
1968    drop(conn);
1969    bump_membership_generation();
1970    Ok(())
1971}
1972
1973/// A Community's cached role graph. Empty (default) for an unknown community or none stored.
1974type RosterCache = Parsed<std::sync::Arc<crate::community::roles::CommunityRoles>, 16>;
1975
1976fn roster_cache() -> std::sync::Arc<std::sync::Mutex<RosterCache>> {
1977    struct Key;
1978    super::current_session().scoped::<Key, std::sync::Mutex<RosterCache>>()
1979}
1980
1981pub fn get_community_roles(
1982    community_id: &str,
1983) -> Result<crate::community::roles::CommunityRoles, String> {
1984    get_community_roles_shared(community_id).map(std::sync::Arc::unwrap_or_clone)
1985}
1986
1987/// [`get_community_roles`] without copying the roster out.
1988pub fn get_community_roles_shared(community_id: &str) -> Result<std::sync::Arc<crate::community::roles::CommunityRoles>, String> {
1989    let cache = roster_cache();
1990    let generation = {
1991        let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
1992        if let Some(hit) = held.get(community_id) {
1993            return Ok(hit);
1994        }
1995        held.generation(community_id)
1996    };
1997    let json = {
1998        let conn = super::get_db_connection_guard_static()?;
1999        stored_roles(&conn, community_id).map_err(|e| format!("get roles: {e}"))?
2000    };
2001    let roles = std::sync::Arc::new(parse_roles(json, dec_txt));
2002    cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, roles.clone());
2003    Ok(roles)
2004}
2005
2006/// A community's roles JSON as stored (sealed when Local Encryption is on).
2007fn stored_roles(conn: &rusqlite::Connection, community_id: &str) -> rusqlite::Result<Option<String>> {
2008    conn.query_row("SELECT roles FROM communities WHERE community_id = ?1", params![community_id], |r| r.get(0))
2009        .optional()
2010}
2011
2012/// Open and parse stored roles; anything missing or unreadable is the empty roster.
2013fn parse_roles(json: Option<String>, open: impl FnOnce(&str) -> String) -> crate::community::roles::CommunityRoles {
2014    json.and_then(|j| serde_json::from_str(&open(&j)).ok()).unwrap_or_default()
2015}
2016
2017/// The `created_at` (secs) of the role-graph edition currently stored, or 0 if none.
2018pub fn get_community_roles_at(community_id: &str) -> Result<i64, String> {
2019    let conn = super::get_db_connection_guard_static()?;
2020    let at: Option<i64> = conn
2021        .query_row(
2022            "SELECT roles_at FROM communities WHERE community_id = ?1",
2023            params![community_id],
2024            |r| r.get(0),
2025        )
2026        .optional()
2027        .map_err(|e| format!("get roles_at: {e}"))?;
2028    Ok(at.unwrap_or(0))
2029}
2030
2031/// Record the current head (version + self_hash) of a control entity's edition chain (keyless model).
2032/// The send side reads this to emit the next edition as `version+1` citing `self_hash` as `prev_hash`;
2033/// the fold uses it as the per-entity refuse-downgrade floor + anchor. Upserts per (community, entity).
2034/// `inner_id` and `author` are the head edition's fork tiebreak key (see [`converge_edition_head_at_epoch`]).
2035pub fn set_edition_head(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32]) -> Result<(), String> {
2036    set_edition_head_inner(community_id, entity_id, version, self_hash, None, None, None)
2037}
2038
2039/// As [`set_edition_head`], but also records the head edition's `inner_id` (the deterministic tiebreak
2040/// key), so a later same-version convergence can rank against it. A plain advance carries it through.
2041pub fn set_edition_head_with_id(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32]) -> Result<(), String> {
2042    set_edition_head_inner(community_id, entity_id, version, self_hash, Some(inner_id), None, None)
2043}
2044
2045/// As [`set_edition_head_with_id`], stamping an EXPLICIT epoch — the epoch the caller's fold actually
2046/// ran under — instead of reading the community row at write time. Closes the TOCTOU where a
2047/// concurrent re-founding bumps `server_root_epoch` between a fold and its head persist, which would
2048/// stamp an old-plane version as the new epoch's floor and wedge the new epoch's genuine head.
2049/// Forget one entity's floor.
2050///
2051/// A floor refuses to fold an edition older than the one we last saw, which is
2052/// what stops a relay rolling our authority backwards. But a floor for an entity
2053/// the plane will never serve again — its author was demoted, so their editions
2054/// stopped counting; or it aged out entirely — is a veto nothing can ever satisfy,
2055/// and it blocks the WHOLE roster cache behind it. Dropping such a floor is only
2056/// safe once a coherent, quorum-backed read has failed to find the entity, which
2057/// is the one caller's job to establish.
2058pub fn delete_edition_head(community_id: &str, entity_id: &str) -> Result<(), String> {
2059    let conn = super::get_write_connection_guard_static()?;
2060    conn.execute(
2061        "DELETE FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
2062        params![community_id, entity_id],
2063    )
2064    .map_err(|e| format!("delete edition head: {e}"))?;
2065    Ok(())
2066}
2067
2068pub fn set_edition_head_at_epoch(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64) -> Result<(), String> {
2069    set_edition_head_inner(community_id, entity_id, version, self_hash, Some(inner_id), Some(author), Some(epoch))
2070}
2071
2072/// [`set_edition_head_at_epoch`] for a head of `family` ([`FLOOR_AUTHORITY`] or
2073/// [`FLOOR_CONTROL`]). An authority head takes a coordinate a control row holds; a control
2074/// head never takes one an authority row holds.
2075#[allow(clippy::too_many_arguments)]
2076pub fn set_family_head_at_epoch(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> Result<(), String> {
2077    set_family_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2078}
2079
2080#[allow(clippy::too_many_arguments)]
2081fn set_family_head_on(conn: &rusqlite::Connection, community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> Result<(), String> {
2082    conn.execute(
2083        "INSERT INTO community_edition_heads (community_id, entity_id, version, self_hash, inner_id, epoch, author, family)
2084         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
2085         ON CONFLICT(community_id, entity_id) DO UPDATE SET
2086            version = excluded.version,
2087            self_hash = excluded.self_hash,
2088            inner_id = excluded.inner_id,
2089            epoch = excluded.epoch,
2090            author = excluded.author,
2091            family = excluded.family
2092         WHERE NOT (community_edition_heads.family IS 'a' AND excluded.family IS NOT 'a')
2093           AND (excluded.epoch > community_edition_heads.epoch
2094            OR (excluded.epoch = community_edition_heads.epoch AND excluded.version > community_edition_heads.version)
2095            OR (excluded.family = 'a' AND community_edition_heads.family IS NOT NULL AND community_edition_heads.family IS NOT 'a'))",
2096        params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
2097    )
2098    .map_err(|e| format!("set edition head: {e}"))?;
2099    Ok(())
2100}
2101
2102/// A floor row: `(epoch, version, self_hash, inner_id, author, family)`.
2103type HeldFloorRow = (u64, u64, Vec<u8>, Option<Vec<u8>>, Option<Vec<u8>>, Option<String>);
2104
2105/// One fold's floor writes, made by [`write_folded_heads`] in a single transaction.
2106pub struct FloorWrites<'c> {
2107    conn: &'c rusqlite::Connection,
2108    community_id: &'c str,
2109    /// Each row as the transaction found it.
2110    held: std::collections::HashMap<String, HeldFloorRow>,
2111    /// Rows written in this transaction, which the snapshot above no longer describes.
2112    touched: std::collections::HashSet<String>,
2113}
2114
2115impl FloorWrites<'_> {
2116    /// The row already records exactly this head at `epoch`, so every write would leave it as it is.
2117    #[allow(clippy::too_many_arguments)]
2118    fn already(&self, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> bool {
2119        !self.touched.contains(entity_id)
2120            && self.held.get(entity_id).is_some_and(|(e, v, h, i, a, f)| {
2121                *e == epoch && *v == version && h.as_slice() == self_hash && i.as_deref() == Some(inner_id.as_slice()) && a.as_deref() == Some(author.as_slice()) && f.as_deref() == Some(family)
2122            })
2123    }
2124
2125    #[allow(clippy::too_many_arguments)]
2126    pub fn set(&mut self, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> Result<(), String> {
2127        if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
2128            return Ok(());
2129        }
2130        self.touched.insert(entity_id.to_string());
2131        set_family_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2132    }
2133
2134    #[allow(clippy::too_many_arguments)]
2135    pub fn converge(&mut self, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> Result<(), String> {
2136        if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
2137            return Ok(());
2138        }
2139        self.touched.insert(entity_id.to_string());
2140        converge_family_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, Some(family))
2141    }
2142
2143    #[allow(clippy::too_many_arguments)]
2144    pub fn rebase(&mut self, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> Result<(), String> {
2145        if self.already(entity_id, version, self_hash, inner_id, author, epoch, family) {
2146            return Ok(());
2147        }
2148        self.touched.insert(entity_id.to_string());
2149        rebase_edition_head_on(self.conn, self.community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2150    }
2151}
2152
2153/// Run one fold's floor writes in a single transaction: all of them land, or none.
2154pub fn write_folded_heads(community_id: &str, write: impl FnOnce(&mut FloorWrites<'_>) -> Result<(), String>) -> Result<(), String> {
2155    let conn = super::get_write_connection_guard_static()?;
2156    let tx = conn.unchecked_transaction().map_err(|e| format!("floor writes tx: {e}"))?;
2157    let held = {
2158        let mut stmt = tx
2159            .prepare_cached("SELECT entity_id, epoch, version, self_hash, inner_id, author, family FROM community_edition_heads WHERE community_id = ?1")
2160            .map_err(|e| format!("floor writes: {e}"))?;
2161        let rows = stmt
2162            .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, (r.get::<_, i64>(1)? as u64, r.get::<_, i64>(2)? as u64, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?))))
2163            .map_err(|e| format!("floor writes: {e}"))?;
2164        rows.collect::<Result<_, _>>().map_err(|e| format!("floor writes: {e}"))?
2165    };
2166    let mut writes = FloorWrites { conn: &tx, community_id, held, touched: Default::default() };
2167    write(&mut writes)?;
2168    tx.commit().map_err(|e| format!("floor writes commit: {e}"))
2169}
2170
2171/// A floor of the authority fold: Roles, Grants, the Banlist, Tenures, overwrites, syncs.
2172pub const FLOOR_AUTHORITY: &str = "a";
2173/// A floor of the control fold: metadata, Channels, Categories, pins, the invite registry.
2174pub const FLOOR_CONTROL: &str = "c";
2175
2176/// Entity → family, for the rows that record one.
2177pub fn edition_head_families(community_id: &str) -> Result<std::collections::HashMap<String, String>, String> {
2178    let conn = super::get_db_connection_guard_static()?;
2179    let mut stmt = conn
2180        .prepare("SELECT entity_id, family FROM community_edition_heads WHERE community_id = ?1 AND family IS NOT NULL")
2181        .map_err(|e| e.to_string())?;
2182    let rows = stmt
2183        .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
2184        .map_err(|e| e.to_string())?;
2185    rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
2186}
2187
2188fn set_edition_head_inner(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: Option<&[u8; 32]>, author: Option<&[u8; 32]>, epoch: Option<u64>) -> Result<(), String> {
2189    let conn = super::get_write_connection_guard_static()?;
2190    // MONOTONIC, EPOCH-PRIMARY: the head IS the refuse-downgrade floor. The recorded `epoch` is
2191    // the fold's epoch when given explicitly, else the community's current server-root epoch
2192    // (re-founding bumps it + resets versions to 1). A higher epoch ALWAYS supersedes (so a
2193    // re-founding's v1 lands over a held v21); within an epoch, version still only advances. So a
2194    // stale/hostile rollback can lower neither the epoch nor the in-epoch version.
2195    conn.execute(
2196        "INSERT INTO community_edition_heads (community_id, entity_id, version, self_hash, inner_id, epoch, author)
2197         VALUES (?1, ?2, ?3, ?4, ?5, COALESCE(?6, (SELECT server_root_epoch FROM communities WHERE community_id = ?1), 0), ?7)
2198         ON CONFLICT(community_id, entity_id) DO UPDATE SET
2199            version = excluded.version,
2200            self_hash = excluded.self_hash,
2201            inner_id = excluded.inner_id,
2202            epoch = excluded.epoch,
2203            author = excluded.author
2204         WHERE excluded.epoch > community_edition_heads.epoch
2205            OR (excluded.epoch = community_edition_heads.epoch AND excluded.version > community_edition_heads.version)",
2206        params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.map(|i| i.as_slice()), epoch.map(|e| e as i64), author.map(|a| a.as_slice())],
2207    )
2208    .map_err(|e| format!("set edition head: {e}"))?;
2209    Ok(())
2210}
2211
2212/// Replace the held head with a same-version fork winner (concurrent-edit resolution). Two
2213/// authorized editors working from one base both produce `version`, and every client must land on
2214/// the same edition. The winner is decided by the CALLER, which alone can rank authors against its
2215/// roster (CORD-04 §1: authority first, then the lower inner id) and which compares against the
2216/// held key from [`get_all_edition_heads_full`]. This only refuses what the caller cannot judge:
2217/// another version, or another epoch (a Refounding is the advance path's job).
2218pub fn converge_edition_head_at_epoch(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64) -> Result<(), String> {
2219    converge_family_head_at_epoch(community_id, entity_id, version, self_hash, inner_id, author, epoch, None)
2220}
2221
2222/// [`converge_edition_head_at_epoch`], touching only a row of `family` (or one that records none).
2223#[allow(clippy::too_many_arguments)]
2224pub fn converge_family_head_at_epoch(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: Option<&str>) -> Result<(), String> {
2225    converge_family_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2226}
2227
2228#[allow(clippy::too_many_arguments)]
2229fn converge_family_head_on(conn: &rusqlite::Connection, community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: Option<&str>) -> Result<(), String> {
2230    conn.execute(
2231        "UPDATE community_edition_heads
2232            SET self_hash = ?4, inner_id = ?5, author = ?7
2233          WHERE community_id = ?1 AND entity_id = ?2
2234            AND version = ?3
2235            AND epoch = ?6
2236            AND (?8 IS NULL OR family IS NULL OR family = ?8)
2237            AND (self_hash IS NOT ?4 OR inner_id IS NOT ?5 OR author IS NOT ?7)",
2238        params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
2239    )
2240    .map_err(|e| format!("converge edition head: {e}"))?;
2241    Ok(())
2242}
2243
2244/// Move a floor DOWN to the newest edition the Roster still admits, within one epoch. The
2245/// caller has proven the held head is served yet refused, on a complete authority fold
2246/// (refuse-downgrade guards the newest authorized edition, CORD-04 §1); nothing else may
2247/// lower a floor, and a different epoch is never touched.
2248/// Only a row of the head's own `family`, or one that records none, moves.
2249#[allow(clippy::too_many_arguments)]
2250pub fn rebase_edition_head_at_epoch(community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> Result<(), String> {
2251    rebase_edition_head_on(&*super::get_write_connection_guard_static()?, community_id, entity_id, version, self_hash, inner_id, author, epoch, family)
2252}
2253
2254#[allow(clippy::too_many_arguments)]
2255fn rebase_edition_head_on(conn: &rusqlite::Connection, community_id: &str, entity_id: &str, version: u64, self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32], epoch: u64, family: &str) -> Result<(), String> {
2256    conn.execute(
2257        "UPDATE community_edition_heads
2258            SET version = ?3, self_hash = ?4, inner_id = ?5, author = ?7, family = COALESCE(family, ?8)
2259          WHERE community_id = ?1 AND entity_id = ?2 AND epoch = ?6 AND (family IS NULL OR family = ?8)",
2260        params![community_id, entity_id, version as i64, self_hash.as_slice(), inner_id.as_slice(), epoch as i64, author.as_slice(), family],
2261    )
2262    .map_err(|e| format!("rebase edition head: {e}"))?;
2263    Ok(())
2264}
2265
2266/// Move a floor a build before marked editions wrote onto the same edition's real hash. Only while
2267/// the row still holds that unsigned hash at that version and epoch, so it never lands over a head
2268/// that moved on in the meantime.
2269#[allow(clippy::too_many_arguments)]
2270pub fn heal_edition_head(community_id: &str, entity_id: &str, epoch: u64, version: u64, unsigned: &[u8; 32], self_hash: &[u8; 32], inner_id: &[u8; 32], author: &[u8; 32]) -> Result<(), String> {
2271    let conn = super::get_write_connection_guard_static()?;
2272    conn.execute(
2273        "UPDATE community_edition_heads SET self_hash = ?6, inner_id = ?7, author = ?8
2274          WHERE community_id = ?1 AND entity_id = ?2 AND epoch = ?3 AND version = ?4 AND self_hash = ?5",
2275        params![community_id, entity_id, epoch as i64, version as i64, unsigned.as_slice(), self_hash.as_slice(), inner_id.as_slice(), author.as_slice()],
2276    )
2277    .map_err(|e| format!("heal edition head: {e}"))?;
2278    Ok(())
2279}
2280
2281/// The held head's inner id, or `None` if unheld or pre-migration (NULL).
2282pub fn get_edition_head_inner_id(community_id: &str, entity_id: &str) -> Result<Option<[u8; 32]>, String> {
2283    let conn = super::get_db_connection_guard_static()?;
2284    let row: Option<Option<Vec<u8>>> = conn
2285        .query_row(
2286            "SELECT inner_id FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
2287            params![community_id, entity_id],
2288            |r| r.get(0),
2289        )
2290        .optional()
2291        .map_err(|e| format!("get edition head inner_id: {e}"))?;
2292    match row.flatten() {
2293        Some(blob) if blob.len() == 32 => {
2294            let mut h = [0u8; 32];
2295            h.copy_from_slice(&blob);
2296            Ok(Some(h))
2297        }
2298        _ => Ok(None),
2299    }
2300}
2301
2302/// The current head `(version, self_hash)` of a control entity's edition chain, or `None` if no
2303/// edition is held yet (so the next edition is the genesis, version 1, no prev_hash).
2304pub fn get_edition_head(community_id: &str, entity_id: &str) -> Result<Option<(u64, [u8; 32])>, String> {
2305    let conn = super::get_db_connection_guard_static()?;
2306    let row: Option<(i64, Vec<u8>)> = conn
2307        .query_row(
2308            "SELECT version, self_hash FROM community_edition_heads WHERE community_id = ?1 AND entity_id = ?2",
2309            params![community_id, entity_id],
2310            |r| Ok((r.get(0)?, r.get(1)?)),
2311        )
2312        .optional()
2313        .map_err(|e| format!("get edition head: {e}"))?;
2314    match row {
2315        Some((v, hash)) if hash.len() == 32 => {
2316            let mut h = [0u8; 32];
2317            h.copy_from_slice(&hash);
2318            Ok(Some((v as u64, h)))
2319        }
2320        _ => Ok(None),
2321    }
2322}
2323
2324/// The set of control-entity ids (hex) this account tracks a head for. A base rotation gates its
2325/// head-advance on re-anchoring covering EVERY one of these (not just a matching count), so a relay
2326/// that withholds one entity's editions while over-serving another's can't slip a thinned control
2327/// plane past the rotator.
2328pub fn edition_head_entity_ids(community_id: &str) -> Result<std::collections::HashSet<String>, String> {
2329    let conn = super::get_db_connection_guard_static()?;
2330    let mut stmt = conn
2331        .prepare("SELECT entity_id FROM community_edition_heads WHERE community_id = ?1")
2332        .map_err(|e| e.to_string())?;
2333    let rows = stmt
2334        .query_map(params![community_id], |r| r.get::<_, String>(0))
2335        .map_err(|e| e.to_string())?;
2336    let mut out = std::collections::HashSet::new();
2337    for row in rows {
2338        out.insert(row.map_err(|e| e.to_string())?);
2339    }
2340    Ok(out)
2341}
2342
2343
2344/// Every tracked head as `entity_hex → (epoch, version, self_hash)` — the epoch-primary floor.
2345/// The caller seeds the fold with ONLY the entities at the community's CURRENT epoch (a head recorded
2346/// at a PRIOR epoch belongs to a superseded founding, so its entity folds fresh from the new epoch's v1
2347/// genesis). This is what lets a re-founding's compacted v1 plane land without a version-only downgrade.
2348/// Every tracked head as `entity_hex → (epoch, version, self_hash, inner_id)` — the epoch-primary
2349/// floor INCLUDING the deterministic tiebreak key, so a fold can resolve a same-version fork at the
2350/// floor (converge to the fork winner) instead of wedging on it.
2351/// `(epoch, version, self_hash, inner_id, author)`.
2352type EditionHeadFull = (u64, u64, [u8; 32], Option<[u8; 32]>, Option<[u8; 32]>, Option<FloorFamily>);
2353
2354/// Which fold a head's floor belongs to, as its row records it.
2355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2356pub enum FloorFamily {
2357    Authority,
2358    Control,
2359    /// A family this build doesn't know: no fold of its own takes it.
2360    Other,
2361}
2362
2363impl FloorFamily {
2364    pub fn of(family: &str) -> Self {
2365        match family {
2366            FLOOR_AUTHORITY => FloorFamily::Authority,
2367            FLOOR_CONTROL => FloorFamily::Control,
2368            _ => FloorFamily::Other,
2369        }
2370    }
2371}
2372/// `(epoch, version, self_hash)`.
2373type EditionHead = (u64, u64, [u8; 32]);
2374
2375pub fn get_all_edition_heads_full(community_id: &str) -> Result<std::collections::HashMap<String, EditionHeadFull>, String> {
2376    let conn = super::get_db_connection_guard_static()?;
2377    let mut stmt = conn
2378        .prepare("SELECT entity_id, epoch, version, self_hash, inner_id, author, family FROM community_edition_heads WHERE community_id = ?1")
2379        .map_err(|e| e.to_string())?;
2380    let rows = stmt
2381        .query_map(params![community_id], |r| {
2382            Ok((
2383                r.get::<_, String>(0)?,
2384                r.get::<_, i64>(1)?,
2385                r.get::<_, i64>(2)?,
2386                r.get::<_, Vec<u8>>(3)?,
2387                r.get::<_, Option<Vec<u8>>>(4)?,
2388                r.get::<_, Option<Vec<u8>>>(5)?,
2389                r.get::<_, Option<String>>(6)?,
2390            ))
2391        })
2392        .map_err(|e| e.to_string())?;
2393    let blob32 = |b: Option<Vec<u8>>| {
2394        b.and_then(|b| {
2395            (b.len() == 32).then(|| {
2396                let mut i = [0u8; 32];
2397                i.copy_from_slice(&b);
2398                i
2399            })
2400        })
2401    };
2402    let mut out = std::collections::HashMap::new();
2403    for row in rows {
2404        let (entity, epoch, version, hash, inner, author, family) = row.map_err(|e| e.to_string())?;
2405        if hash.len() == 32 {
2406            let mut h = [0u8; 32];
2407            h.copy_from_slice(&hash);
2408            out.insert(entity, (epoch as u64, version as u64, h, blob32(inner), blob32(author), family.as_deref().map(FloorFamily::of)));
2409        }
2410    }
2411    Ok(out)
2412}
2413
2414pub fn get_all_edition_heads_epoched(community_id: &str) -> Result<std::collections::HashMap<String, EditionHead>, String> {
2415    let conn = super::get_db_connection_guard_static()?;
2416    let mut stmt = conn
2417        .prepare("SELECT entity_id, epoch, version, self_hash FROM community_edition_heads WHERE community_id = ?1")
2418        .map_err(|e| e.to_string())?;
2419    let rows = stmt
2420        .query_map(params![community_id], |r| {
2421            Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?, r.get::<_, i64>(2)?, r.get::<_, Vec<u8>>(3)?))
2422        })
2423        .map_err(|e| e.to_string())?;
2424    let mut out = std::collections::HashMap::new();
2425    for row in rows {
2426        let (entity, epoch, version, hash) = row.map_err(|e| e.to_string())?;
2427        if hash.len() == 32 {
2428            let mut h = [0u8; 32];
2429            h.copy_from_slice(&hash);
2430            out.insert(entity, (epoch as u64, version as u64, h));
2431        }
2432    }
2433    Ok(out)
2434}
2435
2436/// A Community's current banlist (hex pubkeys). Empty for an unknown community or empty list.
2437pub fn get_community_banlist(community_id: &str) -> Result<Vec<String>, String> {
2438    // A ticket, because the first read may adopt the legacy blob, which seals.
2439    let _seal = crate::crypto::gate::sealing();
2440    let conn = super::get_db_connection_guard_static()?;
2441    let mut stmt = conn
2442        .prepare("SELECT npub FROM community_bans WHERE community_id = ?1")
2443        .map_err(|e| format!("prepare get banlist: {e}"))?;
2444    let rows = stmt
2445        .query_map(params![community_id], |r| r.get::<_, String>(0))
2446        .map_err(|e| format!("get banlist: {e}"))?;
2447    // Back to hex for the protocol; the table holds the sealed bech32.
2448    let mut out: Vec<String> = crate::crypto::open_batch(|at_rest| {
2449        rows.flatten()
2450            .map(|b| at_rest.open_or_keep(b))
2451            .map(|b| PublicKey::parse(&b).map(|pk| pk.to_hex()).unwrap_or(b))
2452            .collect()
2453    });
2454    if !out.is_empty() {
2455        return Ok(out);
2456    }
2457    // Empty may mean "nobody is banned" or "this row predates migration 90". The
2458    // legacy blob is encrypted, so the migration itself could not read it — the key
2459    // is not available at schema time. Adopt it on first read instead, where it is,
2460    // and clear it so this runs once.
2461    drop(stmt);
2462    let legacy: Option<String> = conn
2463        .query_row(
2464            "SELECT banlist FROM communities WHERE community_id = ?1 AND banlist IS NOT NULL AND banlist != ''",
2465            params![community_id],
2466            |r| r.get(0),
2467        )
2468        .optional()
2469        .map_err(|e| format!("read legacy banlist: {e}"))?
2470        .flatten();
2471    let Some(blob) = legacy else { return Ok(out) };
2472    let decoded = dec_txt(&blob);
2473    let Ok(list) = serde_json::from_str::<Vec<String>>(&decoded) else { return Ok(out) };
2474    if list.is_empty() {
2475        return Ok(out);
2476    }
2477    let tx = conn.unchecked_transaction().map_err(|e| format!("adopt tx: {e}"))?;
2478    {
2479        let mut ins = tx
2480            .prepare("INSERT INTO community_bans (community_id, npub) VALUES (?1, ?2)")
2481            .map_err(|e| format!("prepare adopt: {e}"))?;
2482        let joinable: std::collections::BTreeSet<String> = list
2483            .iter()
2484            .map(|hex| {
2485                PublicKey::from_hex(hex)
2486                    .ok()
2487                    .and_then(|pk| pk.to_bech32().ok())
2488                    .unwrap_or_else(|| hex.clone())
2489            })
2490            .collect();
2491        crate::crypto::seal_batch(|seal| {
2492            for npub in &joinable {
2493                ins.execute(params![community_id, seal.seal(npub)?]).map_err(|e| format!("adopt ban: {e}"))?;
2494            }
2495            Ok::<_, String>(())
2496        })?;
2497    }
2498    // The column is NOT NULL; an empty list retires it just as well and reads as "adopted".
2499    tx.execute("UPDATE communities SET banlist = '[]' WHERE community_id = ?1", params![community_id])
2500        .map_err(|e| format!("retire legacy banlist: {e}"))?;
2501    tx.commit().map_err(|e| format!("commit adopt: {e}"))?;
2502    crate::log_info!("[Banlist] adopted {} legacy ban(s) into community_bans", list.len());
2503    out = list;
2504    Ok(out)
2505}
2506
2507/// Replace a Community's cached invite-link registry (active link locators, hex), folded from the
2508/// owner-signed vsk=5 edition. Empty = Private. The version floor lives in `community_edition_heads`
2509/// (the registry's own entity), so this is just the content cache (mirrors `set_community_banlist`).
2510pub fn set_community_invite_registry(community_id: &str, link_locators: &[String]) -> Result<(), String> {
2511    let _seal = crate::crypto::gate::sealing();
2512    let json = enc_txt(&serde_json::to_string(link_locators).map_err(|e| e.to_string())?)?;
2513    let conn = super::get_write_connection_guard_static()?;
2514    conn.execute(
2515        "UPDATE communities SET invite_registry = ?1 WHERE community_id = ?2",
2516        params![json, community_id],
2517    )
2518    .map_err(|e| format!("set invite registry: {e}"))?;
2519    // A first link or a last revoke turns a group chat into a community or back.
2520    crate::notify::invalidate_communities();
2521    Ok(())
2522}
2523
2524/// Every Concord group that is a community rather than a group chat: more than one
2525/// channel we hold, or a live invite link. See [`crate::notify::is_community`].
2526pub fn community_ids_beyond_group_chat() -> Result<std::collections::HashSet<[u8; 32]>, String> {
2527    let conn = super::get_db_connection_guard_static()?;
2528    let mut stmt = conn
2529        .prepare(
2530            "SELECT c.community_id, c.invite_registry,
2531                    (SELECT COUNT(*) FROM community_channels ch WHERE ch.community_id = c.community_id)
2532               FROM communities c",
2533        )
2534        .map_err(|e| format!("prepare community kinds: {e}"))?;
2535    let rows = stmt
2536        .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, i64>(2)?)))
2537        .map_err(|e| format!("query community kinds: {e}"))?
2538        .collect::<Result<Vec<_>, _>>()
2539        .map_err(|e| format!("read community kinds: {e}"))?;
2540    // The reader goes back before every registry is decrypted and parsed.
2541    drop(stmt);
2542    drop(conn);
2543    let mut out = std::collections::HashSet::new();
2544    for (id, registry, channels) in rows {
2545        let links: Vec<String> = serde_json::from_str(&dec_txt(&registry)).unwrap_or_default();
2546        if channels > 1 || !links.is_empty() {
2547            out.extend(crate::community::id32_from_hex(&id));
2548        }
2549    }
2550    Ok(out)
2551}
2552
2553/// A Community's current invite-link registry (active link locators, hex). Empty for an unknown
2554/// community or a Private one. `is_public` = this is non-empty (computed mode).
2555pub fn get_community_invite_registry(community_id: &str) -> Result<Vec<String>, String> {
2556    let conn = super::get_db_connection_guard_static()?;
2557    let json: Option<String> = conn
2558        .query_row(
2559            "SELECT invite_registry FROM communities WHERE community_id = ?1",
2560            params![community_id],
2561            |r| r.get(0),
2562        )
2563        .optional()
2564        .map_err(|e| format!("get invite registry: {e}"))?;
2565    Ok(json.and_then(|j| serde_json::from_str(&dec_txt(&j)).ok()).unwrap_or_default())
2566}
2567
2568/// A folded per-creator public-invite-link set: the creator's pubkey (hex) and their active link
2569/// locators. Used to surface "X has N active invite links" in the UI.
2570pub struct InviteLinkSetRow {
2571    pub creator_hex: String,
2572    pub locators: Vec<String>,
2573}
2574
2575/// The creators the folded invite Registry currently lists for this community —
2576/// the cheap local answer to "might I hold a live public link here?".
2577pub fn invite_link_set_creators(community_id: &str) -> Result<Vec<String>, String> {
2578    let conn = super::get_write_connection_guard_static()?;
2579    let mut stmt = conn
2580        .prepare("SELECT creator FROM community_invite_link_sets WHERE community_id = ?1")
2581        .map_err(|e| e.to_string())?;
2582    let rows = stmt
2583        .query_map(params![community_id], |r| r.get::<_, String>(0))
2584        .map_err(|e| e.to_string())?
2585        .filter_map(|r| r.ok())
2586        .map(|stored| dec_txt(&stored))
2587        .collect();
2588    Ok(rows)
2589}
2590
2591/// Replace ALL of a Community's per-creator invite-link sets with the freshly-folded set (latest-wins).
2592/// Replacing wholesale (not upserting) drops a creator who has revoked every link, so the per-creator
2593/// view stays in lockstep with the flat registry computed in the same fold.
2594pub fn replace_invite_link_sets(community_id: &str, sets: &[InviteLinkSetRow]) -> Result<(), String> {
2595    let _seal = crate::crypto::gate::sealing();
2596    let mut conn = super::get_write_connection_guard_static()?;
2597    let tx = conn.transaction().map_err(|e| format!("invite-link-sets tx: {e}"))?;
2598    tx.execute("DELETE FROM community_invite_link_sets WHERE community_id = ?1", params![community_id])
2599        .map_err(|e| format!("clear invite-link-sets: {e}"))?;
2600    for s in sets {
2601        if s.locators.is_empty() {
2602            continue; // a creator with no active links is just absent (count 0)
2603        }
2604        let enc_creator = enc_txt(&s.creator_hex)?;
2605        let enc_locators = enc_txt(&serde_json::to_string(&s.locators).map_err(|e| e.to_string())?)?;
2606        // Plain INSERT: the DELETE above cleared the community's rows and `sets` has distinct creators
2607        // (an encrypted creator can't act as a dedup key anyway — random nonce per write).
2608        tx.execute(
2609            "INSERT INTO community_invite_link_sets (community_id, creator, locators) VALUES (?1, ?2, ?3)",
2610            params![community_id, enc_creator, enc_locators],
2611        )
2612        .map_err(|e| format!("insert invite-link-set: {e}"))?;
2613    }
2614    tx.commit().map_err(|e| format!("commit invite-link-sets: {e}"))?;
2615    Ok(())
2616}
2617
2618/// Every creator's active invite-link set for a Community (creator hex + locators). Empty for a Private
2619/// community (or one not yet re-folded since this table was added).
2620pub fn get_invite_link_sets(community_id: &str) -> Result<Vec<InviteLinkSetRow>, String> {
2621    let conn = super::get_db_connection_guard_static()?;
2622    let mut stmt = conn
2623        .prepare("SELECT creator, locators FROM community_invite_link_sets WHERE community_id = ?1")
2624        .map_err(|e| format!("prepare invite-link-sets: {e}"))?;
2625    let rows = stmt
2626        .query_map(params![community_id], |r| {
2627            let creator_hex: String = r.get(0)?;
2628            let json: String = r.get(1)?;
2629            Ok((creator_hex, json))
2630        })
2631        .map_err(|e| format!("query invite-link-sets: {e}"))?;
2632    let mut out = Vec::new();
2633    for row in rows {
2634        let (creator_hex, json) = row.map_err(|e| format!("row invite-link-sets: {e}"))?;
2635        let locators: Vec<String> = serde_json::from_str(&dec_txt(&json)).unwrap_or_default();
2636        out.push(InviteLinkSetRow { creator_hex: dec_txt(&creator_hex), locators });
2637    }
2638    Ok(out)
2639}
2640
2641/// Set the owner-dissolution SEAL on a community — PERMANENT + irreversible (no clear path; there
2642/// is no un-dissolve). Idempotent: re-setting an already-dissolved community is a harmless no-op. Once
2643/// set, the control fold stops advancing and the inbound path drops every subsequent event.
2644/// Seal a community as dissolved. Returns whether this call TRANSITIONED it (a
2645/// live→dissolved flip) so the caller can fire the one-time death notification
2646/// exactly once — a re-wrapped tombstone (fresh outer id, same owner seal) then
2647/// can't spam the handler.
2648pub fn set_community_dissolved(community_id: &str) -> Result<bool, String> {
2649    let conn = super::get_write_connection_guard_static()?;
2650    let changed = conn
2651        .execute(
2652            "UPDATE communities SET dissolved = 1 WHERE community_id = ?1 AND dissolved = 0",
2653            params![community_id],
2654        )
2655        .map_err(|e| format!("set dissolved: {e}"))?;
2656    crate::community::v2::realtime::invalidate_held_v2_community(community_id);
2657    Ok(changed > 0)
2658}
2659
2660/// Whether a community has been sealed by a folded + owner-verified GroupDissolved tombstone.
2661/// `false` for an unknown community.
2662pub fn get_community_dissolved(community_id: &str) -> Result<bool, String> {
2663    let conn = super::get_db_connection_guard_static()?;
2664    let v: Option<i64> = conn
2665        .query_row(
2666            "SELECT dissolved FROM communities WHERE community_id = ?1",
2667            params![community_id],
2668            |r| r.get(0),
2669        )
2670        .optional()
2671        .map_err(|e| format!("get dissolved: {e}"))?;
2672    Ok(v.unwrap_or(0) != 0)
2673}
2674
2675/// Ids of every locally-stored Community.
2676pub fn list_community_ids() -> Result<Vec<CommunityId>, String> {
2677    let conn = super::get_db_connection_guard_static()?;
2678    let mut stmt = conn
2679        .prepare("SELECT community_id FROM communities ORDER BY created_at")
2680        .map_err(|e| e.to_string())?;
2681    let rows = stmt
2682        .query_map([], |r| r.get::<_, String>(0))
2683        .map_err(|e| e.to_string())?;
2684    let mut ids = Vec::new();
2685    for row in rows {
2686        ids.push(CommunityId(hex_id_to_32(&row.map_err(|e| e.to_string())?)?));
2687    }
2688    Ok(ids)
2689}
2690
2691/// Every channel id held under a community we still hold.
2692pub fn held_channel_ids() -> Result<std::collections::HashSet<String>, String> {
2693    let conn = super::get_db_connection_guard_static()?;
2694    let mut stmt = conn
2695        .prepare("SELECT ch.channel_id FROM community_channels ch JOIN communities c ON c.community_id = ch.community_id")
2696        .map_err(|e| e.to_string())?;
2697    let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
2698    rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
2699}
2700
2701/// Every relay a held community lists, without opening any key.
2702pub fn held_community_relays() -> Result<std::collections::HashSet<String>, String> {
2703    let sealed: Vec<String> = {
2704        let conn = super::get_db_connection_guard_static()?;
2705        let mut stmt = conn.prepare("SELECT relays FROM communities").map_err(|e| e.to_string())?;
2706        let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
2707        rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
2708    };
2709    Ok(crate::crypto::open_batch(|o| {
2710        sealed
2711            .into_iter()
2712            .filter_map(|s| serde_json::from_str::<Vec<String>>(&o.open_or_keep(s)).ok())
2713            .flatten()
2714            .collect()
2715    }))
2716}
2717
2718/// A community's icon or banner, stored as [`CommunityImage`](crate::community::CommunityImage) JSON.
2719pub fn community_image(community_id: &str, banner: bool) -> Result<Option<crate::community::CommunityImage>, String> {
2720    let sql = if banner {
2721        "SELECT banner FROM communities WHERE community_id = ?1"
2722    } else {
2723        "SELECT icon FROM communities WHERE community_id = ?1"
2724    };
2725    let sealed: Option<String> = {
2726        let conn = super::get_db_connection_guard_static()?;
2727        conn.query_row(sql, params![community_id], |r| r.get::<_, Option<String>>(0))
2728            .optional()
2729            .map_err(|e| e.to_string())?
2730            .flatten()
2731    };
2732    let Some(sealed) = sealed else { return Ok(None) };
2733    let json = crate::crypto::open_batch(|o| o.open_or_keep(sealed));
2734    serde_json::from_str(&json).map(Some).map_err(|e| format!("community image json: {e}"))
2735}
2736
2737// ── Concord v2 storage ───────────────────────────────────────────────────────
2738//
2739// v2 communities reuse the shared community tables (migration 65 added the
2740// `protocol`/`owner_pubkey`/`owner_salt`/`private` columns). The base access key
2741// rides `server_root_key`/`server_root_epoch`.
2742// A public channel stores the community_root in `channel_key` as a placeholder
2743// (its real secret is derived from the root); a private channel stores its own
2744// key. At-rest encryption reuses the same `enc_*`/`dec_*` helpers.
2745
2746/// Whether the community is held locally.
2747pub fn community_held(id: &CommunityId) -> Result<bool, String> {
2748    let conn = super::get_db_connection_guard_static()?;
2749    conn.query_row("SELECT 1 FROM communities WHERE community_id = ?1", params![id.to_hex()], |_| Ok(()))
2750        .optional()
2751        .map(|row| row.is_some())
2752        .map_err(|e| e.to_string())
2753}
2754
2755/// The persisted CORD-02 §6 stash riding a community row: the vsk-0 fields
2756/// Vector doesn't drive but must republish verbatim on its own edits.
2757#[derive(serde::Serialize, serde::Deserialize, Default)]
2758struct CommunityMetaStash {
2759    #[serde(default, skip_serializing_if = "Option::is_none")]
2760    custom: Option<serde_json::Map<String, serde_json::Value>>,
2761    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
2762    extra: serde_json::Map<String, serde_json::Value>,
2763    /// The folded Categories ride here: a fold product like the channels, too small for a
2764    /// table of their own.
2765    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2766    categories: Vec<CategoryStash>,
2767}
2768
2769#[derive(serde::Serialize, serde::Deserialize)]
2770struct CategoryStash {
2771    id: String,
2772    name: String,
2773    #[serde(default, skip_serializing_if = "Option::is_none")]
2774    position: Option<String>,
2775    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
2776    extra: serde_json::Map<String, serde_json::Value>,
2777}
2778
2779/// As [`CommunityMetaStash`], for a channel row (vsk-2: + the voice flag).
2780#[derive(serde::Serialize, serde::Deserialize, Default)]
2781struct ChannelMetaStash {
2782    #[serde(default, skip_serializing_if = "Option::is_none")]
2783    voice: Option<bool>,
2784    #[serde(default, skip_serializing_if = "Option::is_none")]
2785    custom: Option<serde_json::Map<String, serde_json::Value>>,
2786    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
2787    extra: serde_json::Map<String, serde_json::Value>,
2788    #[serde(default, skip_serializing_if = "Option::is_none")]
2789    sealed: Option<crate::community::v2::community::SealedMeta>,
2790}
2791
2792/// Persist a v2 community + its channels atomically. UPSERT so a metadata
2793/// re-save preserves banlist/roles (managed by the fold, not here).
2794pub fn save_community_v2(c: &crate::community::v2::community::CommunityV2) -> Result<(), String> {
2795    let _seal = crate::crypto::gate::sealing();
2796    let conn = super::get_write_connection_guard_static()?;
2797    let id_hex = crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0);
2798    let relays_json = serde_json::to_string(&c.relays).map_err(|e| e.to_string())?;
2799    let created = (c.created_at_ms / 1000) as i64;
2800
2801    let enc_root = enc_key(&c.community_root)?;
2802    let enc_name = enc_txt(&c.name)?;
2803    let enc_relays = enc_txt(&relays_json)?;
2804    let enc_desc = enc_txt_opt(&c.description)?;
2805    let enc_owner_pk = enc_txt(&crate::simd::hex::bytes_to_hex_32(&c.identity.owner_xonly))?;
2806    let enc_owner_salt = enc_txt(&crate::simd::hex::bytes_to_hex_32(&c.identity.owner_salt))?;
2807    // ImageRef serializes to the CommunityImage JSON shape (`ext` rides the
2808    // flattened `extra`), so cache_community_image reads a v2 row's images unchanged.
2809    let icon_json = c.icon.as_ref().map(|i| serde_json::to_string(i).map_err(|e| e.to_string())).transpose()?;
2810    let banner_json = c.banner.as_ref().map(|b| serde_json::to_string(b).map_err(|e| e.to_string())).transpose()?;
2811    let enc_icon = enc_txt_opt(&icon_json)?;
2812    let enc_banner = enc_txt_opt(&banner_json)?;
2813    let categories: Vec<CategoryStash> = c
2814        .categories
2815        .iter()
2816        .map(|k| CategoryStash { id: crate::simd::hex::bytes_to_hex_32(&k.id), name: k.name.clone(), position: k.position.clone(), extra: k.extra.clone() })
2817        .collect();
2818    let stash_json = (c.meta_custom.is_some() || !c.meta_extra.is_empty() || !categories.is_empty())
2819        .then(|| serde_json::to_string(&CommunityMetaStash { custom: c.meta_custom.clone(), extra: c.meta_extra.clone(), categories }).map_err(|e| e.to_string()))
2820        .transpose()?;
2821    let enc_stash = enc_txt_opt(&stash_json)?;
2822    // The split pair (CORD-02 §2): the address as encrypted hex (owner_pubkey's
2823    // treatment), the secret as an encrypted blob (server_root_key's).
2824    let enc_control_pk = enc_txt_opt(&c.control_pk.map(|p| p.to_hex()))?;
2825    let enc_control_root = c.control_root.as_ref().map(enc_key).transpose()?;
2826
2827    let tx = conn.unchecked_transaction().map_err(|e| format!("save v2 community tx: {e}"))?;
2828    tx.execute(
2829        "INSERT INTO communities
2830            (community_id, server_root_key, name, relays, created_at, description,
2831             server_root_epoch, dissolved, protocol, owner_pubkey, owner_salt, icon, banner, meta_extra,
2832             control_pk, control_root)
2833         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 2, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
2834         ON CONFLICT(community_id) DO UPDATE SET
2835            server_root_key=?2, name=?3, relays=?4, description=?6,
2836            server_root_epoch=?7, dissolved=?8, protocol=2, owner_pubkey=?9, owner_salt=?10,
2837            icon=?11, banner=?12, meta_extra=?13, control_pk=?14, control_root=?15",
2838        params![
2839            id_hex, enc_root, enc_name, enc_relays, created, enc_desc,
2840            c.root_epoch.0 as i64, c.dissolved as i64, enc_owner_pk, enc_owner_salt,
2841            enc_icon, enc_banner, enc_stash, enc_control_pk, enc_control_root,
2842        ],
2843    )
2844    .map_err(|e| format!("save v2 community: {e}"))?;
2845
2846    for ch in &c.channels {
2847        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
2848        // channel_id is the sole PRIMARY KEY, so an UPSERT keyed on it alone would
2849        // let a bundle reusing ANOTHER community's channel_id overwrite that row's
2850        // key/epoch/private in place (a chat-plane hijack). Channel ids are random-32
2851        // (a genuine cross-community collision is negligible), so refuse rather than
2852        // clobber a foreign community's row.
2853        let owner_of: Option<String> = tx
2854            .query_row("SELECT community_id FROM community_channels WHERE channel_id=?1", params![ch_hex], |r| r.get(0))
2855            .optional()
2856            .map_err(|e| format!("channel ownership check: {e}"))?;
2857        if let Some(existing) = owner_of.filter(|existing| *existing != id_hex) {
2858            // SKIP the foreign-owned channel rather than fail the whole save: a
2859            // single replayed phantom (a same-owner cross-community vsk-2 edition)
2860            // would otherwise wedge ALL of this community's control-plane persistence
2861            // on every fold. The foreign row stays untouched; this community just
2862            // never acquires a row for that id. Loud on purpose: a community that hits
2863            // this on every fold is otherwise deaf with no trace.
2864            crate::log_warn!(
2865                "[v2:{}] channel {} not saved: its row belongs to community {} (unflipped migration, or a hijack attempt)",
2866                &id_hex[..8],
2867                &ch_hex[..8],
2868                &existing[..8.min(existing.len())]
2869            );
2870            continue;
2871        }
2872        // A public channel has no independent key; store the community_root as a
2873        // placeholder so the NOT NULL column is satisfied (the real secret is
2874        // derived from the root at read time via `channel_secret`).
2875        let stored_key = ch.key.unwrap_or(c.community_root);
2876        let enc_ch_key = enc_key(&stored_key)?;
2877        let enc_ch_name = enc_txt(&ch.name)?;
2878        let ch_stash_json = (ch.voice.is_some() || ch.meta_custom.is_some() || !ch.meta_extra.is_empty() || ch.sealed.is_some())
2879            .then(|| {
2880                serde_json::to_string(&ChannelMetaStash { voice: ch.voice, custom: ch.meta_custom.clone(), extra: ch.meta_extra.clone(), sealed: ch.sealed.clone() })
2881                    .map_err(|e| e.to_string())
2882            })
2883            .transpose()?;
2884        let enc_ch_stash = enc_txt_opt(&ch_stash_json)?;
2885        tx.execute(
2886            "INSERT INTO community_channels
2887                (channel_id, community_id, channel_key, epoch, name, created_at, private, meta_extra)
2888             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
2889             ON CONFLICT(channel_id) DO UPDATE SET
2890                channel_key=?3, epoch=?4, name=?5, private=?7, meta_extra=?8",
2891            params![ch_hex, id_hex, enc_ch_key, ch.epoch.0 as i64, enc_ch_name, created, ch.private as i64, enc_ch_stash],
2892        )
2893        .map_err(|e| format!("save v2 channel: {e}"))?;
2894    }
2895
2896    // Prune channels no longer in the in-memory set — the persisted set is
2897    // authoritative, so a control-follow delete or a rekey removal doesn't
2898    // resurrect (with a stale key) on the next reload. No FK references
2899    // community_channels, so this cascades to nothing.
2900    let keep: Vec<String> = c.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
2901    if keep.is_empty() {
2902        tx.execute("DELETE FROM community_channels WHERE community_id=?1", params![id_hex])
2903            .map_err(|e| format!("prune v2 channels: {e}"))?;
2904    } else {
2905        let placeholders = std::iter::repeat_n("?", keep.len()).collect::<Vec<_>>().join(",");
2906        let sql = format!("DELETE FROM community_channels WHERE community_id=? AND channel_id NOT IN ({placeholders})");
2907        let mut binds: Vec<String> = Vec::with_capacity(keep.len() + 1);
2908        binds.push(id_hex.clone());
2909        binds.extend(keep);
2910        tx.execute(&sql, rusqlite::params_from_iter(binds.iter()))
2911            .map_err(|e| format!("prune v2 channels: {e}"))?;
2912    }
2913
2914    tx.commit().map_err(|e| format!("commit v2 community: {e}"))?;
2915    crate::community::v2::realtime::invalidate_held_v2_community(&id_hex);
2916    // The save may have pruned channels (DELETE ... NOT IN the new set); evict so a
2917    // pruned channel stops resolving to this community.
2918    forget_community_channels(&id_hex);
2919    drop(conn);
2920    match settle_presence_lines(c) {
2921        Ok(true) => crate::emit_event("community_presence_lines", &serde_json::json!({ "community_id": id_hex })),
2922        Ok(false) => {}
2923        Err(e) => crate::log_warn!("[presence] settling {}'s join lines: {e}", &id_hex[..12]),
2924    }
2925    Ok(())
2926}
2927
2928/// The setting that remembers where a community keeps its Join/Leave lines: the channel,
2929/// with `:hidden` when they don't show.
2930fn presence_lines_key(community_id: &str) -> String {
2931    format!("presence_lines:{community_id}")
2932}
2933
2934/// A Join/Leave line among the events rows: a system event of type 0 (left) or 1 (joined).
2935const PRESENCE_LINE: &str = "instr(tags, '[\"d\",\"system-event\"]') > 0 AND (instr(tags, '[\"event-type\",\"1\"]') > 0 OR instr(tags, '[\"event-type\",\"0\"]') > 0)";
2936
2937/// Gather every Join/Leave line of a community into its presence home, and remember where
2938/// that is. True when lines moved or where they show changed.
2939pub fn settle_presence_lines(c: &crate::community::v2::community::CommunityV2) -> Result<bool, String> {
2940    let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
2941    let Some(home) = c.presence_home() else { return Ok(false) };
2942    let home_hex = crate::simd::hex::bytes_to_hex_32(&home.channel.id.0);
2943    let key = presence_lines_key(&cid);
2944    let stamp = if home.shown { home_hex.clone() } else { format!("{home_hex}:hidden") };
2945    let prev = super::settings::get_sql_setting(key.clone())?;
2946    let home_row = super::id_cache::get_chat_id_by_identifier(&home_hex).ok();
2947    let mut sources = community_chat_row_ids(&cid)?;
2948    // A home that was deleted is no longer among the channels: its lines come out too.
2949    if let Some(prev_home) = prev.as_deref().and_then(|p| p.get(..64)).filter(|p| *p != home_hex) {
2950        sources.extend(super::id_cache::get_chat_id_by_identifier(prev_home).ok());
2951    }
2952    sources.sort_unstable();
2953    sources.dedup();
2954    sources.retain(|r| Some(*r) != home_row);
2955    let mut moved = 0;
2956    if !sources.is_empty() {
2957        let sys = crate::stored_event::event_kind::APPLICATION_SPECIFIC;
2958        let placeholders = std::iter::repeat_n("?", sources.len()).collect::<Vec<_>>().join(",");
2959        let stray: bool = {
2960            let conn = super::get_db_connection_guard_static()?;
2961            let sql = format!("SELECT EXISTS(SELECT 1 FROM events WHERE chat_id IN ({placeholders}) AND kind = {sys} AND {PRESENCE_LINE})");
2962            conn.query_row(&sql, rusqlite::params_from_iter(sources.iter()), |r| r.get(0)).map_err(|e| e.to_string())?
2963        };
2964        if stray {
2965            let home_row = match home_row {
2966                Some(r) => r,
2967                None => super::id_cache::get_or_create_chat_id(&home_hex)?,
2968            };
2969            let conn = super::get_write_connection_guard_static()?;
2970            let sql = format!("UPDATE events SET chat_id = ? WHERE chat_id IN ({placeholders}) AND kind = {sys} AND {PRESENCE_LINE}");
2971            let binds = std::iter::once(home_row).chain(sources.iter().copied());
2972            moved = conn.execute(&sql, rusqlite::params_from_iter(binds)).map_err(|e| format!("move join lines: {e}"))?;
2973        }
2974    }
2975    let changed = prev.as_deref() != Some(stamp.as_str());
2976    if changed {
2977        super::settings::set_sql_setting(key, stamp)?;
2978    }
2979    Ok(moved > 0 || changed)
2980}
2981
2982/// Whether `channel_id` shows its community's Join/Leave lines. A community never settled
2983/// yet shows them wherever they are.
2984pub fn presence_lines_shown_in(channel_id: &str) -> Result<bool, String> {
2985    let Some(cid) = community_id_for_channel(channel_id)? else { return Ok(true) };
2986    Ok(match super::settings::get_sql_setting(presence_lines_key(&cid))? {
2987        Some(stamp) => stamp == channel_id,
2988        None => true,
2989    })
2990}
2991
2992/// Load a v2 community by id, or `None` if absent / not a v2 community.
2993pub fn load_community_v2(id: &CommunityId) -> Result<Option<crate::community::v2::community::CommunityV2>, String> {
2994    use crate::community::v2::community::{ChannelV2, CommunityV2};
2995    use crate::community::v2::control::CommunityIdentity;
2996    let conn = super::get_db_connection_guard_static()?;
2997    let id_hex = id.to_hex();
2998
2999    let row = conn
3000        .query_row(
3001            "SELECT server_root_key, name, relays, created_at, description,
3002                    server_root_epoch, dissolved, owner_pubkey, owner_salt,
3003                    icon, banner, meta_extra, control_pk, control_root
3004             FROM communities WHERE community_id = ?1",
3005            params![id_hex],
3006            |r| {
3007                Ok((
3008                    r.get::<_, Vec<u8>>(0)?,
3009                    r.get::<_, String>(1)?,
3010                    r.get::<_, String>(2)?,
3011                    r.get::<_, i64>(3)?,
3012                    r.get::<_, Option<String>>(4)?,
3013                    r.get::<_, i64>(5)?,
3014                    r.get::<_, i64>(6)?,
3015                    r.get::<_, Option<String>>(7)?,
3016                    r.get::<_, Option<String>>(8)?,
3017                    r.get::<_, Option<String>>(9)?,
3018                    r.get::<_, Option<String>>(10)?,
3019                    r.get::<_, Option<String>>(11)?,
3020                    r.get::<_, Option<String>>(12)?,
3021                    r.get::<_, Option<Vec<u8>>>(13)?,
3022                ))
3023            },
3024        )
3025        .optional()
3026        .map_err(|e| e.to_string())?;
3027    let Some((root_blob, name_e, relays_e, created, desc_e, root_epoch, dissolved, owner_pk_e, owner_salt_e, icon_e, banner_e, stash_e, control_pk_e, control_root_b)) = row
3028    else {
3029        return Ok(None);
3030    };
3031    let (Some(owner_pk_e), Some(owner_salt_e)) = (owner_pk_e, owner_salt_e) else {
3032        return Err("v2 community row is missing its owner commitment".to_string());
3033    };
3034
3035    // One vault read for the whole row set.
3036    let dk = |o: &mut crate::crypto::AtRestOpener, b: &[u8]| to_32(&o.open_blob_or_keep(b));
3037    let dt = |o: &mut crate::crypto::AtRestOpener, s: &str| o.open_or_keep(s.to_string());
3038    crate::crypto::open_batch(|o| {
3039        let community_root = dk(o, &root_blob)?;
3040        let owner_xonly = parse_hex32(&dt(o, &owner_pk_e))?;
3041        let owner_salt = parse_hex32(&dt(o, &owner_salt_e))?;
3042        let identity = CommunityIdentity { community_id: *id, owner_xonly, owner_salt };
3043        let relays: Vec<String> = serde_json::from_str(&dt(o, &relays_e)).unwrap_or_default();
3044
3045        let mut channels = Vec::new();
3046        {
3047            let mut stmt = conn
3048                .prepare(
3049                    "SELECT channel_id, channel_key, epoch, name, private, meta_extra
3050                     FROM community_channels WHERE community_id = ?1 ORDER BY created_at",
3051                )
3052                .map_err(|e| e.to_string())?;
3053            let rows = stmt
3054                .query_map(params![id_hex], |r| {
3055                    Ok((
3056                        r.get::<_, String>(0)?,
3057                        r.get::<_, Vec<u8>>(1)?,
3058                        r.get::<_, i64>(2)?,
3059                        r.get::<_, String>(3)?,
3060                        r.get::<_, i64>(4)?,
3061                        r.get::<_, Option<String>>(5)?,
3062                    ))
3063                })
3064                .map_err(|e| e.to_string())?;
3065            for row in rows {
3066                let (ch_hex, key_blob, epoch, name_e, private, ch_stash_e) = row.map_err(|e| e.to_string())?;
3067                let private = private != 0;
3068                let key = dk(o, &key_blob)?;
3069                // Unparseable stash degrades to empty — the fold re-persists the
3070                // authoritative value on its next pass.
3071                let ch_stash: ChannelMetaStash = ch_stash_e
3072                    .map(|s| dt(o, &s))
3073                    .and_then(|j| serde_json::from_str(&j).ok())
3074                    .unwrap_or_default();
3075                channels.push(ChannelV2 {
3076                    id: ChannelId(hex_id_to_32(&ch_hex)?),
3077                    name: dt(o, &name_e),
3078                    private,
3079                    // A public channel derives from the root — drop the placeholder. A
3080                    // PRIVATE channel stored with the root value is the KEYLESS placeholder
3081                    // (key not yet delivered over the rekey plane): a real private key is
3082                    // independently random (CORD-03 §1), never the root, so reconstruct
3083                    // None and keep every read/send path behind the keyless guards instead
3084                    // of silently addressing the public plane.
3085                    key: (private && key != community_root).then_some(key),
3086                    epoch: Epoch(epoch as u64),
3087                    voice: ch_stash.voice,
3088                    meta_custom: ch_stash.custom,
3089                    meta_extra: ch_stash.extra,
3090                    writers: None,
3091                    sealed: ch_stash.sealed,
3092                });
3093            }
3094        }
3095        {
3096            let mut stmt = conn
3097                .prepare("SELECT channel_id, content FROM community_writers WHERE community_id = ?1")
3098                .map_err(|e| e.to_string())?;
3099            let rows = stmt
3100                .query_map(params![id_hex], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
3101                .map_err(|e| e.to_string())?;
3102            for row in rows {
3103                let (ch_hex, content) = row.map_err(|e| e.to_string())?;
3104                let Some(ch) = channels.iter_mut().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == ch_hex) else { continue };
3105                ch.writers = crate::community::v2::writers::Ledger::parse(&dt(o, &content)).filter(|l| l.channel == ch.id.0);
3106            }
3107        }
3108        // The held set keeps these resident; push-growth leaves up to half unused.
3109        channels.shrink_to_fit();
3110
3111        // Unparseable image JSON degrades to no-image rather than failing the load —
3112        // the fold re-persists the authoritative value on its next pass.
3113        let icon = icon_e
3114            .map(|s| dt(o, &s))
3115            .and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
3116        let banner = banner_e
3117            .map(|s| dt(o, &s))
3118            .and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
3119        let stash: CommunityMetaStash = stash_e
3120            .map(|s| dt(o, &s))
3121            .and_then(|j| serde_json::from_str(&j).ok())
3122            .unwrap_or_default();
3123
3124        // The split pair (CORD-02 §2). Fail closed on corruption: an unparseable
3125        // address degrades to the legacy view, and a secret that no longer derives
3126        // to the held address is dropped to read-only rather than signing at an
3127        // address nobody reads.
3128        let control_pk = control_pk_e
3129            .as_deref()
3130            .and_then(|e| nostr_sdk::prelude::PublicKey::from_hex(&dt(o, e)).ok());
3131        let control_root = match (control_pk, control_root_b) {
3132            (Some(pk), Some(blob)) => dk(o, &blob).ok().filter(|cr| {
3133                crate::community::v2::derive::control_signer_group_key(cr, id, Epoch(root_epoch as u64)).pk() == pk
3134            }),
3135            _ => None,
3136        };
3137
3138        Ok(Some(CommunityV2 {
3139            identity,
3140            community_root,
3141            root_epoch: Epoch(root_epoch as u64),
3142            control_pk,
3143            control_root,
3144            name: dt(o, &name_e),
3145            description: desc_e.map(|d| dt(o, &d)),
3146            icon,
3147            banner,
3148            meta_custom: stash.custom,
3149            meta_extra: stash.extra,
3150            relays,
3151            channels,
3152            categories: stash
3153                .categories
3154                .into_iter()
3155                .filter_map(|k| {
3156                    let id = crate::simd::hex::hex_to_bytes_32_checked(&k.id)?;
3157                    Some(crate::community::v2::community::CategoryV2 { id, name: k.name, position: k.position, extra: k.extra })
3158                })
3159                .collect(),
3160            dissolved: dissolved != 0,
3161            created_at_ms: (created as u64).saturating_mul(1000),
3162        }))
3163    })
3164}
3165fn parse_hex32(hex: &str) -> Result<[u8; 32], String> {
3166    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
3167        return Err("stored value is not 32-byte hex".to_string());
3168    }
3169    Ok(crate::simd::hex::hex_to_bytes_32(hex))
3170}
3171
3172/// What was parsed out of a community's stored rows, for the last `CAP` communities read or
3173/// written this session: parsing costs far more than most uses of the result. Each slot carries
3174/// the write generation it was read under, and a writer moves the generation on while it still
3175/// holds the write connection, so a read that overlapped a write is never served after it.
3176struct Parsed<T, const CAP: usize> {
3177    generations: std::collections::HashMap<String, u64>,
3178    /// Most recently used last.
3179    slots: Vec<(String, u64, T)>,
3180}
3181
3182impl<T, const CAP: usize> Default for Parsed<T, CAP> {
3183    fn default() -> Self {
3184        Parsed { generations: Default::default(), slots: Vec::new() }
3185    }
3186}
3187
3188impl<T: Clone, const CAP: usize> Parsed<T, CAP> {
3189    fn generation(&self, community_id: &str) -> u64 {
3190        self.generations.get(community_id).copied().unwrap_or(0)
3191    }
3192
3193    fn get(&mut self, community_id: &str) -> Option<T> {
3194        let generation = self.generation(community_id);
3195        let i = self.slots.iter().position(|(id, g, _)| id == community_id && *g == generation)?;
3196        let slot = self.slots.remove(i);
3197        let held = slot.2.clone();
3198        self.slots.push(slot);
3199        Some(held)
3200    }
3201
3202    fn put(&mut self, community_id: &str, generation: u64, held: T) {
3203        if generation != self.generation(community_id) {
3204            return;
3205        }
3206        self.slots.retain(|(id, ..)| id != community_id);
3207        if self.slots.len() >= CAP {
3208            self.slots.remove(0);
3209        }
3210        self.slots.push((community_id.to_string(), generation, held));
3211    }
3212
3213    /// A write is landing: what was read before it is stale. Returns the new generation.
3214    fn moved(&mut self, community_id: &str) -> u64 {
3215        let generation = self.generation(community_id) + 1;
3216        self.generations.insert(community_id.to_string(), generation);
3217        self.slots.retain(|(id, ..)| id != community_id);
3218        generation
3219    }
3220}
3221
3222/// A community's stored Guestbook in arrival order, found by rumor id.
3223#[derive(Clone, Default)]
3224pub struct Guestbook {
3225    events: Vec<crate::community::v2::guestbook::GuestbookEvent>,
3226    by_id: std::collections::HashMap<[u8; 32], u32>,
3227}
3228
3229impl Guestbook {
3230    /// Keeps the first of any rumor given twice, as the rows do.
3231    fn new(given: Vec<crate::community::v2::guestbook::GuestbookEvent>) -> Self {
3232        let mut book = Guestbook { events: Vec::with_capacity(given.len()), by_id: std::collections::HashMap::with_capacity(given.len()) };
3233        for ev in given {
3234            if !book.by_id.contains_key(&ev.rumor_id) {
3235                book.by_id.insert(ev.rumor_id, book.events.len() as u32);
3236                book.events.push(ev);
3237            }
3238        }
3239        book
3240    }
3241
3242    pub fn get(&self, rumor_id: &[u8; 32]) -> Option<&crate::community::v2::guestbook::GuestbookEvent> {
3243        self.by_id.get(rumor_id).map(|&i| &self.events[i as usize])
3244    }
3245
3246    pub fn into_events(self) -> Vec<crate::community::v2::guestbook::GuestbookEvent> {
3247        self.events
3248    }
3249
3250    /// A rumor held already takes `ev` in its place; a new one goes last.
3251    fn upsert(&mut self, ev: &crate::community::v2::guestbook::GuestbookEvent) {
3252        match self.by_id.get(&ev.rumor_id) {
3253            Some(&i) => self.events[i as usize] = ev.clone(),
3254            None => {
3255                self.by_id.insert(ev.rumor_id, self.events.len() as u32);
3256                self.events.push(ev.clone());
3257            }
3258        }
3259    }
3260}
3261
3262impl std::ops::Deref for Guestbook {
3263    type Target = [crate::community::v2::guestbook::GuestbookEvent];
3264    fn deref(&self) -> &Self::Target {
3265        &self.events
3266    }
3267}
3268
3269type GuestbookShared = (std::sync::Arc<Guestbook>, u64);
3270type GuestbookCache = Parsed<GuestbookShared, 8>;
3271
3272fn guestbook_cache() -> std::sync::Arc<std::sync::Mutex<GuestbookCache>> {
3273    struct Key;
3274    super::current_session().scoped::<Key, std::sync::Mutex<GuestbookCache>>()
3275}
3276
3277/// [`get_guestbook`] without copying the events out: what a fold that only reads them wants.
3278pub fn get_guestbook_shared(community_id: &str) -> Result<GuestbookShared, String> {
3279    let cache = guestbook_cache();
3280    let generation = {
3281        let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3282        if let Some(hit) = held.get(community_id) {
3283            return Ok(hit);
3284        }
3285        held.generation(community_id)
3286    };
3287    let (events, cursor) = read_guestbook(community_id)?;
3288    let shared = (std::sync::Arc::new(Guestbook::new(events)), cursor);
3289    cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, shared.clone());
3290    Ok(shared)
3291}
3292
3293/// A community's persisted Guestbook: its membership events in arrival order and the
3294/// newest-seen cursor (relay seconds). `([], 0)` when never synced.
3295pub fn get_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
3296    let (events, cursor) = get_guestbook_shared(community_id)?;
3297    Ok((std::sync::Arc::unwrap_or_clone(events).into_events(), cursor))
3298}
3299
3300fn read_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
3301    let legacy = {
3302        let conn = super::get_db_connection_guard_static()?;
3303        conn.query_row("SELECT events, cursor_secs FROM community_guestbook WHERE community_id = ?1", params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
3304            .optional()
3305            .map_err(|e| format!("load guestbook: {e}"))?
3306    };
3307    let Some((blob, cursor)) = legacy else {
3308        return Ok((Vec::new(), 0));
3309    };
3310    if !blob.is_empty() {
3311        move_guestbook_blob(community_id, &blob)?;
3312    }
3313    // The reader goes back before the decrypt and decode, which outlast the read by far.
3314    let rows: Vec<([u8; 32], Vec<u8>)> = {
3315        let conn = super::get_db_connection_guard_static()?;
3316        let mut stmt = conn
3317            .prepare_cached(
3318                "SELECT e.rumor_id, e.body FROM community_guestbook_events e
3319                 JOIN community_guestbook_books b ON b.book = e.book
3320                 WHERE b.community_id = ?1 ORDER BY e.seq",
3321            )
3322            .map_err(|e| format!("load guestbook events: {e}"))?;
3323        let rows = stmt
3324            .query_map(params![community_id], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, Vec<u8>>(1)?)))
3325            .map_err(|e| format!("load guestbook events: {e}"))?;
3326        rows.filter_map(|r| r.ok()).filter_map(|(id, body)| Some((id.try_into().ok()?, body))).collect()
3327    };
3328    let events = crate::crypto::open_batch(|o| {
3329        rows.into_iter().filter_map(|(id, body)| crate::community::v2::guestbook::event_from_body(id, &o.open_blob_or_keep(&body))).collect()
3330    });
3331    Ok((events, cursor.max(0) as u64))
3332}
3333
3334/// Move a Guestbook still stored as one blob into rows, leaving the blob column empty. A blob
3335/// that doesn't read (sealed under a key not held) stays as it is.
3336fn move_guestbook_blob(community_id: &str, blob: &str) -> Result<(), String> {
3337    let Ok(events) = serde_json::from_str::<Vec<crate::community::v2::guestbook::GuestbookEvent>>(&dec_txt(blob)) else {
3338        return Ok(());
3339    };
3340    let _seal = crate::crypto::gate::sealing();
3341    let conn = super::get_write_connection_guard_static()?;
3342    let tx = conn.unchecked_transaction().map_err(|e| format!("move guestbook tx: {e}"))?;
3343    // Another read may have moved it first.
3344    let still: Option<String> = tx
3345        .query_row("SELECT events FROM community_guestbook WHERE community_id = ?1", params![community_id], |r| r.get(0))
3346        .optional()
3347        .map_err(|e| format!("move guestbook: {e}"))?;
3348    if still.as_deref() != Some(blob) {
3349        return Ok(());
3350    }
3351    insert_guestbook_events(&tx, community_id, &events, false)?;
3352    tx.execute("UPDATE community_guestbook SET events = '' WHERE community_id = ?1", params![community_id])
3353        .map_err(|e| format!("move guestbook: {e}"))?;
3354    tx.commit().map_err(|e| format!("move guestbook commit: {e}"))
3355}
3356
3357/// The number of `community_id`'s Guestbook, given on first use.
3358fn guestbook_book(tx: &rusqlite::Connection, community_id: &str) -> Result<i64, String> {
3359    tx.prepare_cached("INSERT OR IGNORE INTO community_guestbook_books (community_id) VALUES (?1)")
3360        .and_then(|mut s| s.execute(params![community_id]))
3361        .map_err(|e| format!("guestbook book: {e}"))?;
3362    tx.prepare_cached("SELECT book FROM community_guestbook_books WHERE community_id = ?1")
3363        .and_then(|mut s| s.query_row(params![community_id], |r| r.get(0)))
3364        .map_err(|e| format!("guestbook book: {e}"))
3365}
3366
3367/// Store `events` in order. A rumor already held keeps its place, and with `restamp` takes the
3368/// new body (an epoch or arrival stamp it gained).
3369fn insert_guestbook_events(tx: &rusqlite::Connection, community_id: &str, events: &[crate::community::v2::guestbook::GuestbookEvent], restamp: bool) -> Result<(), String> {
3370    let book = guestbook_book(tx, community_id)?;
3371    let sql = if restamp {
3372        "INSERT INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)
3373         ON CONFLICT (book, rumor_id) DO UPDATE SET body = excluded.body"
3374    } else {
3375        "INSERT OR IGNORE INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)"
3376    };
3377    let mut stmt = tx.prepare_cached(sql).map_err(|e| format!("store guestbook event: {e}"))?;
3378    crate::crypto::seal_batch(|sealer| {
3379        for ev in events {
3380            let body = sealer.seal_blob(&crate::community::v2::guestbook::event_body(ev))?;
3381            stmt.execute(params![book, &ev.rumor_id[..], body]).map_err(|e| format!("store guestbook event: {e}"))?;
3382        }
3383        Ok(())
3384    })
3385}
3386
3387struct StandingCache;
3388/// Per community: the Guestbook write generation and, once read, the Timeouts and Nicknames at it.
3389type StandingMap = std::sync::RwLock<std::collections::HashMap<String, (u64, Option<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>>)>>;
3390
3391fn standing_cache() -> std::sync::Arc<StandingMap> {
3392    crate::db::current_session().scoped::<StandingCache, StandingMap>()
3393}
3394
3395/// The Guestbook's Timeout and Nickname entries, held so every send and paint doesn't reparse
3396/// the whole book.
3397pub fn get_guestbook_standing(community_id: &str) -> Result<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>, String> {
3398    let generation = match standing_cache().read().unwrap_or_else(|e| e.into_inner()).get(community_id) {
3399        Some((_, Some(held))) => return Ok(held.clone()),
3400        Some((generation, None)) => *generation,
3401        None => 0,
3402    };
3403    let (events, _) = get_guestbook(community_id)?;
3404    use crate::community::v2::guestbook::GuestbookEntry;
3405    let standing: std::sync::Arc<Vec<_>> = std::sync::Arc::new(
3406        events.into_iter().filter(|e| matches!(e.entry, GuestbookEntry::Timeout { .. } | GuestbookEntry::Nickname { .. })).collect(),
3407    );
3408    // A write that landed during the read moved the generation on: keep what it left.
3409    let map = standing_cache();
3410    let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
3411    let entry = cache.entry(community_id.to_string()).or_insert((0, None));
3412    if entry.0 == generation {
3413        entry.1 = Some(standing.clone());
3414    }
3415    Ok(standing)
3416}
3417
3418/// Persist a community's Guestbook events + cursor (encrypted at rest, like the
3419/// community row itself). The caller owns dedup/merge — this is a plain replace.
3420struct MembershipGeneration;
3421
3422/// Moves whenever what a Guestbook fold reads may have: a store write here, or a Control fold.
3423pub fn membership_generation() -> u64 {
3424    super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().load(std::sync::atomic::Ordering::Acquire)
3425}
3426
3427pub fn bump_membership_generation() {
3428    super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().fetch_add(1, std::sync::atomic::Ordering::AcqRel);
3429}
3430
3431pub fn set_guestbook(
3432    community_id: &str,
3433    events: &[crate::community::v2::guestbook::GuestbookEvent],
3434    cursor_secs: u64,
3435) -> Result<(), String> {
3436    let _seal = crate::crypto::gate::sealing();
3437    forget_console_verdict(community_id);
3438    let conn = super::get_write_connection_guard_static()?;
3439    let tx = conn.unchecked_transaction().map_err(|e| format!("save guestbook tx: {e}"))?;
3440    let book = guestbook_book(&tx, community_id)?;
3441    tx.execute("DELETE FROM community_guestbook_events WHERE book = ?1", params![book])
3442        .map_err(|e| format!("save guestbook: {e}"))?;
3443    // A replaced Guestbook no longer vouches for the wraps read into the one before it.
3444    tx.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id])
3445        .map_err(|e| format!("save guestbook: {e}"))?;
3446    insert_guestbook_events(&tx, community_id, events, false)?;
3447    upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
3448    tx.commit().map_err(|e| format!("save guestbook commit: {e}"))?;
3449    {
3450        let cache = guestbook_cache();
3451        let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3452        let generation = held.moved(community_id);
3453        held.put(community_id, generation, (std::sync::Arc::new(Guestbook::new(events.to_vec())), cursor_secs));
3454    }
3455    drop(conn);
3456    guestbook_moved_on(community_id);
3457    Ok(())
3458}
3459
3460/// Store the Guestbook events a fold added or restamped, and the cursor: each a row of its own,
3461/// nothing else rewritten.
3462pub fn store_guestbook_events(
3463    community_id: &str,
3464    events: &[crate::community::v2::guestbook::GuestbookEvent],
3465    cursor_secs: u64,
3466) -> Result<(), String> {
3467    let _seal = crate::crypto::gate::sealing();
3468    forget_console_verdict(community_id);
3469    let conn = super::get_write_connection_guard_static()?;
3470    let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook tx: {e}"))?;
3471    insert_guestbook_events(&tx, community_id, events, true)?;
3472    upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
3473    tx.commit().map_err(|e| format!("store guestbook commit: {e}"))?;
3474    guestbook_written(
3475        community_id,
3476        |held| {
3477            for ev in events {
3478                held.upsert(ev);
3479            }
3480        },
3481        cursor_secs,
3482    );
3483    drop(conn);
3484    guestbook_moved_on(community_id);
3485    Ok(())
3486}
3487
3488fn upsert_guestbook_cursor(tx: &rusqlite::Connection, community_id: &str, cursor_secs: u64) -> Result<(), String> {
3489    tx.prepare_cached(
3490        "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, '', ?2)
3491         ON CONFLICT(community_id) DO UPDATE SET cursor_secs = ?2",
3492    )
3493    .and_then(|mut s| s.execute(params![community_id, cursor_secs as i64]))
3494    .map(|_| ())
3495    .map_err(|e| format!("save guestbook cursor: {e}"))
3496}
3497
3498/// Carry a committed write into the parsed copy. Call while the write connection is still held,
3499/// so no later write lands between the two. A copy not cached is read again when next asked for.
3500fn guestbook_written(community_id: &str, apply: impl FnOnce(&mut Guestbook), cursor_secs: u64) {
3501    let cache = guestbook_cache();
3502    let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3503    let before = held.get(community_id);
3504    let generation = held.moved(community_id);
3505    if let Some((events, _)) = before {
3506        let mut events = std::sync::Arc::unwrap_or_clone(events);
3507        apply(&mut events);
3508        held.put(community_id, generation, (std::sync::Arc::new(events), cursor_secs));
3509    }
3510}
3511
3512/// What every Guestbook write moves on, once its write connection is let go.
3513fn guestbook_moved_on(community_id: &str) {
3514    let map = standing_cache();
3515    let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
3516    let entry = cache.entry(community_id.to_string()).or_insert((0, None));
3517    *entry = (entry.0 + 1, None);
3518    drop(cache);
3519    bump_membership_generation();
3520}
3521
3522#[cfg(test)]
3523mod tests {
3524    use super::*;
3525
3526    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3527
3528    /// A unique, syntactically-valid test npub per call (bech32 charset, correct
3529    /// length). Uniqueness isolates each test's account DB so state can't bleed.
3530    fn make_test_npub(n: u32) -> String {
3531        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
3532        let mut payload = vec![b'q'; 58];
3533        let mut x = n as u64;
3534        let mut i = 58;
3535        while x > 0 && i > 0 {
3536            i -= 1;
3537            payload[i] = BECH32[(x as usize) % 32];
3538            x /= 32;
3539        }
3540        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
3541    }
3542
3543    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
3544        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3545        crate::db::close_database();
3546        // Per-account row-id caches survive close_database; clear them so a stale entry from a prior
3547        // test's DB can't point into this fresh account's DB and FK-fail an insert.
3548        crate::db::clear_id_caches();
3549        let tmp = tempfile::tempdir().unwrap();
3550        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3551        let account = make_test_npub(n);
3552        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
3553        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
3554        crate::db::set_current_account(account.clone()).unwrap();
3555        crate::db::init_database(&account).unwrap();
3556        (tmp, guard)
3557    }
3558
3559    #[test]
3560    fn a_channel_holds_its_newest_dated_wraps_up_to_the_cap() {
3561        let (_tmp, _guard) = init_test_db();
3562        let (cid, ch) = ("c".repeat(64), "d".repeat(64));
3563        for i in 0..MAX_HELD_WRAPS + 2 {
3564            hold_wrap(&cid, &ch, &format!("{i:064x}"), &format!("wrap {i}"), "", 1_000 + i as u64).unwrap();
3565        }
3566        hold_wrap(&cid, &"e".repeat(64), &"f".repeat(64), "another channel's", "", 1).unwrap();
3567        let held = held_wraps(&cid).unwrap();
3568        assert_eq!(held.len(), MAX_HELD_WRAPS + 1, "each channel caps on its own");
3569        assert!(!held.iter().any(|(id, ..)| *id == format!("{:064x}", 0) || *id == format!("{:064x}", 1)), "the oldest-dated go first");
3570        assert!(held.iter().any(|(_, _, wrap)| wrap == "wrap 501"), "opened as it was held");
3571        hold_wrap(&cid, &ch, &format!("{:064x}", 501), "again", "", 1).unwrap();
3572        assert_eq!(held_wraps(&cid).unwrap().iter().filter(|(id, ..)| *id == format!("{:064x}", 501)).count(), 1, "once");
3573        release_held_wrap(&format!("{:064x}", 501)).unwrap();
3574        assert!(held_wrap_ids(&[format!("{:064x}", 501), format!("{:064x}", 500)]) == std::collections::HashSet::from([format!("{:064x}", 500)]));
3575    }
3576
3577    /// An unsaved v2 community fresh from genesis, holding one Public `#general` channel.
3578    fn v2_fixture(name: &str, relays: &[&str]) -> crate::community::v2::community::CommunityV2 {
3579        let owner = Keys::generate();
3580        let g = crate::community::v2::control::genesis(
3581            &owner,
3582            crate::community::v2::control::CommunityMetadata { name: name.into(), ..Default::default() },
3583            1_000,
3584        )
3585        .unwrap();
3586        let relays = relays.iter().map(|r| r.to_string()).collect();
3587        crate::community::v2::community::CommunityV2::from_genesis(&g, name, None, relays, 1_000)
3588    }
3589
3590    fn lines_channel(id: u8, name: &str) -> crate::community::v2::community::ChannelV2 {
3591        crate::community::v2::community::ChannelV2 {
3592            id: ChannelId([id; 32]), name: name.into(), private: false, key: None, epoch: Epoch(0), voice: None,
3593            meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None,
3594        }
3595    }
3596
3597    fn lines_to(c: &mut crate::community::v2::community::CommunityV2, channel: Option<&ChannelId>) {
3598        let mut meta = c.metadata();
3599        crate::community::v2::community::set_system_channel_in(&mut meta, channel);
3600        c.meta_custom = meta.custom;
3601    }
3602
3603    async fn save_line(channel: &str, n: u64, kind: crate::stored_event::SystemEventType, npub: &str) {
3604        crate::db::events::save_system_event_at(&format!("{n:064x}"), channel, kind, npub, None, 1_000 + n, None, None).await.unwrap();
3605    }
3606
3607    /// Every system row a channel keeps, shown or not.
3608    fn kept_in(channel: &str) -> usize {
3609        let Ok(row) = super::super::id_cache::get_chat_id_by_identifier(channel) else { return 0 };
3610        let conn = crate::db::get_db_connection_guard_static().unwrap();
3611        conn.query_row(
3612            "SELECT COUNT(*) FROM events WHERE chat_id = ?1 AND kind = ?2",
3613            params![row, crate::stored_event::event_kind::APPLICATION_SPECIFIC as i32],
3614            |r| r.get::<_, i64>(0),
3615        )
3616        .unwrap() as usize
3617    }
3618
3619    fn shown_in(channel: &str) -> usize {
3620        crate::db::events::get_system_events_for_chat(channel).map_or(0, |e| e.len())
3621    }
3622
3623    #[tokio::test]
3624    async fn join_lines_move_to_the_system_channel_and_show_only_there() {
3625        use crate::stored_event::SystemEventType::{MemberJoined, MemberLeft, PinsModified};
3626        let (_tmp, _guard) = init_test_db();
3627        let mut c = v2_fixture("Lines", &["wss://r"]);
3628        c.channels.push(lines_channel(7, "welcome"));
3629        save_community_v2(&c).unwrap();
3630        let general = crate::simd::hex::bytes_to_hex_32(&c.channels[0].id.0);
3631        let welcome = crate::simd::hex::bytes_to_hex_32(&[7; 32]);
3632        let npub = Keys::generate().public_key().to_bech32().unwrap();
3633        save_line(&general, 1, MemberJoined, &npub).await;
3634        save_line(&general, 2, MemberLeft, &npub).await;
3635        save_line(&general, 3, PinsModified, &npub).await;
3636        assert_eq!(shown_in(&general), 3);
3637
3638        lines_to(&mut c, Some(&ChannelId([7; 32])));
3639        save_community_v2(&c).unwrap();
3640        assert_eq!(kept_in(&welcome), 2, "both lines moved");
3641        assert_eq!(shown_in(&welcome), 2);
3642        assert_eq!(kept_in(&general), 1, "a pins line belongs to its own channel");
3643        assert_eq!(shown_in(&general), 1);
3644
3645        // One that landed in the old home on the way still comes over on the next save.
3646        save_line(&general, 4, MemberJoined, &npub).await;
3647        save_community_v2(&c).unwrap();
3648        assert_eq!(kept_in(&welcome), 3);
3649    }
3650
3651    #[tokio::test]
3652    async fn join_lines_turned_off_stay_kept_for_the_member_list() {
3653        use crate::stored_event::SystemEventType::{MemberJoined, MemberLeft};
3654        let (_tmp, _guard) = init_test_db();
3655        let mut c = v2_fixture("Quiet", &["wss://r"]);
3656        lines_to(&mut c, None);
3657        save_community_v2(&c).unwrap();
3658        let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
3659        let general = crate::simd::hex::bytes_to_hex_32(&c.channels[0].id.0);
3660        let (stays, went) = (Keys::generate().public_key().to_bech32().unwrap(), Keys::generate().public_key().to_bech32().unwrap());
3661        save_line(&general, 1, MemberJoined, &stays).await;
3662        save_line(&general, 2, MemberJoined, &went).await;
3663        save_line(&general, 3, MemberLeft, &went).await;
3664        assert_eq!(shown_in(&general), 0, "off: nothing shows");
3665        assert_eq!(kept_in(&general), 3);
3666        let members: Vec<String> = community_member_activity(&cid).unwrap().into_iter().map(|(n, _)| n).collect();
3667        assert!(members.contains(&stays), "a join still counts");
3668        assert!(!members.contains(&went), "and a leave still removes");
3669
3670        c.meta_custom = None;
3671        save_community_v2(&c).unwrap();
3672        assert_eq!(shown_in(&general), 3, "back on, every line is there");
3673    }
3674
3675    #[tokio::test]
3676    async fn a_deleted_system_channel_hands_its_lines_back() {
3677        use crate::stored_event::SystemEventType::MemberJoined;
3678        let (_tmp, _guard) = init_test_db();
3679        let mut c = v2_fixture("Gone", &["wss://r"]);
3680        c.channels.push(lines_channel(7, "welcome"));
3681        lines_to(&mut c, Some(&ChannelId([7; 32])));
3682        save_community_v2(&c).unwrap();
3683        let general = crate::simd::hex::bytes_to_hex_32(&c.channels[0].id.0);
3684        let welcome = crate::simd::hex::bytes_to_hex_32(&[7; 32]);
3685        let npub = Keys::generate().public_key().to_bech32().unwrap();
3686        save_line(&welcome, 1, MemberJoined, &npub).await;
3687        save_line(&welcome, 2, MemberJoined, &npub).await;
3688
3689        c.channels.pop();
3690        save_community_v2(&c).unwrap();
3691        assert_eq!(kept_in(&welcome), 0);
3692        assert_eq!(shown_in(&general), 2, "the default takes them");
3693    }
3694
3695    #[tokio::test]
3696    async fn join_lines_for_a_channel_without_its_key_wait_hidden_until_it_lands() {
3697        use crate::stored_event::SystemEventType::MemberJoined;
3698        let (_tmp, _guard) = init_test_db();
3699        let mut c = v2_fixture("Staff", &["wss://r"]);
3700        let mut staff = lines_channel(7, "staff");
3701        staff.private = true;
3702        c.channels.push(staff);
3703        lines_to(&mut c, Some(&ChannelId([7; 32])));
3704        save_community_v2(&c).unwrap();
3705        let general = crate::simd::hex::bytes_to_hex_32(&c.channels[0].id.0);
3706        let staff = crate::simd::hex::bytes_to_hex_32(&[7; 32]);
3707        save_line(&general, 1, MemberJoined, &Keys::generate().public_key().to_bech32().unwrap()).await;
3708        assert_eq!(shown_in(&general), 0, "not shown where it waits");
3709
3710        c.channels[1].key = Some([3; 32]);
3711        save_community_v2(&c).unwrap();
3712        assert_eq!(shown_in(&staff), 1, "the key brings them in");
3713        assert_eq!(kept_in(&general), 0);
3714    }
3715
3716    /// A saved v2 community with the hex ids of it and its `#general` channel.
3717    /// A bundle this build can join, named `name`.
3718    fn v2_bundle(name: &str) -> String {
3719        let bundle = crate::community::v2::service::bundle_of(
3720            &v2_fixture(name, &["wss://r"]),
3721            crate::community::v2::service::BundleAudience::Link,
3722            None,
3723            None,
3724            None,
3725        );
3726        serde_json::to_string(&bundle).unwrap()
3727    }
3728
3729    fn saved_v2(name: &str) -> (crate::community::v2::community::CommunityV2, String, String) {
3730        let c = v2_fixture(name, &["wss://r"]);
3731        save_community_v2(&c).unwrap();
3732        let (cid, ch) = (c.id().to_hex(), c.channels[0].id.to_hex());
3733        (c, cid, ch)
3734    }
3735
3736    /// A Private channel holding its own key, to sit beside `#general`.
3737    fn private_channel(id: u8, key: u8) -> crate::community::v2::community::ChannelV2 {
3738        crate::community::v2::community::ChannelV2 {
3739            id: ChannelId([id; 32]),
3740            name: "staff".into(),
3741            private: true,
3742            key: Some([key; 32]),
3743            epoch: Epoch(0),
3744            voice: None,
3745            meta_custom: None,
3746            meta_extra: Default::default(),
3747            writers: None,
3748            sealed: None,
3749        }
3750    }
3751
3752    /// A saved v2 community with its root and a Private channel's key archived, as the
3753    /// service leaves one. Returns it with the hex ids of it and the Private channel.
3754    fn archived_v2() -> (crate::community::v2::community::CommunityV2, String, String) {
3755        let mut c = v2_fixture("HQ", &["r1"]);
3756        c.channels.push(private_channel(0x61, 0x62));
3757        save_community_v2(&c).unwrap();
3758        let (cid, private) = (c.id().to_hex(), c.channels[1].id.to_hex());
3759        store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
3760        store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
3761        (c, cid, private)
3762    }
3763
3764    fn encrypted_community_with_messages(n: usize) -> String {
3765        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
3766        crate::state::set_encryption_enabled(true);
3767        let (_, cid, ch) = saved_v2("HQ");
3768        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
3769        for i in 0..n {
3770            let msg = crate::types::Message {
3771                id: format!("{i:064x}"),
3772                content: format!("message number {i}, a few words long"),
3773                at: 1_700_000_000_000 + i as u64 * 1000,
3774                npub: Some(make_test_npub(i as u32 % 7)),
3775                ..Default::default()
3776            };
3777            rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
3778        }
3779        cid
3780    }
3781
3782    #[test]
3783    fn the_policy_window_and_recent_texts_open_sealed_rows() {
3784        let (_tmp, _guard) = init_test_db();
3785        struct Vault;
3786        impl Drop for Vault {
3787            fn drop(&mut self) {
3788                crate::state::set_encryption_enabled(false);
3789                crate::state::ENCRYPTION_KEY.clear(&[]);
3790            }
3791        }
3792        let _vault = Vault;
3793        let cid = encrypted_community_with_messages(5);
3794        let stored: String = crate::db::get_db_connection_guard_static()
3795            .unwrap()
3796            .query_row("SELECT content FROM events WHERE content != '' LIMIT 1", [], |r| r.get(0))
3797            .unwrap();
3798        assert!(crate::crypto::looks_encrypted(&stored), "the rows read back are sealed on disk");
3799        let window = community_policy_messages(&cid, 100).unwrap();
3800        assert_eq!(window.len(), 5);
3801        assert_eq!(window[0].text, "message number 0, a few words long");
3802        let recent = community_recent_texts(&cid, 100).unwrap();
3803        assert_eq!(recent[0].2, "message number 4, a few words long");
3804    }
3805
3806    #[test]
3807    fn an_authority_floor_takes_a_squatted_coordinate_and_keeps_it() {
3808        let (_tmp, _guard) = init_test_db();
3809        let (cid, entity) = ("f".repeat(64), "a".repeat(64));
3810        let head = |v: u64, b: u8, family: &str| set_family_head_at_epoch(&cid, &entity, v, &[b; 32], &[b; 32], &[b; 32], 0, family).unwrap();
3811        let held = || (get_edition_head(&cid, &entity).unwrap().unwrap(), edition_head_families(&cid).unwrap().get(&entity).cloned());
3812        head(50, 0xC0, FLOOR_CONTROL);
3813        head(1, 0xA1, FLOOR_AUTHORITY);
3814        assert_eq!(held(), ((1, [0xA1; 32]), Some("a".into())), "an authority head replaces a control row at any version");
3815        head(99, 0xC1, FLOOR_CONTROL);
3816        assert_eq!(held().0, (1, [0xA1; 32]), "a control head never takes it back");
3817        converge_family_head_at_epoch(&cid, &entity, 1, &[0xC2; 32], &[0xC2; 32], &[0xC2; 32], 0, Some(FLOOR_CONTROL)).unwrap();
3818        assert_eq!(held().0, (1, [0xA1; 32]), "nor converges it");
3819        rebase_edition_head_at_epoch(&cid, &entity, 0, &[0xC3; 32], &[0xC3; 32], &[0xC3; 32], 0, FLOOR_CONTROL).unwrap();
3820        assert_eq!(held().0, (1, [0xA1; 32]), "nor moves it down");
3821        head(1, 0xA0, FLOOR_AUTHORITY);
3822        assert_eq!(held().0, (1, [0xA1; 32]), "within the family the version still only advances");
3823        head(2, 0xA2, FLOOR_AUTHORITY);
3824        assert_eq!(held().0, (2, [0xA2; 32]));
3825    }
3826
3827    #[test]
3828    fn edition_head_round_trips_and_upserts() {
3829        let (_tmp, _guard) = init_test_db();
3830        let cid = "f".repeat(64);
3831        let entity = "a".repeat(64);
3832
3833        // No head yet → None (the next edition is genesis v1).
3834        assert_eq!(get_edition_head(&cid, &entity).unwrap(), None);
3835
3836        // Set v1, read it back exactly.
3837        let h1 = [0x11u8; 32];
3838        set_edition_head(&cid, &entity, 1, &h1).unwrap();
3839        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((1, h1)));
3840
3841        // Upsert to v2 — the head advances in place (one row per (community, entity)).
3842        let h2 = [0x22u8; 32];
3843        set_edition_head(&cid, &entity, 2, &h2).unwrap();
3844        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)));
3845
3846        // MONOTONIC: a lower-or-equal version write is a no-op — the refuse-downgrade floor never
3847        // rolls back, even against a stale or hostile rollback attempt.
3848        set_edition_head(&cid, &entity, 1, &[0xEEu8; 32]).unwrap();
3849        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "rollback to v1 ignored");
3850        set_edition_head(&cid, &entity, 2, &[0xEEu8; 32]).unwrap();
3851        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "equal version is a no-op too");
3852
3853        // A different entity is tracked independently.
3854        let other = "b".repeat(64);
3855        assert_eq!(get_edition_head(&cid, &other).unwrap(), None);
3856    }
3857
3858    #[test]
3859    fn a_floor_written_before_families_still_advances() {
3860        // A row from before floors recorded their family holds NULL there, and `= 'a'` on NULL
3861        // made the whole guard NULL: the row never moved, so every edit was re-minted at v2.
3862        let (_tmp, _guard) = init_test_db();
3863        let (cid, entity) = ("c".repeat(64), "e".repeat(64));
3864        set_edition_head(&cid, &entity, 1, &[0x11; 32]).unwrap();
3865        assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&entity].5, None, "a familyless row");
3866        set_family_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
3867        let f = get_all_edition_heads_full(&cid).unwrap()[&entity];
3868        assert_eq!((f.1, f.2, f.5), (2, [0x22; 32], Some(FloorFamily::of(FLOOR_CONTROL))), "it advances, and takes the family");
3869        // An authority row still refuses a control write over it.
3870        set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 1, &[0x33; 32], &[0x03; 32], &[0xA1; 32], 0, FLOOR_AUTHORITY).unwrap();
3871        set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 2, &[0x44; 32], &[0x04; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
3872        assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&"a".repeat(64)].1, 1);
3873    }
3874
3875    #[test]
3876    fn a_floor_keeps_the_author_of_the_head_it_holds() {
3877        let (_tmp, _guard) = init_test_db();
3878        let cid = "c".repeat(64);
3879        let entity = "e".repeat(64);
3880        let author = |b: u8| [b; 32];
3881        let held = |cid: &str| {
3882            let f = get_all_edition_heads_full(cid).unwrap()[&entity];
3883            (f.0, f.1, f.2, f.3, f.4)
3884        };
3885        set_edition_head_at_epoch(&cid, &entity, 1, &[0x11; 32], &[0x01; 32], &author(0xA1), 0).unwrap();
3886        set_edition_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &author(0xB2), 0).unwrap();
3887        assert_eq!(held(&cid), (0, 2, [0x22; 32], Some([0x02; 32]), Some(author(0xB2))), "an advance records its own author");
3888
3889        // Convergence is the caller's verdict: it replaces the held edition whatever the ids,
3890        // but only at the same version and epoch.
3891        converge_edition_head_at_epoch(&cid, &entity, 2, &[0x33; 32], &[0xFF; 32], &author(0xC3), 0).unwrap();
3892        assert_eq!(held(&cid), (0, 2, [0x33; 32], Some([0xFF; 32]), Some(author(0xC3))), "a higher id can win on authority");
3893        converge_edition_head_at_epoch(&cid, &entity, 3, &[0x44; 32], &[0x00; 32], &author(0xD4), 0).unwrap();
3894        converge_edition_head_at_epoch(&cid, &entity, 2, &[0x55; 32], &[0x00; 32], &author(0xE5), 1).unwrap();
3895        assert_eq!(held(&cid).2, [0x33; 32], "another version or epoch is never converged onto");
3896
3897        // A Refounding's advance into a new epoch takes the new head's author too.
3898        set_edition_head_at_epoch(&cid, &entity, 1, &[0x66; 32], &[0x06; 32], &author(0xF6), 1).unwrap();
3899        assert_eq!(held(&cid), (1, 1, [0x66; 32], Some([0x06; 32]), Some(author(0xF6))));
3900    }
3901
3902    #[test]
3903    fn guestbook_round_trips_events_and_cursor() {
3904        let (_tmp, _guard) = init_test_db();
3905        let member = nostr_sdk::prelude::Keys::generate();
3906        let ev = crate::community::v2::guestbook::GuestbookEvent { epoch: None, observed_at: None,
3907            rumor_id: [7u8; 32],
3908            entry: crate::community::v2::guestbook::GuestbookEntry::Join {
3909                member: member.public_key(),
3910                invited_by: Some(("creator".into(), "label".into())),
3911                at_ms: 1_000,
3912            },
3913        };
3914        let cid = "d".repeat(64);
3915        assert_eq!(get_guestbook(&cid).unwrap(), (Vec::new(), 0), "absent reads as empty at cursor 0");
3916        set_guestbook(&cid, std::slice::from_ref(&ev), 42).unwrap();
3917        let (events, cursor) = read_guestbook(&cid).unwrap();
3918        assert_eq!(events, vec![ev.clone()], "events round-trip through the encrypted blob");
3919        assert_eq!(cursor, 42);
3920        assert_eq!(get_guestbook(&cid).unwrap(), (vec![ev], 42), "and the cached read agrees");
3921    }
3922
3923    fn gb(b: u8, epoch: Option<u64>) -> crate::community::v2::guestbook::GuestbookEvent {
3924        crate::community::v2::guestbook::GuestbookEvent {
3925            rumor_id: [b; 32],
3926            entry: crate::community::v2::guestbook::GuestbookEntry::Join { member: nostr_sdk::prelude::Keys::generate().public_key(), invited_by: None, at_ms: b as u64 * 1000 },
3927            epoch,
3928            observed_at: Some(1_790_000_000 + b as u64),
3929        }
3930    }
3931
3932    #[test]
3933    fn a_guestbook_blob_moves_into_rows_in_order_and_once() {
3934        let (_tmp, _guard) = init_test_db();
3935        let cid = "f".repeat(64);
3936        let events: Vec<_> = [9u8, 3, 7, 1].iter().map(|&b| gb(b, Some(2))).collect();
3937        {
3938            let _seal = crate::crypto::gate::sealing();
3939            let conn = crate::db::get_write_connection_guard_static().unwrap();
3940            conn.execute(
3941                "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, ?2, 55)",
3942                params![cid, enc_txt(&serde_json::to_string(&events).unwrap()).unwrap()],
3943            )
3944            .unwrap();
3945        }
3946        assert_eq!(read_guestbook(&cid).unwrap(), (events.clone(), 55), "arrival order kept");
3947        let blob: String = crate::db::get_db_connection_guard_static().unwrap().query_row("SELECT events FROM community_guestbook WHERE community_id = ?1", params![cid], |r| r.get(0)).unwrap();
3948        assert!(blob.is_empty(), "the blob is moved out, not kept beside the rows");
3949        assert_eq!(read_guestbook(&cid).unwrap(), (events, 55), "and reads the same from rows");
3950    }
3951
3952    #[test]
3953    fn a_guestbook_blob_that_does_not_read_is_left_as_it_is() {
3954        let (_tmp, _guard) = init_test_db();
3955        let cid = "c".repeat(64);
3956        {
3957            let conn = crate::db::get_write_connection_guard_static().unwrap();
3958            conn.execute("INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, 'not json', 3)", params![cid]).unwrap();
3959        }
3960        assert_eq!(read_guestbook(&cid).unwrap(), (Vec::new(), 3));
3961        let blob: String = crate::db::get_db_connection_guard_static().unwrap().query_row("SELECT events FROM community_guestbook WHERE community_id = ?1", params![cid], |r| r.get(0)).unwrap();
3962        assert_eq!(blob, "not json", "nothing it couldn't read is thrown away");
3963    }
3964
3965    #[test]
3966    fn stored_guestbook_events_dedup_restamp_in_place_and_match_the_cache() {
3967        let (_tmp, _guard) = init_test_db();
3968        let cid = "b".repeat(64);
3969        let (a, b, c) = (gb(1, None), gb(2, Some(1)), gb(3, Some(1)));
3970        store_guestbook_events(&cid, &[a.clone(), b.clone()], 10).unwrap();
3971        assert_eq!(get_guestbook(&cid).unwrap().0, vec![a.clone(), b.clone()]);
3972        // The same rumor again changes nothing; a restamp takes its place in the order.
3973        let a2 = crate::community::v2::guestbook::GuestbookEvent { epoch: Some(4), ..a.clone() };
3974        store_guestbook_events(&cid, &[b.clone(), a2.clone(), c.clone()], 20).unwrap();
3975        let want = (vec![a2, b, c], 20);
3976        assert_eq!(get_guestbook(&cid).unwrap(), want, "the cached copy");
3977        assert_eq!(read_guestbook(&cid).unwrap(), want, "the rows");
3978        let rows: i64 = crate::db::get_db_connection_guard_static().unwrap().query_row("SELECT COUNT(*) FROM community_guestbook_events", [], |r| r.get(0)).unwrap();
3979        assert_eq!(rows, 3);
3980        // A whole replace leaves exactly what it was given.
3981        set_guestbook(&cid, &[want.0[2].clone()], 30).unwrap();
3982        assert_eq!(read_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
3983        assert_eq!(get_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
3984    }
3985
3986    #[test]
3987    fn owed_departures_write_only_the_members_that_changed() {
3988        let (_tmp, _guard) = init_test_db();
3989        let cid = "e".repeat(64);
3990        let mut keys: Vec<PublicKey> = (0..3).map(|_| Keys::generate().public_key()).collect();
3991        keys.sort();
3992        let (a, b, c) = (keys[0], keys[1], keys[2]);
3993        let rows = || -> Vec<(i64, Vec<u8>)> {
3994            let conn = crate::db::get_db_connection_guard_static().unwrap();
3995            let mut stmt = conn.prepare("SELECT seq, body FROM community_departures_seen ORDER BY seq").unwrap();
3996            stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(|r| r.unwrap()).collect()
3997        };
3998        let stored = || {
3999            departures_seen_cache().lock().unwrap().moved(&cid);
4000            (*departures_seen(&cid).unwrap().spans).clone()
4001        };
4002        let first: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true)].into())].into_iter().collect();
4003        set_departures_seen(&cid, std::sync::Arc::new(first.clone())).unwrap();
4004        assert_eq!(stored(), first);
4005        let before = rows();
4006        let second: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, Some(4), true), (12, None, false)].into()), (c, vec![(7, None, false)].into())].into_iter().collect();
4007        set_departures_seen(&cid, std::sync::Arc::new(second.clone())).unwrap();
4008        let after = rows();
4009        assert_eq!(after.len(), 3);
4010        assert_eq!(after[0], before[0], "an unchanged member's row is left alone");
4011        assert_eq!(after[1].0, before[1].0, "a changed member keeps its row");
4012        assert_ne!(after[1].1, before[1].1);
4013        assert_eq!(stored(), second);
4014        let third: DepartureSpans = [(c, vec![(7, None, false)].into())].into_iter().collect();
4015        set_departures_seen(&cid, std::sync::Arc::new(third.clone())).unwrap();
4016        assert_eq!(rows().iter().map(|r| r.0).collect::<Vec<_>>(), vec![after[2].0], "a member with no spans left goes");
4017        assert_eq!(stored(), third);
4018        let fourth: DepartureSpans = [(a, vec![(5, Some(9), false)].into())].into_iter().collect();
4019        set_departures_seen(&cid, std::sync::Arc::new(fourth.clone())).unwrap();
4020        assert_eq!(rows().len(), 1, "and one after every member written");
4021        assert_eq!(stored(), fourth);
4022        delete_community(&cid).unwrap();
4023        assert!(departures_seen(&cid).unwrap().spans.is_empty());
4024        assert!(rows().is_empty());
4025    }
4026
4027    #[test]
4028    fn owed_departures_kept_in_settings_move_into_sealed_rows() {
4029        let (_tmp, _guard) = init_test_db();
4030        crate::state::ENCRYPTION_KEY.set([0x37u8; 32], &[]);
4031        crate::state::set_encryption_enabled(true);
4032        let cid = "f".repeat(64);
4033        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
4034        let json = format!(r#"{{"{}":[[5,9,false]],"{}":[[1,null,true],[12,20,false]]}}"#, a.to_hex(), b.to_hex());
4035        super::super::settings::set_sql_setting(format!("departures_seen:{cid}"), json).unwrap();
4036        let want: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true), (12, Some(20), false)].into())].into_iter().collect();
4037        assert_eq!(*departures_seen(&cid).unwrap().spans, want);
4038        assert_eq!(super::super::settings::get_sql_setting(format!("departures_seen:{cid}")).unwrap(), None);
4039        let bodies: Vec<Vec<u8>> = {
4040            let conn = crate::db::get_db_connection_guard_static().unwrap();
4041            let mut stmt = conn.prepare("SELECT body FROM community_departures_seen").unwrap();
4042            stmt.query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect()
4043        };
4044        assert_eq!(bodies.len(), 2);
4045        for body in &bodies {
4046            assert!(!body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes()), "who left is never stored in the clear");
4047        }
4048        departures_seen_cache().lock().unwrap().moved(&cid);
4049        assert_eq!(*departures_seen(&cid).unwrap().spans, want, "read back from the sealed rows");
4050        crate::state::set_encryption_enabled(false);
4051    }
4052
4053    #[test]
4054    fn a_folds_floor_writes_skip_only_what_is_already_stored() {
4055        let (_tmp, _guard) = init_test_db();
4056        let cid = "c".repeat(64);
4057        let row = |eid: &str| get_all_edition_heads_full(&cid).unwrap().get(eid).map(|f| (f.0, f.1, f.2, f.3, f.4));
4058        let (h4, h5, a) = ([4u8; 32], [5u8; 32], [9u8; 32]);
4059        set_family_head_at_epoch(&cid, "e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL).unwrap();
4060        set_family_head_at_epoch(&cid, "e2", 3, &h5, &[8; 32], &a, 2, FLOOR_AUTHORITY).unwrap();
4061        write_folded_heads(&cid, |w| {
4062            // Stepped down, then the very head the transaction found: it is written again.
4063            w.rebase("e1", 4, &h4, &[6; 32], &a, 2, FLOOR_CONTROL)?;
4064            w.set("e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL)?;
4065            // A same-version rival with a lower id is no copy of what is held.
4066            w.converge("e2", 3, &h5, &[1; 32], &a, 2, FLOOR_AUTHORITY)
4067        })
4068        .unwrap();
4069        assert_eq!(row("e1"), Some((2, 5, h5, Some([7; 32]), Some(a))));
4070        assert_eq!(row("e2"), Some((2, 3, h5, Some([1; 32]), Some(a))));
4071        // Nothing lands from a fold whose writes fail part way.
4072        let failed = write_folded_heads(&cid, |w| {
4073            w.set("e3", 1, &h4, &[2; 32], &a, 2, FLOOR_CONTROL)?;
4074            Err("cut short".into())
4075        });
4076        assert!(failed.is_err());
4077        assert_eq!(row("e3"), None);
4078    }
4079
4080    #[test]
4081    fn a_member_list_reads_posts_through_indexes_not_a_scan() {
4082        let (_tmp, _guard) = init_test_db();
4083        let conn = crate::db::get_db_connection_guard_static().unwrap();
4084        let plan = |sql: &str| -> String {
4085            let mut stmt = conn.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
4086            let binds = vec![1i64; stmt.parameter_count()];
4087            stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get::<_, String>(3)).unwrap().map(|r| r.unwrap()).collect::<Vec<_>>().join(" | ") + " "
4088        };
4089        let held = plan(&flagged_sql("?, ?", false));
4090        assert!(held.contains("USING INDEX idx_events_unauthorized ") && !held.contains("writer"), "{held}");
4091        let strict = plan(&flagged_sql("?, ?", true));
4092        assert!(strict.contains("USING INDEX idx_events_unauthorized ") && strict.contains("USING INDEX idx_events_writer_post "), "{strict}");
4093        let activity = plan(&activity_sql("?, ?"));
4094        assert!(activity.contains("idx_events_chat_kind_npub") && !activity.contains("TEMP B-TREE"), "{activity}");
4095    }
4096
4097    #[test]
4098    fn an_owed_author_take_back_widens_narrows_and_settles_as_it_did_in_settings() {
4099        let (_tmp, _guard) = init_test_db();
4100        let (cid, chan) = ("a".repeat(64), "c".repeat(64));
4101        let author = Keys::generate().public_key().to_hex();
4102        let owed = || owed_author_retractions(&cid).unwrap();
4103        owe_author_retraction(&cid, &chan, &author, 10, None).unwrap();
4104        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, None, 1)]);
4105        owe_author_retraction(&cid, &chan, &author, 10, Some(20)).unwrap();
4106        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(20), 2)], "the same span closing narrows its own owe");
4107        owe_author_retraction(&cid, &chan, &author, 15, Some(30)).unwrap();
4108        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(30), 3)]);
4109        owe_author_retraction(&cid, &chan, &author, 5, None).unwrap();
4110        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 5, None, 4)], "any other range widens it");
4111        settle_author_retraction(&cid, &chan, &author, 5, None, 3).unwrap();
4112        assert_eq!(owed().len(), 1, "more was owed since it was read");
4113        settle_author_retraction(&cid, &chan, &author, 5, None, 4).unwrap();
4114        assert!(owed().is_empty());
4115        let other = Keys::generate().public_key().to_hex();
4116        owe_author_retraction(&cid, &chan, &author, 1, None).unwrap();
4117        owe_author_retraction(&cid, &"d".repeat(64), &other, 2, Some(3)).unwrap();
4118        assert_eq!(owed().len(), 2, "one row per author and Channel");
4119        delete_community(&cid).unwrap();
4120        assert!(owed().is_empty());
4121    }
4122
4123    #[test]
4124    fn owed_author_take_backs_kept_in_settings_move_into_sealed_rows() {
4125        let (_tmp, _guard) = init_test_db();
4126        crate::state::ENCRYPTION_KEY.set([0x41u8; 32], &[]);
4127        crate::state::set_encryption_enabled(true);
4128        let (cid, elsewhere, chan) = ("a".repeat(64), "b".repeat(64), "c".repeat(64));
4129        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
4130        let legacy = |c: &str, author: &PublicKey, value: &str| super::super::settings::set_sql_setting(format!("writer_retract_by:{c}:{chan}:{}", author.to_hex()), value.into()).unwrap();
4131        legacy(&cid, &a, "7:3:");
4132        legacy(&cid, &b, "4:1:9");
4133        legacy(&elsewhere, &a, "1:1:");
4134        let mut want = vec![(chan.clone(), a.to_hex(), 7, None, 3), (chan.clone(), b.to_hex(), 4, Some(9), 1)];
4135        want.sort();
4136        assert_eq!(owed_author_retractions(&cid).unwrap(), want);
4137        let conn = crate::db::get_db_connection_guard_static().unwrap();
4138        let left: Vec<String> = conn.prepare("SELECT key FROM settings WHERE key LIKE 'writer_retract_by:%'").unwrap().query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect();
4139        assert_eq!(left, vec![format!("writer_retract_by:{elsewhere}:{chan}:{}", a.to_hex())], "another community's rows wait for their own read");
4140        let bodies: Vec<Vec<u8>> = conn.prepare("SELECT body FROM community_owed_authors").unwrap().query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect();
4141        drop(conn);
4142        assert_eq!(bodies.len(), 2);
4143        for body in &bodies {
4144            assert!(!body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes()), "who is owed a take-back is never stored in the clear");
4145        }
4146        // Owing and settling an author still kept in settings goes through the moved row.
4147        legacy(&elsewhere, &b, "2:5:");
4148        owe_author_retraction(&elsewhere, &chan, &b.to_hex(), 1, None).unwrap();
4149        settle_author_retraction(&elsewhere, &chan, &a.to_hex(), 1, None, 1).unwrap();
4150        assert_eq!(owed_author_retractions(&elsewhere).unwrap(), vec![(chan.clone(), b.to_hex(), 1, None, 6)]);
4151        let conn = crate::db::get_db_connection_guard_static().unwrap();
4152        let bodies: Vec<Vec<u8>> = conn.prepare("SELECT body FROM community_owed_authors").unwrap().query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect();
4153        assert!(bodies.iter().all(|body| !body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes())), "nor once owed again");
4154        drop(conn);
4155        crate::state::set_encryption_enabled(false);
4156    }
4157
4158    #[test]
4159    fn an_owed_author_body_round_trips_and_refuses_what_it_did_not_write() {
4160        let author = [7u8; 32];
4161        for (since, generation, until) in [(0, 0, None), (1, 2, Some(3)), (u64::MAX, u64::MAX, Some(u64::MAX))] {
4162            let body = author_owed_body(&author, since, generation, until);
4163            assert_ne!(body.len(), 32);
4164            assert_eq!(author_owed_from_body(&body), Some((author, since, generation, until)));
4165            let mut longer = body.clone();
4166            longer.push(0);
4167            assert_eq!(author_owed_from_body(&longer), None, "no trailing bytes");
4168            assert_eq!(author_owed_from_body(&body[..body.len() - 1]), None, "no cut body");
4169        }
4170        let mut flags = author_owed_body(&author, 1, 1, None);
4171        *flags.last_mut().unwrap() = 2;
4172        assert_eq!(author_owed_from_body(&flags), None, "unknown flags");
4173        let mut format = author_owed_body(&author, 1, 1, None);
4174        format[0] = 2;
4175        assert_eq!(author_owed_from_body(&format), None);
4176    }
4177
4178    #[test]
4179    fn an_owed_departure_body_round_trips_and_refuses_what_it_did_not_write() {
4180        let member = Keys::generate().public_key();
4181        for spans in [vec![], vec![(0, None, false)], vec![(1, Some(2), true), (u64::MAX, Some(u64::MAX), false), (300, None, true)]] {
4182            let body = departure_body(&member, &spans);
4183            assert_ne!(body.len(), 32);
4184            assert_eq!(departure_from_body(&body), Some((member, spans.clone())));
4185            let mut longer = body.clone();
4186            longer.push(0);
4187            assert_eq!(departure_from_body(&longer), None, "no trailing bytes");
4188            assert_eq!(departure_from_body(&body[..body.len() - 1]), None, "no cut body");
4189        }
4190        let mut forged = departure_body(&member, &[(1, None, false)]);
4191        forged[33] = 0x7f;
4192        assert_eq!(departure_from_body(&forged), None, "a count beyond the body");
4193        let mut flags = departure_body(&member, &[(1, None, false)]);
4194        flags[34] = 0b100;
4195        assert_eq!(departure_from_body(&flags), None, "unknown flags");
4196        let mut format = departure_body(&member, &[]);
4197        format[0] = 2;
4198        assert_eq!(departure_from_body(&format), None);
4199    }
4200
4201    #[test]
4202    fn guestbook_rows_are_sealed_at_rest() {
4203        let (_tmp, _guard) = init_test_db();
4204        crate::state::ENCRYPTION_KEY.set([0x31u8; 32], &[]);
4205        crate::state::set_encryption_enabled(true);
4206        let cid = "d".repeat(64);
4207        let ev = gb(5, Some(1));
4208        store_guestbook_events(&cid, std::slice::from_ref(&ev), 1).unwrap();
4209        let body: Vec<u8> = crate::db::get_db_connection_guard_static().unwrap().query_row("SELECT body FROM community_guestbook_events", [], |r| r.get(0)).unwrap();
4210        assert_ne!(body, crate::community::v2::guestbook::event_body(&ev), "not stored in the clear");
4211        assert_eq!(read_guestbook(&cid).unwrap().0, vec![ev]);
4212        crate::state::set_encryption_enabled(false);
4213        crate::state::ENCRYPTION_KEY.clear(&[]);
4214    }
4215
4216    #[test]
4217    fn a_guestbook_read_overlapping_a_write_is_never_served_after_it() {
4218        let (_tmp, _guard) = init_test_db();
4219        let ev = |b: u8| crate::community::v2::guestbook::GuestbookEvent {
4220            epoch: None,
4221            observed_at: None,
4222            rumor_id: [b; 32],
4223            entry: crate::community::v2::guestbook::GuestbookEntry::Leave { member: nostr_sdk::prelude::Keys::generate().public_key(), at_ms: b as u64 },
4224        };
4225        let cid = "e".repeat(64);
4226        let (one, two) = (ev(1), ev(2));
4227        set_guestbook(&cid, std::slice::from_ref(&one), 1).unwrap();
4228        assert_eq!(get_guestbook(&cid).unwrap().0, vec![one.clone()]);
4229        // A read that began before the write below and finishes after it.
4230        let began_under = guestbook_cache().lock().unwrap().generation(&cid);
4231        set_guestbook(&cid, &[one.clone(), two.clone()], 2).unwrap();
4232        guestbook_cache().lock().unwrap().put(&cid, began_under, (std::sync::Arc::new(Guestbook::new(vec![one.clone()])), 1));
4233        assert_eq!(get_guestbook(&cid).unwrap(), (vec![one, two], 2), "the write stands over the late read");
4234    }
4235
4236    #[test]
4237    fn v2_images_round_trip_and_read_as_community_images() {
4238        let (_tmp, _guard) = init_test_db();
4239        let owner = nostr_sdk::prelude::Keys::generate();
4240        let g = crate::community::v2::control::genesis(
4241            &owner,
4242            crate::community::v2::control::CommunityMetadata { name: "Icons".into(), ..Default::default() },
4243            1_000,
4244        )
4245        .unwrap();
4246        let mut c = crate::community::v2::community::CommunityV2::from_genesis(&g, "Icons", None, vec!["wss://r".into()], 1_000);
4247        let mut extra = serde_json::Map::new();
4248        extra.insert("ext".into(), serde_json::Value::String("webp".into()));
4249        c.icon = Some(crate::community::v2::control::ImageRef {
4250            url: "https://blossom.example/abc".into(),
4251            key: "0".repeat(64),
4252            nonce: "1".repeat(32),
4253            hash: "a".repeat(64),
4254            extra,
4255        });
4256        c.meta_custom = Some({
4257            let mut m = serde_json::Map::new();
4258            m.insert("k".into(), serde_json::Value::from("v"));
4259            m
4260        });
4261        c.channels[0].voice = Some(true);
4262        c.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
4263        save_community_v2(&c).unwrap();
4264
4265        // The v2 loader round-trips the ImageRef exactly (extra included).
4266        let re = load_community_v2(c.id()).unwrap().unwrap();
4267        assert_eq!(re.icon, c.icon);
4268        assert_eq!(re.banner, None);
4269        // The CORD-02 §6 stash survives the encrypted envelope columns.
4270        assert_eq!(re.meta_custom, c.meta_custom);
4271        assert_eq!(re.channels[0].voice, Some(true));
4272        assert_eq!(re.channels[0].meta_extra.get("vnd"), Some(&serde_json::Value::from(7)));
4273
4274        // The stored JSON parses as a CommunityImage (`ext` from the flattened extra),
4275        // so `community_image` serves it from the column alone.
4276        let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
4277        let img = community_image(&cid, false).unwrap().expect("the v2 icon reads as a CommunityImage");
4278        assert_eq!(img.url, "https://blossom.example/abc");
4279        assert_eq!(img.ext, "webp");
4280        assert_eq!(img.hash, "a".repeat(64));
4281        assert_eq!(community_image(&cid, true).unwrap(), None);
4282        assert_eq!(community_image(&"cd".repeat(32), false).unwrap(), None);
4283    }
4284
4285    #[test]
4286    fn column_reads_and_the_owner_check_serve_a_v2_community() {
4287        use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
4288        use crate::community::moderation::is_owner_or_admin;
4289        let (_tmp, _guard) = init_test_db();
4290        let owner = nostr_sdk::prelude::Keys::generate();
4291        let g = crate::community::v2::control::genesis(
4292            &owner,
4293            crate::community::v2::control::CommunityMetadata { name: "Two".into(), ..Default::default() },
4294            1_000,
4295        )
4296        .unwrap();
4297        let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Two", None, vec!["wss://two".into()], 1_000);
4298        save_community_v2(&v2).unwrap();
4299        let mut other = v2_fixture("One", &["wss://one"]);
4300        other.channels.push(private_channel(0x71, 0x72));
4301        save_community_v2(&other).unwrap();
4302
4303        crate::db::get_write_connection_guard_static()
4304            .unwrap()
4305            .execute(
4306                "INSERT INTO community_channels (channel_id, community_id, channel_key, epoch, name, created_at)
4307                 VALUES (?1, ?2, x'00', 0, 'c', 1)",
4308                params!["ee".repeat(32), "ff".repeat(32)],
4309            )
4310            .unwrap();
4311        let channels = held_channel_ids().unwrap();
4312        assert!(!channels.contains(&"ee".repeat(32)), "a channel whose community is gone is not held");
4313        assert!(channels.contains(&crate::simd::hex::bytes_to_hex_32(&v2.channels[0].id.0)));
4314        assert!(other.channels.iter().all(|ch| channels.contains(&ch.id.to_hex())));
4315        assert_eq!(channels.len(), other.channels.len() + v2.channels.len());
4316        let relays = held_community_relays().unwrap();
4317        assert!(relays.contains("wss://two") && relays.contains("wss://one"));
4318
4319        let cid = crate::simd::hex::bytes_to_hex_32(&v2.id().0);
4320        let (admin, social, stranger) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
4321        let role = |id: &str, perms: u64| Role {
4322            role_id: id.repeat(32), name: id.into(), position: 1, permissions: Permissions(perms),
4323            scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
4324        };
4325        let roles = CommunityRoles {
4326            roles: vec![role("aa", Permissions::ADMIN_ALL), role("bb", 0)],
4327            grants: vec![
4328                MemberGrant { member: admin.to_hex(), role_ids: vec!["aa".repeat(32)] },
4329                MemberGrant { member: social.to_hex(), role_ids: vec!["bb".repeat(32)] },
4330            ],
4331            everyone: None,
4332            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
4333        };
4334        set_community_roles(&cid, &roles, 1).unwrap();
4335        assert!(is_owner_or_admin(&cid, &owner.public_key().to_hex()), "a v2 owner proves itself from the id");
4336        assert!(is_owner_or_admin(&cid, &admin.to_hex()));
4337        assert!(!is_owner_or_admin(&cid, &social.to_hex()), "a role without management is not admin");
4338        assert!(!is_owner_or_admin(&cid, &stranger.to_hex()));
4339        assert!(!is_owner_or_admin(&"cd".repeat(32), &owner.public_key().to_hex()));
4340    }
4341
4342    #[test]
4343    fn epoch_key_archive_retains_every_epoch() {
4344        // a member who lived through a rotation must keep OLD epoch keys. Storing a new
4345        // epoch's key must NOT clobber a prior one (the data-loss bug the archive fixes).
4346        let (_tmp, _guard) = init_test_db();
4347        let cid = "f".repeat(64);
4348        let scope = "a".repeat(64);
4349
4350        store_epoch_key(&cid, &scope, 0, &[0xA0u8; 32]).unwrap();
4351        store_epoch_key(&cid, &scope, 1, &[0xA1u8; 32]).unwrap();
4352        store_epoch_key(&cid, &scope, 2, &[0xA2u8; 32]).unwrap();
4353
4354        let held = held_epoch_keys(&cid, &scope).unwrap();
4355        assert_eq!(held.len(), 3, "all three epoch keys retained");
4356        assert_eq!(held[0], (Epoch(0), [0xA0u8; 32]));
4357        assert_eq!(held[1], (Epoch(1), [0xA1u8; 32]));
4358        assert_eq!(held[2], (Epoch(2), [0xA2u8; 32]));
4359
4360        // Point lookup by epoch (what the open path uses to select a decryption key).
4361        assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xA1u8; 32]));
4362        assert_eq!(held_epoch_key(&cid, &scope, 9).unwrap(), None, "unheld epoch is None");
4363
4364        // Same coordinate REPLACE = fork-resolution committing a winning key (only legit overwrite).
4365        store_epoch_key(&cid, &scope, 1, &[0xBBu8; 32]).unwrap();
4366        assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xBBu8; 32]));
4367        assert_eq!(held_epoch_keys(&cid, &scope).unwrap().len(), 3, "replace didn't add a row");
4368
4369        // A different scope is isolated (server-root vs a channel share the table, never collide) —
4370        // at both the list AND the point-lookup level.
4371        assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
4372        assert_eq!(
4373            held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap(),
4374            None,
4375            "epoch 1 under a different scope is not the channel's key"
4376        );
4377    }
4378
4379    #[test]
4380    fn at_rest_encryption_wraps_keys_and_metadata_on_disk() {
4381        let (_tmp, _guard) = init_test_db();
4382        // Local Encryption ON with a known vault key (the db-test guard serializes, so toggling these
4383        // globals is safe; reset at the end). `others: &[]` — the slice only allocates a vault lane.
4384        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4385        crate::state::set_encryption_enabled(true);
4386
4387        let mut c = v2_fixture("Secret HQ", &["wss://relay.example"]);
4388        c.community_root = [0x42u8; 32];
4389        c.description = Some("top secret".into());
4390        c.channels.push(private_channel(0x61, 0x62));
4391        save_community_v2(&c).unwrap();
4392        let cid = c.id().to_hex();
4393        store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
4394        set_community_banlist(&cid, &["deadbeef".repeat(8)], 1).unwrap();
4395
4396        // On disk: secrets are 60-byte ciphertext (12 nonce + 32 + 16 tag), NOT raw 32-byte keys;
4397        // identifying text is hex ciphertext, never the plaintext.
4398        {
4399            let conn = crate::db::get_db_connection_guard_static().unwrap();
4400            let (root_len, control_root_len, name, relays, description): (i64, i64, String, String, String) = conn
4401                .query_row(
4402                    "SELECT length(server_root_key), length(control_root), name, relays, description
4403                     FROM communities WHERE community_id = ?1",
4404                    params![cid],
4405                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
4406                )
4407                .unwrap();
4408            assert_eq!(root_len, 60, "server_root_key must be ciphertext, not a raw 32-byte key");
4409            assert_eq!(control_root_len, 60, "control_root must be ciphertext, not a raw 32-byte key");
4410            for (column, stored, plain) in [
4411                ("name", &name, "Secret HQ"),
4412                ("relays", &relays, r#"["wss://relay.example"]"#),
4413                ("description", &description, "top secret"),
4414            ] {
4415                assert_ne!(stored, plain, "{column} must not be plaintext on disk");
4416                assert!(crate::crypto::looks_encrypted(stored), "{column} column is ciphertext");
4417            }
4418            let (owner_pk, owner_salt, control_pk): (String, String, String) = conn
4419                .query_row(
4420                    "SELECT owner_pubkey, owner_salt, control_pk FROM communities WHERE community_id = ?1",
4421                    params![cid],
4422                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
4423                )
4424                .unwrap();
4425            for (column, stored, plain) in [
4426                ("owner_pubkey", &owner_pk, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_xonly)),
4427                ("owner_salt", &owner_salt, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_salt)),
4428                ("control_pk", &control_pk, c.control_pk.unwrap().to_hex()),
4429            ] {
4430                assert_ne!(*stored, plain, "{column} must not be plaintext on disk");
4431                assert!(crate::crypto::looks_encrypted(stored), "{column} column is ciphertext");
4432            }
4433            let mut stmt = conn
4434                .prepare("SELECT length(channel_key), name FROM community_channels WHERE community_id = ?1")
4435                .unwrap();
4436            let channels: Vec<(i64, String)> =
4437                stmt.query_map(params![cid], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(Result::unwrap).collect();
4438            assert_eq!(channels.len(), 2);
4439            for (key_len, name) in &channels {
4440                assert_eq!(*key_len, 60, "channel_key must be ciphertext, Public placeholder and Private key alike");
4441                assert!(crate::crypto::looks_encrypted(name) && name != "general" && name != "staff", "channel name is ciphertext");
4442            }
4443            // The banlist lives in `community_bans`, sealed; SQL filters are handed the opened list.
4444            let banned_npub: String = conn
4445                .query_row("SELECT npub FROM community_bans WHERE community_id = ?1 LIMIT 1", params![cid], |r| r.get(0))
4446                .unwrap();
4447            assert!(crate::crypto::looks_encrypted(&banned_npub), "who is banned is sealed on disk, got {banned_npub}");
4448            let opened = crate::crypto::maybe_decrypt_text(&banned_npub);
4449            assert!(opened.starts_with("npub1"), "and opens to the form `events.npub` uses");
4450            let key_len: i64 = conn
4451                .query_row(
4452                    "SELECT length(key) FROM community_epoch_keys WHERE community_id = ?1 LIMIT 1",
4453                    params![cid],
4454                    |r| r.get(0),
4455                )
4456                .unwrap();
4457            assert_eq!(key_len, 60, "epoch-archive key must be ciphertext");
4458        }
4459
4460        // In memory: load decrypts everything back to the originals.
4461        let loaded = load_community_v2(c.id()).unwrap().unwrap();
4462        assert_eq!(loaded.name, "Secret HQ");
4463        assert_eq!(loaded.description.as_deref(), Some("top secret"));
4464        assert_eq!(loaded.community_root, [0x42u8; 32]);
4465        assert_eq!(loaded.control_root, c.control_root);
4466        assert_eq!(loaded.control_pk, c.control_pk);
4467        assert_eq!(loaded.identity.owner_xonly, c.identity.owner_xonly);
4468        assert_eq!(loaded.identity.owner_salt, c.identity.owner_salt);
4469        assert_eq!(loaded.relays, vec!["wss://relay.example".to_string()]);
4470        assert_eq!(loaded.channels[0].name, "general");
4471        assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]));
4472        assert_eq!(held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0).unwrap(), Some([0x42u8; 32]));
4473        assert_eq!(get_community_banlist(&cid).unwrap(), vec!["deadbeef".repeat(8)]);
4474
4475        crate::state::set_encryption_enabled(false);
4476        crate::state::ENCRYPTION_KEY.clear(&[]);
4477    }
4478
4479    #[test]
4480    fn an_encrypted_v2_community_loads_back_whole() {
4481        let (_tmp, _guard) = init_test_db();
4482        struct Vault;
4483        impl Drop for Vault {
4484            fn drop(&mut self) {
4485                crate::state::set_encryption_enabled(false);
4486                crate::state::ENCRYPTION_KEY.clear(&[]);
4487            }
4488        }
4489        let _vault = Vault;
4490        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4491        crate::state::set_encryption_enabled(true);
4492
4493        let owner = nostr_sdk::prelude::Keys::generate();
4494        let g = crate::community::v2::control::genesis(
4495            &owner,
4496            crate::community::v2::control::CommunityMetadata { name: "Sealed".into(), ..Default::default() },
4497            1_000,
4498        )
4499        .unwrap();
4500        let mut v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Sealed", Some("about".into()), vec!["wss://r".into()], 1_000);
4501        let mut private = v2.channels[0].clone();
4502        private.id = ChannelId([0x61; 32]);
4503        private.name = "staff".into();
4504        private.private = true;
4505        private.key = Some([0x62; 32]);
4506        v2.channels.push(private);
4507        save_community_v2(&v2).unwrap();
4508
4509        let name: String = crate::db::get_db_connection_guard_static()
4510            .unwrap()
4511            .query_row("SELECT name FROM communities WHERE community_id = ?1", params![v2.id().to_hex()], |r| r.get(0))
4512            .unwrap();
4513        assert!(crate::crypto::looks_encrypted(&name), "sealed on disk");
4514        let loaded = load_community_v2(v2.id()).unwrap().unwrap();
4515        assert_eq!(format!("{loaded:?}"), format!("{v2:?}"), "every field opens back to what was saved");
4516    }
4517
4518    #[test]
4519    fn at_rest_decrypt_tolerates_a_pre_migration_plaintext_row() {
4520        // A row written BEFORE the at-rest pass (raw key + plaintext text) must still read back once
4521        // encryption is on — the 32-vs-60 byte + `looks_encrypted` discriminators handle the mixed DB.
4522        let (_tmp, _guard) = init_test_db();
4523        crate::state::set_encryption_enabled(false);
4524        let mut c = v2_fixture("Legacy HQ", &[]);
4525        c.community_root = [0x42u8; 32];
4526        c.channels.push(private_channel(0x61, 0x62));
4527        save_community_v2(&c).unwrap();
4528
4529        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4530        crate::state::set_encryption_enabled(true);
4531        let loaded = load_community_v2(c.id()).unwrap().unwrap();
4532        assert_eq!(loaded.name, "Legacy HQ", "plaintext name reads through");
4533        assert_eq!(loaded.community_root, [0x42u8; 32], "raw 32-byte key reads through");
4534        assert_eq!(loaded.control_root, c.control_root, "raw 32-byte control root reads through");
4535        assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]), "raw 32-byte channel key reads through");
4536
4537        crate::state::set_encryption_enabled(false);
4538        crate::state::ENCRYPTION_KEY.clear(&[]);
4539    }
4540
4541    #[test]
4542    fn large_epoch_round_trips_losslessly() {
4543        // Epoch >= 2^63 stored as i64 then reinterpreted as u64 must be exact.
4544        let (_tmp, _guard) = init_test_db();
4545        let mut c = v2_fixture("HQ", &[]);
4546        c.root_epoch = Epoch(u64::MAX - 3);
4547        c.channels[0].epoch = Epoch(u64::MAX - 7);
4548        save_community_v2(&c).unwrap();
4549        let loaded = load_community_v2(c.id()).unwrap().unwrap();
4550        assert_eq!(loaded.root_epoch, Epoch(u64::MAX - 3));
4551        assert_eq!(loaded.channels[0].epoch, Epoch(u64::MAX - 7));
4552    }
4553
4554    #[test]
4555    fn malformed_channel_id_row_errors_not_corrupts() {
4556        // A corrupted (short/non-hex) channel_id must error on load, not silently
4557        // reconstruct a wrong-but-self-consistent id.
4558        let (_tmp, _guard) = init_test_db();
4559        let (c, cid, _) = saved_v2("HQ");
4560        {
4561            let conn = crate::db::get_write_connection_guard_static().unwrap();
4562            conn.execute(
4563                "INSERT OR REPLACE INTO community_channels
4564                    (channel_id, community_id, channel_key, epoch, name, created_at)
4565                 VALUES (?1, ?2, ?3, 0, 'bad', 0)",
4566                rusqlite::params!["zz_not_hex", cid, &[0u8; 32][..]],
4567            )
4568            .unwrap();
4569        }
4570        assert!(load_community_v2(c.id()).is_err(), "malformed id must error, not corrupt");
4571    }
4572
4573    #[test]
4574    fn message_key_store_take_round_trip() {
4575        let (_tmp, _guard) = init_test_db();
4576        let eph = Keys::generate();
4577        let relays = vec!["wss://r.one".to_string()];
4578        // Keyed by INNER message id; resolves to the OUTER event id + key + relays.
4579        store_message_key("inner_msg_id", "outer_evid", &eph, &relays).unwrap();
4580
4581        let (loaded, outer, r) = take_message_key("inner_msg_id").unwrap().expect("present");
4582        assert_eq!(
4583            loaded.secret_key().as_secret_bytes(),
4584            eph.secret_key().as_secret_bytes()
4585        );
4586        assert_eq!(outer, "outer_evid");
4587        assert_eq!(r, relays);
4588        // `take` is single-use: the row is removed.
4589        assert!(take_message_key("inner_msg_id").unwrap().is_none());
4590    }
4591
4592    #[test]
4593    fn missing_community_is_none() {
4594        let (_tmp, _guard) = init_test_db();
4595        let absent = CommunityId([0x33u8; 32]);
4596        assert!(load_community_v2(&absent).unwrap().is_none());
4597    }
4598
4599    #[test]
4600    fn list_ids_reflects_saved() {
4601        let (_tmp, _guard) = init_test_db();
4602        let (a, _, _) = saved_v2("A");
4603        let (b, _, _) = saved_v2("B");
4604        let ids = list_community_ids().unwrap();
4605        assert_eq!(ids.len(), 2);
4606        assert!(ids.contains(a.id()) && ids.contains(b.id()));
4607    }
4608
4609    #[test]
4610    fn delete_community_clears_all_local_state() {
4611        let (_tmp, _guard) = init_test_db();
4612        let (c, cid, private) = archived_v2();
4613        save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
4614        save_pending_invite(&"cd".repeat(32), "{}", "npub1x", 0).unwrap();
4615        set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
4616        assert!(!held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
4617        assert!(!held_epoch_keys(&cid, &private).unwrap().is_empty());
4618
4619        delete_community(&cid).unwrap();
4620        assert!(!community_exists(c.id()).unwrap());
4621        assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
4622        assert!(community_id_for_channel(&private).unwrap().is_none());
4623        assert!(list_public_invites(&cid).unwrap().is_empty());
4624        assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None, "edition heads cleared on delete");
4625        assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(), "epoch keys cleared on delete");
4626        assert!(held_epoch_keys(&cid, &private).unwrap().is_empty(), "channel epoch keys cleared on delete");
4627    }
4628
4629    #[test]
4630    fn delete_community_retain_keys_drops_state_but_keeps_epoch_keys() {
4631        // self-removal teardown: drop chat/membership/control state but KEEP the held epoch keys so a
4632        // later self-scrub of own past messages stays possible.
4633        let (_tmp, _guard) = init_test_db();
4634        let (c, cid, private) = archived_v2();
4635        save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
4636        set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
4637
4638        let base_before = held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap();
4639        let chan_before = held_epoch_keys(&cid, &private).unwrap();
4640        assert!(!base_before.is_empty() && !chan_before.is_empty(), "base + channel keys archived");
4641
4642        delete_community_retain_keys(&cid).unwrap();
4643
4644        // State is gone.
4645        assert!(!community_exists(c.id()).unwrap());
4646        assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
4647        assert!(community_id_for_channel(&private).unwrap().is_none());
4648        assert!(list_public_invites(&cid).unwrap().is_empty());
4649        assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None);
4650        // Epoch keys (base + channel, every epoch) survive intact.
4651        assert_eq!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(), base_before,
4652            "base epoch keys retained for self-scrub");
4653        assert_eq!(held_epoch_keys(&cid, &private).unwrap(), chan_before,
4654            "channel epoch keys retained for self-scrub");
4655    }
4656
4657    #[test]
4658    fn channel_resolves_to_owning_community() {
4659        let (_tmp, _guard) = init_test_db();
4660        let (_, cid, chan) = saved_v2("HQ");
4661        assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
4662        assert!(community_id_for_channel(&"ff".repeat(32)).unwrap().is_none());
4663    }
4664
4665    #[test]
4666    fn the_channel_cache_answers_in_bytes_and_hex_alike() {
4667        let (_tmp, _guard) = init_test_db();
4668        let (c, cid, chan) = saved_v2("Bytes");
4669        let ch = c.channels[0].id.0;
4670        // A miss fills the cache; the hit after it answers the same, in either form.
4671        assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
4672        assert_eq!(channel_community_cache().read().unwrap().get(&ch), Some(&c.id().0), "the miss filled the cache");
4673        assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
4674        assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
4675        // Only the exact stored spelling resolves, cached or not.
4676        assert_eq!(community_id_for_channel(&chan.to_uppercase()).unwrap(), None);
4677        assert_eq!(community_for_channel(&[0xFF; 32]).unwrap(), None);
4678        assert!(channel_community_cache().read().unwrap().get(&[0xFF; 32]).is_none(), "a miss is never cached");
4679        // Deleting the community stops both forms resolving.
4680        delete_community_retain_keys(&cid).unwrap();
4681        assert_eq!(community_for_channel(&ch).unwrap(), None);
4682        assert_eq!(community_id_for_channel(&chan).unwrap(), None);
4683    }
4684
4685    #[test]
4686    fn communities_that_ban_nobody_share_one_empty_set() {
4687        let (_tmp, _guard) = init_test_db();
4688        let (a, a_hex, _) = saved_v2("Calm");
4689        let (b, b_hex, _) = saved_v2("Quiet");
4690        let (ea, eb) = (banned_set_of(&a.id().0), banned_set(&b_hex));
4691        assert!(ea.is_empty() && std::sync::Arc::ptr_eq(&ea, &eb), "every empty banlist is the one shared set");
4692
4693        let villain = Keys::generate().public_key();
4694        set_community_banlist(&a_hex, &[villain.to_hex()], 10).unwrap();
4695        assert!(is_author_banned(&a_hex, &villain) && is_author_banned_in(&a.id().0, &villain));
4696        assert!(!is_author_banned_in(&b.id().0, &villain), "a ban stays in its own community");
4697        assert!(!std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()));
4698
4699        set_community_banlist(&a_hex, &[], 11).unwrap();
4700        assert!(std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()), "an emptied banlist returns to the shared set");
4701        assert!(!is_author_banned_in(&a.id().0, &villain));
4702    }
4703
4704    #[test]
4705    fn community_exists_reflects_saved() {
4706        let (_tmp, _guard) = init_test_db();
4707        let c = v2_fixture("A", &[]);
4708        assert!(!community_exists(c.id()).unwrap());
4709        save_community_v2(&c).unwrap();
4710        assert!(community_exists(c.id()).unwrap());
4711    }
4712
4713    #[test]
4714    fn a_block_drops_only_that_persons_parked_invites() {
4715        let (_tmp, _guard) = init_test_db();
4716        let (spam, friend) = ("cd".repeat(32), "ef".repeat(32));
4717        save_pending_invite(&spam, &v2_bundle("Spam"), "npub1spammer", 0).unwrap();
4718        save_pending_invite(&friend, &v2_bundle("Friends"), "npub1friend", 0).unwrap();
4719        assert_eq!(delete_pending_invites_from("npub1spammer").unwrap(), 1);
4720        let left: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
4721        assert_eq!(left, vec![friend], "the friend's invite stays");
4722    }
4723
4724    #[test]
4725    fn pending_invite_first_wins_and_round_trips() {
4726        let (_tmp, _guard) = init_test_db();
4727        let cid = "ab".repeat(32);
4728        let (first, second) = (v2_bundle("First"), v2_bundle("Second"));
4729        // First park inserts; a re-invite for the same id is IGNORED (first-wins, so a
4730        // hostile re-send can't rewrite a parked bundle or re-notify).
4731        assert!(save_pending_invite(&cid, &first, "npub1inviter", 0).unwrap());
4732        assert!(!save_pending_invite(&cid, &second, "npub1other", 0).unwrap());
4733        assert!(pending_invite_exists(&cid).unwrap());
4734
4735        let listed = list_pending_invites().unwrap();
4736        assert_eq!(listed.len(), 1);
4737        assert_eq!(listed[0].community_id, cid);
4738        assert_eq!(listed[0].bundle_json, first, "original bundle preserved");
4739        assert_eq!(listed[0].inviter_npub, "npub1inviter");
4740
4741        // get is non-destructive; delete then removes it.
4742        assert_eq!(get_pending_invite(&cid).unwrap(), Some(first.clone()));
4743        assert!(pending_invite_exists(&cid).unwrap(), "get must not delete");
4744        delete_pending_invite(&cid).unwrap();
4745        assert!(!pending_invite_exists(&cid).unwrap());
4746        assert!(get_pending_invite(&cid).unwrap().is_none());
4747    }
4748
4749    #[test]
4750    fn purge_drops_invites_for_held_communities_only() {
4751        let (_tmp, _guard) = init_test_db();
4752        // A community we hold + a parked invite for it (the cross-device race: invite landed
4753        // before the membership list rehydrated the community).
4754        let (_, held_hex, _) = saved_v2("Held");
4755        save_pending_invite(&held_hex, "{\"bundle\":1}", "npub1inviter", 0).unwrap();
4756        // An invite for a community we do NOT hold must survive the purge.
4757        let stranger = "ab".repeat(32);
4758        save_pending_invite(&stranger, "{\"bundle\":2}", "npub1inviter", 0).unwrap();
4759
4760        let n = purge_pending_invites_for_held_communities().unwrap();
4761        assert_eq!(n, 1, "only the held community's invite is purged");
4762        assert!(!pending_invite_exists(&held_hex).unwrap(), "held → invite gone");
4763        assert!(pending_invite_exists(&stranger).unwrap(), "unknown community → invite kept");
4764    }
4765
4766    #[test]
4767    fn an_invites_lifetime_runs_from_when_it_was_sent() {
4768        let (_tmp, _guard) = init_test_db();
4769        let lifetime = crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64;
4770        let now = now_secs();
4771        let (old, fresh, unknown, deadline) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32), "a4".repeat(32));
4772        for cid in [&old, &fresh, &unknown] {
4773            save_pending_invite(cid, "{}", "npub1x", 0).unwrap();
4774        }
4775        save_pending_invite(&deadline, "{}", "npub1x", now + 60).unwrap();
4776        set_pending_invite_sent(&old, now - lifetime - 1).unwrap();
4777        set_pending_invite_sent(&fresh, now - 60).unwrap();
4778        set_pending_invite_sent(&fresh, 1).unwrap();
4779        set_pending_invite_sent(&deadline, now - 60).unwrap();
4780
4781        let listed = list_pending_invites().unwrap();
4782        let get = |cid: &str| listed.iter().find(|i| i.community_id == cid);
4783        assert!(get(&old).is_none(), "sent past its lifetime, so gone though parked just now");
4784        let f = get(&fresh).unwrap();
4785        assert_eq!((f.sent_at, f.ends_at), (now - 60, now - 60 + lifetime), "the first send time stands");
4786        let u = get(&unknown).unwrap();
4787        assert_eq!((u.sent_at, u.ends_at), (0, u.received_at + lifetime));
4788        assert_eq!(get(&deadline).unwrap().ends_at, now + 60, "the sender's earlier deadline wins");
4789        assert_eq!(purge_expired_pending_invites().unwrap(), 1);
4790    }
4791
4792    #[test]
4793    fn an_invites_wraps_are_kept_once_each_up_to_a_cap_and_go_with_it() {
4794        let (_tmp, _guard) = init_test_db();
4795        let cid = "ef".repeat(32);
4796        note_pending_invite_wrap(&cid, &"01".repeat(32)).unwrap();
4797        assert!(pending_invite_wraps(&cid).unwrap().is_empty(), "no parked invite, nothing kept");
4798        save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
4799        for n in [1u8, 2, 1] {
4800            note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
4801        }
4802        assert_eq!(pending_invite_wraps(&cid).unwrap(), ["01".repeat(32), "02".repeat(32)]);
4803        for n in 3u8..40 {
4804            note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
4805        }
4806        assert_eq!(pending_invite_wraps(&cid).unwrap().len(), 16);
4807        delete_pending_invite(&cid).unwrap();
4808        assert!(pending_invite_wraps(&cid).unwrap().is_empty());
4809    }
4810
4811    #[test]
4812    fn decline_drops_pending_invite() {
4813        let (_tmp, _guard) = init_test_db();
4814        let cid = "cd".repeat(32);
4815        save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
4816        delete_pending_invite(&cid).unwrap();
4817        assert!(!pending_invite_exists(&cid).unwrap());
4818    }
4819
4820    #[test]
4821    fn pending_invites_are_capped_keeping_the_newest() {
4822        let (_tmp, _guard) = init_test_db();
4823        // 150 distinct invites with strictly increasing received_at (the helper stamps now_secs(),
4824        // so vary the id and rely on insertion order; to make ordering deterministic we bump the
4825        // stored time directly after each insert isn't needed — received_at ties break on id DESC).
4826        // Insert 150; the table must cap at 100.
4827        let bundle = v2_bundle("Flood");
4828        for i in 0..150u32 {
4829            let cid = format!("{:064x}", i);
4830            save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
4831        }
4832        let all = list_pending_invites().unwrap();
4833        assert_eq!(all.len(), 100, "table capped at MAX_PENDING_INVITES");
4834        // A spam flood can't grow it past the cap regardless of how many arrive.
4835        for i in 150..400u32 {
4836            let cid = format!("{:064x}", i);
4837            save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
4838        }
4839        assert_eq!(list_pending_invites().unwrap().len(), 100, "cap holds under flood");
4840    }
4841
4842    /// A parked invite past its sender-declared NIP-40 deadline is invisible to BOTH reads:
4843    /// the list (so it stops cluttering) and the peek the accept path uses (so it can't be
4844    /// redeemed). Relays only stop delivering an expired invite; the already-parked row is
4845    /// ours to enforce.
4846    #[test]
4847    fn expired_parked_invites_are_hidden_from_list_and_accept() {
4848        let (_tmp, _guard) = init_test_db();
4849        let now = now_secs();
4850        let live = "aa".repeat(32);
4851        let expired = "bb".repeat(32);
4852        let permanent = "cc".repeat(32);
4853
4854        save_pending_invite(&live, &v2_bundle("Live"), "npub1x", now + 3600).unwrap();
4855        save_pending_invite(&expired, &v2_bundle("Dead"), "npub1x", now - 1).unwrap();
4856        // 0 = the sender declared no deadline (a pre-expiry client): stays permanent, because
4857        // an invite whose sender never promised a deadline isn't ours to revoke.
4858        save_pending_invite(&permanent, &v2_bundle("Forever"), "npub1x", 0).unwrap();
4859
4860        let listed: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
4861        assert!(listed.contains(&live), "an unexpired invite still lists");
4862        assert!(listed.contains(&permanent), "a no-deadline invite still lists");
4863        assert!(!listed.contains(&expired), "an expired invite is hidden from the list");
4864
4865        assert!(get_pending_invite(&live).unwrap().is_some());
4866        assert!(get_pending_invite(&permanent).unwrap().is_some());
4867        assert!(
4868            get_pending_invite(&expired).unwrap().is_none(),
4869            "an expired invite must not be redeemable"
4870        );
4871
4872        // The row still exists until swept, and the sweep reclaims exactly the expired one.
4873        assert!(pending_invite_exists(&expired).unwrap(), "hidden, not yet deleted");
4874        assert_eq!(purge_expired_pending_invites().unwrap(), 1);
4875        assert!(!pending_invite_exists(&expired).unwrap());
4876        assert!(pending_invite_exists(&live).unwrap(), "the sweep spares live invites");
4877        assert!(pending_invite_exists(&permanent).unwrap(), "and no-deadline ones");
4878    }
4879
4880    /// The expiry is per-invite from the SENDER's tag, not derived from local receive time,
4881    /// so a short-fuse invite expires on the sender's schedule even if it was just received.
4882    #[test]
4883    fn expiry_follows_the_senders_deadline_not_receipt_time() {
4884        let (_tmp, _guard) = init_test_db();
4885        let cid = "de".repeat(32);
4886        // Received right now, but the sender's deadline already passed (a stale wrap that a
4887        // NIP-40-ignoring relay still served).
4888        save_pending_invite(&cid, "{}", "npub1x", now_secs() - 10).unwrap();
4889        assert!(list_pending_invites().unwrap().is_empty(), "receipt time does not extend the deadline");
4890        assert!(get_pending_invite(&cid).unwrap().is_none());
4891    }
4892
4893    /// A legacy banlist blob is adopted into `community_bans` on first read, and the blob is retired
4894    /// without tripping the column's NOT NULL: a failed adoption read as "nobody is banned".
4895    #[test]
4896    fn a_legacy_banlist_is_adopted_on_first_read() {
4897        let (_tmp, _guard) = init_test_db();
4898        let (_, cid, _) = saved_v2("Legacy bans");
4899        let banned = "ab".repeat(32);
4900        {
4901            let conn = crate::db::get_write_connection_guard_static().unwrap();
4902            conn.execute("DELETE FROM community_bans WHERE community_id = ?1", params![cid]).unwrap();
4903            conn.execute("UPDATE communities SET banlist = ?1 WHERE community_id = ?2", params![format!("[\"{banned}\"]"), cid]).unwrap();
4904        }
4905        assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned.clone()]);
4906        assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned], "and stays adopted");
4907    }
4908
4909    /// A task of a swapped-out account can't seal into its own store: not as plaintext right after
4910    /// the swap, and not under the next account's key once that one has unlocked.
4911    #[test]
4912    fn a_task_of_a_swapped_out_account_cannot_seal() {
4913        struct Vault;
4914        impl Drop for Vault {
4915            fn drop(&mut self) {
4916                crate::state::ENCRYPTION_KEY.clear(&[]);
4917                crate::state::set_encryption_enabled(false);
4918            }
4919        }
4920        const KA: [u8; 32] = [0x61; 32];
4921        const KB: [u8; 32] = [0x62; 32];
4922        let (_tmp, _guard) = init_test_db();
4923        let _vault = Vault;
4924        let account_a = crate::db::get_current_account().unwrap();
4925        crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4926        crate::state::ENCRYPTION_KEY.set(KA, &[]);
4927        crate::state::set_encryption_enabled(true);
4928        let (_, cid, ch) = saved_v2("A");
4929
4930        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4931        let late_write = |label: &'static str| {
4932            let (go, wait) = tokio::sync::oneshot::channel::<()>();
4933            let (cid, ch) = (cid.clone(), ch.clone());
4934            let task = {
4935                let _rt = rt.enter();
4936                crate::db::spawn_bound(async move {
4937                    let _ = wait.await;
4938                    set_community_pins(&cid, &ch, &format!("{{\"{label}\":1}}"), 1)
4939                })
4940            };
4941            (go, task)
4942        };
4943        let (go_plain, plain) = late_write("plain");
4944        let (go_foreign, foreign) = late_write("foreign");
4945
4946        // The swap: the vault and the flag drop first, then account B opens and unlocks.
4947        let account_b = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
4948        crate::state::ENCRYPTION_KEY.clear(&[]);
4949        crate::state::set_encryption_enabled(false);
4950        crate::db::set_current_account(account_b.clone()).unwrap();
4951        crate::db::init_database(&account_b).unwrap();
4952        go_plain.send(()).unwrap();
4953        assert!(rt.block_on(plain).unwrap().is_err(), "no plaintext into an encrypted store");
4954        crate::state::ENCRYPTION_KEY.set(KB, &[]);
4955        crate::state::set_encryption_enabled(true);
4956        go_foreign.send(()).unwrap();
4957        assert!(rt.block_on(foreign).unwrap().is_err(), "no seal under another account's key");
4958
4959        crate::db::set_current_account(account_a.clone()).unwrap();
4960        crate::db::init_database(&account_a).unwrap();
4961        crate::state::ENCRYPTION_KEY.set(KA, &[]);
4962        assert_eq!(get_community_pins(&cid, &ch).unwrap(), None, "account A's store is untouched");
4963    }
4964
4965    /// A legacy-salted account moves onto its own salt at its first unlock: everything reads back,
4966    /// nothing anywhere still opens under the legacy key, and the derivation is recorded. A wrong
4967    /// key or a biometric account changes nothing.
4968    #[test]
4969    fn a_legacy_account_moves_onto_its_own_salt_at_unlock() {
4970        use crate::crypto::{derive_key, Kdf};
4971        use crate::db::at_rest;
4972        struct Vault;
4973        impl Drop for Vault {
4974            fn drop(&mut self) {
4975                crate::state::ENCRYPTION_KEY.clear(&[]);
4976                crate::state::set_encryption_enabled(false);
4977            }
4978        }
4979        let (_tmp, _guard) = init_test_db();
4980        let _vault = Vault;
4981        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4982        let pin = "123456";
4983        let legacy = rt.block_on(derive_key(pin, &Kdf::Legacy));
4984        crate::state::ENCRYPTION_KEY.set(legacy, &[]);
4985        crate::state::set_encryption_enabled(true);
4986        crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4987        crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
4988        crate::db::set_sql_setting("last_vacuum".to_string(), "1".to_string()).unwrap();
4989        crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1legacyaccount", &legacy).unwrap()).unwrap();
4990        let mut community = v2_fixture("Old", &["wss://r"]);
4991        community.channels.push(private_channel(0x61, 0x62));
4992        save_community_v2(&community).unwrap();
4993        let (cid, ch) = (community.id().to_hex(), community.channels[0].id.to_hex());
4994        set_community_pins(&cid, &ch, r#"{"pins":["old"]}"#, 1).unwrap();
4995        let dm_chat = make_test_npub(900_002);
4996        let dm = crate::types::Message { id: "e1".repeat(32), content: "said long ago".into(), at: 1_600_000_000_000, mine: true, ..Default::default() };
4997        rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
4998        let dm_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
4999        let read = || {
5000            (
5001                get_community_pins(&cid, &ch).unwrap(),
5002                load_community_v2(community.id()).unwrap().map(|c| format!("{c:?}")),
5003                rt.block_on(crate::db::events::get_message_views(dm_int, 10, 0)).unwrap().into_iter().map(|m| m.content).collect::<Vec<_>>(),
5004            )
5005        };
5006        let before = read();
5007        assert_eq!(before.1, Some(format!("{community:?}")));
5008        assert_eq!(before.2, vec!["said long ago".to_string()]);
5009
5010        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &[0x77; 32])).unwrap(), "a key that proves nothing moves nothing");
5011        assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy);
5012        crate::db::set_sql_setting("security_type".to_string(), "biometric".to_string()).unwrap();
5013        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "a biometric account stays put");
5014        crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
5015        assert_eq!(read(), before);
5016
5017        // A failed upgrade leaves everything as it was and waits a day before the next attempt.
5018        {
5019            let conn = crate::db::get_write_connection_guard_static().unwrap();
5020            conn.execute_batch("CREATE TABLE unaddressable (k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID;").unwrap();
5021            conn.execute("INSERT INTO unaddressable VALUES ('a', ?1)", [crate::crypto::encrypt_with_key("x", &legacy).unwrap()]).unwrap();
5022        }
5023        assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).is_err());
5024        assert_eq!((Kdf::of_account().unwrap(), read()), (Kdf::Legacy, before.clone()), "nothing moved");
5025        assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(legacy));
5026        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "backed off");
5027        crate::db::get_write_connection_guard_static().unwrap().execute_batch("DROP TABLE unaddressable;").unwrap();
5028        crate::db::settings::remove_setting("kdf_upgrade_attempt").unwrap();
5029
5030        assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap());
5031        let kdf = Kdf::of_account().unwrap();
5032        assert!(!kdf.is_legacy(), "the salt is recorded");
5033        let salted = rt.block_on(derive_key(pin, &kdf));
5034        assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted), "the session carries on under the new key");
5035        assert_eq!(read(), before, "everything reads back");
5036        {
5037            let conn = crate::db::get_write_connection_guard_static().unwrap();
5038            let tx = conn.unchecked_transaction().unwrap();
5039            assert_eq!(at_rest::sweep_residue_in_tx(&tx, &legacy, None).unwrap(), 0, "nothing opens under the legacy key");
5040        }
5041        assert_eq!(crate::db::get_sql_setting("last_vacuum".to_string()).unwrap(), None, "a vacuum is due");
5042        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &salted)).unwrap(), "the next unlock has nothing to do");
5043
5044        // A second unlock that derived under the legacy salt before this upgrade committed can't
5045        // put that key back, and can't run an upgrade of its own.
5046        assert!(crate::crypto::install_unlocked_key(&legacy, &Kdf::Legacy).is_err());
5047        assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted));
5048        let again = Kdf::fresh();
5049        let again_key = rt.block_on(derive_key(pin, &again));
5050        assert!(!at_rest::upgrade_legacy_derivation(&legacy, &again_key, &again, &|_| {}).unwrap());
5051        assert_eq!(Kdf::of_account().unwrap(), kdf);
5052    }
5053
5054    const CRASH_PIN: &str = "424242";
5055
5056    /// Child half of `the_upgrade_survives_a_kill_at_any_moment`: open the account, unlock with
5057    /// the legacy key and run the upgrade until killed. Inert unless the parent set it up.
5058    #[test]
5059    #[ignore = "driven by the_upgrade_survives_a_kill_at_any_moment"]
5060    fn upgrade_crash_child() {
5061        use std::io::Write;
5062        let (Ok(root), Ok(npub)) = (std::env::var("VECTOR_CRASH_ROOT"), std::env::var("VECTOR_CRASH_NPUB")) else { return };
5063        crate::db::set_app_data_dir(root.into());
5064        crate::db::set_current_account(npub.clone()).unwrap();
5065        crate::db::init_database(&npub).unwrap();
5066        crate::state::init_encryption_enabled();
5067        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5068        let legacy = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &crate::crypto::Kdf::Legacy));
5069        crate::state::ENCRYPTION_KEY.set(legacy, &[]);
5070        // Derived before READY, so the parent's kills fall across the transaction alone.
5071        let kdf = crate::crypto::Kdf::fresh();
5072        let salted = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &kdf));
5073        println!("CHILD READY");
5074        std::io::stdout().flush().unwrap();
5075        assert!(crate::db::at_rest::upgrade_legacy_derivation(&legacy, &salted, &kdf, &|_| {}).unwrap());
5076        println!("CHILD DONE");
5077        std::io::stdout().flush().unwrap();
5078    }
5079
5080    /// The upgrade killed at moments swept across a whole run, in a separate process: every
5081    /// database left behind opens whole under exactly the key its recorded derivation names,
5082    /// and nothing is left under the other.
5083    #[test]
5084    #[ignore = "spawns and kills child processes; run with --ignored"]
5085    fn the_upgrade_survives_a_kill_at_any_moment() {
5086        use crate::crypto::{derive_key, Kdf};
5087        use std::io::BufRead;
5088        struct Vault;
5089        impl Drop for Vault {
5090            fn drop(&mut self) {
5091                crate::state::ENCRYPTION_KEY.clear(&[]);
5092                crate::state::set_encryption_enabled(false);
5093            }
5094        }
5095        let (_tmp, _guard) = init_test_db();
5096        let _vault = Vault;
5097        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5098        let legacy = rt.block_on(derive_key(CRASH_PIN, &Kdf::Legacy));
5099
5100        // A legacy account big enough that the transaction takes real time.
5101        let template = crate::db::get_current_account().unwrap();
5102        crate::state::ENCRYPTION_KEY.set(legacy, &[]);
5103        crate::state::set_encryption_enabled(true);
5104        crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
5105        crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
5106        crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1crashaccount", &legacy).unwrap()).unwrap();
5107        let (_, cid, ch) = saved_v2("Crash");
5108        set_community_pins(&cid, &ch, r#"{"pins":["kept"]}"#, 1).unwrap();
5109        let chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_003)).unwrap();
5110        {
5111            let mut conn = crate::db::get_write_connection_guard_static().unwrap();
5112            let tx = conn.transaction().unwrap();
5113            for i in 0..20_000u32 {
5114                tx.execute(
5115                    "INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, 14, ?2, ?3, ?4, ?4)",
5116                    rusqlite::params![format!("{i:064x}"), chat, crate::crypto::encrypt_with_key(&format!("message {i}"), &legacy).unwrap(), i],
5117                ).unwrap();
5118            }
5119            tx.commit().unwrap();
5120        }
5121        crate::db::close_database();
5122        let root = crate::db::shared_test_data_dir().to_path_buf();
5123
5124        let copy_of_template = || -> String {
5125            let npub = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
5126            std::fs::create_dir_all(root.join(&npub)).unwrap();
5127            for entry in std::fs::read_dir(root.join(&template)).unwrap().flatten() {
5128                std::fs::copy(entry.path(), root.join(&npub).join(entry.file_name())).unwrap();
5129            }
5130            npub
5131        };
5132        // One child run, killed `after` READY, or left to finish when `None`.
5133        let run_child = |npub: &str, after: Option<std::time::Duration>| -> std::time::Duration {
5134            let mut child = std::process::Command::new(std::env::current_exe().unwrap())
5135                .args(["--exact", "db::community::tests::upgrade_crash_child", "--ignored", "--nocapture", "--test-threads=1"])
5136                .env("VECTOR_CRASH_ROOT", &root)
5137                .env("VECTOR_CRASH_NPUB", npub)
5138                .stdout(std::process::Stdio::piped())
5139                .stderr(std::process::Stdio::null())
5140                .spawn()
5141                .unwrap();
5142            let mut lines = std::io::BufReader::new(child.stdout.take().unwrap()).lines();
5143            while let Some(Ok(line)) = lines.next() {
5144                if line.contains("CHILD READY") {
5145                    break;
5146                }
5147            }
5148            let ready = std::time::Instant::now();
5149            match after {
5150                Some(delay) => {
5151                    std::thread::sleep(delay);
5152                    let _ = child.kill();
5153                }
5154                None => {
5155                    while let Some(Ok(line)) = lines.next() {
5156                        if line.contains("CHILD DONE") {
5157                            break;
5158                        }
5159                    }
5160                }
5161            }
5162            let _ = child.wait();
5163            ready.elapsed()
5164        };
5165        let verify = |npub: &str| -> bool {
5166            crate::db::set_current_account(npub.to_string()).unwrap();
5167            crate::db::init_database(npub).unwrap();
5168            let kdf = Kdf::of_account().unwrap();
5169            let key = rt.block_on(derive_key(CRASH_PIN, &kdf));
5170            crate::state::ENCRYPTION_KEY.set(key, &[]);
5171            let pkey = crate::db::get_pkey().unwrap().unwrap();
5172            assert_eq!(crate::crypto::decrypt_with_key(&pkey, &key).unwrap(), "nsec1crashaccount", "{npub}: the stored key opens");
5173            assert_eq!(get_community_pins(&cid, &ch).unwrap().map(|p| p.0).as_deref(), Some(r#"{"pins":["kept"]}"#));
5174            let conn = crate::db::get_db_connection_guard_static().unwrap();
5175            let mut stmt = conn.prepare("SELECT content FROM events WHERE chat_id = ?1").unwrap();
5176            let unopened = stmt
5177                .query_map([chat], |r| r.get::<_, String>(0)).unwrap()
5178                .flatten()
5179                .filter(|c| crate::crypto::decrypt_with_key(c, &key).is_err())
5180                .count();
5181            assert_eq!(unopened, 0, "{npub}: every message opens under the recorded derivation");
5182            !kdf.is_legacy()
5183        };
5184
5185        // Measure one whole run, then kill at moments spread across it and a little past.
5186        let first = copy_of_template();
5187        let whole = run_child(&first, None);
5188        assert!(verify(&first), "an uninterrupted run upgrades");
5189        let mut outcomes = (0, 0);
5190        let mut trace = String::new();
5191        for step in 0..24u32 {
5192            let npub = copy_of_template();
5193            run_child(&npub, Some(whole * step / 21));
5194            let upgraded = verify(&npub);
5195            trace.push(if upgraded { 'U' } else { 'L' });
5196            if upgraded { outcomes.1 += 1 } else { outcomes.0 += 1 }
5197        }
5198        println!("kill outcomes in time order: {trace}");
5199        println!("crash sweep over a {whole:?} transaction: {} left legacy, {} upgraded", outcomes.0, outcomes.1);
5200        assert!(outcomes.0 >= 10, "most kills land inside the transaction and roll it back");
5201        assert!(outcomes.1 > 0, "and the sweep reaches past the commit");
5202    }
5203
5204    /// The stored derivation always describes the key the data is under: setup records it, enable
5205    /// and a PIN change replace it in their own transaction, disable drops it, and a refused PIN
5206    /// change leaves it alone.
5207    #[test]
5208    fn the_key_derivation_moves_with_every_migration() {
5209        use crate::crypto::Kdf;
5210        use crate::db::at_rest;
5211        struct Vault;
5212        impl Drop for Vault {
5213            fn drop(&mut self) {
5214                crate::state::ENCRYPTION_KEY.clear(&[]);
5215                crate::state::set_encryption_enabled(false);
5216            }
5217        }
5218        let (_tmp, _guard) = init_test_db();
5219        let _vault = Vault;
5220        assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "no row reads as the legacy salt");
5221        save_community_v2(&v2_fixture("K", &[])).unwrap();
5222
5223        let (k1, key1) = (Kdf::fresh(), [0x51; 32]);
5224        at_rest::enable(&key1, &k1, "pin", None, None, &|_| {}).unwrap();
5225        assert_eq!(Kdf::of_account().unwrap(), k1);
5226
5227        let (k2, key2) = (Kdf::fresh(), [0x52; 32]);
5228        assert!(at_rest::rekey(&[0x5F; 32], &key2, &k2, "pin", None, &|_| {}).is_err());
5229        assert_eq!(Kdf::of_account().unwrap(), k1, "a refused change keeps the derivation");
5230        at_rest::rekey(&key1, &key2, &k2, "pin", None, &|_| {}).unwrap();
5231        assert_eq!(Kdf::of_account().unwrap(), k2);
5232
5233        at_rest::disable(&key2, &|_| {}).unwrap();
5234        assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "a plaintext store keeps no derivation");
5235
5236        let k3 = Kdf::fresh();
5237        let sealed = crate::crypto::encrypt_with_key("nsec1setup", &[0x53; 32]).unwrap();
5238        crate::db::settings::commit_account_setup(&sealed, true, Some("pin"), None, None, k3.descriptor().as_deref()).unwrap();
5239        assert_eq!(Kdf::of_account().unwrap(), k3, "setup records the salt with the key it sealed");
5240    }
5241
5242    #[test]
5243    fn the_identity_opens_under_the_users_proof_and_nothing_else() {
5244        use crate::crypto::{derive_key, Kdf};
5245        use crate::db::at_rest::{self, open_identity_secrets, CREDENTIAL_INCORRECT};
5246        struct Vault;
5247        impl Drop for Vault {
5248            fn drop(&mut self) {
5249                crate::state::ENCRYPTION_KEY.clear(&[]);
5250                crate::state::set_encryption_enabled(false);
5251            }
5252        }
5253        let (_tmp, _guard) = init_test_db();
5254        let _vault = Vault;
5255        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5256        crate::db::set_pkey("nsec1identity").unwrap();
5257        crate::db::set_seed("abandon ability able").unwrap();
5258        let plain = open_identity_secrets(None).unwrap();
5259        assert_eq!((plain.0.as_str(), plain.1.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
5260
5261        let kdf = Kdf::fresh();
5262        let key = rt.block_on(derive_key("424242", &kdf));
5263        at_rest::enable(&key, &kdf, "pin", None, None, &|_| {}).unwrap();
5264        assert!(crate::state::ENCRYPTION_KEY.get().is_some(), "the session holds the key");
5265        assert!(open_identity_secrets(None).is_err(), "a sealed store opens nothing on the session alone");
5266        assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5267        assert_eq!(open_identity_secrets(Some(&[0x09; 32])).unwrap_err(), CREDENTIAL_INCORRECT);
5268
5269        let proven = rt.block_on(at_rest::prove_credential("424242")).unwrap();
5270        let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
5271        assert_eq!((nsec.as_str(), seed.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
5272
5273        // Misses past the free ones lock even the right PIN out for a while, and a success clears them.
5274        for _ in 0..4 {
5275            assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5276        }
5277        assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5278        let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
5279        assert!(locked.starts_with("CREDENTIAL_LOCKED:"), "{locked}");
5280        crate::db::remove_setting("credential_retry_at").unwrap();
5281        rt.block_on(at_rest::prove_credential("424242")).unwrap();
5282        assert!(crate::db::get_sql_setting("credential_failures".to_string()).unwrap().is_none());
5283
5284        // A clock set back far can't stretch the wait past the longest one a miss earns.
5285        let far = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 86_400 * 30;
5286        crate::db::set_sql_setting("credential_retry_at".to_string(), far.to_string()).unwrap();
5287        let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
5288        let secs: u64 = locked.strip_prefix("CREDENTIAL_LOCKED:").unwrap().parse().unwrap();
5289        assert!(secs <= 15 * 60, "{secs}");
5290        crate::db::remove_setting("credential_retry_at").unwrap();
5291
5292        // A seed left in plaintext from before encryption still exports; one that won't open stays behind.
5293        crate::db::set_seed("abandon ability able").unwrap();
5294        assert_eq!(open_identity_secrets(Some(&proven)).unwrap().1.as_deref().map(|s| s.as_str()), Some("abandon ability able"));
5295        crate::db::set_seed("deadbeef").unwrap();
5296        let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
5297        assert!(nsec.starts_with("nsec1") && seed.is_none());
5298    }
5299
5300    /// Reads racing a stream of PIN changes always open: a row read just before a commit and
5301    /// opened just after, or read just after and opened before the vault moved, never comes
5302    /// back as ciphertext.
5303    #[test]
5304    fn reads_racing_pin_changes_always_open() {
5305        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5306        use std::sync::Arc;
5307        struct Vault;
5308        impl Drop for Vault {
5309            fn drop(&mut self) {
5310                crate::state::ENCRYPTION_KEY.clear(&[]);
5311                crate::state::set_encryption_enabled(false);
5312            }
5313        }
5314        let (_tmp, _guard) = init_test_db();
5315        let _vault = Vault;
5316        let keys: Vec<[u8; 32]> = (0u8..31).map(|i| [0x90 + i; 32]).collect();
5317        crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
5318        crate::state::set_encryption_enabled(true);
5319        let (_, cid, ch) = saved_v2("Read");
5320        let pinned = r#"{"pins":["kept"]}"#;
5321        set_community_pins(&cid, &ch, pinned, 1).unwrap();
5322
5323        let stop = Arc::new(AtomicBool::new(false));
5324        let (reads, garbled) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
5325        let reader = {
5326            let (stop, reads, garbled, cid, ch) = (stop.clone(), reads.clone(), garbled.clone(), cid.clone(), ch.clone());
5327            std::thread::spawn(move || {
5328                while !stop.load(Ordering::SeqCst) {
5329                    let got = get_community_pins(&cid, &ch).unwrap().map(|(c, _)| c);
5330                    reads.fetch_add(1, Ordering::SeqCst);
5331                    if got.as_deref() != Some(pinned) {
5332                        garbled.fetch_add(1, Ordering::SeqCst);
5333                    }
5334                }
5335            })
5336        };
5337        for pair in keys.windows(2) {
5338            crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5339            // The grace covers a read straddling ONE change; real PIN changes are seconds apart,
5340            // so let a read that began after this one finish before the next.
5341            let seen = reads.load(Ordering::SeqCst);
5342            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
5343            while reads.load(Ordering::SeqCst) < seen + 2 {
5344                assert!(std::time::Instant::now() < deadline, "reads stopped completing across a PIN change");
5345                std::thread::yield_now();
5346            }
5347        }
5348        stop.store(true, Ordering::SeqCst);
5349        reader.join().unwrap();
5350        assert!(reads.load(Ordering::SeqCst) > 0);
5351        assert_eq!(garbled.load(Ordering::SeqCst), 0, "no read across a PIN change came back unopened");
5352        std::thread::sleep(std::time::Duration::from_millis(600));
5353        assert!(!crate::state::PREVIOUS_AT_REST_KEY.has_key(), "the replaced key is wiped after its grace");
5354    }
5355
5356    /// Writes racing a stream of PIN changes all land on the key the store ends on, and a
5357    /// read-modify-write never loses what it merged into.
5358    #[test]
5359    fn writes_racing_pin_changes_land_on_the_final_key() {
5360        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5361        use std::sync::Arc;
5362        struct Vault;
5363        impl Drop for Vault {
5364            fn drop(&mut self) {
5365                crate::state::ENCRYPTION_KEY.clear(&[]);
5366                crate::state::set_encryption_enabled(false);
5367            }
5368        }
5369        let (_tmp, _guard) = init_test_db();
5370        let _vault = Vault;
5371        let keys: Vec<[u8; 32]> = (0u8..21).map(|i| [0x40 + i; 32]).collect();
5372        crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
5373        crate::state::set_encryption_enabled(true);
5374        let (_, cid, ch) = saved_v2("Race");
5375
5376        let stop = Arc::new(AtomicBool::new(false));
5377        let last = Arc::new(AtomicU64::new(0));
5378        let writer = {
5379            let (stop, last, cid, ch) = (stop.clone(), last.clone(), cid.clone(), ch.clone());
5380            std::thread::spawn(move || {
5381                let mut i = 0u64;
5382                while !stop.load(Ordering::SeqCst) {
5383                    i += 1;
5384                    set_community_pins(&cid, &ch, &format!("{{\"v\":{i}}}"), i as i64).unwrap();
5385                    merge_community_ban_marks(&cid, &[(format!("npub{i}"), i)].into_iter().collect()).unwrap();
5386                    last.store(i, Ordering::SeqCst);
5387                }
5388            })
5389        };
5390        while last.load(Ordering::SeqCst) == 0 {
5391            std::thread::yield_now();
5392        }
5393        for pair in keys.windows(2) {
5394            crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5395        }
5396        stop.store(true, Ordering::SeqCst);
5397        writer.join().unwrap();
5398
5399        let n = last.load(Ordering::SeqCst);
5400        assert_eq!(get_community_pins(&cid, &ch).unwrap(), Some((format!("{{\"v\":{n}}}"), n as i64)));
5401        let marks = get_community_ban_marks(&cid).unwrap();
5402        assert_eq!(marks.len() as u64, n, "every merged mark survives the key changes");
5403    }
5404
5405    /// Every encrypting writer, on the real schema, through a PIN change and a disable. The
5406    /// sweep list alone must leave nothing on the old key, so a writer whose column it misses
5407    /// fails here. A new writer that encrypts a column belongs in this test.
5408    #[test]
5409    fn a_v2_link_counts_the_members_who_joined_through_it() {
5410        use crate::community::v2::guestbook::{GuestbookEntry, GuestbookEvent};
5411        let (_tmp, _guard) = init_test_db();
5412        let owner = nostr_sdk::prelude::Keys::generate();
5413        let g = crate::community::v2::control::genesis(
5414            &owner,
5415            crate::community::v2::control::CommunityMetadata { name: "Hub".into(), ..Default::default() },
5416            1_000,
5417        )
5418        .unwrap();
5419        let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Hub", None, vec!["wss://r".into()], 1_000);
5420        save_community_v2(&v2).unwrap();
5421        let cid = v2.id().to_hex();
5422
5423        let me = owner.public_key();
5424        let someone_else = nostr_sdk::prelude::Keys::generate().public_key();
5425        let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
5426        let join = |n: u8, member: PublicKey, by: Option<(String, &str)>| GuestbookEvent {
5427            epoch: None,
5428            observed_at: None,
5429            rumor_id: [n; 32],
5430            entry: GuestbookEntry::Join { member, invited_by: by.map(|(c, l)| (c, l.to_string())), at_ms: n as u64 },
5431        };
5432        let events = vec![
5433            join(1, a, Some((me.to_hex(), "hub"))),
5434            join(2, b, Some((me.to_bech32().unwrap(), "hub"))),
5435            join(3, a, Some((me.to_hex(), "hub"))),
5436            join(4, c, Some((me.to_hex(), ""))),
5437            join(5, c, Some((someone_else.to_hex(), "hub"))),
5438            join(6, b, None),
5439        ];
5440        set_guestbook(&cid, &events, 9).unwrap();
5441
5442        let counts = community_invite_join_counts(&cid, &me).unwrap();
5443        assert_eq!(counts.get("hub"), Some(&2), "a rejoin counts once, either spelling of the creator counts");
5444        assert_eq!(counts.get(""), Some(&1), "an unlabeled link's joins are kept apart");
5445        assert_eq!(counts.len(), 2, "another creator's link and a bare join count for nobody here");
5446    }
5447
5448    #[test]
5449    fn a_group_chat_becomes_a_community_with_a_second_channel_or_an_invite_link() {
5450        let (_tmp, _guard) = init_test_db();
5451        let is = |c: &crate::community::v2::community::CommunityV2| crate::notify::is_community(&c.id().to_hex());
5452
5453        let mut chat = v2_fixture("Friends", &["wss://r"]);
5454        save_community_v2(&chat).unwrap();
5455        assert!(!is(&chat), "one channel, no link: a group chat");
5456        assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::All);
5457
5458        let mut second = chat.channels[0].clone();
5459        second.id = crate::community::ChannelId([0x42; 32]);
5460        second.name = "random".into();
5461        chat.channels.push(second);
5462        save_community_v2(&chat).unwrap();
5463        assert!(is(&chat), "a second channel makes it a community");
5464        assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::Mentions);
5465
5466        let open = v2_fixture("Open", &["wss://r"]);
5467        save_community_v2(&open).unwrap();
5468        assert!(!is(&open));
5469        set_community_invite_registry(&open.id().to_hex(), &["loc1".into()]).unwrap();
5470        assert!(is(&open), "an invite link makes it a community");
5471        set_community_invite_registry(&open.id().to_hex(), &[]).unwrap();
5472        assert!(!is(&open), "revoking the last link makes it a group chat again");
5473
5474        assert_eq!(crate::notify::default_level(None), crate::notify::NotifyLevel::All, "a DM rings for everything");
5475    }
5476
5477    #[test]
5478    fn every_encrypting_writer_is_covered_by_the_at_rest_sweep() {
5479        use crate::db::at_rest;
5480        const K: [u8; 32] = [0x31; 32];
5481        const K2: [u8; 32] = [0x32; 32];
5482        const WRONG: [u8; 32] = [0x39; 32];
5483        struct Vault;
5484        impl Drop for Vault {
5485            fn drop(&mut self) {
5486                crate::state::ENCRYPTION_KEY.clear(&[]);
5487                crate::state::set_encryption_enabled(false);
5488            }
5489        }
5490        let (_tmp, _guard) = init_test_db();
5491        let _vault = Vault;
5492        crate::state::ENCRYPTION_KEY.set(K, &[]);
5493        crate::state::set_encryption_enabled(true);
5494
5495        let mut v2 = v2_fixture("HQ", &["wss://r"]);
5496        v2.description = Some("about".into());
5497        let image = |url: &str| crate::community::v2::control::ImageRef {
5498            url: url.into(), key: "0".repeat(64), nonce: "1".repeat(32), hash: "a".repeat(64), extra: Default::default(),
5499        };
5500        v2.icon = Some(image("https://blossom.example/icon"));
5501        v2.banner = Some(image("https://blossom.example/banner"));
5502        v2.meta_custom = Some([("k".to_string(), serde_json::Value::from("v"))].into_iter().collect());
5503        v2.channels[0].voice = Some(true);
5504        v2.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
5505        v2.channels.push(private_channel(0x61, 0x62));
5506        save_community_v2(&v2).unwrap();
5507        let cid = v2.id().to_hex();
5508        let ch = v2.channels[0].id.to_hex();
5509        let private = v2.channels[1].id.to_hex();
5510        store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &v2.community_root).unwrap();
5511        store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
5512        park_channel_key(&cid, &private, 3, &[0x33; 32], &"ab".repeat(32)).unwrap();
5513        store_message_key("m1", "o1", &nostr_sdk::prelude::Keys::generate(), &["wss://r".into()]).unwrap();
5514        let owner = nostr_sdk::prelude::Keys::generate();
5515        store_wrap_owner("m1", "o1", &owner, &["wss://r".into()]).unwrap();
5516        save_pending_invite(&"de".repeat(32), r#"{"bundle":1}"#, "npub1inviter", now_secs() + 3600).unwrap();
5517        save_public_invite(&"ab".repeat(32), &cid, "https://vectorapp.io/invite#x", None, Some("Label")).unwrap();
5518        set_community_policy(&cid, "p1", r#"{"format":1}"#, "hh", true, 0).unwrap();
5519        merge_community_ban_marks(&cid, &[("npub1banned".to_string(), 5u64)].into_iter().collect()).unwrap();
5520        set_community_roles(&cid, &crate::community::roles::CommunityRoles::default(), 1).unwrap();
5521        set_community_invite_registry(&cid, &["loc1".into()]).unwrap();
5522        replace_invite_link_sets(&cid, &[InviteLinkSetRow { creator_hex: "cd".repeat(32), locators: vec!["l1".into()] }]).unwrap();
5523        set_guestbook(&cid, &[], 9).unwrap();
5524        set_community_pins(&cid, &ch, r#"{"pins":["x"]}"#, 1).unwrap();
5525        record_audit_local(&cid, "e1", 5, r#"{"action":"message_delete"}"#).unwrap();
5526        let control_wrap = br#"{"kind":1059,"content":"a control wrap as a relay served it"}"#.to_vec();
5527        store_control_wraps(&cid, &[0x77; 32], 1, 5, &[([0x11; 32], 5, Some(control_wrap.clone())), ([0x12; 32], 6, None)]).unwrap();
5528        let control_wraps = || control_wrap_page(&cid, &[0x77; 32], None, 10).unwrap();
5529        assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())]);
5530        let on_disk: Vec<u8> = crate::db::get_db_connection_guard_static().unwrap()
5531            .query_row("SELECT wrap FROM community_control_wraps WHERE wrap IS NOT NULL", [], |r| r.get(0)).unwrap();
5532        assert_ne!(on_disk, control_wrap, "a held Control wrap is sealed on disk");
5533
5534        // A DM with a link preview and a file, and an unconfirmed send's retained rumor.
5535        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5536        let dm_chat = make_test_npub(900_000);
5537        let dm = crate::types::Message {
5538            id: "a1".repeat(32),
5539            content: "the message itself".into(),
5540            at: 1_700_000_000_000,
5541            mine: true,
5542            preview_metadata: Some(crate::types::SiteMetadata {
5543                domain: "example.com".into(), og_title: Some("A title".into()), og_description: None,
5544                og_image: None, og_url: Some("https://example.com/a".into()), og_type: None,
5545                title: None, description: None, favicon: None,
5546            }),
5547            attachments: vec![crate::types::Attachment {
5548                id: "b2".repeat(32), key: "c3".repeat(32), nonce: "d4".repeat(16), extension: "jpg".into(),
5549                name: "passport.jpg".into(), url: "https://blossom.example/x.jpg".into(), size: 42,
5550                img_meta: Some(crate::types::ImageMetadata { thumbhash: "thumb".into(), width: 4, height: 3 }),
5551                fallback_urls: vec!["https://mirror.example/x.jpg".into()],
5552                ..Default::default()
5553            }],
5554            ..Default::default()
5555        };
5556        rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
5557        let dm_chat_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
5558        let (wrap, rumor) = {
5559            use crate::event_ext::FinalizeUnsignedWithId;
5560            use nostr_sdk::prelude::*;
5561            let ephemeral = Keys::generate();
5562            let wrap = EventBuilder::new(Kind::TextNote, "wrap").finalize(&ephemeral).unwrap();
5563            let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "still sending")
5564                .finalize_unsigned_with_id(Keys::generate().public_key());
5565            crate::db::nip17_keys::store_wrap_key(
5566                &wrap.id, &rumor.id.unwrap(), &Keys::generate().public_key(),
5567                crate::db::nip17_keys::WrapRole::Recipient, ephemeral.secret_key(), &[],
5568            ).unwrap();
5569            (wrap, rumor)
5570        };
5571        crate::db::nip17_keys::stash_resend_payload(&wrap.id, "pending-1", &wrap, &rumor).unwrap();
5572        // A stranger's wallpaper, held until their request is accepted.
5573        crate::db::chats::hold_wallpaper(&dm_chat, 5, r#"{"url":"https://blossom.example/held-wallpaper"}"#).unwrap();
5574        // A kept file's key.
5575        let kept = crate::db::media_store::StoredMedia {
5576            hash: [0x5b; 32], file: "f".into(), key: "e5".repeat(32), nonce: "f6".repeat(16), blob_sha256: "aa".repeat(32),
5577            pt_len: 9, mime: "image/png".into(), origin: crate::db::media_store::Origin::Received,
5578        };
5579        crate::db::media_store::insert(&kept).unwrap();
5580
5581        // A ban set while sealed still hides its author from the channel and its unread count.
5582        let (banned, allowed) = {
5583            use nostr_sdk::prelude::ToBech32;
5584            (nostr_sdk::prelude::Keys::generate().public_key(), nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap())
5585        };
5586        set_community_banlist(&cid, &[banned.to_hex()], 1).unwrap();
5587        for (id, author) in [("c7", { use nostr_sdk::prelude::ToBech32; banned.to_bech32().unwrap() }), ("d8", allowed)] {
5588            let msg = crate::types::Message { id: id.repeat(32), content: "in the channel".into(), at: 1_700_000_000_000, npub: Some(author), ..Default::default() };
5589            rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
5590        }
5591        let ch_int = crate::db::id_cache::get_or_create_chat_id(&ch).unwrap();
5592
5593        let read = || {
5594            (
5595                get_pending_channel_keys(&cid).unwrap().iter().map(|k| (k.key, k.sender.clone())).collect::<Vec<_>>(),
5596                get_community_ban_marks(&cid).unwrap(),
5597                get_community_pins(&cid, &ch).unwrap(),
5598                load_community_v2(v2.id()).unwrap().map(|c| format!("{c:?}")),
5599                (
5600                    held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(),
5601                    held_epoch_keys(&cid, &private).unwrap(),
5602                    get_audit_local(&cid).unwrap(),
5603                ),
5604                rt.block_on(crate::db::events::get_message_views(dm_chat_int, 10, 0)).unwrap()
5605                    .into_iter().map(|m| (m.content, m.preview_metadata, m.attachments)).collect::<Vec<_>>(),
5606                crate::db::nip17_keys::get_resend_payload_by_pending("pending-1").unwrap().map(|p| p.rumor.content),
5607                (
5608                    get_community_banlist(&cid).unwrap(),
5609                    rt.block_on(crate::db::events::get_message_views(ch_int, 10, 0)).unwrap().into_iter().map(|m| m.id).collect::<Vec<_>>(),
5610                    rt.block_on(crate::db::events::unread_count_for_chat(&ch)).unwrap(),
5611                    rt.block_on(crate::db::events::unread_counts()).unwrap().get(&ch).copied(),
5612                ),
5613                wrap_owners("m1").unwrap().into_iter().map(|(k, outer, relays)| (k.public_key(), outer, relays)).collect::<Vec<_>>(),
5614                crate::db::media_store::get(&[0x5b; 32]).unwrap(),
5615            )
5616        };
5617        let before = read();
5618        assert_eq!(before.8, vec![(owner.public_key(), "o1".to_string(), vec!["wss://r".to_string()])]);
5619        assert_eq!(before.9.as_ref(), Some(&kept));
5620        assert_eq!(before.0, vec![([0x33; 32], "ab".repeat(32))]);
5621        assert_eq!(before.2, Some((r#"{"pins":["x"]}"#.to_string(), 1)));
5622        assert_eq!(before.3, Some(format!("{v2:?}")));
5623        assert_eq!(
5624            before.4,
5625            (vec![(Epoch(0), v2.community_root)], vec![(Epoch(0), [0x62; 32])], vec![("e1".to_string(), 5, r#"{"action":"message_delete"}"#.to_string())])
5626        );
5627        // File captions are stored but not shown again yet; the view still carries the rest.
5628        assert_eq!(before.5, vec![(String::new(), dm.preview_metadata.clone(), dm.attachments.clone())]);
5629        assert_eq!(before.6.as_deref(), Some("still sending"));
5630        assert_eq!(before.7, (vec![banned.to_hex()], vec!["d8".repeat(32)], 1, Some(1)), "the banned author stays hidden");
5631        let sealed: (String, String, String) = crate::db::get_db_connection_guard_static().unwrap().query_row(
5632            "SELECT a.name || e.preview_metadata || e.content, w.rumor_json, a.key FROM attachments a, events e, nip17_wrap_keys w
5633             WHERE e.id = a.event_id AND w.pending_id = 'pending-1'", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
5634        ).unwrap();
5635        for plain in ["passport", "A title", "the message itself"] {
5636            assert!(!sealed.0.contains(plain), "{plain} is sealed on disk");
5637        }
5638        assert!(!sealed.1.contains("still sending") && sealed.2 != "c3".repeat(32), "unconfirmed sends and file keys are sealed");
5639        let held: String = crate::db::get_db_connection_guard_static().unwrap()
5640            .query_row("SELECT payload FROM dm_held_wallpapers", [], |r| r.get(0)).unwrap();
5641        assert!(!held.contains("held-wallpaper"), "a held wallpaper is sealed on disk");
5642
5643        {
5644            let conn = crate::db::get_write_connection_guard_static().unwrap();
5645            let tx = conn.unchecked_transaction().unwrap();
5646            at_rest::rekey_listed_in_tx(&tx, &K, &K2, &|_| {}).unwrap();
5647            assert_eq!(
5648                at_rest::sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(),
5649                0,
5650                "the sweep list must name every column these writers encrypt"
5651            );
5652        }
5653
5654        assert!(at_rest::rekey(&WRONG, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).is_err(), "a key the store does not open is refused");
5655        at_rest::rekey(&K, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5656        crate::state::ENCRYPTION_KEY.set(K2, &[]);
5657        assert_eq!(read(), before, "every value reads back after a PIN change");
5658        assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())], "a held Control wrap moves with the key");
5659        assert_eq!(control_wrap_counts(&cid, &[0x77; 32]).unwrap().1, 1, "and a refusal, which holds no body, stays as it was");
5660        assert_eq!(
5661            crate::db::chats::take_held_wallpaper(&dm_chat).unwrap().as_deref(),
5662            Some(r#"{"url":"https://blossom.example/held-wallpaper"}"#),
5663            "a held wallpaper moves with the key"
5664        );
5665
5666        let mode = || crate::db::get_sql_setting("security_type".to_string()).unwrap();
5667        at_rest::rekey(&K2, &K2, &crate::crypto::Kdf::of_account().unwrap(), "password", None, &|_| {}).unwrap();
5668        assert_eq!((read(), mode().as_deref()), (before.clone(), Some("password")), "the same key on both sides only switches the mode");
5669
5670        // Rows from before this build: a plaintext caption and a DM whose plaintext looks sealed.
5671        let legacy_chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_001)).unwrap();
5672        let hexish = "ab".repeat(40);
5673        {
5674            let conn = crate::db::get_write_connection_guard_static().unwrap();
5675            for (id, kind, content) in [("e5", 15, "old caption"), ("f6", 14, hexish.as_str())] {
5676                conn.execute(
5677                    "INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, ?2, ?3, ?4, 1, 1)",
5678                    rusqlite::params![id.repeat(32), kind, legacy_chat, content],
5679                ).unwrap();
5680            }
5681        }
5682        let flag = || crate::db::get_sql_setting("community_at_rest_encrypted".to_string()).unwrap();
5683        crate::db::set_sql_setting("community_at_rest_encrypted".to_string(), "1".to_string()).unwrap();
5684        crate::state::ENCRYPTION_KEY.set(WRONG, &[]);
5685        assert!(at_rest::backfill_at_rest().is_err(), "the backfill never wraps under a key it cannot prove");
5686        assert_eq!(flag().as_deref(), Some("1"));
5687        crate::state::ENCRYPTION_KEY.set(K2, &[]);
5688        at_rest::backfill_at_rest().unwrap();
5689        assert_eq!((read(), flag().as_deref()), (before.clone(), Some("8")));
5690        let stored = |id: &str| -> String {
5691            crate::db::get_db_connection_guard_static().unwrap()
5692                .query_row("SELECT content FROM events WHERE id = ?1", [id.repeat(32)], |r| r.get(0)).unwrap()
5693        };
5694        assert!(stored("e5") != "old caption" && stored("f6") != hexish, "the backfill seals legacy plaintext messages");
5695        let legacy = rt.block_on(crate::db::events::get_message_views(legacy_chat, 10, 0)).unwrap();
5696        assert!(legacy.iter().any(|m| m.content == hexish), "and they still read back");
5697
5698        assert!(at_rest::disable(&WRONG, &|_| {}).is_err(), "a wrong key never turns encryption off");
5699        assert_eq!(read(), before);
5700        at_rest::disable(&K2, &|_| {}).unwrap();
5701        crate::state::ENCRYPTION_KEY.clear(&[]);
5702        assert_eq!(read(), before, "every value reads back after Local Encryption is turned off");
5703    }
5704}
5705
5706// ── Pin lists (CORD-04 §7) ───────────────────────────────────────────────────
5707
5708/// Persist a channel's folded Pin List head — the RAW carried content (either
5709/// self-describing form), never a re-serialization: republishing must carry the
5710/// exact bytes, and the byte cap judges what the wire carried. Encrypted at
5711/// rest like the banlist — a public-form list carries disclosed message keys.
5712///
5713/// Monotonic IN THE STATEMENT: fold persists and publish echoes race (the fold
5714/// reads relay windows while an echo lands), and a read-check-then-write let a
5715/// stale fold clobber a newer echo. Equal versions still write — a same-version
5716/// fork's converged winner must be adoptable. Returns whether a row changed.
5717pub fn set_community_pins(community_id: &str, channel_id: &str, content: &str, version: i64) -> Result<bool, String> {
5718    let _seal = crate::crypto::gate::sealing();
5719    let enc = enc_txt(content)?;
5720    let conn = super::get_write_connection_guard_static()?;
5721    let changed = conn
5722        .execute(
5723            "INSERT INTO community_pins (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
5724             ON CONFLICT(community_id, channel_id) DO UPDATE SET
5725                 content = excluded.content, version = excluded.version
5726             WHERE excluded.version >= community_pins.version",
5727            params![community_id, channel_id, enc, version],
5728        )
5729        .map_err(|e| format!("set pins: {e}"))?;
5730    Ok(changed > 0)
5731}
5732
5733/// Persist a channel's folded Writers ledger head (CORD-03 §1), monotonic on version.
5734pub fn set_community_writers(community_id: &str, channel_id: &str, content: &str, version: i64, replace: bool) -> Result<bool, String> {
5735    let _seal = crate::crypto::gate::sealing();
5736    let enc = enc_txt(content)?;
5737    let conn = super::get_write_connection_guard_static()?;
5738    let old: Option<String> = conn
5739        .query_row("SELECT content FROM community_writers WHERE community_id = ?1 AND channel_id = ?2", params![community_id, channel_id], |r| r.get(0))
5740        .optional()
5741        .map_err(|e| format!("get writers: {e}"))?
5742        .map(|c: String| dec_txt(&c));
5743    let changed = conn
5744        .execute(
5745            "INSERT INTO community_writers (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
5746             ON CONFLICT(community_id, channel_id) DO UPDATE SET
5747                 content = excluded.content, version = excluded.version
5748             WHERE ?5 OR excluded.version >= community_writers.version",
5749            params![community_id, channel_id, enc, version, replace],
5750        )
5751        .map_err(|e| format!("set writers: {e}"))?;
5752    // Whichever fold stored it, what a new writer or stop entry undoes is owed a retraction.
5753    if changed > 0 {
5754        crate::community::v2::realtime::invalidate_held_v2_community(community_id);
5755        if let Some(since) = retraction_since(old.as_deref(), content) {
5756            owe_retraction(&conn, community_id, channel_id, since)?;
5757        }
5758        for (writer, since) in stop_owes(old.as_deref(), content) {
5759            owe_author_retraction_on(&conn, community_id, channel_id, &crate::simd::hex::bytes_to_hex_32(&writer), since, None)?;
5760        }
5761    }
5762    Ok(changed > 0)
5763}
5764
5765/// From when a move from `old` to `new` can change everyone's verdicts: the earliest writer entry
5766/// it added, or entry a fork switch dropped. An `open` added takes nothing back, an entry the cap
5767/// trimmed from the front moves no window, and a stop is its writer's alone ([`stop_owes`]).
5768pub(crate) fn retraction_since(old: Option<&str>, new: &str) -> Option<u64> {
5769    use crate::community::v2::writers::{Ledger, Spell};
5770    let new = Ledger::parse(new)?;
5771    let old = old.and_then(Ledger::parse);
5772    let added = new.entries.iter().filter(|e| matches!(e.spell, Spell::Writer { .. })).filter(|e| !old.as_ref().is_some_and(|o| o.entries.contains(e)));
5773    let front = new.entries.first().map_or(u64::MAX, |e| e.at);
5774    let dropped = old.iter().flat_map(|o| o.entries.iter()).filter(|e| !matches!(e.spell, Spell::Other) && e.at >= front && !new.entries.contains(e));
5775    added.chain(dropped).map(|e| e.effective()).min()
5776}
5777
5778/// The stops a move from `old` to `new` added: whose posts each undoes, and from when.
5779pub(crate) fn stop_owes(old: Option<&str>, new: &str) -> Vec<([u8; 32], u64)> {
5780    use crate::community::v2::writers::{Ledger, Spell};
5781    let Some(new) = Ledger::parse(new) else { return Vec::new() };
5782    let old = old.and_then(Ledger::parse);
5783    new.entries
5784        .iter()
5785        .filter(|e| !old.as_ref().is_some_and(|o| o.entries.contains(e)))
5786        .filter_map(|e| match e.spell {
5787            Spell::Stop { writer } => Some((writer, e.effective())),
5788            _ => None,
5789        })
5790        .collect()
5791}
5792
5793fn retraction_key(community_id: &str, channel_id: &str) -> String {
5794    format!("writer_retract:{community_id}:{channel_id}")
5795}
5796
5797/// Stored as `since:generation`: a drain clears only the value it read, so what is owed while it
5798/// runs survives it.
5799fn parse_owed(value: &str) -> Option<(u64, u64)> {
5800    let mut parts = value.split(':');
5801    Some((parts.next()?.parse().ok()?, parts.next().and_then(|g| g.parse().ok()).unwrap_or(0)))
5802}
5803
5804fn owe_retraction(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, since: u64) -> Result<(), String> {
5805    let key = retraction_key(community_id, channel_id);
5806    let held: Option<String> = conn.query_row("SELECT value FROM settings WHERE key = ?1", params![key], |r| r.get(0)).optional().map_err(|e| format!("owed retraction: {e}"))?;
5807    let (since, generation) = held.as_deref().and_then(parse_owed).map_or((since, 1), |(s, g)| (s.min(since), g + 1));
5808    conn.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)", params![key, format!("{since}:{generation}")]).map_err(|e| format!("owe retraction: {e}"))?;
5809    Ok(())
5810}
5811
5812/// Owe `channel_id` a retraction of what it shows dated from `since_ms`.
5813pub fn owe_writer_retraction(community_id: &str, channel_id: &str, since_ms: u64) -> Result<(), String> {
5814    let conn = super::get_write_connection_guard_static()?;
5815    owe_retraction(&conn, community_id, channel_id, since_ms)
5816}
5817
5818/// The Channels of `community_id` owed a retraction: `(channel, since_ms, generation)`.
5819pub fn owed_retractions(community_id: &str) -> Result<Vec<(String, u64, u64)>, String> {
5820    let prefix = retraction_key(community_id, "");
5821    let conn = super::get_db_connection_guard_static()?;
5822    let mut stmt = conn.prepare("SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1").map_err(|e| format!("owed retractions: {e}"))?;
5823    let rows = stmt.query_map(params![prefix], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(|e| format!("owed retractions: {e}"))?;
5824    Ok(rows.flatten().filter_map(|(k, v)| parse_owed(&v).map(|(since, generation)| (k[prefix.len()..].to_string(), since, generation))).collect())
5825}
5826
5827/// The settings rows owed author take-backs were kept in before they were sealed.
5828fn legacy_author_retraction_range(community_id: &str) -> (String, String) {
5829    (format!("writer_retract_by:{community_id}:"), format!("writer_retract_by:{community_id};"))
5830}
5831
5832/// Owe `channel_id` a retraction of what `author` (hex) posted there from `since_ms`, before
5833/// `until_ms` when given.
5834pub fn owe_author_retraction(community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
5835    let _seal = crate::crypto::gate::sealing();
5836    let conn = super::get_write_connection_guard_static()?;
5837    owe_author_retraction_on(&conn, community_id, channel_id, author, since_ms, until_ms)
5838}
5839
5840/// Stored as `since:generation:until`, `until` empty when open.
5841fn parse_author_owed(value: &str) -> Option<(u64, u64, Option<u64>)> {
5842    let mut parts = value.split(':');
5843    let since = parts.next()?.parse().ok()?;
5844    let generation = parts.next().and_then(|g| g.parse().ok()).unwrap_or(0);
5845    let until = parts.next().and_then(|u| u.parse().ok());
5846    Some((since, generation, until))
5847}
5848
5849/// One author's owed take-back in a Channel.
5850struct AuthorOwed {
5851    seq: i64,
5852    channel: String,
5853    author: [u8; 32],
5854    since: u64,
5855    generation: u64,
5856    until: Option<u64>,
5857}
5858
5859/// An owed take-back at rest: `[format = 1][author][since][generation][flags: until][until]`,
5860/// numbers as LEB128. Sealed, so who is owed one is never kept in the clear.
5861fn author_owed_body(author: &[u8; 32], since: u64, generation: u64, until: Option<u64>) -> Vec<u8> {
5862    let mut out = Vec::with_capacity(64);
5863    out.push(1);
5864    out.extend_from_slice(author);
5865    varint(&mut out, since);
5866    varint(&mut out, generation);
5867    out.push(until.is_some() as u8);
5868    if let Some(until) = until {
5869        varint(&mut out, until);
5870    }
5871    out
5872}
5873
5874fn author_owed_from_body(body: &[u8]) -> Option<([u8; 32], u64, u64, Option<u64>)> {
5875    let (&1, rest) = body.split_first()? else { return None };
5876    let (author, mut rest) = rest.split_at_checked(32)?;
5877    let since = take_varint(&mut rest)?;
5878    let generation = take_varint(&mut rest)?;
5879    let (&flags, tail) = rest.split_first()?;
5880    rest = tail;
5881    let until = match flags {
5882        0 => None,
5883        1 => Some(take_varint(&mut rest)?),
5884        _ => return None,
5885    };
5886    rest.is_empty().then_some((author.try_into().ok()?, since, generation, until))
5887}
5888
5889/// `community_id`'s owed author take-backs, in `channel_id` alone when given.
5890fn held_author_retractions(conn: &rusqlite::Connection, community_id: &str, channel_id: Option<&str>) -> Result<Vec<AuthorOwed>, String> {
5891    let rows: Vec<(i64, String, Vec<u8>)> = {
5892        let mut stmt = conn
5893            .prepare_cached(
5894                "SELECT o.seq, o.channel_id, o.body FROM community_owed_authors o
5895                 JOIN community_guestbook_books b ON b.book = o.book
5896                 WHERE b.community_id = ?1 AND (?2 IS NULL OR o.channel_id = ?2) ORDER BY o.seq",
5897            )
5898            .map_err(|e| format!("owed retractions: {e}"))?;
5899        let rows = stmt.query_map(params![community_id, channel_id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).map_err(|e| format!("owed retractions: {e}"))?;
5900        rows.filter_map(|r| r.ok()).collect()
5901    };
5902    Ok(crate::crypto::open_batch(|o| {
5903        rows.into_iter()
5904            .filter_map(|(seq, channel, body)| {
5905                let (author, since, generation, until) = author_owed_from_body(&o.open_blob_or_keep(&body))?;
5906                Some(AuthorOwed { seq, channel, author, since, generation, until })
5907            })
5908            .collect()
5909    }))
5910}
5911
5912fn has_legacy_author_retractions(conn: &rusqlite::Connection, community_id: &str) -> Result<bool, String> {
5913    let (lo, hi) = legacy_author_retraction_range(community_id);
5914    conn.query_row("SELECT 1 FROM settings WHERE key >= ?1 AND key < ?2 LIMIT 1", params![lo, hi], |_| Ok(()))
5915        .optional()
5916        .map(|r| r.is_some())
5917        .map_err(|e| format!("owed retractions: {e}"))
5918}
5919
5920/// Move owed take-backs still kept as settings rows into sealed rows. One that doesn't parse
5921/// was never read as owed, and goes.
5922fn move_author_retraction_settings(conn: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
5923    let (lo, hi) = legacy_author_retraction_range(community_id);
5924    let legacy: Vec<(String, String)> = {
5925        let mut stmt = conn.prepare_cached("SELECT key, value FROM settings WHERE key >= ?1 AND key < ?2").map_err(|e| format!("move owed retractions: {e}"))?;
5926        let rows = stmt.query_map(params![lo, hi], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("move owed retractions: {e}"))?;
5927        rows.filter_map(|r| r.ok()).collect()
5928    };
5929    if legacy.is_empty() {
5930        return Ok(());
5931    }
5932    let book = guestbook_book(conn, community_id)?;
5933    let mut insert = conn.prepare_cached("INSERT INTO community_owed_authors (book, channel_id, body) VALUES (?1, ?2, ?3)").map_err(|e| format!("move owed retractions: {e}"))?;
5934    crate::crypto::seal_batch(|sealer| {
5935        for (key, value) in &legacy {
5936            let Some((channel, author)) = key[lo.len()..].split_once(':') else { continue };
5937            let (Some(author), Some((since, generation, until))) = (crate::simd::hex::hex_to_bytes_32_checked(author), parse_author_owed(value)) else { continue };
5938            insert.execute(params![book, channel, sealer.seal_blob(&author_owed_body(&author, since, generation, until))?]).map_err(|e| format!("move owed retractions: {e}"))?;
5939        }
5940        Ok::<(), String>(())
5941    })?;
5942    conn.execute("DELETE FROM settings WHERE key >= ?1 AND key < ?2", params![lo, hi]).map_err(|e| format!("move owed retractions: {e}"))?;
5943    Ok(())
5944}
5945
5946/// Run `f` as one unit on `conn`, inside a caller's transaction or not.
5947fn in_savepoint<T>(conn: &rusqlite::Connection, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
5948    conn.execute_batch("SAVEPOINT owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
5949    match f() {
5950        Ok(v) => {
5951            conn.execute_batch("RELEASE owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
5952            Ok(v)
5953        }
5954        Err(e) => {
5955            let _ = conn.execute_batch("ROLLBACK TO owed_authors; RELEASE owed_authors");
5956            Err(e)
5957        }
5958    }
5959}
5960
5961/// On the write connection, under a sealing ticket.
5962fn owe_author_retraction_on(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
5963    let author = crate::simd::hex::hex_to_bytes_32_checked(author).ok_or_else(|| format!("owe retraction: not an author key: {author}"))?;
5964    in_savepoint(conn, || {
5965        move_author_retraction_settings(conn, community_id)?;
5966        let held = held_author_retractions(conn, community_id, Some(channel_id))?.into_iter().find(|o| o.author == author);
5967        let (since, generation, until) = match &held {
5968            // The same span closing narrows its own owe; any other range widens it.
5969            Some(o) => (o.since.min(since_ms), o.generation + 1, match (o.until, until_ms) {
5970                (Some(a), Some(b)) => Some(a.max(b)),
5971                (None, Some(b)) if o.since == since_ms => Some(b),
5972                _ => None,
5973            }),
5974            None => (since_ms, 1, until_ms),
5975        };
5976        let body = crate::crypto::seal_batch(|sealer| sealer.seal_blob(&author_owed_body(&author, since, generation, until)))?;
5977        match held {
5978            Some(o) => conn.execute("UPDATE community_owed_authors SET body = ?1 WHERE seq = ?2", params![body, o.seq]),
5979            None => conn.execute("INSERT INTO community_owed_authors (book, channel_id, body) VALUES (?1, ?2, ?3)", params![guestbook_book(conn, community_id)?, channel_id, body]),
5980        }
5981        .map_err(|e| format!("owe retraction: {e}"))?;
5982        Ok(())
5983    })
5984}
5985
5986/// What `community_id` owes one author's posts: `(channel, author hex, since_ms, until_ms, generation)`.
5987pub fn owed_author_retractions(community_id: &str) -> Result<Vec<(String, String, u64, Option<u64>, u64)>, String> {
5988    if has_legacy_author_retractions(&*super::get_db_connection_guard_static()?, community_id)? {
5989        let _seal = crate::crypto::gate::sealing();
5990        let conn = super::get_write_connection_guard_static()?;
5991        in_savepoint(&conn, || move_author_retraction_settings(&conn, community_id))?;
5992    }
5993    let mut owed: Vec<_> = held_author_retractions(&*super::get_db_connection_guard_static()?, community_id, None)?
5994        .into_iter()
5995        .map(|o| (o.channel, crate::simd::hex::bytes_to_hex_32(&o.author), o.since, o.until, o.generation))
5996        .collect();
5997    owed.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
5998    Ok(owed)
5999}
6000
6001/// Clear one author's owed retraction once done, unless more was owed since it was read.
6002pub fn settle_author_retraction(community_id: &str, channel_id: &str, author: &str, since: u64, until: Option<u64>, generation: u64) -> Result<(), String> {
6003    let Some(author) = crate::simd::hex::hex_to_bytes_32_checked(author) else { return Ok(()) };
6004    let _seal = crate::crypto::gate::sealing();
6005    let conn = super::get_write_connection_guard_static()?;
6006    in_savepoint(&conn, || {
6007        move_author_retraction_settings(&conn, community_id)?;
6008        let done = held_author_retractions(&conn, community_id, Some(channel_id))?
6009            .into_iter()
6010            .filter(|o| o.author == author && o.since == since && o.until == until && o.generation == generation);
6011        for o in done {
6012            conn.execute("DELETE FROM community_owed_authors WHERE seq = ?1", params![o.seq]).map_err(|e| format!("settle retraction: {e}"))?;
6013        }
6014        Ok(())
6015    })
6016}
6017
6018/// Each departed member's spans away, as the Guestbook fold reads them. Shared, so a fold that
6019/// moves one member copies no one else's.
6020pub type DepartureSpans = std::collections::BTreeMap<PublicKey, std::sync::Arc<[crate::community::v2::guestbook::Span]>>;
6021
6022/// The departures this device has already owed take-backs for, and the row each member's sits in.
6023#[derive(Default)]
6024pub struct DeparturesSeen {
6025    pub spans: std::sync::Arc<DepartureSpans>,
6026    /// The row of each of `spans` in turn.
6027    rows: Vec<i64>,
6028}
6029
6030type DeparturesSeenCache = Parsed<std::sync::Arc<DeparturesSeen>, 8>;
6031
6032fn departures_seen_cache() -> std::sync::Arc<std::sync::Mutex<DeparturesSeenCache>> {
6033    struct Key;
6034    super::current_session().scoped::<Key, std::sync::Mutex<DeparturesSeenCache>>()
6035}
6036
6037fn legacy_departures_key(community_id: &str) -> String {
6038    format!("departures_seen:{community_id}")
6039}
6040
6041pub fn departures_seen(community_id: &str) -> Result<std::sync::Arc<DeparturesSeen>, String> {
6042    let cache = departures_seen_cache();
6043    let generation = {
6044        let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
6045        if let Some(hit) = held.get(community_id) {
6046            return Ok(hit);
6047        }
6048        held.generation(community_id)
6049    };
6050    let legacy = super::get_db_connection_guard_static()?
6051        .query_row("SELECT 1 FROM settings WHERE key = ?1", params![legacy_departures_key(community_id)], |_| Ok(()))
6052        .optional()
6053        .map_err(|e| format!("load departures: {e}"))?
6054        .is_some();
6055    if legacy {
6056        let _seal = crate::crypto::gate::sealing();
6057        let conn = super::get_write_connection_guard_static()?;
6058        let tx = conn.unchecked_transaction().map_err(|e| format!("move departures tx: {e}"))?;
6059        move_departures_setting(&tx, community_id)?;
6060        tx.commit().map_err(|e| format!("move departures commit: {e}"))?;
6061    }
6062    let seen = std::sync::Arc::new(read_departures(&*super::get_db_connection_guard_static()?, community_id)?);
6063    cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, seen.clone());
6064    Ok(seen)
6065}
6066
6067fn read_departures(conn: &rusqlite::Connection, community_id: &str) -> Result<DeparturesSeen, String> {
6068    let rows: Vec<(i64, Vec<u8>)> = {
6069        let mut stmt = conn
6070            .prepare_cached(
6071                "SELECT d.seq, d.body FROM community_departures_seen d
6072                 JOIN community_guestbook_books b ON b.book = d.book
6073                 WHERE b.community_id = ?1 ORDER BY d.seq",
6074            )
6075            .map_err(|e| format!("load departures: {e}"))?;
6076        let rows = stmt.query_map(params![community_id], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("load departures: {e}"))?;
6077        rows.filter_map(|r| r.ok()).collect()
6078    };
6079    let held: std::collections::BTreeMap<PublicKey, (i64, Vec<crate::community::v2::guestbook::Span>)> = crate::crypto::open_batch(|o| {
6080        rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_or_keep(&body)).map(|(member, owed)| (member, (seq, owed)))).collect()
6081    });
6082    let rows = held.values().map(|(seq, _)| *seq).collect();
6083    Ok(DeparturesSeen { spans: std::sync::Arc::new(held.into_iter().map(|(member, (_, owed))| (member, owed.into())).collect()), rows })
6084}
6085
6086/// Move a record still kept as one settings row into rows. One that doesn't parse read as nothing seen.
6087fn move_departures_setting(tx: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
6088    let key = legacy_departures_key(community_id);
6089    let Some(json) = tx.query_row("SELECT value FROM settings WHERE key = ?1", params![key], |r| r.get::<_, String>(0)).optional().map_err(|e| format!("move departures: {e}"))? else {
6090        return Ok(());
6091    };
6092    let by_hex: std::collections::BTreeMap<String, Vec<crate::community::v2::guestbook::Span>> = serde_json::from_str(&json).unwrap_or_default();
6093    let book = guestbook_book(tx, community_id)?;
6094    let mut stmt = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("move departures: {e}"))?;
6095    crate::crypto::seal_batch(|sealer| {
6096        for (member, owed) in by_hex.iter().filter_map(|(k, v)| Some((PublicKey::from_hex(k).ok()?, v))) {
6097            stmt.execute(params![book, sealer.seal_blob(&departure_body(&member, owed))?]).map_err(|e| format!("move departures: {e}"))?;
6098        }
6099        Ok::<(), String>(())
6100    })?;
6101    tx.execute("DELETE FROM settings WHERE key = ?1", params![key]).map_err(|e| format!("move departures: {e}"))?;
6102    Ok(())
6103}
6104
6105/// Record `now` as owed for, writing only the members whose spans changed.
6106pub fn set_departures_seen(community_id: &str, now: std::sync::Arc<DepartureSpans>) -> Result<(), String> {
6107    let _seal = crate::crypto::gate::sealing();
6108    let conn = super::get_write_connection_guard_static()?;
6109    let tx = conn.unchecked_transaction().map_err(|e| format!("store departures tx: {e}"))?;
6110    move_departures_setting(&tx, community_id)?;
6111    let cache = departures_seen_cache();
6112    let cached = cache.lock().unwrap_or_else(|e| e.into_inner()).get(community_id);
6113    let held = match cached {
6114        Some(held) => held,
6115        None => std::sync::Arc::new(read_departures(&tx, community_id)?),
6116    };
6117    let book = guestbook_book(&tx, community_id)?;
6118    let mut rows = Vec::with_capacity(now.len());
6119    {
6120        let mut update = tx.prepare_cached("UPDATE community_departures_seen SET body = ?1 WHERE seq = ?2").map_err(|e| format!("store departures: {e}"))?;
6121        let mut insert = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("store departures: {e}"))?;
6122        let mut delete = tx.prepare_cached("DELETE FROM community_departures_seen WHERE seq = ?1").map_err(|e| format!("store departures: {e}"))?;
6123        // Both sides are in key order: one walk pairs each member with its row.
6124        let mut was = held.spans.iter().zip(held.rows.iter().copied()).peekable();
6125        crate::crypto::seal_batch(|sealer| {
6126            for (member, owed) in now.iter() {
6127                while let Some((_, seq)) = was.next_if(|((m, _), _)| *m < member) {
6128                    delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
6129                }
6130                let seq = match was.next_if(|((m, _), _)| *m == member) {
6131                    Some(((_, before), seq)) if before == owed => seq,
6132                    Some((_, seq)) => {
6133                        update.execute(params![sealer.seal_blob(&departure_body(member, owed))?, seq]).map_err(|e| format!("store departures: {e}"))?;
6134                        seq
6135                    }
6136                    None => {
6137                        insert.execute(params![book, sealer.seal_blob(&departure_body(member, owed))?]).map_err(|e| format!("store departures: {e}"))?;
6138                        tx.last_insert_rowid()
6139                    }
6140                };
6141                rows.push(seq);
6142            }
6143            for (_, seq) in was.by_ref() {
6144                delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
6145            }
6146            Ok::<(), String>(())
6147        })?;
6148    }
6149    tx.commit().map_err(|e| format!("store departures commit: {e}"))?;
6150    let mut cached = cache.lock().unwrap_or_else(|e| e.into_inner());
6151    let generation = cached.moved(community_id);
6152    cached.put(community_id, generation, std::sync::Arc::new(DeparturesSeen { spans: now, rows }));
6153    Ok(())
6154}
6155
6156fn varint(out: &mut Vec<u8>, mut v: u64) {
6157    while v >= 0x80 {
6158        out.push(v as u8 | 0x80);
6159        v >>= 7;
6160    }
6161    out.push(v as u8);
6162}
6163
6164fn take_varint(rest: &mut &[u8]) -> Option<u64> {
6165    let mut v = 0u64;
6166    for shift in (0..64).step_by(7) {
6167        let (&b, tail) = rest.split_first()?;
6168        *rest = tail;
6169        v |= ((b & 0x7f) as u64).checked_shl(shift)?;
6170        if b & 0x80 == 0 {
6171            return Some(v);
6172        }
6173    }
6174    None
6175}
6176
6177/// A member's owed spans at rest: `[format = 1][member][count][flags: until, kicked][from][until]…`,
6178/// numbers as LEB128. Sealed with the rest, so who left and when is never kept in the clear.
6179fn departure_body(member: &PublicKey, spans: &[crate::community::v2::guestbook::Span]) -> Vec<u8> {
6180    let mut out = Vec::with_capacity(34 + spans.len() * 13);
6181    out.push(1);
6182    out.extend_from_slice(member.as_bytes());
6183    varint(&mut out, spans.len() as u64);
6184    for &(from, until, kicked) in spans {
6185        out.push(until.is_some() as u8 | (kicked as u8) << 1);
6186        varint(&mut out, from);
6187        if let Some(until) = until {
6188            varint(&mut out, until);
6189        }
6190    }
6191    out
6192}
6193
6194fn departure_from_body(body: &[u8]) -> Option<(PublicKey, Vec<crate::community::v2::guestbook::Span>)> {
6195    let (&1, rest) = body.split_first()? else { return None };
6196    let (member, mut rest) = rest.split_at_checked(32)?;
6197    let member = PublicKey::from_byte_array(member.try_into().ok()?);
6198    let count = take_varint(&mut rest)?;
6199    // Each span takes at least two bytes, so a count beyond that is a forged length.
6200    if count > rest.len() as u64 / 2 {
6201        return None;
6202    }
6203    let mut spans = Vec::with_capacity(count as usize);
6204    for _ in 0..count {
6205        let (&flags, tail) = rest.split_first()?;
6206        rest = tail;
6207        if flags & !0b11 != 0 {
6208            return None;
6209        }
6210        let from = take_varint(&mut rest)?;
6211        let until = if flags & 1 != 0 { Some(take_varint(&mut rest)?) } else { None };
6212        spans.push((from, until, flags & 2 != 0));
6213    }
6214    rest.is_empty().then_some((member, spans))
6215}
6216
6217/// Clear `channel_id`'s owed retraction once done, unless more was owed since it was read.
6218pub fn settle_retraction(community_id: &str, channel_id: &str, since: u64, generation: u64) -> Result<(), String> {
6219    let conn = super::get_write_connection_guard_static()?;
6220    conn.execute("DELETE FROM settings WHERE key = ?1 AND value = ?2", params![retraction_key(community_id, channel_id), format!("{since}:{generation}")])
6221        .map_err(|e| format!("settle retraction: {e}"))?;
6222    Ok(())
6223}
6224
6225pub fn get_community_writers(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
6226    let conn = super::get_db_connection_guard_static()?;
6227    let row: Option<(String, i64)> = conn
6228        .query_row(
6229            "SELECT content, version FROM community_writers WHERE community_id = ?1 AND channel_id = ?2",
6230            params![community_id, channel_id],
6231            |r| Ok((r.get(0)?, r.get(1)?)),
6232        )
6233        .optional()
6234        .map_err(|e| format!("get writers: {e}"))?;
6235    Ok(row.map(|(content, version)| (dec_txt(&content), version)))
6236}
6237
6238/// How many held wraps one Channel keeps, how many bytes, how many one author, and how many
6239/// bytes a Community: past any, those dated furthest from now go first, so a flood dated years
6240/// ahead or behind, or one author's, evicts only itself.
6241pub const MAX_HELD_WRAPS: usize = 500;
6242pub const MAX_HELD_BYTES: usize = 4 * 1024 * 1024;
6243pub const MAX_HELD_PER_AUTHOR: usize = MAX_HELD_WRAPS / 10;
6244pub const MAX_HELD_COMMUNITY_BYTES: usize = 16 * 1024 * 1024;
6245
6246/// How far past this device's clock a post may be dated and still be held (CORD-02 §5's horizon):
6247/// a later one is left on the relay for a later read.
6248pub const HELD_HORIZON_MS: u64 = 60 * 60 * 1000;
6249
6250/// Hold `wrap`, a post by `author` (hex) `channel_id`'s rules didn't stand behind on arrival,
6251/// dated `at_ms`. Whether it is held: a post dated past the horizon isn't, nor one the caps
6252/// evict at once. A marked copy kept beside an evicted wrap goes with it.
6253pub fn hold_wrap(community_id: &str, channel_id: &str, wrap_id: &str, wrap: &str, author: &str, at_ms: u64) -> Result<bool, String> {
6254    let now = now_secs().max(0) as u64 * 1000;
6255    if at_ms > now.saturating_add(HELD_HORIZON_MS) {
6256        let held = deferred();
6257        let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
6258        map.insert(wrap_id.to_string(), at_ms);
6259        // Bounded: one dropped costs only a decrypt on the next read.
6260        if map.len() > MAX_DEFERRED {
6261            if let Some(furthest) = map.iter().max_by_key(|(_, at)| **at).map(|(id, _)| id.clone()) {
6262                map.remove(&furthest);
6263            }
6264        }
6265        return Ok(false);
6266    }
6267    let _seal = crate::crypto::gate::sealing();
6268    let enc = enc_txt(wrap)?;
6269    let conn = super::get_write_connection_guard_static()?;
6270    conn.execute(
6271        "INSERT OR IGNORE INTO community_held_wraps (wrap_id, community_id, channel_id, wrap, at_ms, author, bytes) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
6272        params![wrap_id, community_id, channel_id, enc, at_ms as i64, author, enc.len() as i64],
6273    )
6274    .map_err(|e| format!("hold wrap: {e}"))?;
6275    // Nearest now first, across the Community; each row counts against its Channel and author.
6276    let ranked: Vec<(String, String, String, usize)> = {
6277        let mut stmt = conn
6278            .prepare("SELECT wrap_id, channel_id, author, bytes FROM community_held_wraps WHERE community_id = ?1 ORDER BY ABS(at_ms - ?2), wrap_id")
6279            .map_err(|e| format!("rank held wraps: {e}"))?;
6280        let rows = stmt
6281            .query_map(params![community_id, now as i64], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, i64>(3)?.max(0) as usize)))
6282            .map_err(|e| format!("rank held wraps: {e}"))?;
6283        rows.flatten().collect()
6284    };
6285    let (mut channels, mut authors) = (std::collections::HashMap::<&str, (usize, usize)>::new(), std::collections::HashMap::<(&str, &str), usize>::new());
6286    let mut evicted: Vec<&String> = Vec::new();
6287    let mut kept: Vec<(&String, &str, usize)> = Vec::new();
6288    for (id, ch, who, len) in &ranked {
6289        let c = channels.entry(ch.as_str()).or_default();
6290        let a = authors.entry((ch.as_str(), who.as_str())).or_default();
6291        if c.0 >= MAX_HELD_WRAPS || c.1 + len > MAX_HELD_BYTES || (!who.is_empty() && *a >= MAX_HELD_PER_AUTHOR) {
6292            evicted.push(id);
6293            continue;
6294        }
6295        c.0 += 1;
6296        c.1 += len;
6297        *a += 1;
6298        kept.push((id, ch.as_str(), *len));
6299    }
6300    // Past the Community's bytes, the Channel holding the most gives up its furthest-dated first,
6301    // so one Channel's flood never empties another.
6302    let mut total: usize = kept.iter().map(|k| k.2).sum();
6303    while total > MAX_HELD_COMMUNITY_BYTES {
6304        let most = channels.values().map(|c| c.1).max().unwrap_or(0);
6305        let Some(i) = kept.iter().rposition(|k| channels.get(k.1).is_some_and(|c| c.1 == most)) else { break };
6306        let (id, ch, len) = kept.remove(i);
6307        if let Some(c) = channels.get_mut(ch) {
6308            c.1 -= len;
6309        }
6310        total -= len;
6311        evicted.push(id);
6312    }
6313    for id in &evicted {
6314        conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![id]).map_err(|e| format!("trim held wraps: {e}"))?;
6315        conn.execute("DELETE FROM events WHERE wrapper_event_id = ?1 AND instr(tags, '[\"unauthorized\"]') > 0", params![id]).map_err(|e| format!("trim held copy: {e}"))?;
6316    }
6317    Ok(!evicted.iter().any(|id| *id == wrap_id))
6318}
6319
6320// ── Control wraps: every wrap of a Control Plane view this device has read ──
6321
6322/// A stored Control wrap: its id, its own timestamp (seconds), and its body unless it was refused.
6323pub type ControlWrapRow = ([u8; 32], u64, Option<Vec<u8>>);
6324
6325/// Every wrap id held for `view`, the refused ones too, each with its timestamp.
6326pub fn control_wrap_ids(community_id: &str, view: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
6327    let conn = super::get_db_connection_guard_static()?;
6328    let mut stmt = conn
6329        .prepare_cached("SELECT wrap_id, created_at FROM community_control_wraps WHERE community_id = ?1 AND view = ?2")
6330        .map_err(|e| format!("control wrap ids: {e}"))?;
6331    let rows = stmt
6332        .query_map(params![community_id, &view[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
6333        .map_err(|e| format!("control wrap ids: {e}"))?;
6334    let mut out = Vec::new();
6335    for row in rows {
6336        let (id, at) = row.map_err(|e| format!("control wrap ids: {e}"))?;
6337        out.push((id.try_into().map_err(|_| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
6338    }
6339    Ok(out)
6340}
6341
6342/// Store `rows` judged under `rules`, all or none. A wrap already held keeps its row. Returns how
6343/// many were new.
6344pub fn store_control_wraps(community_id: &str, view: &[u8; 32], rules: u32, now_secs: u64, rows: &[ControlWrapRow]) -> Result<usize, String> {
6345    if rows.is_empty() {
6346        return Ok(0);
6347    }
6348    let _seal = crate::crypto::gate::sealing();
6349    let conn = super::get_write_connection_guard_static()?;
6350    let tx = conn.unchecked_transaction().map_err(|e| format!("store control wraps tx: {e}"))?;
6351    let mut stored = 0usize;
6352    {
6353        let mut stmt = tx
6354            .prepare_cached(
6355                "INSERT OR IGNORE INTO community_control_wraps (community_id, view, wrap_id, created_at, wrap, rules, judged_at)
6356                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
6357            )
6358            .map_err(|e| format!("store control wraps: {e}"))?;
6359        crate::crypto::seal_batch(|sealer| -> Result<(), String> {
6360            for (id, at, body) in rows {
6361                let sealed = body.as_deref().map(|b| sealer.seal_blob(b)).transpose()?;
6362                stored += stmt
6363                    .execute(params![community_id, &view[..], &id[..], *at as i64, sealed, rules, now_secs as i64])
6364                    .map_err(|e| format!("store control wraps: {e}"))?;
6365            }
6366            Ok(())
6367        })?;
6368    }
6369    tx.commit().map_err(|e| format!("store control wraps commit: {e}"))?;
6370    Ok(stored)
6371}
6372
6373/// The next `limit` bodies of `view` below `below` (a wrap's timestamp and id), newest first.
6374pub fn control_wrap_page(community_id: &str, view: &[u8; 32], below: Option<(u64, [u8; 32])>, limit: usize) -> Result<Vec<([u8; 32], u64, Vec<u8>)>, String> {
6375    let rows: Vec<(Vec<u8>, i64, Vec<u8>)> = {
6376        let conn = super::get_db_connection_guard_static()?;
6377        // The far corner of the order stands in for no bound.
6378        let (at, id) = below.map_or((i64::MAX, vec![0xff; 33]), |(at, id)| (at as i64, id.to_vec()));
6379        let mut stmt = conn
6380            .prepare_cached(
6381                "SELECT wrap_id, created_at, wrap FROM community_control_wraps
6382                 WHERE community_id = ?1 AND view = ?2 AND wrap IS NOT NULL AND (created_at, wrap_id) < (?3, ?4)
6383                 ORDER BY created_at DESC, wrap_id DESC LIMIT ?5",
6384            )
6385            .map_err(|e| format!("control wrap page: {e}"))?;
6386        let rows = stmt
6387            .query_map(params![community_id, &view[..], at, id, limit as i64], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
6388            .map_err(|e| format!("control wrap page: {e}"))?;
6389        rows.collect::<Result<_, _>>().map_err(|e| format!("control wrap page: {e}"))?
6390    };
6391    crate::crypto::open_batch(|o| {
6392        rows.into_iter()
6393            .map(|(id, at, body)| Ok((id.try_into().map_err(|_| "control wrap page: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64, o.open_blob_or_keep(&body))))
6394            .collect()
6395    })
6396}
6397
6398/// The bodies of `ids` in `view`, opened, for those held with one.
6399pub fn control_wrap_bodies(community_id: &str, view: &[u8; 32], ids: &[[u8; 32]]) -> Result<Vec<Vec<u8>>, String> {
6400    let mut sealed: Vec<Vec<u8>> = Vec::with_capacity(ids.len());
6401    {
6402        let conn = super::get_db_connection_guard_static()?;
6403        let mut stmt = conn
6404            .prepare_cached("SELECT wrap FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3 AND wrap IS NOT NULL")
6405            .map_err(|e| format!("control wrap bodies: {e}"))?;
6406        for id in ids {
6407            if let Some(body) = stmt.query_row(params![community_id, &view[..], &id[..]], |r| r.get::<_, Vec<u8>>(0)).optional().map_err(|e| format!("control wrap bodies: {e}"))? {
6408                sealed.push(body);
6409            }
6410        }
6411    }
6412    crate::crypto::open_batch(|o| Ok(sealed.iter().map(|body| o.open_blob_or_keep(body)).collect()))
6413}
6414
6415/// What `view` holds: bodies, refusals, and the bodies' bytes as stored.
6416pub fn control_wrap_counts(community_id: &str, view: &[u8; 32]) -> Result<(usize, usize, usize), String> {
6417    let conn = super::get_db_connection_guard_static()?;
6418    conn.query_row(
6419        "SELECT COUNT(wrap), COUNT(*) - COUNT(wrap), COALESCE(SUM(length(wrap)), 0) FROM community_control_wraps WHERE community_id = ?1 AND view = ?2",
6420        params![community_id, &view[..]],
6421        |r| Ok((r.get::<_, i64>(0)? as usize, r.get::<_, i64>(1)? as usize, r.get::<_, i64>(2)? as usize)),
6422    )
6423    .map_err(|e| format!("control wrap counts: {e}"))
6424}
6425
6426/// The Guestbook wraps of `plane` this device has read, with their timestamps.
6427pub fn guestbook_wrap_ids(community_id: &str, plane: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
6428    let conn = super::get_db_connection_guard_static()?;
6429    let mut stmt = conn
6430        .prepare_cached("SELECT wrap_id, created_at FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2")
6431        .map_err(|e| format!("guestbook wrap ids: {e}"))?;
6432    let rows = stmt
6433        .query_map(params![community_id, &plane[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
6434        .map_err(|e| format!("guestbook wrap ids: {e}"))?;
6435    let mut out = Vec::new();
6436    for row in rows {
6437        let (id, at) = row.map_err(|e| format!("guestbook wrap ids: {e}"))?;
6438        out.push((id.try_into().map_err(|_| "guestbook wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
6439    }
6440    Ok(out)
6441}
6442
6443/// Record Guestbook wraps as read: (id, timestamp, rules), `rules` 0 for one whose entry is stored.
6444pub fn store_guestbook_wraps(community_id: &str, plane: &[u8; 32], now_secs: u64, rows: &[([u8; 32], u64, u32)]) -> Result<(), String> {
6445    if rows.is_empty() {
6446        return Ok(());
6447    }
6448    let conn = super::get_write_connection_guard_static()?;
6449    let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook wraps tx: {e}"))?;
6450    {
6451        let mut stmt = tx
6452            .prepare_cached("INSERT OR IGNORE INTO community_guestbook_wraps (community_id, plane, wrap_id, created_at, rules, judged_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)")
6453            .map_err(|e| format!("store guestbook wraps: {e}"))?;
6454        for (id, at, rules) in rows {
6455            stmt.execute(params![community_id, &plane[..], &id[..], *at as i64, rules, now_secs as i64]).map_err(|e| format!("store guestbook wraps: {e}"))?;
6456        }
6457    }
6458    tx.commit().map_err(|e| format!("store guestbook wraps commit: {e}"))
6459}
6460
6461/// Forget the Guestbook wraps of any plane but `plane`, the refusals of `plane` judged under
6462/// rules other than `rules`, and the `oldest` longest standing of its other refusals.
6463pub fn forget_guestbook_wraps(community_id: &str, plane: &[u8; 32], rules: u32, oldest: usize) -> Result<(), String> {
6464    let conn = super::get_write_connection_guard_static()?;
6465    conn.execute(
6466        "DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND (plane != ?2 OR (rules != 0 AND rules != ?3))",
6467        params![community_id, &plane[..], rules],
6468    )
6469    .map_err(|e| format!("forget guestbook wraps: {e}"))?;
6470    if oldest > 0 {
6471        conn.execute(
6472            "DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND wrap_id IN (
6473                 SELECT wrap_id FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND rules != 0 ORDER BY judged_at LIMIT ?3)",
6474            params![community_id, &plane[..], oldest as i64],
6475        )
6476        .map_err(|e| format!("forget guestbook wraps: {e}"))?;
6477    }
6478    Ok(())
6479}
6480
6481/// Drop every Guestbook wrap recorded for a community, and how its relays were read.
6482pub fn purge_guestbook_wraps(community_id: &str) -> Result<(), String> {
6483    let conn = super::get_write_connection_guard_static()?;
6484    conn.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
6485    conn.execute("DELETE FROM settings WHERE key = 'gbk_reads:' || ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
6486    Ok(())
6487}
6488
6489/// Drop everything held of a community's Control Plane, and how its relays were read.
6490pub fn purge_control_wraps(community_id: &str) -> Result<(), String> {
6491    let conn = super::get_write_connection_guard_static()?;
6492    conn.execute("DELETE FROM community_control_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge control wraps: {e}"))?;
6493    conn.execute("DELETE FROM settings WHERE key LIKE 'ctl_reads:' || ?1 || '%' OR key LIKE 'pln_reads:' || ?1 || '%'", params![community_id]).map_err(|e| format!("purge control wraps: {e}"))?;
6494    Ok(())
6495}
6496
6497/// Forget one wrap of `view`, so a sync asks for it again.
6498pub fn drop_control_wrap(community_id: &str, view: &[u8; 32], wrap_id: &[u8; 32]) -> Result<(), String> {
6499    let conn = super::get_write_connection_guard_static()?;
6500    conn.execute(
6501        "DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3",
6502        params![community_id, &view[..], &wrap_id[..]],
6503    )
6504    .map_err(|e| format!("drop control wrap: {e}"))?;
6505    Ok(())
6506}
6507
6508/// Forget `view`'s refusals judged under any rules but `rules`, and the `oldest` longest
6509/// standing of the rest, so each is fetched and judged again. Returns how many went.
6510pub fn forget_control_refusals(community_id: &str, view: &[u8; 32], rules: u32, oldest: usize) -> Result<usize, String> {
6511    let conn = super::get_write_connection_guard_static()?;
6512    let other = conn
6513        .execute(
6514            "DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL AND rules != ?3",
6515            params![community_id, &view[..], rules],
6516        )
6517        .map_err(|e| format!("forget control refusals: {e}"))?;
6518    let aged = conn
6519        .execute(
6520            "DELETE FROM community_control_wraps WHERE rowid IN (
6521                 SELECT rowid FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL
6522                 ORDER BY judged_at, wrap_id LIMIT ?3)",
6523            params![community_id, &view[..], oldest as i64],
6524        )
6525        .map_err(|e| format!("forget control refusals: {e}"))?;
6526    Ok(other + aged)
6527}
6528
6529/// Note an Audit Log act no Control edition records (a moderator's delete, a voice directive),
6530/// keyed by the event that carried it so a re-delivery notes nothing twice.
6531pub fn record_audit_local(community_id: &str, id: &str, at_ms: u64, entry: &str) -> Result<(), String> {
6532    let _seal = crate::crypto::gate::sealing();
6533    let enc = enc_txt(entry)?;
6534    let conn = super::get_write_connection_guard_static()?;
6535    conn.execute(
6536        "INSERT OR IGNORE INTO community_audit_local (id, community_id, at_ms, entry) VALUES (?1, ?2, ?3, ?4)",
6537        params![id, community_id, at_ms as i64, enc],
6538    )
6539    .map_err(|e| format!("record audit: {e}"))?;
6540    Ok(())
6541}
6542
6543/// Every act [`record_audit_local`] noted for `community_id`: `(id, at_ms, entry)`.
6544pub fn get_audit_local(community_id: &str) -> Result<Vec<(String, u64, String)>, String> {
6545    let conn = super::get_db_connection_guard_static()?;
6546    let mut stmt = conn
6547        .prepare("SELECT id, at_ms, entry FROM community_audit_local WHERE community_id = ?1 ORDER BY at_ms")
6548        .map_err(|e| format!("read audit: {e}"))?;
6549    let rows = stmt
6550        .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?)))
6551        .map_err(|e| format!("read audit: {e}"))?;
6552    Ok(rows.flatten().map(|(id, at, entry)| (id, at, dec_txt(&entry))).collect())
6553}
6554
6555/// The Channels of `community_id` holding wraps.
6556pub fn held_wrap_channels(community_id: &str) -> Result<Vec<String>, String> {
6557    let conn = super::get_db_connection_guard_static()?;
6558    let mut stmt = conn.prepare("SELECT DISTINCT channel_id FROM community_held_wraps WHERE community_id = ?1").map_err(|e| format!("held channels: {e}"))?;
6559    let rows = stmt.query_map(params![community_id], |r| r.get(0)).map_err(|e| format!("held channels: {e}"))?;
6560    Ok(rows.flatten().collect())
6561}
6562
6563/// The ids of the wraps held for one Channel.
6564pub fn held_wrap_ids_in(community_id: &str, channel_id: &str) -> Result<Vec<String>, String> {
6565    let conn = super::get_db_connection_guard_static()?;
6566    let mut stmt = conn.prepare("SELECT wrap_id FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2").map_err(|e| format!("held ids: {e}"))?;
6567    let rows = stmt.query_map(params![community_id, channel_id], |r| r.get(0)).map_err(|e| format!("held ids: {e}"))?;
6568    Ok(rows.flatten().collect())
6569}
6570
6571/// The wraps held for one Channel, as `(wrap_id, wrap)`, oldest-dated first.
6572pub fn held_wraps_in(community_id: &str, channel_id: &str) -> Result<Vec<(String, String)>, String> {
6573    let conn = super::get_db_connection_guard_static()?;
6574    let mut stmt = conn
6575        .prepare("SELECT wrap_id, wrap FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2 ORDER BY at_ms")
6576        .map_err(|e| format!("held wraps: {e}"))?;
6577    let rows = stmt.query_map(params![community_id, channel_id], |r| Ok((r.get(0)?, r.get::<_, String>(1)?))).map_err(|e| format!("held wraps: {e}"))?;
6578    Ok(rows.flatten().map(|(id, wrap)| (id, dec_txt(&wrap))).collect())
6579}
6580
6581/// Every wrap held for `community_id`, as `(wrap_id, channel_id, wrap)`, oldest-dated first.
6582pub fn held_wraps(community_id: &str) -> Result<Vec<(String, String, String)>, String> {
6583    let conn = super::get_db_connection_guard_static()?;
6584    let mut stmt = conn
6585        .prepare("SELECT wrap_id, channel_id, wrap FROM community_held_wraps WHERE community_id = ?1 ORDER BY at_ms")
6586        .map_err(|e| format!("held wraps: {e}"))?;
6587    let rows = stmt.query_map(params![community_id], |r| Ok((r.get(0)?, r.get(1)?, r.get::<_, String>(2)?))).map_err(|e| format!("held wraps: {e}"))?;
6588    Ok(rows.flatten().map(|(id, ch, wrap)| (id, ch, dec_txt(&wrap))).collect())
6589}
6590
6591/// Whether `community_id` holds any wrap.
6592pub fn holds_wraps(community_id: &str) -> bool {
6593    super::get_db_connection_guard_static()
6594        .ok()
6595        .and_then(|conn| conn.query_row("SELECT 1 FROM community_held_wraps WHERE community_id = ?1 LIMIT 1", params![community_id], |_| Ok(())).optional().ok().flatten())
6596        .is_some()
6597}
6598
6599/// Whether `channel_id` holds a wrap by `author` (hex) sent to `address` (a writer address),
6600/// waiting for a later judgment.
6601pub fn holds_wraps_at(community_id: &str, channel_id: &str, author: &str, address: &[u8; 32]) -> bool {
6602    let wraps: Vec<String> = {
6603        let Ok(conn) = super::get_db_connection_guard_static() else { return false };
6604        let Ok(mut stmt) = conn.prepare("SELECT wrap FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2 AND author = ?3") else { return false };
6605        let Ok(rows) = stmt.query_map(params![community_id, channel_id, author], |r| r.get::<_, String>(0)) else { return false };
6606        rows.flatten().collect()
6607    };
6608    wraps.iter().any(|w| crate::event_json::event(&dec_txt(w)).is_ok_and(|e| e.pubkey.to_bytes() == *address))
6609}
6610
6611struct DeferredWraps;
6612
6613pub const MAX_DEFERRED: usize = 4096;
6614
6615/// Wraps refused for a date past the horizon, by id: a read skips each until its date nears.
6616fn deferred() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, u64>>> {
6617    super::current_session().scoped::<DeferredWraps, _>()
6618}
6619
6620/// Of `wrap_ids`, those held, or deferred while their date is still past the horizon.
6621pub fn held_wrap_ids(wrap_ids: &[String]) -> std::collections::HashSet<String> {
6622    let now = now_secs().max(0) as u64 * 1000;
6623    let waiting: std::collections::HashSet<String> = {
6624        let held = deferred();
6625        let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
6626        map.retain(|_, at| *at > now.saturating_add(HELD_HORIZON_MS));
6627        wrap_ids.iter().filter(|id| map.contains_key(*id)).cloned().collect()
6628    };
6629    let mut out = held_wrap_rows(wrap_ids);
6630    out.extend(waiting);
6631    out
6632}
6633
6634fn held_wrap_rows(wrap_ids: &[String]) -> std::collections::HashSet<String> {
6635    let Ok(conn) = super::get_db_connection_guard_static() else { return Default::default() };
6636    let Ok(json) = serde_json::to_string(wrap_ids) else { return Default::default() };
6637    let Ok(mut stmt) = conn.prepare("SELECT wrap_id FROM community_held_wraps WHERE wrap_id IN (SELECT value FROM json_each(?1))") else { return Default::default() };
6638    stmt.query_map(params![json], |r| r.get::<_, String>(0)).map(|rows| rows.flatten().collect()).unwrap_or_default()
6639}
6640
6641/// Let `wrap_id` go: it stands now.
6642pub fn release_held_wrap(wrap_id: &str) -> Result<(), String> {
6643    let conn = super::get_write_connection_guard_static()?;
6644    conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![wrap_id]).map_err(|e| format!("release held wrap: {e}"))?;
6645    Ok(())
6646}
6647
6648/// A channel's stored Pin List head: `(raw content, version)`, `None` when no
6649/// edition has ever folded for it.
6650/// Each channel's folded Pin List version, without opening a list.
6651pub fn get_community_pin_versions(community_id: &str) -> Result<std::collections::HashMap<String, i64>, String> {
6652    let conn = super::get_db_connection_guard_static()?;
6653    let mut stmt = conn
6654        .prepare("SELECT channel_id, version FROM community_pins WHERE community_id = ?1")
6655        .map_err(|e| format!("get pin versions: {e}"))?;
6656    let rows = stmt
6657        .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
6658        .map_err(|e| format!("get pin versions: {e}"))?;
6659    rows.collect::<Result<_, _>>().map_err(|e| format!("get pin versions: {e}"))
6660}
6661
6662pub fn get_community_pins(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
6663    let conn = super::get_db_connection_guard_static()?;
6664    let row: Option<(String, i64)> = conn
6665        .query_row(
6666            "SELECT content, version FROM community_pins WHERE community_id = ?1 AND channel_id = ?2",
6667            params![community_id, channel_id],
6668            |r| Ok((r.get(0)?, r.get(1)?)),
6669        )
6670        .optional()
6671        .map_err(|e| format!("get pins: {e}"))?;
6672    Ok(row.map(|(content, version)| (dec_txt(&content), version)))
6673}