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    Ok(())
2920}
2921
2922/// Load a v2 community by id, or `None` if absent / not a v2 community.
2923pub fn load_community_v2(id: &CommunityId) -> Result<Option<crate::community::v2::community::CommunityV2>, String> {
2924    use crate::community::v2::community::{ChannelV2, CommunityV2};
2925    use crate::community::v2::control::CommunityIdentity;
2926    let conn = super::get_db_connection_guard_static()?;
2927    let id_hex = id.to_hex();
2928
2929    let row = conn
2930        .query_row(
2931            "SELECT server_root_key, name, relays, created_at, description,
2932                    server_root_epoch, dissolved, owner_pubkey, owner_salt,
2933                    icon, banner, meta_extra, control_pk, control_root
2934             FROM communities WHERE community_id = ?1",
2935            params![id_hex],
2936            |r| {
2937                Ok((
2938                    r.get::<_, Vec<u8>>(0)?,
2939                    r.get::<_, String>(1)?,
2940                    r.get::<_, String>(2)?,
2941                    r.get::<_, i64>(3)?,
2942                    r.get::<_, Option<String>>(4)?,
2943                    r.get::<_, i64>(5)?,
2944                    r.get::<_, i64>(6)?,
2945                    r.get::<_, Option<String>>(7)?,
2946                    r.get::<_, Option<String>>(8)?,
2947                    r.get::<_, Option<String>>(9)?,
2948                    r.get::<_, Option<String>>(10)?,
2949                    r.get::<_, Option<String>>(11)?,
2950                    r.get::<_, Option<String>>(12)?,
2951                    r.get::<_, Option<Vec<u8>>>(13)?,
2952                ))
2953            },
2954        )
2955        .optional()
2956        .map_err(|e| e.to_string())?;
2957    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
2958    else {
2959        return Ok(None);
2960    };
2961    let (Some(owner_pk_e), Some(owner_salt_e)) = (owner_pk_e, owner_salt_e) else {
2962        return Err("v2 community row is missing its owner commitment".to_string());
2963    };
2964
2965    // One vault read for the whole row set.
2966    let dk = |o: &mut crate::crypto::AtRestOpener, b: &[u8]| to_32(&o.open_blob_or_keep(b));
2967    let dt = |o: &mut crate::crypto::AtRestOpener, s: &str| o.open_or_keep(s.to_string());
2968    crate::crypto::open_batch(|o| {
2969        let community_root = dk(o, &root_blob)?;
2970        let owner_xonly = parse_hex32(&dt(o, &owner_pk_e))?;
2971        let owner_salt = parse_hex32(&dt(o, &owner_salt_e))?;
2972        let identity = CommunityIdentity { community_id: *id, owner_xonly, owner_salt };
2973        let relays: Vec<String> = serde_json::from_str(&dt(o, &relays_e)).unwrap_or_default();
2974
2975        let mut channels = Vec::new();
2976        {
2977            let mut stmt = conn
2978                .prepare(
2979                    "SELECT channel_id, channel_key, epoch, name, private, meta_extra
2980                     FROM community_channels WHERE community_id = ?1 ORDER BY created_at",
2981                )
2982                .map_err(|e| e.to_string())?;
2983            let rows = stmt
2984                .query_map(params![id_hex], |r| {
2985                    Ok((
2986                        r.get::<_, String>(0)?,
2987                        r.get::<_, Vec<u8>>(1)?,
2988                        r.get::<_, i64>(2)?,
2989                        r.get::<_, String>(3)?,
2990                        r.get::<_, i64>(4)?,
2991                        r.get::<_, Option<String>>(5)?,
2992                    ))
2993                })
2994                .map_err(|e| e.to_string())?;
2995            for row in rows {
2996                let (ch_hex, key_blob, epoch, name_e, private, ch_stash_e) = row.map_err(|e| e.to_string())?;
2997                let private = private != 0;
2998                let key = dk(o, &key_blob)?;
2999                // Unparseable stash degrades to empty — the fold re-persists the
3000                // authoritative value on its next pass.
3001                let ch_stash: ChannelMetaStash = ch_stash_e
3002                    .map(|s| dt(o, &s))
3003                    .and_then(|j| serde_json::from_str(&j).ok())
3004                    .unwrap_or_default();
3005                channels.push(ChannelV2 {
3006                    id: ChannelId(hex_id_to_32(&ch_hex)?),
3007                    name: dt(o, &name_e),
3008                    private,
3009                    // A public channel derives from the root — drop the placeholder. A
3010                    // PRIVATE channel stored with the root value is the KEYLESS placeholder
3011                    // (key not yet delivered over the rekey plane): a real private key is
3012                    // independently random (CORD-03 §1), never the root, so reconstruct
3013                    // None and keep every read/send path behind the keyless guards instead
3014                    // of silently addressing the public plane.
3015                    key: (private && key != community_root).then_some(key),
3016                    epoch: Epoch(epoch as u64),
3017                    voice: ch_stash.voice,
3018                    meta_custom: ch_stash.custom,
3019                    meta_extra: ch_stash.extra,
3020                    writers: None,
3021                    sealed: ch_stash.sealed,
3022                });
3023            }
3024        }
3025        {
3026            let mut stmt = conn
3027                .prepare("SELECT channel_id, content FROM community_writers WHERE community_id = ?1")
3028                .map_err(|e| e.to_string())?;
3029            let rows = stmt
3030                .query_map(params![id_hex], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
3031                .map_err(|e| e.to_string())?;
3032            for row in rows {
3033                let (ch_hex, content) = row.map_err(|e| e.to_string())?;
3034                let Some(ch) = channels.iter_mut().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == ch_hex) else { continue };
3035                ch.writers = crate::community::v2::writers::Ledger::parse(&dt(o, &content)).filter(|l| l.channel == ch.id.0);
3036            }
3037        }
3038        // The held set keeps these resident; push-growth leaves up to half unused.
3039        channels.shrink_to_fit();
3040
3041        // Unparseable image JSON degrades to no-image rather than failing the load —
3042        // the fold re-persists the authoritative value on its next pass.
3043        let icon = icon_e
3044            .map(|s| dt(o, &s))
3045            .and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
3046        let banner = banner_e
3047            .map(|s| dt(o, &s))
3048            .and_then(|j| serde_json::from_str::<crate::community::v2::control::ImageRef>(&j).ok());
3049        let stash: CommunityMetaStash = stash_e
3050            .map(|s| dt(o, &s))
3051            .and_then(|j| serde_json::from_str(&j).ok())
3052            .unwrap_or_default();
3053
3054        // The split pair (CORD-02 §2). Fail closed on corruption: an unparseable
3055        // address degrades to the legacy view, and a secret that no longer derives
3056        // to the held address is dropped to read-only rather than signing at an
3057        // address nobody reads.
3058        let control_pk = control_pk_e
3059            .as_deref()
3060            .and_then(|e| nostr_sdk::prelude::PublicKey::from_hex(&dt(o, e)).ok());
3061        let control_root = match (control_pk, control_root_b) {
3062            (Some(pk), Some(blob)) => dk(o, &blob).ok().filter(|cr| {
3063                crate::community::v2::derive::control_signer_group_key(cr, id, Epoch(root_epoch as u64)).pk() == pk
3064            }),
3065            _ => None,
3066        };
3067
3068        Ok(Some(CommunityV2 {
3069            identity,
3070            community_root,
3071            root_epoch: Epoch(root_epoch as u64),
3072            control_pk,
3073            control_root,
3074            name: dt(o, &name_e),
3075            description: desc_e.map(|d| dt(o, &d)),
3076            icon,
3077            banner,
3078            meta_custom: stash.custom,
3079            meta_extra: stash.extra,
3080            relays,
3081            channels,
3082            categories: stash
3083                .categories
3084                .into_iter()
3085                .filter_map(|k| {
3086                    let id = crate::simd::hex::hex_to_bytes_32_checked(&k.id)?;
3087                    Some(crate::community::v2::community::CategoryV2 { id, name: k.name, position: k.position, extra: k.extra })
3088                })
3089                .collect(),
3090            dissolved: dissolved != 0,
3091            created_at_ms: (created as u64).saturating_mul(1000),
3092        }))
3093    })
3094}
3095fn parse_hex32(hex: &str) -> Result<[u8; 32], String> {
3096    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
3097        return Err("stored value is not 32-byte hex".to_string());
3098    }
3099    Ok(crate::simd::hex::hex_to_bytes_32(hex))
3100}
3101
3102/// What was parsed out of a community's stored rows, for the last `CAP` communities read or
3103/// written this session: parsing costs far more than most uses of the result. Each slot carries
3104/// the write generation it was read under, and a writer moves the generation on while it still
3105/// holds the write connection, so a read that overlapped a write is never served after it.
3106struct Parsed<T, const CAP: usize> {
3107    generations: std::collections::HashMap<String, u64>,
3108    /// Most recently used last.
3109    slots: Vec<(String, u64, T)>,
3110}
3111
3112impl<T, const CAP: usize> Default for Parsed<T, CAP> {
3113    fn default() -> Self {
3114        Parsed { generations: Default::default(), slots: Vec::new() }
3115    }
3116}
3117
3118impl<T: Clone, const CAP: usize> Parsed<T, CAP> {
3119    fn generation(&self, community_id: &str) -> u64 {
3120        self.generations.get(community_id).copied().unwrap_or(0)
3121    }
3122
3123    fn get(&mut self, community_id: &str) -> Option<T> {
3124        let generation = self.generation(community_id);
3125        let i = self.slots.iter().position(|(id, g, _)| id == community_id && *g == generation)?;
3126        let slot = self.slots.remove(i);
3127        let held = slot.2.clone();
3128        self.slots.push(slot);
3129        Some(held)
3130    }
3131
3132    fn put(&mut self, community_id: &str, generation: u64, held: T) {
3133        if generation != self.generation(community_id) {
3134            return;
3135        }
3136        self.slots.retain(|(id, ..)| id != community_id);
3137        if self.slots.len() >= CAP {
3138            self.slots.remove(0);
3139        }
3140        self.slots.push((community_id.to_string(), generation, held));
3141    }
3142
3143    /// A write is landing: what was read before it is stale. Returns the new generation.
3144    fn moved(&mut self, community_id: &str) -> u64 {
3145        let generation = self.generation(community_id) + 1;
3146        self.generations.insert(community_id.to_string(), generation);
3147        self.slots.retain(|(id, ..)| id != community_id);
3148        generation
3149    }
3150}
3151
3152/// A community's stored Guestbook in arrival order, found by rumor id.
3153#[derive(Clone, Default)]
3154pub struct Guestbook {
3155    events: Vec<crate::community::v2::guestbook::GuestbookEvent>,
3156    by_id: std::collections::HashMap<[u8; 32], u32>,
3157}
3158
3159impl Guestbook {
3160    /// Keeps the first of any rumor given twice, as the rows do.
3161    fn new(given: Vec<crate::community::v2::guestbook::GuestbookEvent>) -> Self {
3162        let mut book = Guestbook { events: Vec::with_capacity(given.len()), by_id: std::collections::HashMap::with_capacity(given.len()) };
3163        for ev in given {
3164            if !book.by_id.contains_key(&ev.rumor_id) {
3165                book.by_id.insert(ev.rumor_id, book.events.len() as u32);
3166                book.events.push(ev);
3167            }
3168        }
3169        book
3170    }
3171
3172    pub fn get(&self, rumor_id: &[u8; 32]) -> Option<&crate::community::v2::guestbook::GuestbookEvent> {
3173        self.by_id.get(rumor_id).map(|&i| &self.events[i as usize])
3174    }
3175
3176    pub fn into_events(self) -> Vec<crate::community::v2::guestbook::GuestbookEvent> {
3177        self.events
3178    }
3179
3180    /// A rumor held already takes `ev` in its place; a new one goes last.
3181    fn upsert(&mut self, ev: &crate::community::v2::guestbook::GuestbookEvent) {
3182        match self.by_id.get(&ev.rumor_id) {
3183            Some(&i) => self.events[i as usize] = ev.clone(),
3184            None => {
3185                self.by_id.insert(ev.rumor_id, self.events.len() as u32);
3186                self.events.push(ev.clone());
3187            }
3188        }
3189    }
3190}
3191
3192impl std::ops::Deref for Guestbook {
3193    type Target = [crate::community::v2::guestbook::GuestbookEvent];
3194    fn deref(&self) -> &Self::Target {
3195        &self.events
3196    }
3197}
3198
3199type GuestbookShared = (std::sync::Arc<Guestbook>, u64);
3200type GuestbookCache = Parsed<GuestbookShared, 8>;
3201
3202fn guestbook_cache() -> std::sync::Arc<std::sync::Mutex<GuestbookCache>> {
3203    struct Key;
3204    super::current_session().scoped::<Key, std::sync::Mutex<GuestbookCache>>()
3205}
3206
3207/// [`get_guestbook`] without copying the events out: what a fold that only reads them wants.
3208pub fn get_guestbook_shared(community_id: &str) -> Result<GuestbookShared, String> {
3209    let cache = guestbook_cache();
3210    let generation = {
3211        let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3212        if let Some(hit) = held.get(community_id) {
3213            return Ok(hit);
3214        }
3215        held.generation(community_id)
3216    };
3217    let (events, cursor) = read_guestbook(community_id)?;
3218    let shared = (std::sync::Arc::new(Guestbook::new(events)), cursor);
3219    cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, shared.clone());
3220    Ok(shared)
3221}
3222
3223/// A community's persisted Guestbook: its membership events in arrival order and the
3224/// newest-seen cursor (relay seconds). `([], 0)` when never synced.
3225pub fn get_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
3226    let (events, cursor) = get_guestbook_shared(community_id)?;
3227    Ok((std::sync::Arc::unwrap_or_clone(events).into_events(), cursor))
3228}
3229
3230fn read_guestbook(community_id: &str) -> Result<(Vec<crate::community::v2::guestbook::GuestbookEvent>, u64), String> {
3231    let legacy = {
3232        let conn = super::get_db_connection_guard_static()?;
3233        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)?)))
3234            .optional()
3235            .map_err(|e| format!("load guestbook: {e}"))?
3236    };
3237    let Some((blob, cursor)) = legacy else {
3238        return Ok((Vec::new(), 0));
3239    };
3240    if !blob.is_empty() {
3241        move_guestbook_blob(community_id, &blob)?;
3242    }
3243    // The reader goes back before the decrypt and decode, which outlast the read by far.
3244    let rows: Vec<([u8; 32], Vec<u8>)> = {
3245        let conn = super::get_db_connection_guard_static()?;
3246        let mut stmt = conn
3247            .prepare_cached(
3248                "SELECT e.rumor_id, e.body FROM community_guestbook_events e
3249                 JOIN community_guestbook_books b ON b.book = e.book
3250                 WHERE b.community_id = ?1 ORDER BY e.seq",
3251            )
3252            .map_err(|e| format!("load guestbook events: {e}"))?;
3253        let rows = stmt
3254            .query_map(params![community_id], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, Vec<u8>>(1)?)))
3255            .map_err(|e| format!("load guestbook events: {e}"))?;
3256        rows.filter_map(|r| r.ok()).filter_map(|(id, body)| Some((id.try_into().ok()?, body))).collect()
3257    };
3258    let events = crate::crypto::open_batch(|o| {
3259        rows.into_iter().filter_map(|(id, body)| crate::community::v2::guestbook::event_from_body(id, &o.open_blob_or_keep(&body))).collect()
3260    });
3261    Ok((events, cursor.max(0) as u64))
3262}
3263
3264/// Move a Guestbook still stored as one blob into rows, leaving the blob column empty. A blob
3265/// that doesn't read (sealed under a key not held) stays as it is.
3266fn move_guestbook_blob(community_id: &str, blob: &str) -> Result<(), String> {
3267    let Ok(events) = serde_json::from_str::<Vec<crate::community::v2::guestbook::GuestbookEvent>>(&dec_txt(blob)) else {
3268        return Ok(());
3269    };
3270    let _seal = crate::crypto::gate::sealing();
3271    let conn = super::get_write_connection_guard_static()?;
3272    let tx = conn.unchecked_transaction().map_err(|e| format!("move guestbook tx: {e}"))?;
3273    // Another read may have moved it first.
3274    let still: Option<String> = tx
3275        .query_row("SELECT events FROM community_guestbook WHERE community_id = ?1", params![community_id], |r| r.get(0))
3276        .optional()
3277        .map_err(|e| format!("move guestbook: {e}"))?;
3278    if still.as_deref() != Some(blob) {
3279        return Ok(());
3280    }
3281    insert_guestbook_events(&tx, community_id, &events, false)?;
3282    tx.execute("UPDATE community_guestbook SET events = '' WHERE community_id = ?1", params![community_id])
3283        .map_err(|e| format!("move guestbook: {e}"))?;
3284    tx.commit().map_err(|e| format!("move guestbook commit: {e}"))
3285}
3286
3287/// The number of `community_id`'s Guestbook, given on first use.
3288fn guestbook_book(tx: &rusqlite::Connection, community_id: &str) -> Result<i64, String> {
3289    tx.prepare_cached("INSERT OR IGNORE INTO community_guestbook_books (community_id) VALUES (?1)")
3290        .and_then(|mut s| s.execute(params![community_id]))
3291        .map_err(|e| format!("guestbook book: {e}"))?;
3292    tx.prepare_cached("SELECT book FROM community_guestbook_books WHERE community_id = ?1")
3293        .and_then(|mut s| s.query_row(params![community_id], |r| r.get(0)))
3294        .map_err(|e| format!("guestbook book: {e}"))
3295}
3296
3297/// Store `events` in order. A rumor already held keeps its place, and with `restamp` takes the
3298/// new body (an epoch or arrival stamp it gained).
3299fn insert_guestbook_events(tx: &rusqlite::Connection, community_id: &str, events: &[crate::community::v2::guestbook::GuestbookEvent], restamp: bool) -> Result<(), String> {
3300    let book = guestbook_book(tx, community_id)?;
3301    let sql = if restamp {
3302        "INSERT INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)
3303         ON CONFLICT (book, rumor_id) DO UPDATE SET body = excluded.body"
3304    } else {
3305        "INSERT OR IGNORE INTO community_guestbook_events (book, rumor_id, body) VALUES (?1, ?2, ?3)"
3306    };
3307    let mut stmt = tx.prepare_cached(sql).map_err(|e| format!("store guestbook event: {e}"))?;
3308    crate::crypto::seal_batch(|sealer| {
3309        for ev in events {
3310            let body = sealer.seal_blob(&crate::community::v2::guestbook::event_body(ev))?;
3311            stmt.execute(params![book, &ev.rumor_id[..], body]).map_err(|e| format!("store guestbook event: {e}"))?;
3312        }
3313        Ok(())
3314    })
3315}
3316
3317struct StandingCache;
3318/// Per community: the Guestbook write generation and, once read, the Timeouts and Nicknames at it.
3319type StandingMap = std::sync::RwLock<std::collections::HashMap<String, (u64, Option<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>>)>>;
3320
3321fn standing_cache() -> std::sync::Arc<StandingMap> {
3322    crate::db::current_session().scoped::<StandingCache, StandingMap>()
3323}
3324
3325/// The Guestbook's Timeout and Nickname entries, held so every send and paint doesn't reparse
3326/// the whole book.
3327pub fn get_guestbook_standing(community_id: &str) -> Result<std::sync::Arc<Vec<crate::community::v2::guestbook::GuestbookEvent>>, String> {
3328    let generation = match standing_cache().read().unwrap_or_else(|e| e.into_inner()).get(community_id) {
3329        Some((_, Some(held))) => return Ok(held.clone()),
3330        Some((generation, None)) => *generation,
3331        None => 0,
3332    };
3333    let (events, _) = get_guestbook(community_id)?;
3334    use crate::community::v2::guestbook::GuestbookEntry;
3335    let standing: std::sync::Arc<Vec<_>> = std::sync::Arc::new(
3336        events.into_iter().filter(|e| matches!(e.entry, GuestbookEntry::Timeout { .. } | GuestbookEntry::Nickname { .. })).collect(),
3337    );
3338    // A write that landed during the read moved the generation on: keep what it left.
3339    let map = standing_cache();
3340    let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
3341    let entry = cache.entry(community_id.to_string()).or_insert((0, None));
3342    if entry.0 == generation {
3343        entry.1 = Some(standing.clone());
3344    }
3345    Ok(standing)
3346}
3347
3348/// Persist a community's Guestbook events + cursor (encrypted at rest, like the
3349/// community row itself). The caller owns dedup/merge — this is a plain replace.
3350struct MembershipGeneration;
3351
3352/// Moves whenever what a Guestbook fold reads may have: a store write here, or a Control fold.
3353pub fn membership_generation() -> u64 {
3354    super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().load(std::sync::atomic::Ordering::Acquire)
3355}
3356
3357pub fn bump_membership_generation() {
3358    super::current_session().scoped::<MembershipGeneration, std::sync::atomic::AtomicU64>().fetch_add(1, std::sync::atomic::Ordering::AcqRel);
3359}
3360
3361pub fn set_guestbook(
3362    community_id: &str,
3363    events: &[crate::community::v2::guestbook::GuestbookEvent],
3364    cursor_secs: u64,
3365) -> Result<(), String> {
3366    let _seal = crate::crypto::gate::sealing();
3367    forget_console_verdict(community_id);
3368    let conn = super::get_write_connection_guard_static()?;
3369    let tx = conn.unchecked_transaction().map_err(|e| format!("save guestbook tx: {e}"))?;
3370    let book = guestbook_book(&tx, community_id)?;
3371    tx.execute("DELETE FROM community_guestbook_events WHERE book = ?1", params![book])
3372        .map_err(|e| format!("save guestbook: {e}"))?;
3373    // A replaced Guestbook no longer vouches for the wraps read into the one before it.
3374    tx.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id])
3375        .map_err(|e| format!("save guestbook: {e}"))?;
3376    insert_guestbook_events(&tx, community_id, events, false)?;
3377    upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
3378    tx.commit().map_err(|e| format!("save guestbook commit: {e}"))?;
3379    {
3380        let cache = guestbook_cache();
3381        let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3382        let generation = held.moved(community_id);
3383        held.put(community_id, generation, (std::sync::Arc::new(Guestbook::new(events.to_vec())), cursor_secs));
3384    }
3385    drop(conn);
3386    guestbook_moved_on(community_id);
3387    Ok(())
3388}
3389
3390/// Store the Guestbook events a fold added or restamped, and the cursor: each a row of its own,
3391/// nothing else rewritten.
3392pub fn store_guestbook_events(
3393    community_id: &str,
3394    events: &[crate::community::v2::guestbook::GuestbookEvent],
3395    cursor_secs: u64,
3396) -> Result<(), String> {
3397    let _seal = crate::crypto::gate::sealing();
3398    forget_console_verdict(community_id);
3399    let conn = super::get_write_connection_guard_static()?;
3400    let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook tx: {e}"))?;
3401    insert_guestbook_events(&tx, community_id, events, true)?;
3402    upsert_guestbook_cursor(&tx, community_id, cursor_secs)?;
3403    tx.commit().map_err(|e| format!("store guestbook commit: {e}"))?;
3404    guestbook_written(
3405        community_id,
3406        |held| {
3407            for ev in events {
3408                held.upsert(ev);
3409            }
3410        },
3411        cursor_secs,
3412    );
3413    drop(conn);
3414    guestbook_moved_on(community_id);
3415    Ok(())
3416}
3417
3418fn upsert_guestbook_cursor(tx: &rusqlite::Connection, community_id: &str, cursor_secs: u64) -> Result<(), String> {
3419    tx.prepare_cached(
3420        "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, '', ?2)
3421         ON CONFLICT(community_id) DO UPDATE SET cursor_secs = ?2",
3422    )
3423    .and_then(|mut s| s.execute(params![community_id, cursor_secs as i64]))
3424    .map(|_| ())
3425    .map_err(|e| format!("save guestbook cursor: {e}"))
3426}
3427
3428/// Carry a committed write into the parsed copy. Call while the write connection is still held,
3429/// so no later write lands between the two. A copy not cached is read again when next asked for.
3430fn guestbook_written(community_id: &str, apply: impl FnOnce(&mut Guestbook), cursor_secs: u64) {
3431    let cache = guestbook_cache();
3432    let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
3433    let before = held.get(community_id);
3434    let generation = held.moved(community_id);
3435    if let Some((events, _)) = before {
3436        let mut events = std::sync::Arc::unwrap_or_clone(events);
3437        apply(&mut events);
3438        held.put(community_id, generation, (std::sync::Arc::new(events), cursor_secs));
3439    }
3440}
3441
3442/// What every Guestbook write moves on, once its write connection is let go.
3443fn guestbook_moved_on(community_id: &str) {
3444    let map = standing_cache();
3445    let mut cache = map.write().unwrap_or_else(|e| e.into_inner());
3446    let entry = cache.entry(community_id.to_string()).or_insert((0, None));
3447    *entry = (entry.0 + 1, None);
3448    drop(cache);
3449    bump_membership_generation();
3450}
3451
3452#[cfg(test)]
3453mod tests {
3454    use super::*;
3455
3456    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3457
3458    /// A unique, syntactically-valid test npub per call (bech32 charset, correct
3459    /// length). Uniqueness isolates each test's account DB so state can't bleed.
3460    fn make_test_npub(n: u32) -> String {
3461        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
3462        let mut payload = vec![b'q'; 58];
3463        let mut x = n as u64;
3464        let mut i = 58;
3465        while x > 0 && i > 0 {
3466            i -= 1;
3467            payload[i] = BECH32[(x as usize) % 32];
3468            x /= 32;
3469        }
3470        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
3471    }
3472
3473    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
3474        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3475        crate::db::close_database();
3476        // Per-account row-id caches survive close_database; clear them so a stale entry from a prior
3477        // test's DB can't point into this fresh account's DB and FK-fail an insert.
3478        crate::db::clear_id_caches();
3479        let tmp = tempfile::tempdir().unwrap();
3480        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3481        let account = make_test_npub(n);
3482        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
3483        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
3484        crate::db::set_current_account(account.clone()).unwrap();
3485        crate::db::init_database(&account).unwrap();
3486        (tmp, guard)
3487    }
3488
3489    #[test]
3490    fn a_channel_holds_its_newest_dated_wraps_up_to_the_cap() {
3491        let (_tmp, _guard) = init_test_db();
3492        let (cid, ch) = ("c".repeat(64), "d".repeat(64));
3493        for i in 0..MAX_HELD_WRAPS + 2 {
3494            hold_wrap(&cid, &ch, &format!("{i:064x}"), &format!("wrap {i}"), "", 1_000 + i as u64).unwrap();
3495        }
3496        hold_wrap(&cid, &"e".repeat(64), &"f".repeat(64), "another channel's", "", 1).unwrap();
3497        let held = held_wraps(&cid).unwrap();
3498        assert_eq!(held.len(), MAX_HELD_WRAPS + 1, "each channel caps on its own");
3499        assert!(!held.iter().any(|(id, ..)| *id == format!("{:064x}", 0) || *id == format!("{:064x}", 1)), "the oldest-dated go first");
3500        assert!(held.iter().any(|(_, _, wrap)| wrap == "wrap 501"), "opened as it was held");
3501        hold_wrap(&cid, &ch, &format!("{:064x}", 501), "again", "", 1).unwrap();
3502        assert_eq!(held_wraps(&cid).unwrap().iter().filter(|(id, ..)| *id == format!("{:064x}", 501)).count(), 1, "once");
3503        release_held_wrap(&format!("{:064x}", 501)).unwrap();
3504        assert!(held_wrap_ids(&[format!("{:064x}", 501), format!("{:064x}", 500)]) == std::collections::HashSet::from([format!("{:064x}", 500)]));
3505    }
3506
3507    /// An unsaved v2 community fresh from genesis, holding one Public `#general` channel.
3508    fn v2_fixture(name: &str, relays: &[&str]) -> crate::community::v2::community::CommunityV2 {
3509        let owner = Keys::generate();
3510        let g = crate::community::v2::control::genesis(
3511            &owner,
3512            crate::community::v2::control::CommunityMetadata { name: name.into(), ..Default::default() },
3513            1_000,
3514        )
3515        .unwrap();
3516        let relays = relays.iter().map(|r| r.to_string()).collect();
3517        crate::community::v2::community::CommunityV2::from_genesis(&g, name, None, relays, 1_000)
3518    }
3519
3520    /// A saved v2 community with the hex ids of it and its `#general` channel.
3521    /// A bundle this build can join, named `name`.
3522    fn v2_bundle(name: &str) -> String {
3523        let bundle = crate::community::v2::service::bundle_of(
3524            &v2_fixture(name, &["wss://r"]),
3525            crate::community::v2::service::BundleAudience::Link,
3526            None,
3527            None,
3528            None,
3529        );
3530        serde_json::to_string(&bundle).unwrap()
3531    }
3532
3533    fn saved_v2(name: &str) -> (crate::community::v2::community::CommunityV2, String, String) {
3534        let c = v2_fixture(name, &["wss://r"]);
3535        save_community_v2(&c).unwrap();
3536        let (cid, ch) = (c.id().to_hex(), c.channels[0].id.to_hex());
3537        (c, cid, ch)
3538    }
3539
3540    /// A Private channel holding its own key, to sit beside `#general`.
3541    fn private_channel(id: u8, key: u8) -> crate::community::v2::community::ChannelV2 {
3542        crate::community::v2::community::ChannelV2 {
3543            id: ChannelId([id; 32]),
3544            name: "staff".into(),
3545            private: true,
3546            key: Some([key; 32]),
3547            epoch: Epoch(0),
3548            voice: None,
3549            meta_custom: None,
3550            meta_extra: Default::default(),
3551            writers: None,
3552            sealed: None,
3553        }
3554    }
3555
3556    /// A saved v2 community with its root and a Private channel's key archived, as the
3557    /// service leaves one. Returns it with the hex ids of it and the Private channel.
3558    fn archived_v2() -> (crate::community::v2::community::CommunityV2, String, String) {
3559        let mut c = v2_fixture("HQ", &["r1"]);
3560        c.channels.push(private_channel(0x61, 0x62));
3561        save_community_v2(&c).unwrap();
3562        let (cid, private) = (c.id().to_hex(), c.channels[1].id.to_hex());
3563        store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
3564        store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
3565        (c, cid, private)
3566    }
3567
3568    fn encrypted_community_with_messages(n: usize) -> String {
3569        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
3570        crate::state::set_encryption_enabled(true);
3571        let (_, cid, ch) = saved_v2("HQ");
3572        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
3573        for i in 0..n {
3574            let msg = crate::types::Message {
3575                id: format!("{i:064x}"),
3576                content: format!("message number {i}, a few words long"),
3577                at: 1_700_000_000_000 + i as u64 * 1000,
3578                npub: Some(make_test_npub(i as u32 % 7)),
3579                ..Default::default()
3580            };
3581            rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
3582        }
3583        cid
3584    }
3585
3586    #[test]
3587    fn the_policy_window_and_recent_texts_open_sealed_rows() {
3588        let (_tmp, _guard) = init_test_db();
3589        struct Vault;
3590        impl Drop for Vault {
3591            fn drop(&mut self) {
3592                crate::state::set_encryption_enabled(false);
3593                crate::state::ENCRYPTION_KEY.clear(&[]);
3594            }
3595        }
3596        let _vault = Vault;
3597        let cid = encrypted_community_with_messages(5);
3598        let stored: String = crate::db::get_db_connection_guard_static()
3599            .unwrap()
3600            .query_row("SELECT content FROM events WHERE content != '' LIMIT 1", [], |r| r.get(0))
3601            .unwrap();
3602        assert!(crate::crypto::looks_encrypted(&stored), "the rows read back are sealed on disk");
3603        let window = community_policy_messages(&cid, 100).unwrap();
3604        assert_eq!(window.len(), 5);
3605        assert_eq!(window[0].text, "message number 0, a few words long");
3606        let recent = community_recent_texts(&cid, 100).unwrap();
3607        assert_eq!(recent[0].2, "message number 4, a few words long");
3608    }
3609
3610    #[test]
3611    fn an_authority_floor_takes_a_squatted_coordinate_and_keeps_it() {
3612        let (_tmp, _guard) = init_test_db();
3613        let (cid, entity) = ("f".repeat(64), "a".repeat(64));
3614        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();
3615        let held = || (get_edition_head(&cid, &entity).unwrap().unwrap(), edition_head_families(&cid).unwrap().get(&entity).cloned());
3616        head(50, 0xC0, FLOOR_CONTROL);
3617        head(1, 0xA1, FLOOR_AUTHORITY);
3618        assert_eq!(held(), ((1, [0xA1; 32]), Some("a".into())), "an authority head replaces a control row at any version");
3619        head(99, 0xC1, FLOOR_CONTROL);
3620        assert_eq!(held().0, (1, [0xA1; 32]), "a control head never takes it back");
3621        converge_family_head_at_epoch(&cid, &entity, 1, &[0xC2; 32], &[0xC2; 32], &[0xC2; 32], 0, Some(FLOOR_CONTROL)).unwrap();
3622        assert_eq!(held().0, (1, [0xA1; 32]), "nor converges it");
3623        rebase_edition_head_at_epoch(&cid, &entity, 0, &[0xC3; 32], &[0xC3; 32], &[0xC3; 32], 0, FLOOR_CONTROL).unwrap();
3624        assert_eq!(held().0, (1, [0xA1; 32]), "nor moves it down");
3625        head(1, 0xA0, FLOOR_AUTHORITY);
3626        assert_eq!(held().0, (1, [0xA1; 32]), "within the family the version still only advances");
3627        head(2, 0xA2, FLOOR_AUTHORITY);
3628        assert_eq!(held().0, (2, [0xA2; 32]));
3629    }
3630
3631    #[test]
3632    fn edition_head_round_trips_and_upserts() {
3633        let (_tmp, _guard) = init_test_db();
3634        let cid = "f".repeat(64);
3635        let entity = "a".repeat(64);
3636
3637        // No head yet → None (the next edition is genesis v1).
3638        assert_eq!(get_edition_head(&cid, &entity).unwrap(), None);
3639
3640        // Set v1, read it back exactly.
3641        let h1 = [0x11u8; 32];
3642        set_edition_head(&cid, &entity, 1, &h1).unwrap();
3643        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((1, h1)));
3644
3645        // Upsert to v2 — the head advances in place (one row per (community, entity)).
3646        let h2 = [0x22u8; 32];
3647        set_edition_head(&cid, &entity, 2, &h2).unwrap();
3648        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)));
3649
3650        // MONOTONIC: a lower-or-equal version write is a no-op — the refuse-downgrade floor never
3651        // rolls back, even against a stale or hostile rollback attempt.
3652        set_edition_head(&cid, &entity, 1, &[0xEEu8; 32]).unwrap();
3653        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "rollback to v1 ignored");
3654        set_edition_head(&cid, &entity, 2, &[0xEEu8; 32]).unwrap();
3655        assert_eq!(get_edition_head(&cid, &entity).unwrap(), Some((2, h2)), "equal version is a no-op too");
3656
3657        // A different entity is tracked independently.
3658        let other = "b".repeat(64);
3659        assert_eq!(get_edition_head(&cid, &other).unwrap(), None);
3660    }
3661
3662    #[test]
3663    fn a_floor_written_before_families_still_advances() {
3664        // A row from before floors recorded their family holds NULL there, and `= 'a'` on NULL
3665        // made the whole guard NULL: the row never moved, so every edit was re-minted at v2.
3666        let (_tmp, _guard) = init_test_db();
3667        let (cid, entity) = ("c".repeat(64), "e".repeat(64));
3668        set_edition_head(&cid, &entity, 1, &[0x11; 32]).unwrap();
3669        assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&entity].5, None, "a familyless row");
3670        set_family_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
3671        let f = get_all_edition_heads_full(&cid).unwrap()[&entity];
3672        assert_eq!((f.1, f.2, f.5), (2, [0x22; 32], Some(FloorFamily::of(FLOOR_CONTROL))), "it advances, and takes the family");
3673        // An authority row still refuses a control write over it.
3674        set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 1, &[0x33; 32], &[0x03; 32], &[0xA1; 32], 0, FLOOR_AUTHORITY).unwrap();
3675        set_family_head_at_epoch(&cid, "a".repeat(64).as_str(), 2, &[0x44; 32], &[0x04; 32], &[0xA1; 32], 0, FLOOR_CONTROL).unwrap();
3676        assert_eq!(get_all_edition_heads_full(&cid).unwrap()[&"a".repeat(64)].1, 1);
3677    }
3678
3679    #[test]
3680    fn a_floor_keeps_the_author_of_the_head_it_holds() {
3681        let (_tmp, _guard) = init_test_db();
3682        let cid = "c".repeat(64);
3683        let entity = "e".repeat(64);
3684        let author = |b: u8| [b; 32];
3685        let held = |cid: &str| {
3686            let f = get_all_edition_heads_full(cid).unwrap()[&entity];
3687            (f.0, f.1, f.2, f.3, f.4)
3688        };
3689        set_edition_head_at_epoch(&cid, &entity, 1, &[0x11; 32], &[0x01; 32], &author(0xA1), 0).unwrap();
3690        set_edition_head_at_epoch(&cid, &entity, 2, &[0x22; 32], &[0x02; 32], &author(0xB2), 0).unwrap();
3691        assert_eq!(held(&cid), (0, 2, [0x22; 32], Some([0x02; 32]), Some(author(0xB2))), "an advance records its own author");
3692
3693        // Convergence is the caller's verdict: it replaces the held edition whatever the ids,
3694        // but only at the same version and epoch.
3695        converge_edition_head_at_epoch(&cid, &entity, 2, &[0x33; 32], &[0xFF; 32], &author(0xC3), 0).unwrap();
3696        assert_eq!(held(&cid), (0, 2, [0x33; 32], Some([0xFF; 32]), Some(author(0xC3))), "a higher id can win on authority");
3697        converge_edition_head_at_epoch(&cid, &entity, 3, &[0x44; 32], &[0x00; 32], &author(0xD4), 0).unwrap();
3698        converge_edition_head_at_epoch(&cid, &entity, 2, &[0x55; 32], &[0x00; 32], &author(0xE5), 1).unwrap();
3699        assert_eq!(held(&cid).2, [0x33; 32], "another version or epoch is never converged onto");
3700
3701        // A Refounding's advance into a new epoch takes the new head's author too.
3702        set_edition_head_at_epoch(&cid, &entity, 1, &[0x66; 32], &[0x06; 32], &author(0xF6), 1).unwrap();
3703        assert_eq!(held(&cid), (1, 1, [0x66; 32], Some([0x06; 32]), Some(author(0xF6))));
3704    }
3705
3706    #[test]
3707    fn guestbook_round_trips_events_and_cursor() {
3708        let (_tmp, _guard) = init_test_db();
3709        let member = nostr_sdk::prelude::Keys::generate();
3710        let ev = crate::community::v2::guestbook::GuestbookEvent { epoch: None, observed_at: None,
3711            rumor_id: [7u8; 32],
3712            entry: crate::community::v2::guestbook::GuestbookEntry::Join {
3713                member: member.public_key(),
3714                invited_by: Some(("creator".into(), "label".into())),
3715                at_ms: 1_000,
3716            },
3717        };
3718        let cid = "d".repeat(64);
3719        assert_eq!(get_guestbook(&cid).unwrap(), (Vec::new(), 0), "absent reads as empty at cursor 0");
3720        set_guestbook(&cid, std::slice::from_ref(&ev), 42).unwrap();
3721        let (events, cursor) = read_guestbook(&cid).unwrap();
3722        assert_eq!(events, vec![ev.clone()], "events round-trip through the encrypted blob");
3723        assert_eq!(cursor, 42);
3724        assert_eq!(get_guestbook(&cid).unwrap(), (vec![ev], 42), "and the cached read agrees");
3725    }
3726
3727    fn gb(b: u8, epoch: Option<u64>) -> crate::community::v2::guestbook::GuestbookEvent {
3728        crate::community::v2::guestbook::GuestbookEvent {
3729            rumor_id: [b; 32],
3730            entry: crate::community::v2::guestbook::GuestbookEntry::Join { member: nostr_sdk::prelude::Keys::generate().public_key(), invited_by: None, at_ms: b as u64 * 1000 },
3731            epoch,
3732            observed_at: Some(1_790_000_000 + b as u64),
3733        }
3734    }
3735
3736    #[test]
3737    fn a_guestbook_blob_moves_into_rows_in_order_and_once() {
3738        let (_tmp, _guard) = init_test_db();
3739        let cid = "f".repeat(64);
3740        let events: Vec<_> = [9u8, 3, 7, 1].iter().map(|&b| gb(b, Some(2))).collect();
3741        {
3742            let _seal = crate::crypto::gate::sealing();
3743            let conn = crate::db::get_write_connection_guard_static().unwrap();
3744            conn.execute(
3745                "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, ?2, 55)",
3746                params![cid, enc_txt(&serde_json::to_string(&events).unwrap()).unwrap()],
3747            )
3748            .unwrap();
3749        }
3750        assert_eq!(read_guestbook(&cid).unwrap(), (events.clone(), 55), "arrival order kept");
3751        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();
3752        assert!(blob.is_empty(), "the blob is moved out, not kept beside the rows");
3753        assert_eq!(read_guestbook(&cid).unwrap(), (events, 55), "and reads the same from rows");
3754    }
3755
3756    #[test]
3757    fn a_guestbook_blob_that_does_not_read_is_left_as_it_is() {
3758        let (_tmp, _guard) = init_test_db();
3759        let cid = "c".repeat(64);
3760        {
3761            let conn = crate::db::get_write_connection_guard_static().unwrap();
3762            conn.execute("INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, 'not json', 3)", params![cid]).unwrap();
3763        }
3764        assert_eq!(read_guestbook(&cid).unwrap(), (Vec::new(), 3));
3765        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();
3766        assert_eq!(blob, "not json", "nothing it couldn't read is thrown away");
3767    }
3768
3769    #[test]
3770    fn stored_guestbook_events_dedup_restamp_in_place_and_match_the_cache() {
3771        let (_tmp, _guard) = init_test_db();
3772        let cid = "b".repeat(64);
3773        let (a, b, c) = (gb(1, None), gb(2, Some(1)), gb(3, Some(1)));
3774        store_guestbook_events(&cid, &[a.clone(), b.clone()], 10).unwrap();
3775        assert_eq!(get_guestbook(&cid).unwrap().0, vec![a.clone(), b.clone()]);
3776        // The same rumor again changes nothing; a restamp takes its place in the order.
3777        let a2 = crate::community::v2::guestbook::GuestbookEvent { epoch: Some(4), ..a.clone() };
3778        store_guestbook_events(&cid, &[b.clone(), a2.clone(), c.clone()], 20).unwrap();
3779        let want = (vec![a2, b, c], 20);
3780        assert_eq!(get_guestbook(&cid).unwrap(), want, "the cached copy");
3781        assert_eq!(read_guestbook(&cid).unwrap(), want, "the rows");
3782        let rows: i64 = crate::db::get_db_connection_guard_static().unwrap().query_row("SELECT COUNT(*) FROM community_guestbook_events", [], |r| r.get(0)).unwrap();
3783        assert_eq!(rows, 3);
3784        // A whole replace leaves exactly what it was given.
3785        set_guestbook(&cid, &[want.0[2].clone()], 30).unwrap();
3786        assert_eq!(read_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
3787        assert_eq!(get_guestbook(&cid).unwrap(), (vec![want.0[2].clone()], 30));
3788    }
3789
3790    #[test]
3791    fn owed_departures_write_only_the_members_that_changed() {
3792        let (_tmp, _guard) = init_test_db();
3793        let cid = "e".repeat(64);
3794        let mut keys: Vec<PublicKey> = (0..3).map(|_| Keys::generate().public_key()).collect();
3795        keys.sort();
3796        let (a, b, c) = (keys[0], keys[1], keys[2]);
3797        let rows = || -> Vec<(i64, Vec<u8>)> {
3798            let conn = crate::db::get_db_connection_guard_static().unwrap();
3799            let mut stmt = conn.prepare("SELECT seq, body FROM community_departures_seen ORDER BY seq").unwrap();
3800            stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(|r| r.unwrap()).collect()
3801        };
3802        let stored = || {
3803            departures_seen_cache().lock().unwrap().moved(&cid);
3804            (*departures_seen(&cid).unwrap().spans).clone()
3805        };
3806        let first: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true)].into())].into_iter().collect();
3807        set_departures_seen(&cid, std::sync::Arc::new(first.clone())).unwrap();
3808        assert_eq!(stored(), first);
3809        let before = rows();
3810        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();
3811        set_departures_seen(&cid, std::sync::Arc::new(second.clone())).unwrap();
3812        let after = rows();
3813        assert_eq!(after.len(), 3);
3814        assert_eq!(after[0], before[0], "an unchanged member's row is left alone");
3815        assert_eq!(after[1].0, before[1].0, "a changed member keeps its row");
3816        assert_ne!(after[1].1, before[1].1);
3817        assert_eq!(stored(), second);
3818        let third: DepartureSpans = [(c, vec![(7, None, false)].into())].into_iter().collect();
3819        set_departures_seen(&cid, std::sync::Arc::new(third.clone())).unwrap();
3820        assert_eq!(rows().iter().map(|r| r.0).collect::<Vec<_>>(), vec![after[2].0], "a member with no spans left goes");
3821        assert_eq!(stored(), third);
3822        let fourth: DepartureSpans = [(a, vec![(5, Some(9), false)].into())].into_iter().collect();
3823        set_departures_seen(&cid, std::sync::Arc::new(fourth.clone())).unwrap();
3824        assert_eq!(rows().len(), 1, "and one after every member written");
3825        assert_eq!(stored(), fourth);
3826        delete_community(&cid).unwrap();
3827        assert!(departures_seen(&cid).unwrap().spans.is_empty());
3828        assert!(rows().is_empty());
3829    }
3830
3831    #[test]
3832    fn owed_departures_kept_in_settings_move_into_sealed_rows() {
3833        let (_tmp, _guard) = init_test_db();
3834        crate::state::ENCRYPTION_KEY.set([0x37u8; 32], &[]);
3835        crate::state::set_encryption_enabled(true);
3836        let cid = "f".repeat(64);
3837        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
3838        let json = format!(r#"{{"{}":[[5,9,false]],"{}":[[1,null,true],[12,20,false]]}}"#, a.to_hex(), b.to_hex());
3839        super::super::settings::set_sql_setting(format!("departures_seen:{cid}"), json).unwrap();
3840        let want: DepartureSpans = [(a, vec![(5, Some(9), false)].into()), (b, vec![(1, None, true), (12, Some(20), false)].into())].into_iter().collect();
3841        assert_eq!(*departures_seen(&cid).unwrap().spans, want);
3842        assert_eq!(super::super::settings::get_sql_setting(format!("departures_seen:{cid}")).unwrap(), None);
3843        let bodies: Vec<Vec<u8>> = {
3844            let conn = crate::db::get_db_connection_guard_static().unwrap();
3845            let mut stmt = conn.prepare("SELECT body FROM community_departures_seen").unwrap();
3846            stmt.query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect()
3847        };
3848        assert_eq!(bodies.len(), 2);
3849        for body in &bodies {
3850            assert!(!body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes()), "who left is never stored in the clear");
3851        }
3852        departures_seen_cache().lock().unwrap().moved(&cid);
3853        assert_eq!(*departures_seen(&cid).unwrap().spans, want, "read back from the sealed rows");
3854        crate::state::set_encryption_enabled(false);
3855    }
3856
3857    #[test]
3858    fn a_folds_floor_writes_skip_only_what_is_already_stored() {
3859        let (_tmp, _guard) = init_test_db();
3860        let cid = "c".repeat(64);
3861        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));
3862        let (h4, h5, a) = ([4u8; 32], [5u8; 32], [9u8; 32]);
3863        set_family_head_at_epoch(&cid, "e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL).unwrap();
3864        set_family_head_at_epoch(&cid, "e2", 3, &h5, &[8; 32], &a, 2, FLOOR_AUTHORITY).unwrap();
3865        write_folded_heads(&cid, |w| {
3866            // Stepped down, then the very head the transaction found: it is written again.
3867            w.rebase("e1", 4, &h4, &[6; 32], &a, 2, FLOOR_CONTROL)?;
3868            w.set("e1", 5, &h5, &[7; 32], &a, 2, FLOOR_CONTROL)?;
3869            // A same-version rival with a lower id is no copy of what is held.
3870            w.converge("e2", 3, &h5, &[1; 32], &a, 2, FLOOR_AUTHORITY)
3871        })
3872        .unwrap();
3873        assert_eq!(row("e1"), Some((2, 5, h5, Some([7; 32]), Some(a))));
3874        assert_eq!(row("e2"), Some((2, 3, h5, Some([1; 32]), Some(a))));
3875        // Nothing lands from a fold whose writes fail part way.
3876        let failed = write_folded_heads(&cid, |w| {
3877            w.set("e3", 1, &h4, &[2; 32], &a, 2, FLOOR_CONTROL)?;
3878            Err("cut short".into())
3879        });
3880        assert!(failed.is_err());
3881        assert_eq!(row("e3"), None);
3882    }
3883
3884    #[test]
3885    fn a_member_list_reads_posts_through_indexes_not_a_scan() {
3886        let (_tmp, _guard) = init_test_db();
3887        let conn = crate::db::get_db_connection_guard_static().unwrap();
3888        let plan = |sql: &str| -> String {
3889            let mut stmt = conn.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
3890            let binds = vec![1i64; stmt.parameter_count()];
3891            stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get::<_, String>(3)).unwrap().map(|r| r.unwrap()).collect::<Vec<_>>().join(" | ") + " "
3892        };
3893        let held = plan(&flagged_sql("?, ?", false));
3894        assert!(held.contains("USING INDEX idx_events_unauthorized ") && !held.contains("writer"), "{held}");
3895        let strict = plan(&flagged_sql("?, ?", true));
3896        assert!(strict.contains("USING INDEX idx_events_unauthorized ") && strict.contains("USING INDEX idx_events_writer_post "), "{strict}");
3897        let activity = plan(&activity_sql("?, ?"));
3898        assert!(activity.contains("idx_events_chat_kind_npub") && !activity.contains("TEMP B-TREE"), "{activity}");
3899    }
3900
3901    #[test]
3902    fn an_owed_author_take_back_widens_narrows_and_settles_as_it_did_in_settings() {
3903        let (_tmp, _guard) = init_test_db();
3904        let (cid, chan) = ("a".repeat(64), "c".repeat(64));
3905        let author = Keys::generate().public_key().to_hex();
3906        let owed = || owed_author_retractions(&cid).unwrap();
3907        owe_author_retraction(&cid, &chan, &author, 10, None).unwrap();
3908        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, None, 1)]);
3909        owe_author_retraction(&cid, &chan, &author, 10, Some(20)).unwrap();
3910        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(20), 2)], "the same span closing narrows its own owe");
3911        owe_author_retraction(&cid, &chan, &author, 15, Some(30)).unwrap();
3912        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 10, Some(30), 3)]);
3913        owe_author_retraction(&cid, &chan, &author, 5, None).unwrap();
3914        assert_eq!(owed(), vec![(chan.clone(), author.clone(), 5, None, 4)], "any other range widens it");
3915        settle_author_retraction(&cid, &chan, &author, 5, None, 3).unwrap();
3916        assert_eq!(owed().len(), 1, "more was owed since it was read");
3917        settle_author_retraction(&cid, &chan, &author, 5, None, 4).unwrap();
3918        assert!(owed().is_empty());
3919        let other = Keys::generate().public_key().to_hex();
3920        owe_author_retraction(&cid, &chan, &author, 1, None).unwrap();
3921        owe_author_retraction(&cid, &"d".repeat(64), &other, 2, Some(3)).unwrap();
3922        assert_eq!(owed().len(), 2, "one row per author and Channel");
3923        delete_community(&cid).unwrap();
3924        assert!(owed().is_empty());
3925    }
3926
3927    #[test]
3928    fn owed_author_take_backs_kept_in_settings_move_into_sealed_rows() {
3929        let (_tmp, _guard) = init_test_db();
3930        crate::state::ENCRYPTION_KEY.set([0x41u8; 32], &[]);
3931        crate::state::set_encryption_enabled(true);
3932        let (cid, elsewhere, chan) = ("a".repeat(64), "b".repeat(64), "c".repeat(64));
3933        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
3934        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();
3935        legacy(&cid, &a, "7:3:");
3936        legacy(&cid, &b, "4:1:9");
3937        legacy(&elsewhere, &a, "1:1:");
3938        let mut want = vec![(chan.clone(), a.to_hex(), 7, None, 3), (chan.clone(), b.to_hex(), 4, Some(9), 1)];
3939        want.sort();
3940        assert_eq!(owed_author_retractions(&cid).unwrap(), want);
3941        let conn = crate::db::get_db_connection_guard_static().unwrap();
3942        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();
3943        assert_eq!(left, vec![format!("writer_retract_by:{elsewhere}:{chan}:{}", a.to_hex())], "another community's rows wait for their own read");
3944        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();
3945        drop(conn);
3946        assert_eq!(bodies.len(), 2);
3947        for body in &bodies {
3948            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");
3949        }
3950        // Owing and settling an author still kept in settings goes through the moved row.
3951        legacy(&elsewhere, &b, "2:5:");
3952        owe_author_retraction(&elsewhere, &chan, &b.to_hex(), 1, None).unwrap();
3953        settle_author_retraction(&elsewhere, &chan, &a.to_hex(), 1, None, 1).unwrap();
3954        assert_eq!(owed_author_retractions(&elsewhere).unwrap(), vec![(chan.clone(), b.to_hex(), 1, None, 6)]);
3955        let conn = crate::db::get_db_connection_guard_static().unwrap();
3956        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();
3957        assert!(bodies.iter().all(|body| !body.windows(32).any(|w| w == a.as_bytes() || w == b.as_bytes())), "nor once owed again");
3958        drop(conn);
3959        crate::state::set_encryption_enabled(false);
3960    }
3961
3962    #[test]
3963    fn an_owed_author_body_round_trips_and_refuses_what_it_did_not_write() {
3964        let author = [7u8; 32];
3965        for (since, generation, until) in [(0, 0, None), (1, 2, Some(3)), (u64::MAX, u64::MAX, Some(u64::MAX))] {
3966            let body = author_owed_body(&author, since, generation, until);
3967            assert_ne!(body.len(), 32);
3968            assert_eq!(author_owed_from_body(&body), Some((author, since, generation, until)));
3969            let mut longer = body.clone();
3970            longer.push(0);
3971            assert_eq!(author_owed_from_body(&longer), None, "no trailing bytes");
3972            assert_eq!(author_owed_from_body(&body[..body.len() - 1]), None, "no cut body");
3973        }
3974        let mut flags = author_owed_body(&author, 1, 1, None);
3975        *flags.last_mut().unwrap() = 2;
3976        assert_eq!(author_owed_from_body(&flags), None, "unknown flags");
3977        let mut format = author_owed_body(&author, 1, 1, None);
3978        format[0] = 2;
3979        assert_eq!(author_owed_from_body(&format), None);
3980    }
3981
3982    #[test]
3983    fn an_owed_departure_body_round_trips_and_refuses_what_it_did_not_write() {
3984        let member = Keys::generate().public_key();
3985        for spans in [vec![], vec![(0, None, false)], vec![(1, Some(2), true), (u64::MAX, Some(u64::MAX), false), (300, None, true)]] {
3986            let body = departure_body(&member, &spans);
3987            assert_ne!(body.len(), 32);
3988            assert_eq!(departure_from_body(&body), Some((member, spans.clone())));
3989            let mut longer = body.clone();
3990            longer.push(0);
3991            assert_eq!(departure_from_body(&longer), None, "no trailing bytes");
3992            assert_eq!(departure_from_body(&body[..body.len() - 1]), None, "no cut body");
3993        }
3994        let mut forged = departure_body(&member, &[(1, None, false)]);
3995        forged[33] = 0x7f;
3996        assert_eq!(departure_from_body(&forged), None, "a count beyond the body");
3997        let mut flags = departure_body(&member, &[(1, None, false)]);
3998        flags[34] = 0b100;
3999        assert_eq!(departure_from_body(&flags), None, "unknown flags");
4000        let mut format = departure_body(&member, &[]);
4001        format[0] = 2;
4002        assert_eq!(departure_from_body(&format), None);
4003    }
4004
4005    #[test]
4006    fn guestbook_rows_are_sealed_at_rest() {
4007        let (_tmp, _guard) = init_test_db();
4008        crate::state::ENCRYPTION_KEY.set([0x31u8; 32], &[]);
4009        crate::state::set_encryption_enabled(true);
4010        let cid = "d".repeat(64);
4011        let ev = gb(5, Some(1));
4012        store_guestbook_events(&cid, std::slice::from_ref(&ev), 1).unwrap();
4013        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();
4014        assert_ne!(body, crate::community::v2::guestbook::event_body(&ev), "not stored in the clear");
4015        assert_eq!(read_guestbook(&cid).unwrap().0, vec![ev]);
4016        crate::state::set_encryption_enabled(false);
4017        crate::state::ENCRYPTION_KEY.clear(&[]);
4018    }
4019
4020    #[test]
4021    fn a_guestbook_read_overlapping_a_write_is_never_served_after_it() {
4022        let (_tmp, _guard) = init_test_db();
4023        let ev = |b: u8| crate::community::v2::guestbook::GuestbookEvent {
4024            epoch: None,
4025            observed_at: None,
4026            rumor_id: [b; 32],
4027            entry: crate::community::v2::guestbook::GuestbookEntry::Leave { member: nostr_sdk::prelude::Keys::generate().public_key(), at_ms: b as u64 },
4028        };
4029        let cid = "e".repeat(64);
4030        let (one, two) = (ev(1), ev(2));
4031        set_guestbook(&cid, std::slice::from_ref(&one), 1).unwrap();
4032        assert_eq!(get_guestbook(&cid).unwrap().0, vec![one.clone()]);
4033        // A read that began before the write below and finishes after it.
4034        let began_under = guestbook_cache().lock().unwrap().generation(&cid);
4035        set_guestbook(&cid, &[one.clone(), two.clone()], 2).unwrap();
4036        guestbook_cache().lock().unwrap().put(&cid, began_under, (std::sync::Arc::new(Guestbook::new(vec![one.clone()])), 1));
4037        assert_eq!(get_guestbook(&cid).unwrap(), (vec![one, two], 2), "the write stands over the late read");
4038    }
4039
4040    #[test]
4041    fn v2_images_round_trip_and_read_as_community_images() {
4042        let (_tmp, _guard) = init_test_db();
4043        let owner = nostr_sdk::prelude::Keys::generate();
4044        let g = crate::community::v2::control::genesis(
4045            &owner,
4046            crate::community::v2::control::CommunityMetadata { name: "Icons".into(), ..Default::default() },
4047            1_000,
4048        )
4049        .unwrap();
4050        let mut c = crate::community::v2::community::CommunityV2::from_genesis(&g, "Icons", None, vec!["wss://r".into()], 1_000);
4051        let mut extra = serde_json::Map::new();
4052        extra.insert("ext".into(), serde_json::Value::String("webp".into()));
4053        c.icon = Some(crate::community::v2::control::ImageRef {
4054            url: "https://blossom.example/abc".into(),
4055            key: "0".repeat(64),
4056            nonce: "1".repeat(32),
4057            hash: "a".repeat(64),
4058            extra,
4059        });
4060        c.meta_custom = Some({
4061            let mut m = serde_json::Map::new();
4062            m.insert("k".into(), serde_json::Value::from("v"));
4063            m
4064        });
4065        c.channels[0].voice = Some(true);
4066        c.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
4067        save_community_v2(&c).unwrap();
4068
4069        // The v2 loader round-trips the ImageRef exactly (extra included).
4070        let re = load_community_v2(c.id()).unwrap().unwrap();
4071        assert_eq!(re.icon, c.icon);
4072        assert_eq!(re.banner, None);
4073        // The CORD-02 §6 stash survives the encrypted envelope columns.
4074        assert_eq!(re.meta_custom, c.meta_custom);
4075        assert_eq!(re.channels[0].voice, Some(true));
4076        assert_eq!(re.channels[0].meta_extra.get("vnd"), Some(&serde_json::Value::from(7)));
4077
4078        // The stored JSON parses as a CommunityImage (`ext` from the flattened extra),
4079        // so `community_image` serves it from the column alone.
4080        let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
4081        let img = community_image(&cid, false).unwrap().expect("the v2 icon reads as a CommunityImage");
4082        assert_eq!(img.url, "https://blossom.example/abc");
4083        assert_eq!(img.ext, "webp");
4084        assert_eq!(img.hash, "a".repeat(64));
4085        assert_eq!(community_image(&cid, true).unwrap(), None);
4086        assert_eq!(community_image(&"cd".repeat(32), false).unwrap(), None);
4087    }
4088
4089    #[test]
4090    fn column_reads_and_the_owner_check_serve_a_v2_community() {
4091        use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
4092        use crate::community::moderation::is_owner_or_admin;
4093        let (_tmp, _guard) = init_test_db();
4094        let owner = nostr_sdk::prelude::Keys::generate();
4095        let g = crate::community::v2::control::genesis(
4096            &owner,
4097            crate::community::v2::control::CommunityMetadata { name: "Two".into(), ..Default::default() },
4098            1_000,
4099        )
4100        .unwrap();
4101        let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Two", None, vec!["wss://two".into()], 1_000);
4102        save_community_v2(&v2).unwrap();
4103        let mut other = v2_fixture("One", &["wss://one"]);
4104        other.channels.push(private_channel(0x71, 0x72));
4105        save_community_v2(&other).unwrap();
4106
4107        crate::db::get_write_connection_guard_static()
4108            .unwrap()
4109            .execute(
4110                "INSERT INTO community_channels (channel_id, community_id, channel_key, epoch, name, created_at)
4111                 VALUES (?1, ?2, x'00', 0, 'c', 1)",
4112                params!["ee".repeat(32), "ff".repeat(32)],
4113            )
4114            .unwrap();
4115        let channels = held_channel_ids().unwrap();
4116        assert!(!channels.contains(&"ee".repeat(32)), "a channel whose community is gone is not held");
4117        assert!(channels.contains(&crate::simd::hex::bytes_to_hex_32(&v2.channels[0].id.0)));
4118        assert!(other.channels.iter().all(|ch| channels.contains(&ch.id.to_hex())));
4119        assert_eq!(channels.len(), other.channels.len() + v2.channels.len());
4120        let relays = held_community_relays().unwrap();
4121        assert!(relays.contains("wss://two") && relays.contains("wss://one"));
4122
4123        let cid = crate::simd::hex::bytes_to_hex_32(&v2.id().0);
4124        let (admin, social, stranger) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
4125        let role = |id: &str, perms: u64| Role {
4126            role_id: id.repeat(32), name: id.into(), position: 1, permissions: Permissions(perms),
4127            scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
4128        };
4129        let roles = CommunityRoles {
4130            roles: vec![role("aa", Permissions::ADMIN_ALL), role("bb", 0)],
4131            grants: vec![
4132                MemberGrant { member: admin.to_hex(), role_ids: vec!["aa".repeat(32)] },
4133                MemberGrant { member: social.to_hex(), role_ids: vec!["bb".repeat(32)] },
4134            ],
4135            everyone: None,
4136            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
4137        };
4138        set_community_roles(&cid, &roles, 1).unwrap();
4139        assert!(is_owner_or_admin(&cid, &owner.public_key().to_hex()), "a v2 owner proves itself from the id");
4140        assert!(is_owner_or_admin(&cid, &admin.to_hex()));
4141        assert!(!is_owner_or_admin(&cid, &social.to_hex()), "a role without management is not admin");
4142        assert!(!is_owner_or_admin(&cid, &stranger.to_hex()));
4143        assert!(!is_owner_or_admin(&"cd".repeat(32), &owner.public_key().to_hex()));
4144    }
4145
4146    #[test]
4147    fn epoch_key_archive_retains_every_epoch() {
4148        // a member who lived through a rotation must keep OLD epoch keys. Storing a new
4149        // epoch's key must NOT clobber a prior one (the data-loss bug the archive fixes).
4150        let (_tmp, _guard) = init_test_db();
4151        let cid = "f".repeat(64);
4152        let scope = "a".repeat(64);
4153
4154        store_epoch_key(&cid, &scope, 0, &[0xA0u8; 32]).unwrap();
4155        store_epoch_key(&cid, &scope, 1, &[0xA1u8; 32]).unwrap();
4156        store_epoch_key(&cid, &scope, 2, &[0xA2u8; 32]).unwrap();
4157
4158        let held = held_epoch_keys(&cid, &scope).unwrap();
4159        assert_eq!(held.len(), 3, "all three epoch keys retained");
4160        assert_eq!(held[0], (Epoch(0), [0xA0u8; 32]));
4161        assert_eq!(held[1], (Epoch(1), [0xA1u8; 32]));
4162        assert_eq!(held[2], (Epoch(2), [0xA2u8; 32]));
4163
4164        // Point lookup by epoch (what the open path uses to select a decryption key).
4165        assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xA1u8; 32]));
4166        assert_eq!(held_epoch_key(&cid, &scope, 9).unwrap(), None, "unheld epoch is None");
4167
4168        // Same coordinate REPLACE = fork-resolution committing a winning key (only legit overwrite).
4169        store_epoch_key(&cid, &scope, 1, &[0xBBu8; 32]).unwrap();
4170        assert_eq!(held_epoch_key(&cid, &scope, 1).unwrap(), Some([0xBBu8; 32]));
4171        assert_eq!(held_epoch_keys(&cid, &scope).unwrap().len(), 3, "replace didn't add a row");
4172
4173        // A different scope is isolated (server-root vs a channel share the table, never collide) —
4174        // at both the list AND the point-lookup level.
4175        assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
4176        assert_eq!(
4177            held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap(),
4178            None,
4179            "epoch 1 under a different scope is not the channel's key"
4180        );
4181    }
4182
4183    #[test]
4184    fn at_rest_encryption_wraps_keys_and_metadata_on_disk() {
4185        let (_tmp, _guard) = init_test_db();
4186        // Local Encryption ON with a known vault key (the db-test guard serializes, so toggling these
4187        // globals is safe; reset at the end). `others: &[]` — the slice only allocates a vault lane.
4188        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4189        crate::state::set_encryption_enabled(true);
4190
4191        let mut c = v2_fixture("Secret HQ", &["wss://relay.example"]);
4192        c.community_root = [0x42u8; 32];
4193        c.description = Some("top secret".into());
4194        c.channels.push(private_channel(0x61, 0x62));
4195        save_community_v2(&c).unwrap();
4196        let cid = c.id().to_hex();
4197        store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &c.community_root).unwrap();
4198        set_community_banlist(&cid, &["deadbeef".repeat(8)], 1).unwrap();
4199
4200        // On disk: secrets are 60-byte ciphertext (12 nonce + 32 + 16 tag), NOT raw 32-byte keys;
4201        // identifying text is hex ciphertext, never the plaintext.
4202        {
4203            let conn = crate::db::get_db_connection_guard_static().unwrap();
4204            let (root_len, control_root_len, name, relays, description): (i64, i64, String, String, String) = conn
4205                .query_row(
4206                    "SELECT length(server_root_key), length(control_root), name, relays, description
4207                     FROM communities WHERE community_id = ?1",
4208                    params![cid],
4209                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
4210                )
4211                .unwrap();
4212            assert_eq!(root_len, 60, "server_root_key must be ciphertext, not a raw 32-byte key");
4213            assert_eq!(control_root_len, 60, "control_root must be ciphertext, not a raw 32-byte key");
4214            for (column, stored, plain) in [
4215                ("name", &name, "Secret HQ"),
4216                ("relays", &relays, r#"["wss://relay.example"]"#),
4217                ("description", &description, "top secret"),
4218            ] {
4219                assert_ne!(stored, plain, "{column} must not be plaintext on disk");
4220                assert!(crate::crypto::looks_encrypted(stored), "{column} column is ciphertext");
4221            }
4222            let (owner_pk, owner_salt, control_pk): (String, String, String) = conn
4223                .query_row(
4224                    "SELECT owner_pubkey, owner_salt, control_pk FROM communities WHERE community_id = ?1",
4225                    params![cid],
4226                    |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
4227                )
4228                .unwrap();
4229            for (column, stored, plain) in [
4230                ("owner_pubkey", &owner_pk, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_xonly)),
4231                ("owner_salt", &owner_salt, crate::simd::hex::bytes_to_hex_32(&c.identity.owner_salt)),
4232                ("control_pk", &control_pk, c.control_pk.unwrap().to_hex()),
4233            ] {
4234                assert_ne!(*stored, plain, "{column} must not be plaintext on disk");
4235                assert!(crate::crypto::looks_encrypted(stored), "{column} column is ciphertext");
4236            }
4237            let mut stmt = conn
4238                .prepare("SELECT length(channel_key), name FROM community_channels WHERE community_id = ?1")
4239                .unwrap();
4240            let channels: Vec<(i64, String)> =
4241                stmt.query_map(params![cid], |r| Ok((r.get(0)?, r.get(1)?))).unwrap().map(Result::unwrap).collect();
4242            assert_eq!(channels.len(), 2);
4243            for (key_len, name) in &channels {
4244                assert_eq!(*key_len, 60, "channel_key must be ciphertext, Public placeholder and Private key alike");
4245                assert!(crate::crypto::looks_encrypted(name) && name != "general" && name != "staff", "channel name is ciphertext");
4246            }
4247            // The banlist lives in `community_bans`, sealed; SQL filters are handed the opened list.
4248            let banned_npub: String = conn
4249                .query_row("SELECT npub FROM community_bans WHERE community_id = ?1 LIMIT 1", params![cid], |r| r.get(0))
4250                .unwrap();
4251            assert!(crate::crypto::looks_encrypted(&banned_npub), "who is banned is sealed on disk, got {banned_npub}");
4252            let opened = crate::crypto::maybe_decrypt_text(&banned_npub);
4253            assert!(opened.starts_with("npub1"), "and opens to the form `events.npub` uses");
4254            let key_len: i64 = conn
4255                .query_row(
4256                    "SELECT length(key) FROM community_epoch_keys WHERE community_id = ?1 LIMIT 1",
4257                    params![cid],
4258                    |r| r.get(0),
4259                )
4260                .unwrap();
4261            assert_eq!(key_len, 60, "epoch-archive key must be ciphertext");
4262        }
4263
4264        // In memory: load decrypts everything back to the originals.
4265        let loaded = load_community_v2(c.id()).unwrap().unwrap();
4266        assert_eq!(loaded.name, "Secret HQ");
4267        assert_eq!(loaded.description.as_deref(), Some("top secret"));
4268        assert_eq!(loaded.community_root, [0x42u8; 32]);
4269        assert_eq!(loaded.control_root, c.control_root);
4270        assert_eq!(loaded.control_pk, c.control_pk);
4271        assert_eq!(loaded.identity.owner_xonly, c.identity.owner_xonly);
4272        assert_eq!(loaded.identity.owner_salt, c.identity.owner_salt);
4273        assert_eq!(loaded.relays, vec!["wss://relay.example".to_string()]);
4274        assert_eq!(loaded.channels[0].name, "general");
4275        assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]));
4276        assert_eq!(held_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0).unwrap(), Some([0x42u8; 32]));
4277        assert_eq!(get_community_banlist(&cid).unwrap(), vec!["deadbeef".repeat(8)]);
4278
4279        crate::state::set_encryption_enabled(false);
4280        crate::state::ENCRYPTION_KEY.clear(&[]);
4281    }
4282
4283    #[test]
4284    fn an_encrypted_v2_community_loads_back_whole() {
4285        let (_tmp, _guard) = init_test_db();
4286        struct Vault;
4287        impl Drop for Vault {
4288            fn drop(&mut self) {
4289                crate::state::set_encryption_enabled(false);
4290                crate::state::ENCRYPTION_KEY.clear(&[]);
4291            }
4292        }
4293        let _vault = Vault;
4294        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4295        crate::state::set_encryption_enabled(true);
4296
4297        let owner = nostr_sdk::prelude::Keys::generate();
4298        let g = crate::community::v2::control::genesis(
4299            &owner,
4300            crate::community::v2::control::CommunityMetadata { name: "Sealed".into(), ..Default::default() },
4301            1_000,
4302        )
4303        .unwrap();
4304        let mut v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Sealed", Some("about".into()), vec!["wss://r".into()], 1_000);
4305        let mut private = v2.channels[0].clone();
4306        private.id = ChannelId([0x61; 32]);
4307        private.name = "staff".into();
4308        private.private = true;
4309        private.key = Some([0x62; 32]);
4310        v2.channels.push(private);
4311        save_community_v2(&v2).unwrap();
4312
4313        let name: String = crate::db::get_db_connection_guard_static()
4314            .unwrap()
4315            .query_row("SELECT name FROM communities WHERE community_id = ?1", params![v2.id().to_hex()], |r| r.get(0))
4316            .unwrap();
4317        assert!(crate::crypto::looks_encrypted(&name), "sealed on disk");
4318        let loaded = load_community_v2(v2.id()).unwrap().unwrap();
4319        assert_eq!(format!("{loaded:?}"), format!("{v2:?}"), "every field opens back to what was saved");
4320    }
4321
4322    #[test]
4323    fn at_rest_decrypt_tolerates_a_pre_migration_plaintext_row() {
4324        // A row written BEFORE the at-rest pass (raw key + plaintext text) must still read back once
4325        // encryption is on — the 32-vs-60 byte + `looks_encrypted` discriminators handle the mixed DB.
4326        let (_tmp, _guard) = init_test_db();
4327        crate::state::set_encryption_enabled(false);
4328        let mut c = v2_fixture("Legacy HQ", &[]);
4329        c.community_root = [0x42u8; 32];
4330        c.channels.push(private_channel(0x61, 0x62));
4331        save_community_v2(&c).unwrap();
4332
4333        crate::state::ENCRYPTION_KEY.set([0x55u8; 32], &[]);
4334        crate::state::set_encryption_enabled(true);
4335        let loaded = load_community_v2(c.id()).unwrap().unwrap();
4336        assert_eq!(loaded.name, "Legacy HQ", "plaintext name reads through");
4337        assert_eq!(loaded.community_root, [0x42u8; 32], "raw 32-byte key reads through");
4338        assert_eq!(loaded.control_root, c.control_root, "raw 32-byte control root reads through");
4339        assert_eq!(loaded.channels[1].key, Some([0x62u8; 32]), "raw 32-byte channel key reads through");
4340
4341        crate::state::set_encryption_enabled(false);
4342        crate::state::ENCRYPTION_KEY.clear(&[]);
4343    }
4344
4345    #[test]
4346    fn large_epoch_round_trips_losslessly() {
4347        // Epoch >= 2^63 stored as i64 then reinterpreted as u64 must be exact.
4348        let (_tmp, _guard) = init_test_db();
4349        let mut c = v2_fixture("HQ", &[]);
4350        c.root_epoch = Epoch(u64::MAX - 3);
4351        c.channels[0].epoch = Epoch(u64::MAX - 7);
4352        save_community_v2(&c).unwrap();
4353        let loaded = load_community_v2(c.id()).unwrap().unwrap();
4354        assert_eq!(loaded.root_epoch, Epoch(u64::MAX - 3));
4355        assert_eq!(loaded.channels[0].epoch, Epoch(u64::MAX - 7));
4356    }
4357
4358    #[test]
4359    fn malformed_channel_id_row_errors_not_corrupts() {
4360        // A corrupted (short/non-hex) channel_id must error on load, not silently
4361        // reconstruct a wrong-but-self-consistent id.
4362        let (_tmp, _guard) = init_test_db();
4363        let (c, cid, _) = saved_v2("HQ");
4364        {
4365            let conn = crate::db::get_write_connection_guard_static().unwrap();
4366            conn.execute(
4367                "INSERT OR REPLACE INTO community_channels
4368                    (channel_id, community_id, channel_key, epoch, name, created_at)
4369                 VALUES (?1, ?2, ?3, 0, 'bad', 0)",
4370                rusqlite::params!["zz_not_hex", cid, &[0u8; 32][..]],
4371            )
4372            .unwrap();
4373        }
4374        assert!(load_community_v2(c.id()).is_err(), "malformed id must error, not corrupt");
4375    }
4376
4377    #[test]
4378    fn message_key_store_take_round_trip() {
4379        let (_tmp, _guard) = init_test_db();
4380        let eph = Keys::generate();
4381        let relays = vec!["wss://r.one".to_string()];
4382        // Keyed by INNER message id; resolves to the OUTER event id + key + relays.
4383        store_message_key("inner_msg_id", "outer_evid", &eph, &relays).unwrap();
4384
4385        let (loaded, outer, r) = take_message_key("inner_msg_id").unwrap().expect("present");
4386        assert_eq!(
4387            loaded.secret_key().as_secret_bytes(),
4388            eph.secret_key().as_secret_bytes()
4389        );
4390        assert_eq!(outer, "outer_evid");
4391        assert_eq!(r, relays);
4392        // `take` is single-use: the row is removed.
4393        assert!(take_message_key("inner_msg_id").unwrap().is_none());
4394    }
4395
4396    #[test]
4397    fn missing_community_is_none() {
4398        let (_tmp, _guard) = init_test_db();
4399        let absent = CommunityId([0x33u8; 32]);
4400        assert!(load_community_v2(&absent).unwrap().is_none());
4401    }
4402
4403    #[test]
4404    fn list_ids_reflects_saved() {
4405        let (_tmp, _guard) = init_test_db();
4406        let (a, _, _) = saved_v2("A");
4407        let (b, _, _) = saved_v2("B");
4408        let ids = list_community_ids().unwrap();
4409        assert_eq!(ids.len(), 2);
4410        assert!(ids.contains(a.id()) && ids.contains(b.id()));
4411    }
4412
4413    #[test]
4414    fn delete_community_clears_all_local_state() {
4415        let (_tmp, _guard) = init_test_db();
4416        let (c, cid, private) = archived_v2();
4417        save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
4418        save_pending_invite(&"cd".repeat(32), "{}", "npub1x", 0).unwrap();
4419        set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
4420        assert!(!held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty());
4421        assert!(!held_epoch_keys(&cid, &private).unwrap().is_empty());
4422
4423        delete_community(&cid).unwrap();
4424        assert!(!community_exists(c.id()).unwrap());
4425        assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
4426        assert!(community_id_for_channel(&private).unwrap().is_none());
4427        assert!(list_public_invites(&cid).unwrap().is_empty());
4428        assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None, "edition heads cleared on delete");
4429        assert!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(), "epoch keys cleared on delete");
4430        assert!(held_epoch_keys(&cid, &private).unwrap().is_empty(), "channel epoch keys cleared on delete");
4431    }
4432
4433    #[test]
4434    fn delete_community_retain_keys_drops_state_but_keeps_epoch_keys() {
4435        // self-removal teardown: drop chat/membership/control state but KEEP the held epoch keys so a
4436        // later self-scrub of own past messages stays possible.
4437        let (_tmp, _guard) = init_test_db();
4438        let (c, cid, private) = archived_v2();
4439        save_public_invite(&"ab".repeat(32), &cid, "url", None, None).unwrap();
4440        set_edition_head(&cid, &"a".repeat(64), 3, &[0x11u8; 32]).unwrap();
4441
4442        let base_before = held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap();
4443        let chan_before = held_epoch_keys(&cid, &private).unwrap();
4444        assert!(!base_before.is_empty() && !chan_before.is_empty(), "base + channel keys archived");
4445
4446        delete_community_retain_keys(&cid).unwrap();
4447
4448        // State is gone.
4449        assert!(!community_exists(c.id()).unwrap());
4450        assert!(community_id_for_channel(&c.channels[0].id.to_hex()).unwrap().is_none());
4451        assert!(community_id_for_channel(&private).unwrap().is_none());
4452        assert!(list_public_invites(&cid).unwrap().is_empty());
4453        assert_eq!(get_edition_head(&cid, &"a".repeat(64)).unwrap(), None);
4454        // Epoch keys (base + channel, every epoch) survive intact.
4455        assert_eq!(held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(), base_before,
4456            "base epoch keys retained for self-scrub");
4457        assert_eq!(held_epoch_keys(&cid, &private).unwrap(), chan_before,
4458            "channel epoch keys retained for self-scrub");
4459    }
4460
4461    #[test]
4462    fn channel_resolves_to_owning_community() {
4463        let (_tmp, _guard) = init_test_db();
4464        let (_, cid, chan) = saved_v2("HQ");
4465        assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
4466        assert!(community_id_for_channel(&"ff".repeat(32)).unwrap().is_none());
4467    }
4468
4469    #[test]
4470    fn the_channel_cache_answers_in_bytes_and_hex_alike() {
4471        let (_tmp, _guard) = init_test_db();
4472        let (c, cid, chan) = saved_v2("Bytes");
4473        let ch = c.channels[0].id.0;
4474        // A miss fills the cache; the hit after it answers the same, in either form.
4475        assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
4476        assert_eq!(channel_community_cache().read().unwrap().get(&ch), Some(&c.id().0), "the miss filled the cache");
4477        assert_eq!(community_for_channel(&ch).unwrap(), Some(c.id().0));
4478        assert_eq!(community_id_for_channel(&chan).unwrap().as_deref(), Some(cid.as_str()));
4479        // Only the exact stored spelling resolves, cached or not.
4480        assert_eq!(community_id_for_channel(&chan.to_uppercase()).unwrap(), None);
4481        assert_eq!(community_for_channel(&[0xFF; 32]).unwrap(), None);
4482        assert!(channel_community_cache().read().unwrap().get(&[0xFF; 32]).is_none(), "a miss is never cached");
4483        // Deleting the community stops both forms resolving.
4484        delete_community_retain_keys(&cid).unwrap();
4485        assert_eq!(community_for_channel(&ch).unwrap(), None);
4486        assert_eq!(community_id_for_channel(&chan).unwrap(), None);
4487    }
4488
4489    #[test]
4490    fn communities_that_ban_nobody_share_one_empty_set() {
4491        let (_tmp, _guard) = init_test_db();
4492        let (a, a_hex, _) = saved_v2("Calm");
4493        let (b, b_hex, _) = saved_v2("Quiet");
4494        let (ea, eb) = (banned_set_of(&a.id().0), banned_set(&b_hex));
4495        assert!(ea.is_empty() && std::sync::Arc::ptr_eq(&ea, &eb), "every empty banlist is the one shared set");
4496
4497        let villain = Keys::generate().public_key();
4498        set_community_banlist(&a_hex, &[villain.to_hex()], 10).unwrap();
4499        assert!(is_author_banned(&a_hex, &villain) && is_author_banned_in(&a.id().0, &villain));
4500        assert!(!is_author_banned_in(&b.id().0, &villain), "a ban stays in its own community");
4501        assert!(!std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()));
4502
4503        set_community_banlist(&a_hex, &[], 11).unwrap();
4504        assert!(std::sync::Arc::ptr_eq(&banned_set_of(&a.id().0), &empty_ban_set()), "an emptied banlist returns to the shared set");
4505        assert!(!is_author_banned_in(&a.id().0, &villain));
4506    }
4507
4508    #[test]
4509    fn community_exists_reflects_saved() {
4510        let (_tmp, _guard) = init_test_db();
4511        let c = v2_fixture("A", &[]);
4512        assert!(!community_exists(c.id()).unwrap());
4513        save_community_v2(&c).unwrap();
4514        assert!(community_exists(c.id()).unwrap());
4515    }
4516
4517    #[test]
4518    fn a_block_drops_only_that_persons_parked_invites() {
4519        let (_tmp, _guard) = init_test_db();
4520        let (spam, friend) = ("cd".repeat(32), "ef".repeat(32));
4521        save_pending_invite(&spam, &v2_bundle("Spam"), "npub1spammer", 0).unwrap();
4522        save_pending_invite(&friend, &v2_bundle("Friends"), "npub1friend", 0).unwrap();
4523        assert_eq!(delete_pending_invites_from("npub1spammer").unwrap(), 1);
4524        let left: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
4525        assert_eq!(left, vec![friend], "the friend's invite stays");
4526    }
4527
4528    #[test]
4529    fn pending_invite_first_wins_and_round_trips() {
4530        let (_tmp, _guard) = init_test_db();
4531        let cid = "ab".repeat(32);
4532        let (first, second) = (v2_bundle("First"), v2_bundle("Second"));
4533        // First park inserts; a re-invite for the same id is IGNORED (first-wins, so a
4534        // hostile re-send can't rewrite a parked bundle or re-notify).
4535        assert!(save_pending_invite(&cid, &first, "npub1inviter", 0).unwrap());
4536        assert!(!save_pending_invite(&cid, &second, "npub1other", 0).unwrap());
4537        assert!(pending_invite_exists(&cid).unwrap());
4538
4539        let listed = list_pending_invites().unwrap();
4540        assert_eq!(listed.len(), 1);
4541        assert_eq!(listed[0].community_id, cid);
4542        assert_eq!(listed[0].bundle_json, first, "original bundle preserved");
4543        assert_eq!(listed[0].inviter_npub, "npub1inviter");
4544
4545        // get is non-destructive; delete then removes it.
4546        assert_eq!(get_pending_invite(&cid).unwrap(), Some(first.clone()));
4547        assert!(pending_invite_exists(&cid).unwrap(), "get must not delete");
4548        delete_pending_invite(&cid).unwrap();
4549        assert!(!pending_invite_exists(&cid).unwrap());
4550        assert!(get_pending_invite(&cid).unwrap().is_none());
4551    }
4552
4553    #[test]
4554    fn purge_drops_invites_for_held_communities_only() {
4555        let (_tmp, _guard) = init_test_db();
4556        // A community we hold + a parked invite for it (the cross-device race: invite landed
4557        // before the membership list rehydrated the community).
4558        let (_, held_hex, _) = saved_v2("Held");
4559        save_pending_invite(&held_hex, "{\"bundle\":1}", "npub1inviter", 0).unwrap();
4560        // An invite for a community we do NOT hold must survive the purge.
4561        let stranger = "ab".repeat(32);
4562        save_pending_invite(&stranger, "{\"bundle\":2}", "npub1inviter", 0).unwrap();
4563
4564        let n = purge_pending_invites_for_held_communities().unwrap();
4565        assert_eq!(n, 1, "only the held community's invite is purged");
4566        assert!(!pending_invite_exists(&held_hex).unwrap(), "held → invite gone");
4567        assert!(pending_invite_exists(&stranger).unwrap(), "unknown community → invite kept");
4568    }
4569
4570    #[test]
4571    fn an_invites_lifetime_runs_from_when_it_was_sent() {
4572        let (_tmp, _guard) = init_test_db();
4573        let lifetime = crate::event_handler::DIRECT_INVITE_LIFETIME_SECS as i64;
4574        let now = now_secs();
4575        let (old, fresh, unknown, deadline) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32), "a4".repeat(32));
4576        for cid in [&old, &fresh, &unknown] {
4577            save_pending_invite(cid, "{}", "npub1x", 0).unwrap();
4578        }
4579        save_pending_invite(&deadline, "{}", "npub1x", now + 60).unwrap();
4580        set_pending_invite_sent(&old, now - lifetime - 1).unwrap();
4581        set_pending_invite_sent(&fresh, now - 60).unwrap();
4582        set_pending_invite_sent(&fresh, 1).unwrap();
4583        set_pending_invite_sent(&deadline, now - 60).unwrap();
4584
4585        let listed = list_pending_invites().unwrap();
4586        let get = |cid: &str| listed.iter().find(|i| i.community_id == cid);
4587        assert!(get(&old).is_none(), "sent past its lifetime, so gone though parked just now");
4588        let f = get(&fresh).unwrap();
4589        assert_eq!((f.sent_at, f.ends_at), (now - 60, now - 60 + lifetime), "the first send time stands");
4590        let u = get(&unknown).unwrap();
4591        assert_eq!((u.sent_at, u.ends_at), (0, u.received_at + lifetime));
4592        assert_eq!(get(&deadline).unwrap().ends_at, now + 60, "the sender's earlier deadline wins");
4593        assert_eq!(purge_expired_pending_invites().unwrap(), 1);
4594    }
4595
4596    #[test]
4597    fn an_invites_wraps_are_kept_once_each_up_to_a_cap_and_go_with_it() {
4598        let (_tmp, _guard) = init_test_db();
4599        let cid = "ef".repeat(32);
4600        note_pending_invite_wrap(&cid, &"01".repeat(32)).unwrap();
4601        assert!(pending_invite_wraps(&cid).unwrap().is_empty(), "no parked invite, nothing kept");
4602        save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
4603        for n in [1u8, 2, 1] {
4604            note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
4605        }
4606        assert_eq!(pending_invite_wraps(&cid).unwrap(), ["01".repeat(32), "02".repeat(32)]);
4607        for n in 3u8..40 {
4608            note_pending_invite_wrap(&cid, &format!("{n:02x}").repeat(32)).unwrap();
4609        }
4610        assert_eq!(pending_invite_wraps(&cid).unwrap().len(), 16);
4611        delete_pending_invite(&cid).unwrap();
4612        assert!(pending_invite_wraps(&cid).unwrap().is_empty());
4613    }
4614
4615    #[test]
4616    fn decline_drops_pending_invite() {
4617        let (_tmp, _guard) = init_test_db();
4618        let cid = "cd".repeat(32);
4619        save_pending_invite(&cid, "{}", "npub1x", 0).unwrap();
4620        delete_pending_invite(&cid).unwrap();
4621        assert!(!pending_invite_exists(&cid).unwrap());
4622    }
4623
4624    #[test]
4625    fn pending_invites_are_capped_keeping_the_newest() {
4626        let (_tmp, _guard) = init_test_db();
4627        // 150 distinct invites with strictly increasing received_at (the helper stamps now_secs(),
4628        // so vary the id and rely on insertion order; to make ordering deterministic we bump the
4629        // stored time directly after each insert isn't needed — received_at ties break on id DESC).
4630        // Insert 150; the table must cap at 100.
4631        let bundle = v2_bundle("Flood");
4632        for i in 0..150u32 {
4633            let cid = format!("{:064x}", i);
4634            save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
4635        }
4636        let all = list_pending_invites().unwrap();
4637        assert_eq!(all.len(), 100, "table capped at MAX_PENDING_INVITES");
4638        // A spam flood can't grow it past the cap regardless of how many arrive.
4639        for i in 150..400u32 {
4640            let cid = format!("{:064x}", i);
4641            save_pending_invite(&cid, &bundle, "npub1x", 0).unwrap();
4642        }
4643        assert_eq!(list_pending_invites().unwrap().len(), 100, "cap holds under flood");
4644    }
4645
4646    /// A parked invite past its sender-declared NIP-40 deadline is invisible to BOTH reads:
4647    /// the list (so it stops cluttering) and the peek the accept path uses (so it can't be
4648    /// redeemed). Relays only stop delivering an expired invite; the already-parked row is
4649    /// ours to enforce.
4650    #[test]
4651    fn expired_parked_invites_are_hidden_from_list_and_accept() {
4652        let (_tmp, _guard) = init_test_db();
4653        let now = now_secs();
4654        let live = "aa".repeat(32);
4655        let expired = "bb".repeat(32);
4656        let permanent = "cc".repeat(32);
4657
4658        save_pending_invite(&live, &v2_bundle("Live"), "npub1x", now + 3600).unwrap();
4659        save_pending_invite(&expired, &v2_bundle("Dead"), "npub1x", now - 1).unwrap();
4660        // 0 = the sender declared no deadline (a pre-expiry client): stays permanent, because
4661        // an invite whose sender never promised a deadline isn't ours to revoke.
4662        save_pending_invite(&permanent, &v2_bundle("Forever"), "npub1x", 0).unwrap();
4663
4664        let listed: Vec<String> = list_pending_invites().unwrap().into_iter().map(|i| i.community_id).collect();
4665        assert!(listed.contains(&live), "an unexpired invite still lists");
4666        assert!(listed.contains(&permanent), "a no-deadline invite still lists");
4667        assert!(!listed.contains(&expired), "an expired invite is hidden from the list");
4668
4669        assert!(get_pending_invite(&live).unwrap().is_some());
4670        assert!(get_pending_invite(&permanent).unwrap().is_some());
4671        assert!(
4672            get_pending_invite(&expired).unwrap().is_none(),
4673            "an expired invite must not be redeemable"
4674        );
4675
4676        // The row still exists until swept, and the sweep reclaims exactly the expired one.
4677        assert!(pending_invite_exists(&expired).unwrap(), "hidden, not yet deleted");
4678        assert_eq!(purge_expired_pending_invites().unwrap(), 1);
4679        assert!(!pending_invite_exists(&expired).unwrap());
4680        assert!(pending_invite_exists(&live).unwrap(), "the sweep spares live invites");
4681        assert!(pending_invite_exists(&permanent).unwrap(), "and no-deadline ones");
4682    }
4683
4684    /// The expiry is per-invite from the SENDER's tag, not derived from local receive time,
4685    /// so a short-fuse invite expires on the sender's schedule even if it was just received.
4686    #[test]
4687    fn expiry_follows_the_senders_deadline_not_receipt_time() {
4688        let (_tmp, _guard) = init_test_db();
4689        let cid = "de".repeat(32);
4690        // Received right now, but the sender's deadline already passed (a stale wrap that a
4691        // NIP-40-ignoring relay still served).
4692        save_pending_invite(&cid, "{}", "npub1x", now_secs() - 10).unwrap();
4693        assert!(list_pending_invites().unwrap().is_empty(), "receipt time does not extend the deadline");
4694        assert!(get_pending_invite(&cid).unwrap().is_none());
4695    }
4696
4697    /// A legacy banlist blob is adopted into `community_bans` on first read, and the blob is retired
4698    /// without tripping the column's NOT NULL: a failed adoption read as "nobody is banned".
4699    #[test]
4700    fn a_legacy_banlist_is_adopted_on_first_read() {
4701        let (_tmp, _guard) = init_test_db();
4702        let (_, cid, _) = saved_v2("Legacy bans");
4703        let banned = "ab".repeat(32);
4704        {
4705            let conn = crate::db::get_write_connection_guard_static().unwrap();
4706            conn.execute("DELETE FROM community_bans WHERE community_id = ?1", params![cid]).unwrap();
4707            conn.execute("UPDATE communities SET banlist = ?1 WHERE community_id = ?2", params![format!("[\"{banned}\"]"), cid]).unwrap();
4708        }
4709        assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned.clone()]);
4710        assert_eq!(get_community_banlist(&cid).unwrap(), vec![banned], "and stays adopted");
4711    }
4712
4713    /// A task of a swapped-out account can't seal into its own store: not as plaintext right after
4714    /// the swap, and not under the next account's key once that one has unlocked.
4715    #[test]
4716    fn a_task_of_a_swapped_out_account_cannot_seal() {
4717        struct Vault;
4718        impl Drop for Vault {
4719            fn drop(&mut self) {
4720                crate::state::ENCRYPTION_KEY.clear(&[]);
4721                crate::state::set_encryption_enabled(false);
4722            }
4723        }
4724        const KA: [u8; 32] = [0x61; 32];
4725        const KB: [u8; 32] = [0x62; 32];
4726        let (_tmp, _guard) = init_test_db();
4727        let _vault = Vault;
4728        let account_a = crate::db::get_current_account().unwrap();
4729        crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4730        crate::state::ENCRYPTION_KEY.set(KA, &[]);
4731        crate::state::set_encryption_enabled(true);
4732        let (_, cid, ch) = saved_v2("A");
4733
4734        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4735        let late_write = |label: &'static str| {
4736            let (go, wait) = tokio::sync::oneshot::channel::<()>();
4737            let (cid, ch) = (cid.clone(), ch.clone());
4738            let task = {
4739                let _rt = rt.enter();
4740                crate::db::spawn_bound(async move {
4741                    let _ = wait.await;
4742                    set_community_pins(&cid, &ch, &format!("{{\"{label}\":1}}"), 1)
4743                })
4744            };
4745            (go, task)
4746        };
4747        let (go_plain, plain) = late_write("plain");
4748        let (go_foreign, foreign) = late_write("foreign");
4749
4750        // The swap: the vault and the flag drop first, then account B opens and unlocks.
4751        let account_b = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
4752        crate::state::ENCRYPTION_KEY.clear(&[]);
4753        crate::state::set_encryption_enabled(false);
4754        crate::db::set_current_account(account_b.clone()).unwrap();
4755        crate::db::init_database(&account_b).unwrap();
4756        go_plain.send(()).unwrap();
4757        assert!(rt.block_on(plain).unwrap().is_err(), "no plaintext into an encrypted store");
4758        crate::state::ENCRYPTION_KEY.set(KB, &[]);
4759        crate::state::set_encryption_enabled(true);
4760        go_foreign.send(()).unwrap();
4761        assert!(rt.block_on(foreign).unwrap().is_err(), "no seal under another account's key");
4762
4763        crate::db::set_current_account(account_a.clone()).unwrap();
4764        crate::db::init_database(&account_a).unwrap();
4765        crate::state::ENCRYPTION_KEY.set(KA, &[]);
4766        assert_eq!(get_community_pins(&cid, &ch).unwrap(), None, "account A's store is untouched");
4767    }
4768
4769    /// A legacy-salted account moves onto its own salt at its first unlock: everything reads back,
4770    /// nothing anywhere still opens under the legacy key, and the derivation is recorded. A wrong
4771    /// key or a biometric account changes nothing.
4772    #[test]
4773    fn a_legacy_account_moves_onto_its_own_salt_at_unlock() {
4774        use crate::crypto::{derive_key, Kdf};
4775        use crate::db::at_rest;
4776        struct Vault;
4777        impl Drop for Vault {
4778            fn drop(&mut self) {
4779                crate::state::ENCRYPTION_KEY.clear(&[]);
4780                crate::state::set_encryption_enabled(false);
4781            }
4782        }
4783        let (_tmp, _guard) = init_test_db();
4784        let _vault = Vault;
4785        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4786        let pin = "123456";
4787        let legacy = rt.block_on(derive_key(pin, &Kdf::Legacy));
4788        crate::state::ENCRYPTION_KEY.set(legacy, &[]);
4789        crate::state::set_encryption_enabled(true);
4790        crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4791        crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
4792        crate::db::set_sql_setting("last_vacuum".to_string(), "1".to_string()).unwrap();
4793        crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1legacyaccount", &legacy).unwrap()).unwrap();
4794        let mut community = v2_fixture("Old", &["wss://r"]);
4795        community.channels.push(private_channel(0x61, 0x62));
4796        save_community_v2(&community).unwrap();
4797        let (cid, ch) = (community.id().to_hex(), community.channels[0].id.to_hex());
4798        set_community_pins(&cid, &ch, r#"{"pins":["old"]}"#, 1).unwrap();
4799        let dm_chat = make_test_npub(900_002);
4800        let dm = crate::types::Message { id: "e1".repeat(32), content: "said long ago".into(), at: 1_600_000_000_000, mine: true, ..Default::default() };
4801        rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
4802        let dm_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
4803        let read = || {
4804            (
4805                get_community_pins(&cid, &ch).unwrap(),
4806                load_community_v2(community.id()).unwrap().map(|c| format!("{c:?}")),
4807                rt.block_on(crate::db::events::get_message_views(dm_int, 10, 0)).unwrap().into_iter().map(|m| m.content).collect::<Vec<_>>(),
4808            )
4809        };
4810        let before = read();
4811        assert_eq!(before.1, Some(format!("{community:?}")));
4812        assert_eq!(before.2, vec!["said long ago".to_string()]);
4813
4814        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &[0x77; 32])).unwrap(), "a key that proves nothing moves nothing");
4815        assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy);
4816        crate::db::set_sql_setting("security_type".to_string(), "biometric".to_string()).unwrap();
4817        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "a biometric account stays put");
4818        crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
4819        assert_eq!(read(), before);
4820
4821        // A failed upgrade leaves everything as it was and waits a day before the next attempt.
4822        {
4823            let conn = crate::db::get_write_connection_guard_static().unwrap();
4824            conn.execute_batch("CREATE TABLE unaddressable (k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID;").unwrap();
4825            conn.execute("INSERT INTO unaddressable VALUES ('a', ?1)", [crate::crypto::encrypt_with_key("x", &legacy).unwrap()]).unwrap();
4826        }
4827        assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).is_err());
4828        assert_eq!((Kdf::of_account().unwrap(), read()), (Kdf::Legacy, before.clone()), "nothing moved");
4829        assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(legacy));
4830        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap(), "backed off");
4831        crate::db::get_write_connection_guard_static().unwrap().execute_batch("DROP TABLE unaddressable;").unwrap();
4832        crate::db::settings::remove_setting("kdf_upgrade_attempt").unwrap();
4833
4834        assert!(rt.block_on(at_rest::upgrade_after_unlock(pin, &legacy)).unwrap());
4835        let kdf = Kdf::of_account().unwrap();
4836        assert!(!kdf.is_legacy(), "the salt is recorded");
4837        let salted = rt.block_on(derive_key(pin, &kdf));
4838        assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted), "the session carries on under the new key");
4839        assert_eq!(read(), before, "everything reads back");
4840        {
4841            let conn = crate::db::get_write_connection_guard_static().unwrap();
4842            let tx = conn.unchecked_transaction().unwrap();
4843            assert_eq!(at_rest::sweep_residue_in_tx(&tx, &legacy, None).unwrap(), 0, "nothing opens under the legacy key");
4844        }
4845        assert_eq!(crate::db::get_sql_setting("last_vacuum".to_string()).unwrap(), None, "a vacuum is due");
4846        assert!(!rt.block_on(at_rest::upgrade_after_unlock(pin, &salted)).unwrap(), "the next unlock has nothing to do");
4847
4848        // A second unlock that derived under the legacy salt before this upgrade committed can't
4849        // put that key back, and can't run an upgrade of its own.
4850        assert!(crate::crypto::install_unlocked_key(&legacy, &Kdf::Legacy).is_err());
4851        assert_eq!(crate::state::ENCRYPTION_KEY.get(), Some(salted));
4852        let again = Kdf::fresh();
4853        let again_key = rt.block_on(derive_key(pin, &again));
4854        assert!(!at_rest::upgrade_legacy_derivation(&legacy, &again_key, &again, &|_| {}).unwrap());
4855        assert_eq!(Kdf::of_account().unwrap(), kdf);
4856    }
4857
4858    const CRASH_PIN: &str = "424242";
4859
4860    /// Child half of `the_upgrade_survives_a_kill_at_any_moment`: open the account, unlock with
4861    /// the legacy key and run the upgrade until killed. Inert unless the parent set it up.
4862    #[test]
4863    #[ignore = "driven by the_upgrade_survives_a_kill_at_any_moment"]
4864    fn upgrade_crash_child() {
4865        use std::io::Write;
4866        let (Ok(root), Ok(npub)) = (std::env::var("VECTOR_CRASH_ROOT"), std::env::var("VECTOR_CRASH_NPUB")) else { return };
4867        crate::db::set_app_data_dir(root.into());
4868        crate::db::set_current_account(npub.clone()).unwrap();
4869        crate::db::init_database(&npub).unwrap();
4870        crate::state::init_encryption_enabled();
4871        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4872        let legacy = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &crate::crypto::Kdf::Legacy));
4873        crate::state::ENCRYPTION_KEY.set(legacy, &[]);
4874        // Derived before READY, so the parent's kills fall across the transaction alone.
4875        let kdf = crate::crypto::Kdf::fresh();
4876        let salted = rt.block_on(crate::crypto::derive_key(CRASH_PIN, &kdf));
4877        println!("CHILD READY");
4878        std::io::stdout().flush().unwrap();
4879        assert!(crate::db::at_rest::upgrade_legacy_derivation(&legacy, &salted, &kdf, &|_| {}).unwrap());
4880        println!("CHILD DONE");
4881        std::io::stdout().flush().unwrap();
4882    }
4883
4884    /// The upgrade killed at moments swept across a whole run, in a separate process: every
4885    /// database left behind opens whole under exactly the key its recorded derivation names,
4886    /// and nothing is left under the other.
4887    #[test]
4888    #[ignore = "spawns and kills child processes; run with --ignored"]
4889    fn the_upgrade_survives_a_kill_at_any_moment() {
4890        use crate::crypto::{derive_key, Kdf};
4891        use std::io::BufRead;
4892        struct Vault;
4893        impl Drop for Vault {
4894            fn drop(&mut self) {
4895                crate::state::ENCRYPTION_KEY.clear(&[]);
4896                crate::state::set_encryption_enabled(false);
4897            }
4898        }
4899        let (_tmp, _guard) = init_test_db();
4900        let _vault = Vault;
4901        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
4902        let legacy = rt.block_on(derive_key(CRASH_PIN, &Kdf::Legacy));
4903
4904        // A legacy account big enough that the transaction takes real time.
4905        let template = crate::db::get_current_account().unwrap();
4906        crate::state::ENCRYPTION_KEY.set(legacy, &[]);
4907        crate::state::set_encryption_enabled(true);
4908        crate::db::set_sql_setting("encryption_enabled".to_string(), "true".to_string()).unwrap();
4909        crate::db::set_sql_setting("security_type".to_string(), "pin".to_string()).unwrap();
4910        crate::db::set_pkey(&crate::crypto::encrypt_with_key("nsec1crashaccount", &legacy).unwrap()).unwrap();
4911        let (_, cid, ch) = saved_v2("Crash");
4912        set_community_pins(&cid, &ch, r#"{"pins":["kept"]}"#, 1).unwrap();
4913        let chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_003)).unwrap();
4914        {
4915            let mut conn = crate::db::get_write_connection_guard_static().unwrap();
4916            let tx = conn.transaction().unwrap();
4917            for i in 0..20_000u32 {
4918                tx.execute(
4919                    "INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, 14, ?2, ?3, ?4, ?4)",
4920                    rusqlite::params![format!("{i:064x}"), chat, crate::crypto::encrypt_with_key(&format!("message {i}"), &legacy).unwrap(), i],
4921                ).unwrap();
4922            }
4923            tx.commit().unwrap();
4924        }
4925        crate::db::close_database();
4926        let root = crate::db::shared_test_data_dir().to_path_buf();
4927
4928        let copy_of_template = || -> String {
4929            let npub = make_test_npub(TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
4930            std::fs::create_dir_all(root.join(&npub)).unwrap();
4931            for entry in std::fs::read_dir(root.join(&template)).unwrap().flatten() {
4932                std::fs::copy(entry.path(), root.join(&npub).join(entry.file_name())).unwrap();
4933            }
4934            npub
4935        };
4936        // One child run, killed `after` READY, or left to finish when `None`.
4937        let run_child = |npub: &str, after: Option<std::time::Duration>| -> std::time::Duration {
4938            let mut child = std::process::Command::new(std::env::current_exe().unwrap())
4939                .args(["--exact", "db::community::tests::upgrade_crash_child", "--ignored", "--nocapture", "--test-threads=1"])
4940                .env("VECTOR_CRASH_ROOT", &root)
4941                .env("VECTOR_CRASH_NPUB", npub)
4942                .stdout(std::process::Stdio::piped())
4943                .stderr(std::process::Stdio::null())
4944                .spawn()
4945                .unwrap();
4946            let mut lines = std::io::BufReader::new(child.stdout.take().unwrap()).lines();
4947            while let Some(Ok(line)) = lines.next() {
4948                if line.contains("CHILD READY") {
4949                    break;
4950                }
4951            }
4952            let ready = std::time::Instant::now();
4953            match after {
4954                Some(delay) => {
4955                    std::thread::sleep(delay);
4956                    let _ = child.kill();
4957                }
4958                None => {
4959                    while let Some(Ok(line)) = lines.next() {
4960                        if line.contains("CHILD DONE") {
4961                            break;
4962                        }
4963                    }
4964                }
4965            }
4966            let _ = child.wait();
4967            ready.elapsed()
4968        };
4969        let verify = |npub: &str| -> bool {
4970            crate::db::set_current_account(npub.to_string()).unwrap();
4971            crate::db::init_database(npub).unwrap();
4972            let kdf = Kdf::of_account().unwrap();
4973            let key = rt.block_on(derive_key(CRASH_PIN, &kdf));
4974            crate::state::ENCRYPTION_KEY.set(key, &[]);
4975            let pkey = crate::db::get_pkey().unwrap().unwrap();
4976            assert_eq!(crate::crypto::decrypt_with_key(&pkey, &key).unwrap(), "nsec1crashaccount", "{npub}: the stored key opens");
4977            assert_eq!(get_community_pins(&cid, &ch).unwrap().map(|p| p.0).as_deref(), Some(r#"{"pins":["kept"]}"#));
4978            let conn = crate::db::get_db_connection_guard_static().unwrap();
4979            let mut stmt = conn.prepare("SELECT content FROM events WHERE chat_id = ?1").unwrap();
4980            let unopened = stmt
4981                .query_map([chat], |r| r.get::<_, String>(0)).unwrap()
4982                .flatten()
4983                .filter(|c| crate::crypto::decrypt_with_key(c, &key).is_err())
4984                .count();
4985            assert_eq!(unopened, 0, "{npub}: every message opens under the recorded derivation");
4986            !kdf.is_legacy()
4987        };
4988
4989        // Measure one whole run, then kill at moments spread across it and a little past.
4990        let first = copy_of_template();
4991        let whole = run_child(&first, None);
4992        assert!(verify(&first), "an uninterrupted run upgrades");
4993        let mut outcomes = (0, 0);
4994        let mut trace = String::new();
4995        for step in 0..24u32 {
4996            let npub = copy_of_template();
4997            run_child(&npub, Some(whole * step / 21));
4998            let upgraded = verify(&npub);
4999            trace.push(if upgraded { 'U' } else { 'L' });
5000            if upgraded { outcomes.1 += 1 } else { outcomes.0 += 1 }
5001        }
5002        println!("kill outcomes in time order: {trace}");
5003        println!("crash sweep over a {whole:?} transaction: {} left legacy, {} upgraded", outcomes.0, outcomes.1);
5004        assert!(outcomes.0 >= 10, "most kills land inside the transaction and roll it back");
5005        assert!(outcomes.1 > 0, "and the sweep reaches past the commit");
5006    }
5007
5008    /// The stored derivation always describes the key the data is under: setup records it, enable
5009    /// and a PIN change replace it in their own transaction, disable drops it, and a refused PIN
5010    /// change leaves it alone.
5011    #[test]
5012    fn the_key_derivation_moves_with_every_migration() {
5013        use crate::crypto::Kdf;
5014        use crate::db::at_rest;
5015        struct Vault;
5016        impl Drop for Vault {
5017            fn drop(&mut self) {
5018                crate::state::ENCRYPTION_KEY.clear(&[]);
5019                crate::state::set_encryption_enabled(false);
5020            }
5021        }
5022        let (_tmp, _guard) = init_test_db();
5023        let _vault = Vault;
5024        assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "no row reads as the legacy salt");
5025        save_community_v2(&v2_fixture("K", &[])).unwrap();
5026
5027        let (k1, key1) = (Kdf::fresh(), [0x51; 32]);
5028        at_rest::enable(&key1, &k1, "pin", None, None, &|_| {}).unwrap();
5029        assert_eq!(Kdf::of_account().unwrap(), k1);
5030
5031        let (k2, key2) = (Kdf::fresh(), [0x52; 32]);
5032        assert!(at_rest::rekey(&[0x5F; 32], &key2, &k2, "pin", None, &|_| {}).is_err());
5033        assert_eq!(Kdf::of_account().unwrap(), k1, "a refused change keeps the derivation");
5034        at_rest::rekey(&key1, &key2, &k2, "pin", None, &|_| {}).unwrap();
5035        assert_eq!(Kdf::of_account().unwrap(), k2);
5036
5037        at_rest::disable(&key2, &|_| {}).unwrap();
5038        assert_eq!(Kdf::of_account().unwrap(), Kdf::Legacy, "a plaintext store keeps no derivation");
5039
5040        let k3 = Kdf::fresh();
5041        let sealed = crate::crypto::encrypt_with_key("nsec1setup", &[0x53; 32]).unwrap();
5042        crate::db::settings::commit_account_setup(&sealed, true, Some("pin"), None, None, k3.descriptor().as_deref()).unwrap();
5043        assert_eq!(Kdf::of_account().unwrap(), k3, "setup records the salt with the key it sealed");
5044    }
5045
5046    #[test]
5047    fn the_identity_opens_under_the_users_proof_and_nothing_else() {
5048        use crate::crypto::{derive_key, Kdf};
5049        use crate::db::at_rest::{self, open_identity_secrets, CREDENTIAL_INCORRECT};
5050        struct Vault;
5051        impl Drop for Vault {
5052            fn drop(&mut self) {
5053                crate::state::ENCRYPTION_KEY.clear(&[]);
5054                crate::state::set_encryption_enabled(false);
5055            }
5056        }
5057        let (_tmp, _guard) = init_test_db();
5058        let _vault = Vault;
5059        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5060        crate::db::set_pkey("nsec1identity").unwrap();
5061        crate::db::set_seed("abandon ability able").unwrap();
5062        let plain = open_identity_secrets(None).unwrap();
5063        assert_eq!((plain.0.as_str(), plain.1.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
5064
5065        let kdf = Kdf::fresh();
5066        let key = rt.block_on(derive_key("424242", &kdf));
5067        at_rest::enable(&key, &kdf, "pin", None, None, &|_| {}).unwrap();
5068        assert!(crate::state::ENCRYPTION_KEY.get().is_some(), "the session holds the key");
5069        assert!(open_identity_secrets(None).is_err(), "a sealed store opens nothing on the session alone");
5070        assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5071        assert_eq!(open_identity_secrets(Some(&[0x09; 32])).unwrap_err(), CREDENTIAL_INCORRECT);
5072
5073        let proven = rt.block_on(at_rest::prove_credential("424242")).unwrap();
5074        let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
5075        assert_eq!((nsec.as_str(), seed.as_deref().map(|s| s.as_str())), ("nsec1identity", Some("abandon ability able")));
5076
5077        // Misses past the free ones lock even the right PIN out for a while, and a success clears them.
5078        for _ in 0..4 {
5079            assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5080        }
5081        assert_eq!(rt.block_on(at_rest::prove_credential("000000")).unwrap_err(), CREDENTIAL_INCORRECT);
5082        let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
5083        assert!(locked.starts_with("CREDENTIAL_LOCKED:"), "{locked}");
5084        crate::db::remove_setting("credential_retry_at").unwrap();
5085        rt.block_on(at_rest::prove_credential("424242")).unwrap();
5086        assert!(crate::db::get_sql_setting("credential_failures".to_string()).unwrap().is_none());
5087
5088        // A clock set back far can't stretch the wait past the longest one a miss earns.
5089        let far = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 86_400 * 30;
5090        crate::db::set_sql_setting("credential_retry_at".to_string(), far.to_string()).unwrap();
5091        let locked = rt.block_on(at_rest::prove_credential("424242")).unwrap_err();
5092        let secs: u64 = locked.strip_prefix("CREDENTIAL_LOCKED:").unwrap().parse().unwrap();
5093        assert!(secs <= 15 * 60, "{secs}");
5094        crate::db::remove_setting("credential_retry_at").unwrap();
5095
5096        // A seed left in plaintext from before encryption still exports; one that won't open stays behind.
5097        crate::db::set_seed("abandon ability able").unwrap();
5098        assert_eq!(open_identity_secrets(Some(&proven)).unwrap().1.as_deref().map(|s| s.as_str()), Some("abandon ability able"));
5099        crate::db::set_seed("deadbeef").unwrap();
5100        let (nsec, seed) = open_identity_secrets(Some(&proven)).unwrap();
5101        assert!(nsec.starts_with("nsec1") && seed.is_none());
5102    }
5103
5104    /// Reads racing a stream of PIN changes always open: a row read just before a commit and
5105    /// opened just after, or read just after and opened before the vault moved, never comes
5106    /// back as ciphertext.
5107    #[test]
5108    fn reads_racing_pin_changes_always_open() {
5109        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5110        use std::sync::Arc;
5111        struct Vault;
5112        impl Drop for Vault {
5113            fn drop(&mut self) {
5114                crate::state::ENCRYPTION_KEY.clear(&[]);
5115                crate::state::set_encryption_enabled(false);
5116            }
5117        }
5118        let (_tmp, _guard) = init_test_db();
5119        let _vault = Vault;
5120        let keys: Vec<[u8; 32]> = (0u8..31).map(|i| [0x90 + i; 32]).collect();
5121        crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
5122        crate::state::set_encryption_enabled(true);
5123        let (_, cid, ch) = saved_v2("Read");
5124        let pinned = r#"{"pins":["kept"]}"#;
5125        set_community_pins(&cid, &ch, pinned, 1).unwrap();
5126
5127        let stop = Arc::new(AtomicBool::new(false));
5128        let (reads, garbled) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
5129        let reader = {
5130            let (stop, reads, garbled, cid, ch) = (stop.clone(), reads.clone(), garbled.clone(), cid.clone(), ch.clone());
5131            std::thread::spawn(move || {
5132                while !stop.load(Ordering::SeqCst) {
5133                    let got = get_community_pins(&cid, &ch).unwrap().map(|(c, _)| c);
5134                    reads.fetch_add(1, Ordering::SeqCst);
5135                    if got.as_deref() != Some(pinned) {
5136                        garbled.fetch_add(1, Ordering::SeqCst);
5137                    }
5138                }
5139            })
5140        };
5141        for pair in keys.windows(2) {
5142            crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5143            // The grace covers a read straddling ONE change; real PIN changes are seconds apart,
5144            // so let a read that began after this one finish before the next.
5145            let seen = reads.load(Ordering::SeqCst);
5146            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
5147            while reads.load(Ordering::SeqCst) < seen + 2 {
5148                assert!(std::time::Instant::now() < deadline, "reads stopped completing across a PIN change");
5149                std::thread::yield_now();
5150            }
5151        }
5152        stop.store(true, Ordering::SeqCst);
5153        reader.join().unwrap();
5154        assert!(reads.load(Ordering::SeqCst) > 0);
5155        assert_eq!(garbled.load(Ordering::SeqCst), 0, "no read across a PIN change came back unopened");
5156        std::thread::sleep(std::time::Duration::from_millis(600));
5157        assert!(!crate::state::PREVIOUS_AT_REST_KEY.has_key(), "the replaced key is wiped after its grace");
5158    }
5159
5160    /// Writes racing a stream of PIN changes all land on the key the store ends on, and a
5161    /// read-modify-write never loses what it merged into.
5162    #[test]
5163    fn writes_racing_pin_changes_land_on_the_final_key() {
5164        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5165        use std::sync::Arc;
5166        struct Vault;
5167        impl Drop for Vault {
5168            fn drop(&mut self) {
5169                crate::state::ENCRYPTION_KEY.clear(&[]);
5170                crate::state::set_encryption_enabled(false);
5171            }
5172        }
5173        let (_tmp, _guard) = init_test_db();
5174        let _vault = Vault;
5175        let keys: Vec<[u8; 32]> = (0u8..21).map(|i| [0x40 + i; 32]).collect();
5176        crate::state::ENCRYPTION_KEY.set(keys[0], &[]);
5177        crate::state::set_encryption_enabled(true);
5178        let (_, cid, ch) = saved_v2("Race");
5179
5180        let stop = Arc::new(AtomicBool::new(false));
5181        let last = Arc::new(AtomicU64::new(0));
5182        let writer = {
5183            let (stop, last, cid, ch) = (stop.clone(), last.clone(), cid.clone(), ch.clone());
5184            std::thread::spawn(move || {
5185                let mut i = 0u64;
5186                while !stop.load(Ordering::SeqCst) {
5187                    i += 1;
5188                    set_community_pins(&cid, &ch, &format!("{{\"v\":{i}}}"), i as i64).unwrap();
5189                    merge_community_ban_marks(&cid, &[(format!("npub{i}"), i)].into_iter().collect()).unwrap();
5190                    last.store(i, Ordering::SeqCst);
5191                }
5192            })
5193        };
5194        while last.load(Ordering::SeqCst) == 0 {
5195            std::thread::yield_now();
5196        }
5197        for pair in keys.windows(2) {
5198            crate::db::at_rest::rekey(&pair[0], &pair[1], &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5199        }
5200        stop.store(true, Ordering::SeqCst);
5201        writer.join().unwrap();
5202
5203        let n = last.load(Ordering::SeqCst);
5204        assert_eq!(get_community_pins(&cid, &ch).unwrap(), Some((format!("{{\"v\":{n}}}"), n as i64)));
5205        let marks = get_community_ban_marks(&cid).unwrap();
5206        assert_eq!(marks.len() as u64, n, "every merged mark survives the key changes");
5207    }
5208
5209    /// Every encrypting writer, on the real schema, through a PIN change and a disable. The
5210    /// sweep list alone must leave nothing on the old key, so a writer whose column it misses
5211    /// fails here. A new writer that encrypts a column belongs in this test.
5212    #[test]
5213    fn a_v2_link_counts_the_members_who_joined_through_it() {
5214        use crate::community::v2::guestbook::{GuestbookEntry, GuestbookEvent};
5215        let (_tmp, _guard) = init_test_db();
5216        let owner = nostr_sdk::prelude::Keys::generate();
5217        let g = crate::community::v2::control::genesis(
5218            &owner,
5219            crate::community::v2::control::CommunityMetadata { name: "Hub".into(), ..Default::default() },
5220            1_000,
5221        )
5222        .unwrap();
5223        let v2 = crate::community::v2::community::CommunityV2::from_genesis(&g, "Hub", None, vec!["wss://r".into()], 1_000);
5224        save_community_v2(&v2).unwrap();
5225        let cid = v2.id().to_hex();
5226
5227        let me = owner.public_key();
5228        let someone_else = nostr_sdk::prelude::Keys::generate().public_key();
5229        let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
5230        let join = |n: u8, member: PublicKey, by: Option<(String, &str)>| GuestbookEvent {
5231            epoch: None,
5232            observed_at: None,
5233            rumor_id: [n; 32],
5234            entry: GuestbookEntry::Join { member, invited_by: by.map(|(c, l)| (c, l.to_string())), at_ms: n as u64 },
5235        };
5236        let events = vec![
5237            join(1, a, Some((me.to_hex(), "hub"))),
5238            join(2, b, Some((me.to_bech32().unwrap(), "hub"))),
5239            join(3, a, Some((me.to_hex(), "hub"))),
5240            join(4, c, Some((me.to_hex(), ""))),
5241            join(5, c, Some((someone_else.to_hex(), "hub"))),
5242            join(6, b, None),
5243        ];
5244        set_guestbook(&cid, &events, 9).unwrap();
5245
5246        let counts = community_invite_join_counts(&cid, &me).unwrap();
5247        assert_eq!(counts.get("hub"), Some(&2), "a rejoin counts once, either spelling of the creator counts");
5248        assert_eq!(counts.get(""), Some(&1), "an unlabeled link's joins are kept apart");
5249        assert_eq!(counts.len(), 2, "another creator's link and a bare join count for nobody here");
5250    }
5251
5252    #[test]
5253    fn a_group_chat_becomes_a_community_with_a_second_channel_or_an_invite_link() {
5254        let (_tmp, _guard) = init_test_db();
5255        let is = |c: &crate::community::v2::community::CommunityV2| crate::notify::is_community(&c.id().to_hex());
5256
5257        let mut chat = v2_fixture("Friends", &["wss://r"]);
5258        save_community_v2(&chat).unwrap();
5259        assert!(!is(&chat), "one channel, no link: a group chat");
5260        assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::All);
5261
5262        let mut second = chat.channels[0].clone();
5263        second.id = crate::community::ChannelId([0x42; 32]);
5264        second.name = "random".into();
5265        chat.channels.push(second);
5266        save_community_v2(&chat).unwrap();
5267        assert!(is(&chat), "a second channel makes it a community");
5268        assert_eq!(crate::notify::default_level(Some(&chat.id().to_hex())), crate::notify::NotifyLevel::Mentions);
5269
5270        let open = v2_fixture("Open", &["wss://r"]);
5271        save_community_v2(&open).unwrap();
5272        assert!(!is(&open));
5273        set_community_invite_registry(&open.id().to_hex(), &["loc1".into()]).unwrap();
5274        assert!(is(&open), "an invite link makes it a community");
5275        set_community_invite_registry(&open.id().to_hex(), &[]).unwrap();
5276        assert!(!is(&open), "revoking the last link makes it a group chat again");
5277
5278        assert_eq!(crate::notify::default_level(None), crate::notify::NotifyLevel::All, "a DM rings for everything");
5279    }
5280
5281    #[test]
5282    fn every_encrypting_writer_is_covered_by_the_at_rest_sweep() {
5283        use crate::db::at_rest;
5284        const K: [u8; 32] = [0x31; 32];
5285        const K2: [u8; 32] = [0x32; 32];
5286        const WRONG: [u8; 32] = [0x39; 32];
5287        struct Vault;
5288        impl Drop for Vault {
5289            fn drop(&mut self) {
5290                crate::state::ENCRYPTION_KEY.clear(&[]);
5291                crate::state::set_encryption_enabled(false);
5292            }
5293        }
5294        let (_tmp, _guard) = init_test_db();
5295        let _vault = Vault;
5296        crate::state::ENCRYPTION_KEY.set(K, &[]);
5297        crate::state::set_encryption_enabled(true);
5298
5299        let mut v2 = v2_fixture("HQ", &["wss://r"]);
5300        v2.description = Some("about".into());
5301        let image = |url: &str| crate::community::v2::control::ImageRef {
5302            url: url.into(), key: "0".repeat(64), nonce: "1".repeat(32), hash: "a".repeat(64), extra: Default::default(),
5303        };
5304        v2.icon = Some(image("https://blossom.example/icon"));
5305        v2.banner = Some(image("https://blossom.example/banner"));
5306        v2.meta_custom = Some([("k".to_string(), serde_json::Value::from("v"))].into_iter().collect());
5307        v2.channels[0].voice = Some(true);
5308        v2.channels[0].meta_extra.insert("vnd".into(), serde_json::Value::from(7));
5309        v2.channels.push(private_channel(0x61, 0x62));
5310        save_community_v2(&v2).unwrap();
5311        let cid = v2.id().to_hex();
5312        let ch = v2.channels[0].id.to_hex();
5313        let private = v2.channels[1].id.to_hex();
5314        store_epoch_key(&cid, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &v2.community_root).unwrap();
5315        store_epoch_key(&cid, &private, 0, &[0x62; 32]).unwrap();
5316        park_channel_key(&cid, &private, 3, &[0x33; 32], &"ab".repeat(32)).unwrap();
5317        store_message_key("m1", "o1", &nostr_sdk::prelude::Keys::generate(), &["wss://r".into()]).unwrap();
5318        let owner = nostr_sdk::prelude::Keys::generate();
5319        store_wrap_owner("m1", "o1", &owner, &["wss://r".into()]).unwrap();
5320        save_pending_invite(&"de".repeat(32), r#"{"bundle":1}"#, "npub1inviter", now_secs() + 3600).unwrap();
5321        save_public_invite(&"ab".repeat(32), &cid, "https://vectorapp.io/invite#x", None, Some("Label")).unwrap();
5322        set_community_policy(&cid, "p1", r#"{"format":1}"#, "hh", true, 0).unwrap();
5323        merge_community_ban_marks(&cid, &[("npub1banned".to_string(), 5u64)].into_iter().collect()).unwrap();
5324        set_community_roles(&cid, &crate::community::roles::CommunityRoles::default(), 1).unwrap();
5325        set_community_invite_registry(&cid, &["loc1".into()]).unwrap();
5326        replace_invite_link_sets(&cid, &[InviteLinkSetRow { creator_hex: "cd".repeat(32), locators: vec!["l1".into()] }]).unwrap();
5327        set_guestbook(&cid, &[], 9).unwrap();
5328        set_community_pins(&cid, &ch, r#"{"pins":["x"]}"#, 1).unwrap();
5329        record_audit_local(&cid, "e1", 5, r#"{"action":"message_delete"}"#).unwrap();
5330        let control_wrap = br#"{"kind":1059,"content":"a control wrap as a relay served it"}"#.to_vec();
5331        store_control_wraps(&cid, &[0x77; 32], 1, 5, &[([0x11; 32], 5, Some(control_wrap.clone())), ([0x12; 32], 6, None)]).unwrap();
5332        let control_wraps = || control_wrap_page(&cid, &[0x77; 32], None, 10).unwrap();
5333        assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())]);
5334        let on_disk: Vec<u8> = crate::db::get_db_connection_guard_static().unwrap()
5335            .query_row("SELECT wrap FROM community_control_wraps WHERE wrap IS NOT NULL", [], |r| r.get(0)).unwrap();
5336        assert_ne!(on_disk, control_wrap, "a held Control wrap is sealed on disk");
5337
5338        // A DM with a link preview and a file, and an unconfirmed send's retained rumor.
5339        let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
5340        let dm_chat = make_test_npub(900_000);
5341        let dm = crate::types::Message {
5342            id: "a1".repeat(32),
5343            content: "the message itself".into(),
5344            at: 1_700_000_000_000,
5345            mine: true,
5346            preview_metadata: Some(crate::types::SiteMetadata {
5347                domain: "example.com".into(), og_title: Some("A title".into()), og_description: None,
5348                og_image: None, og_url: Some("https://example.com/a".into()), og_type: None,
5349                title: None, description: None, favicon: None,
5350            }),
5351            attachments: vec![crate::types::Attachment {
5352                id: "b2".repeat(32), key: "c3".repeat(32), nonce: "d4".repeat(16), extension: "jpg".into(),
5353                name: "passport.jpg".into(), url: "https://blossom.example/x.jpg".into(), size: 42,
5354                img_meta: Some(crate::types::ImageMetadata { thumbhash: "thumb".into(), width: 4, height: 3 }),
5355                fallback_urls: vec!["https://mirror.example/x.jpg".into()],
5356                ..Default::default()
5357            }],
5358            ..Default::default()
5359        };
5360        rt.block_on(crate::db::events::save_message(&dm_chat, &dm)).unwrap();
5361        let dm_chat_int = crate::db::id_cache::get_or_create_chat_id(&dm_chat).unwrap();
5362        let (wrap, rumor) = {
5363            use crate::event_ext::FinalizeUnsignedWithId;
5364            use nostr_sdk::prelude::*;
5365            let ephemeral = Keys::generate();
5366            let wrap = EventBuilder::new(Kind::TextNote, "wrap").finalize(&ephemeral).unwrap();
5367            let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "still sending")
5368                .finalize_unsigned_with_id(Keys::generate().public_key());
5369            crate::db::nip17_keys::store_wrap_key(
5370                &wrap.id, &rumor.id.unwrap(), &Keys::generate().public_key(),
5371                crate::db::nip17_keys::WrapRole::Recipient, ephemeral.secret_key(), &[],
5372            ).unwrap();
5373            (wrap, rumor)
5374        };
5375        crate::db::nip17_keys::stash_resend_payload(&wrap.id, "pending-1", &wrap, &rumor).unwrap();
5376        // A stranger's wallpaper, held until their request is accepted.
5377        crate::db::chats::hold_wallpaper(&dm_chat, 5, r#"{"url":"https://blossom.example/held-wallpaper"}"#).unwrap();
5378        // A kept file's key.
5379        let kept = crate::db::media_store::StoredMedia {
5380            hash: [0x5b; 32], file: "f".into(), key: "e5".repeat(32), nonce: "f6".repeat(16), blob_sha256: "aa".repeat(32),
5381            pt_len: 9, mime: "image/png".into(), origin: crate::db::media_store::Origin::Received,
5382        };
5383        crate::db::media_store::insert(&kept).unwrap();
5384
5385        // A ban set while sealed still hides its author from the channel and its unread count.
5386        let (banned, allowed) = {
5387            use nostr_sdk::prelude::ToBech32;
5388            (nostr_sdk::prelude::Keys::generate().public_key(), nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap())
5389        };
5390        set_community_banlist(&cid, &[banned.to_hex()], 1).unwrap();
5391        for (id, author) in [("c7", { use nostr_sdk::prelude::ToBech32; banned.to_bech32().unwrap() }), ("d8", allowed)] {
5392            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() };
5393            rt.block_on(crate::db::events::save_message(&ch, &msg)).unwrap();
5394        }
5395        let ch_int = crate::db::id_cache::get_or_create_chat_id(&ch).unwrap();
5396
5397        let read = || {
5398            (
5399                get_pending_channel_keys(&cid).unwrap().iter().map(|k| (k.key, k.sender.clone())).collect::<Vec<_>>(),
5400                get_community_ban_marks(&cid).unwrap(),
5401                get_community_pins(&cid, &ch).unwrap(),
5402                load_community_v2(v2.id()).unwrap().map(|c| format!("{c:?}")),
5403                (
5404                    held_epoch_keys(&cid, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap(),
5405                    held_epoch_keys(&cid, &private).unwrap(),
5406                    get_audit_local(&cid).unwrap(),
5407                ),
5408                rt.block_on(crate::db::events::get_message_views(dm_chat_int, 10, 0)).unwrap()
5409                    .into_iter().map(|m| (m.content, m.preview_metadata, m.attachments)).collect::<Vec<_>>(),
5410                crate::db::nip17_keys::get_resend_payload_by_pending("pending-1").unwrap().map(|p| p.rumor.content),
5411                (
5412                    get_community_banlist(&cid).unwrap(),
5413                    rt.block_on(crate::db::events::get_message_views(ch_int, 10, 0)).unwrap().into_iter().map(|m| m.id).collect::<Vec<_>>(),
5414                    rt.block_on(crate::db::events::unread_count_for_chat(&ch)).unwrap(),
5415                    rt.block_on(crate::db::events::unread_counts()).unwrap().get(&ch).copied(),
5416                ),
5417                wrap_owners("m1").unwrap().into_iter().map(|(k, outer, relays)| (k.public_key(), outer, relays)).collect::<Vec<_>>(),
5418                crate::db::media_store::get(&[0x5b; 32]).unwrap(),
5419            )
5420        };
5421        let before = read();
5422        assert_eq!(before.8, vec![(owner.public_key(), "o1".to_string(), vec!["wss://r".to_string()])]);
5423        assert_eq!(before.9.as_ref(), Some(&kept));
5424        assert_eq!(before.0, vec![([0x33; 32], "ab".repeat(32))]);
5425        assert_eq!(before.2, Some((r#"{"pins":["x"]}"#.to_string(), 1)));
5426        assert_eq!(before.3, Some(format!("{v2:?}")));
5427        assert_eq!(
5428            before.4,
5429            (vec![(Epoch(0), v2.community_root)], vec![(Epoch(0), [0x62; 32])], vec![("e1".to_string(), 5, r#"{"action":"message_delete"}"#.to_string())])
5430        );
5431        // File captions are stored but not shown again yet; the view still carries the rest.
5432        assert_eq!(before.5, vec![(String::new(), dm.preview_metadata.clone(), dm.attachments.clone())]);
5433        assert_eq!(before.6.as_deref(), Some("still sending"));
5434        assert_eq!(before.7, (vec![banned.to_hex()], vec!["d8".repeat(32)], 1, Some(1)), "the banned author stays hidden");
5435        let sealed: (String, String, String) = crate::db::get_db_connection_guard_static().unwrap().query_row(
5436            "SELECT a.name || e.preview_metadata || e.content, w.rumor_json, a.key FROM attachments a, events e, nip17_wrap_keys w
5437             WHERE e.id = a.event_id AND w.pending_id = 'pending-1'", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
5438        ).unwrap();
5439        for plain in ["passport", "A title", "the message itself"] {
5440            assert!(!sealed.0.contains(plain), "{plain} is sealed on disk");
5441        }
5442        assert!(!sealed.1.contains("still sending") && sealed.2 != "c3".repeat(32), "unconfirmed sends and file keys are sealed");
5443        let held: String = crate::db::get_db_connection_guard_static().unwrap()
5444            .query_row("SELECT payload FROM dm_held_wallpapers", [], |r| r.get(0)).unwrap();
5445        assert!(!held.contains("held-wallpaper"), "a held wallpaper is sealed on disk");
5446
5447        {
5448            let conn = crate::db::get_write_connection_guard_static().unwrap();
5449            let tx = conn.unchecked_transaction().unwrap();
5450            at_rest::rekey_listed_in_tx(&tx, &K, &K2, &|_| {}).unwrap();
5451            assert_eq!(
5452                at_rest::sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(),
5453                0,
5454                "the sweep list must name every column these writers encrypt"
5455            );
5456        }
5457
5458        assert!(at_rest::rekey(&WRONG, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).is_err(), "a key the store does not open is refused");
5459        at_rest::rekey(&K, &K2, &crate::crypto::Kdf::fresh(), "pin", None, &|_| {}).unwrap();
5460        crate::state::ENCRYPTION_KEY.set(K2, &[]);
5461        assert_eq!(read(), before, "every value reads back after a PIN change");
5462        assert_eq!(control_wraps(), vec![([0x11; 32], 5, control_wrap.clone())], "a held Control wrap moves with the key");
5463        assert_eq!(control_wrap_counts(&cid, &[0x77; 32]).unwrap().1, 1, "and a refusal, which holds no body, stays as it was");
5464        assert_eq!(
5465            crate::db::chats::take_held_wallpaper(&dm_chat).unwrap().as_deref(),
5466            Some(r#"{"url":"https://blossom.example/held-wallpaper"}"#),
5467            "a held wallpaper moves with the key"
5468        );
5469
5470        let mode = || crate::db::get_sql_setting("security_type".to_string()).unwrap();
5471        at_rest::rekey(&K2, &K2, &crate::crypto::Kdf::of_account().unwrap(), "password", None, &|_| {}).unwrap();
5472        assert_eq!((read(), mode().as_deref()), (before.clone(), Some("password")), "the same key on both sides only switches the mode");
5473
5474        // Rows from before this build: a plaintext caption and a DM whose plaintext looks sealed.
5475        let legacy_chat = crate::db::id_cache::get_or_create_chat_id(&make_test_npub(900_001)).unwrap();
5476        let hexish = "ab".repeat(40);
5477        {
5478            let conn = crate::db::get_write_connection_guard_static().unwrap();
5479            for (id, kind, content) in [("e5", 15, "old caption"), ("f6", 14, hexish.as_str())] {
5480                conn.execute(
5481                    "INSERT INTO events (id, kind, chat_id, content, created_at, received_at) VALUES (?1, ?2, ?3, ?4, 1, 1)",
5482                    rusqlite::params![id.repeat(32), kind, legacy_chat, content],
5483                ).unwrap();
5484            }
5485        }
5486        let flag = || crate::db::get_sql_setting("community_at_rest_encrypted".to_string()).unwrap();
5487        crate::db::set_sql_setting("community_at_rest_encrypted".to_string(), "1".to_string()).unwrap();
5488        crate::state::ENCRYPTION_KEY.set(WRONG, &[]);
5489        assert!(at_rest::backfill_at_rest().is_err(), "the backfill never wraps under a key it cannot prove");
5490        assert_eq!(flag().as_deref(), Some("1"));
5491        crate::state::ENCRYPTION_KEY.set(K2, &[]);
5492        at_rest::backfill_at_rest().unwrap();
5493        assert_eq!((read(), flag().as_deref()), (before.clone(), Some("8")));
5494        let stored = |id: &str| -> String {
5495            crate::db::get_db_connection_guard_static().unwrap()
5496                .query_row("SELECT content FROM events WHERE id = ?1", [id.repeat(32)], |r| r.get(0)).unwrap()
5497        };
5498        assert!(stored("e5") != "old caption" && stored("f6") != hexish, "the backfill seals legacy plaintext messages");
5499        let legacy = rt.block_on(crate::db::events::get_message_views(legacy_chat, 10, 0)).unwrap();
5500        assert!(legacy.iter().any(|m| m.content == hexish), "and they still read back");
5501
5502        assert!(at_rest::disable(&WRONG, &|_| {}).is_err(), "a wrong key never turns encryption off");
5503        assert_eq!(read(), before);
5504        at_rest::disable(&K2, &|_| {}).unwrap();
5505        crate::state::ENCRYPTION_KEY.clear(&[]);
5506        assert_eq!(read(), before, "every value reads back after Local Encryption is turned off");
5507    }
5508}
5509
5510// ── Pin lists (CORD-04 §7) ───────────────────────────────────────────────────
5511
5512/// Persist a channel's folded Pin List head — the RAW carried content (either
5513/// self-describing form), never a re-serialization: republishing must carry the
5514/// exact bytes, and the byte cap judges what the wire carried. Encrypted at
5515/// rest like the banlist — a public-form list carries disclosed message keys.
5516///
5517/// Monotonic IN THE STATEMENT: fold persists and publish echoes race (the fold
5518/// reads relay windows while an echo lands), and a read-check-then-write let a
5519/// stale fold clobber a newer echo. Equal versions still write — a same-version
5520/// fork's converged winner must be adoptable. Returns whether a row changed.
5521pub fn set_community_pins(community_id: &str, channel_id: &str, content: &str, version: i64) -> Result<bool, String> {
5522    let _seal = crate::crypto::gate::sealing();
5523    let enc = enc_txt(content)?;
5524    let conn = super::get_write_connection_guard_static()?;
5525    let changed = conn
5526        .execute(
5527            "INSERT INTO community_pins (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
5528             ON CONFLICT(community_id, channel_id) DO UPDATE SET
5529                 content = excluded.content, version = excluded.version
5530             WHERE excluded.version >= community_pins.version",
5531            params![community_id, channel_id, enc, version],
5532        )
5533        .map_err(|e| format!("set pins: {e}"))?;
5534    Ok(changed > 0)
5535}
5536
5537/// Persist a channel's folded Writers ledger head (CORD-03 §1), monotonic on version.
5538pub fn set_community_writers(community_id: &str, channel_id: &str, content: &str, version: i64, replace: bool) -> Result<bool, String> {
5539    let _seal = crate::crypto::gate::sealing();
5540    let enc = enc_txt(content)?;
5541    let conn = super::get_write_connection_guard_static()?;
5542    let old: Option<String> = conn
5543        .query_row("SELECT content FROM community_writers WHERE community_id = ?1 AND channel_id = ?2", params![community_id, channel_id], |r| r.get(0))
5544        .optional()
5545        .map_err(|e| format!("get writers: {e}"))?
5546        .map(|c: String| dec_txt(&c));
5547    let changed = conn
5548        .execute(
5549            "INSERT INTO community_writers (community_id, channel_id, content, version) VALUES (?1, ?2, ?3, ?4)
5550             ON CONFLICT(community_id, channel_id) DO UPDATE SET
5551                 content = excluded.content, version = excluded.version
5552             WHERE ?5 OR excluded.version >= community_writers.version",
5553            params![community_id, channel_id, enc, version, replace],
5554        )
5555        .map_err(|e| format!("set writers: {e}"))?;
5556    // Whichever fold stored it, what a new writer or stop entry undoes is owed a retraction.
5557    if changed > 0 {
5558        crate::community::v2::realtime::invalidate_held_v2_community(community_id);
5559        if let Some(since) = retraction_since(old.as_deref(), content) {
5560            owe_retraction(&conn, community_id, channel_id, since)?;
5561        }
5562        for (writer, since) in stop_owes(old.as_deref(), content) {
5563            owe_author_retraction_on(&conn, community_id, channel_id, &crate::simd::hex::bytes_to_hex_32(&writer), since, None)?;
5564        }
5565    }
5566    Ok(changed > 0)
5567}
5568
5569/// From when a move from `old` to `new` can change everyone's verdicts: the earliest writer entry
5570/// it added, or entry a fork switch dropped. An `open` added takes nothing back, an entry the cap
5571/// trimmed from the front moves no window, and a stop is its writer's alone ([`stop_owes`]).
5572pub(crate) fn retraction_since(old: Option<&str>, new: &str) -> Option<u64> {
5573    use crate::community::v2::writers::{Ledger, Spell};
5574    let new = Ledger::parse(new)?;
5575    let old = old.and_then(Ledger::parse);
5576    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)));
5577    let front = new.entries.first().map_or(u64::MAX, |e| e.at);
5578    let dropped = old.iter().flat_map(|o| o.entries.iter()).filter(|e| !matches!(e.spell, Spell::Other) && e.at >= front && !new.entries.contains(e));
5579    added.chain(dropped).map(|e| e.effective()).min()
5580}
5581
5582/// The stops a move from `old` to `new` added: whose posts each undoes, and from when.
5583pub(crate) fn stop_owes(old: Option<&str>, new: &str) -> Vec<([u8; 32], u64)> {
5584    use crate::community::v2::writers::{Ledger, Spell};
5585    let Some(new) = Ledger::parse(new) else { return Vec::new() };
5586    let old = old.and_then(Ledger::parse);
5587    new.entries
5588        .iter()
5589        .filter(|e| !old.as_ref().is_some_and(|o| o.entries.contains(e)))
5590        .filter_map(|e| match e.spell {
5591            Spell::Stop { writer } => Some((writer, e.effective())),
5592            _ => None,
5593        })
5594        .collect()
5595}
5596
5597fn retraction_key(community_id: &str, channel_id: &str) -> String {
5598    format!("writer_retract:{community_id}:{channel_id}")
5599}
5600
5601/// Stored as `since:generation`: a drain clears only the value it read, so what is owed while it
5602/// runs survives it.
5603fn parse_owed(value: &str) -> Option<(u64, u64)> {
5604    let mut parts = value.split(':');
5605    Some((parts.next()?.parse().ok()?, parts.next().and_then(|g| g.parse().ok()).unwrap_or(0)))
5606}
5607
5608fn owe_retraction(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, since: u64) -> Result<(), String> {
5609    let key = retraction_key(community_id, channel_id);
5610    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}"))?;
5611    let (since, generation) = held.as_deref().and_then(parse_owed).map_or((since, 1), |(s, g)| (s.min(since), g + 1));
5612    conn.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)", params![key, format!("{since}:{generation}")]).map_err(|e| format!("owe retraction: {e}"))?;
5613    Ok(())
5614}
5615
5616/// Owe `channel_id` a retraction of what it shows dated from `since_ms`.
5617pub fn owe_writer_retraction(community_id: &str, channel_id: &str, since_ms: u64) -> Result<(), String> {
5618    let conn = super::get_write_connection_guard_static()?;
5619    owe_retraction(&conn, community_id, channel_id, since_ms)
5620}
5621
5622/// The Channels of `community_id` owed a retraction: `(channel, since_ms, generation)`.
5623pub fn owed_retractions(community_id: &str) -> Result<Vec<(String, u64, u64)>, String> {
5624    let prefix = retraction_key(community_id, "");
5625    let conn = super::get_db_connection_guard_static()?;
5626    let mut stmt = conn.prepare("SELECT key, value FROM settings WHERE substr(key, 1, length(?1)) = ?1").map_err(|e| format!("owed retractions: {e}"))?;
5627    let rows = stmt.query_map(params![prefix], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(|e| format!("owed retractions: {e}"))?;
5628    Ok(rows.flatten().filter_map(|(k, v)| parse_owed(&v).map(|(since, generation)| (k[prefix.len()..].to_string(), since, generation))).collect())
5629}
5630
5631/// The settings rows owed author take-backs were kept in before they were sealed.
5632fn legacy_author_retraction_range(community_id: &str) -> (String, String) {
5633    (format!("writer_retract_by:{community_id}:"), format!("writer_retract_by:{community_id};"))
5634}
5635
5636/// Owe `channel_id` a retraction of what `author` (hex) posted there from `since_ms`, before
5637/// `until_ms` when given.
5638pub fn owe_author_retraction(community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
5639    let _seal = crate::crypto::gate::sealing();
5640    let conn = super::get_write_connection_guard_static()?;
5641    owe_author_retraction_on(&conn, community_id, channel_id, author, since_ms, until_ms)
5642}
5643
5644/// Stored as `since:generation:until`, `until` empty when open.
5645fn parse_author_owed(value: &str) -> Option<(u64, u64, Option<u64>)> {
5646    let mut parts = value.split(':');
5647    let since = parts.next()?.parse().ok()?;
5648    let generation = parts.next().and_then(|g| g.parse().ok()).unwrap_or(0);
5649    let until = parts.next().and_then(|u| u.parse().ok());
5650    Some((since, generation, until))
5651}
5652
5653/// One author's owed take-back in a Channel.
5654struct AuthorOwed {
5655    seq: i64,
5656    channel: String,
5657    author: [u8; 32],
5658    since: u64,
5659    generation: u64,
5660    until: Option<u64>,
5661}
5662
5663/// An owed take-back at rest: `[format = 1][author][since][generation][flags: until][until]`,
5664/// numbers as LEB128. Sealed, so who is owed one is never kept in the clear.
5665fn author_owed_body(author: &[u8; 32], since: u64, generation: u64, until: Option<u64>) -> Vec<u8> {
5666    let mut out = Vec::with_capacity(64);
5667    out.push(1);
5668    out.extend_from_slice(author);
5669    varint(&mut out, since);
5670    varint(&mut out, generation);
5671    out.push(until.is_some() as u8);
5672    if let Some(until) = until {
5673        varint(&mut out, until);
5674    }
5675    out
5676}
5677
5678fn author_owed_from_body(body: &[u8]) -> Option<([u8; 32], u64, u64, Option<u64>)> {
5679    let (&1, rest) = body.split_first()? else { return None };
5680    let (author, mut rest) = rest.split_at_checked(32)?;
5681    let since = take_varint(&mut rest)?;
5682    let generation = take_varint(&mut rest)?;
5683    let (&flags, tail) = rest.split_first()?;
5684    rest = tail;
5685    let until = match flags {
5686        0 => None,
5687        1 => Some(take_varint(&mut rest)?),
5688        _ => return None,
5689    };
5690    rest.is_empty().then_some((author.try_into().ok()?, since, generation, until))
5691}
5692
5693/// `community_id`'s owed author take-backs, in `channel_id` alone when given.
5694fn held_author_retractions(conn: &rusqlite::Connection, community_id: &str, channel_id: Option<&str>) -> Result<Vec<AuthorOwed>, String> {
5695    let rows: Vec<(i64, String, Vec<u8>)> = {
5696        let mut stmt = conn
5697            .prepare_cached(
5698                "SELECT o.seq, o.channel_id, o.body FROM community_owed_authors o
5699                 JOIN community_guestbook_books b ON b.book = o.book
5700                 WHERE b.community_id = ?1 AND (?2 IS NULL OR o.channel_id = ?2) ORDER BY o.seq",
5701            )
5702            .map_err(|e| format!("owed retractions: {e}"))?;
5703        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}"))?;
5704        rows.filter_map(|r| r.ok()).collect()
5705    };
5706    Ok(crate::crypto::open_batch(|o| {
5707        rows.into_iter()
5708            .filter_map(|(seq, channel, body)| {
5709                let (author, since, generation, until) = author_owed_from_body(&o.open_blob_or_keep(&body))?;
5710                Some(AuthorOwed { seq, channel, author, since, generation, until })
5711            })
5712            .collect()
5713    }))
5714}
5715
5716fn has_legacy_author_retractions(conn: &rusqlite::Connection, community_id: &str) -> Result<bool, String> {
5717    let (lo, hi) = legacy_author_retraction_range(community_id);
5718    conn.query_row("SELECT 1 FROM settings WHERE key >= ?1 AND key < ?2 LIMIT 1", params![lo, hi], |_| Ok(()))
5719        .optional()
5720        .map(|r| r.is_some())
5721        .map_err(|e| format!("owed retractions: {e}"))
5722}
5723
5724/// Move owed take-backs still kept as settings rows into sealed rows. One that doesn't parse
5725/// was never read as owed, and goes.
5726fn move_author_retraction_settings(conn: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
5727    let (lo, hi) = legacy_author_retraction_range(community_id);
5728    let legacy: Vec<(String, String)> = {
5729        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}"))?;
5730        let rows = stmt.query_map(params![lo, hi], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("move owed retractions: {e}"))?;
5731        rows.filter_map(|r| r.ok()).collect()
5732    };
5733    if legacy.is_empty() {
5734        return Ok(());
5735    }
5736    let book = guestbook_book(conn, community_id)?;
5737    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}"))?;
5738    crate::crypto::seal_batch(|sealer| {
5739        for (key, value) in &legacy {
5740            let Some((channel, author)) = key[lo.len()..].split_once(':') else { continue };
5741            let (Some(author), Some((since, generation, until))) = (crate::simd::hex::hex_to_bytes_32_checked(author), parse_author_owed(value)) else { continue };
5742            insert.execute(params![book, channel, sealer.seal_blob(&author_owed_body(&author, since, generation, until))?]).map_err(|e| format!("move owed retractions: {e}"))?;
5743        }
5744        Ok::<(), String>(())
5745    })?;
5746    conn.execute("DELETE FROM settings WHERE key >= ?1 AND key < ?2", params![lo, hi]).map_err(|e| format!("move owed retractions: {e}"))?;
5747    Ok(())
5748}
5749
5750/// Run `f` as one unit on `conn`, inside a caller's transaction or not.
5751fn in_savepoint<T>(conn: &rusqlite::Connection, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
5752    conn.execute_batch("SAVEPOINT owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
5753    match f() {
5754        Ok(v) => {
5755            conn.execute_batch("RELEASE owed_authors").map_err(|e| format!("owed retractions: {e}"))?;
5756            Ok(v)
5757        }
5758        Err(e) => {
5759            let _ = conn.execute_batch("ROLLBACK TO owed_authors; RELEASE owed_authors");
5760            Err(e)
5761        }
5762    }
5763}
5764
5765/// On the write connection, under a sealing ticket.
5766fn owe_author_retraction_on(conn: &rusqlite::Connection, community_id: &str, channel_id: &str, author: &str, since_ms: u64, until_ms: Option<u64>) -> Result<(), String> {
5767    let author = crate::simd::hex::hex_to_bytes_32_checked(author).ok_or_else(|| format!("owe retraction: not an author key: {author}"))?;
5768    in_savepoint(conn, || {
5769        move_author_retraction_settings(conn, community_id)?;
5770        let held = held_author_retractions(conn, community_id, Some(channel_id))?.into_iter().find(|o| o.author == author);
5771        let (since, generation, until) = match &held {
5772            // The same span closing narrows its own owe; any other range widens it.
5773            Some(o) => (o.since.min(since_ms), o.generation + 1, match (o.until, until_ms) {
5774                (Some(a), Some(b)) => Some(a.max(b)),
5775                (None, Some(b)) if o.since == since_ms => Some(b),
5776                _ => None,
5777            }),
5778            None => (since_ms, 1, until_ms),
5779        };
5780        let body = crate::crypto::seal_batch(|sealer| sealer.seal_blob(&author_owed_body(&author, since, generation, until)))?;
5781        match held {
5782            Some(o) => conn.execute("UPDATE community_owed_authors SET body = ?1 WHERE seq = ?2", params![body, o.seq]),
5783            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]),
5784        }
5785        .map_err(|e| format!("owe retraction: {e}"))?;
5786        Ok(())
5787    })
5788}
5789
5790/// What `community_id` owes one author's posts: `(channel, author hex, since_ms, until_ms, generation)`.
5791pub fn owed_author_retractions(community_id: &str) -> Result<Vec<(String, String, u64, Option<u64>, u64)>, String> {
5792    if has_legacy_author_retractions(&*super::get_db_connection_guard_static()?, community_id)? {
5793        let _seal = crate::crypto::gate::sealing();
5794        let conn = super::get_write_connection_guard_static()?;
5795        in_savepoint(&conn, || move_author_retraction_settings(&conn, community_id))?;
5796    }
5797    let mut owed: Vec<_> = held_author_retractions(&*super::get_db_connection_guard_static()?, community_id, None)?
5798        .into_iter()
5799        .map(|o| (o.channel, crate::simd::hex::bytes_to_hex_32(&o.author), o.since, o.until, o.generation))
5800        .collect();
5801    owed.sort_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
5802    Ok(owed)
5803}
5804
5805/// Clear one author's owed retraction once done, unless more was owed since it was read.
5806pub fn settle_author_retraction(community_id: &str, channel_id: &str, author: &str, since: u64, until: Option<u64>, generation: u64) -> Result<(), String> {
5807    let Some(author) = crate::simd::hex::hex_to_bytes_32_checked(author) else { return Ok(()) };
5808    let _seal = crate::crypto::gate::sealing();
5809    let conn = super::get_write_connection_guard_static()?;
5810    in_savepoint(&conn, || {
5811        move_author_retraction_settings(&conn, community_id)?;
5812        let done = held_author_retractions(&conn, community_id, Some(channel_id))?
5813            .into_iter()
5814            .filter(|o| o.author == author && o.since == since && o.until == until && o.generation == generation);
5815        for o in done {
5816            conn.execute("DELETE FROM community_owed_authors WHERE seq = ?1", params![o.seq]).map_err(|e| format!("settle retraction: {e}"))?;
5817        }
5818        Ok(())
5819    })
5820}
5821
5822/// Each departed member's spans away, as the Guestbook fold reads them. Shared, so a fold that
5823/// moves one member copies no one else's.
5824pub type DepartureSpans = std::collections::BTreeMap<PublicKey, std::sync::Arc<[crate::community::v2::guestbook::Span]>>;
5825
5826/// The departures this device has already owed take-backs for, and the row each member's sits in.
5827#[derive(Default)]
5828pub struct DeparturesSeen {
5829    pub spans: std::sync::Arc<DepartureSpans>,
5830    /// The row of each of `spans` in turn.
5831    rows: Vec<i64>,
5832}
5833
5834type DeparturesSeenCache = Parsed<std::sync::Arc<DeparturesSeen>, 8>;
5835
5836fn departures_seen_cache() -> std::sync::Arc<std::sync::Mutex<DeparturesSeenCache>> {
5837    struct Key;
5838    super::current_session().scoped::<Key, std::sync::Mutex<DeparturesSeenCache>>()
5839}
5840
5841fn legacy_departures_key(community_id: &str) -> String {
5842    format!("departures_seen:{community_id}")
5843}
5844
5845pub fn departures_seen(community_id: &str) -> Result<std::sync::Arc<DeparturesSeen>, String> {
5846    let cache = departures_seen_cache();
5847    let generation = {
5848        let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
5849        if let Some(hit) = held.get(community_id) {
5850            return Ok(hit);
5851        }
5852        held.generation(community_id)
5853    };
5854    let legacy = super::get_db_connection_guard_static()?
5855        .query_row("SELECT 1 FROM settings WHERE key = ?1", params![legacy_departures_key(community_id)], |_| Ok(()))
5856        .optional()
5857        .map_err(|e| format!("load departures: {e}"))?
5858        .is_some();
5859    if legacy {
5860        let _seal = crate::crypto::gate::sealing();
5861        let conn = super::get_write_connection_guard_static()?;
5862        let tx = conn.unchecked_transaction().map_err(|e| format!("move departures tx: {e}"))?;
5863        move_departures_setting(&tx, community_id)?;
5864        tx.commit().map_err(|e| format!("move departures commit: {e}"))?;
5865    }
5866    let seen = std::sync::Arc::new(read_departures(&*super::get_db_connection_guard_static()?, community_id)?);
5867    cache.lock().unwrap_or_else(|e| e.into_inner()).put(community_id, generation, seen.clone());
5868    Ok(seen)
5869}
5870
5871fn read_departures(conn: &rusqlite::Connection, community_id: &str) -> Result<DeparturesSeen, String> {
5872    let rows: Vec<(i64, Vec<u8>)> = {
5873        let mut stmt = conn
5874            .prepare_cached(
5875                "SELECT d.seq, d.body FROM community_departures_seen d
5876                 JOIN community_guestbook_books b ON b.book = d.book
5877                 WHERE b.community_id = ?1 ORDER BY d.seq",
5878            )
5879            .map_err(|e| format!("load departures: {e}"))?;
5880        let rows = stmt.query_map(params![community_id], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| format!("load departures: {e}"))?;
5881        rows.filter_map(|r| r.ok()).collect()
5882    };
5883    let held: std::collections::BTreeMap<PublicKey, (i64, Vec<crate::community::v2::guestbook::Span>)> = crate::crypto::open_batch(|o| {
5884        rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_or_keep(&body)).map(|(member, owed)| (member, (seq, owed)))).collect()
5885    });
5886    let rows = held.values().map(|(seq, _)| *seq).collect();
5887    Ok(DeparturesSeen { spans: std::sync::Arc::new(held.into_iter().map(|(member, (_, owed))| (member, owed.into())).collect()), rows })
5888}
5889
5890/// Move a record still kept as one settings row into rows. One that doesn't parse read as nothing seen.
5891fn move_departures_setting(tx: &rusqlite::Connection, community_id: &str) -> Result<(), String> {
5892    let key = legacy_departures_key(community_id);
5893    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 {
5894        return Ok(());
5895    };
5896    let by_hex: std::collections::BTreeMap<String, Vec<crate::community::v2::guestbook::Span>> = serde_json::from_str(&json).unwrap_or_default();
5897    let book = guestbook_book(tx, community_id)?;
5898    let mut stmt = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("move departures: {e}"))?;
5899    crate::crypto::seal_batch(|sealer| {
5900        for (member, owed) in by_hex.iter().filter_map(|(k, v)| Some((PublicKey::from_hex(k).ok()?, v))) {
5901            stmt.execute(params![book, sealer.seal_blob(&departure_body(&member, owed))?]).map_err(|e| format!("move departures: {e}"))?;
5902        }
5903        Ok::<(), String>(())
5904    })?;
5905    tx.execute("DELETE FROM settings WHERE key = ?1", params![key]).map_err(|e| format!("move departures: {e}"))?;
5906    Ok(())
5907}
5908
5909/// Record `now` as owed for, writing only the members whose spans changed.
5910pub fn set_departures_seen(community_id: &str, now: std::sync::Arc<DepartureSpans>) -> Result<(), String> {
5911    let _seal = crate::crypto::gate::sealing();
5912    let conn = super::get_write_connection_guard_static()?;
5913    let tx = conn.unchecked_transaction().map_err(|e| format!("store departures tx: {e}"))?;
5914    move_departures_setting(&tx, community_id)?;
5915    let cache = departures_seen_cache();
5916    let cached = cache.lock().unwrap_or_else(|e| e.into_inner()).get(community_id);
5917    let held = match cached {
5918        Some(held) => held,
5919        None => std::sync::Arc::new(read_departures(&tx, community_id)?),
5920    };
5921    let book = guestbook_book(&tx, community_id)?;
5922    let mut rows = Vec::with_capacity(now.len());
5923    {
5924        let mut update = tx.prepare_cached("UPDATE community_departures_seen SET body = ?1 WHERE seq = ?2").map_err(|e| format!("store departures: {e}"))?;
5925        let mut insert = tx.prepare_cached("INSERT INTO community_departures_seen (book, body) VALUES (?1, ?2)").map_err(|e| format!("store departures: {e}"))?;
5926        let mut delete = tx.prepare_cached("DELETE FROM community_departures_seen WHERE seq = ?1").map_err(|e| format!("store departures: {e}"))?;
5927        // Both sides are in key order: one walk pairs each member with its row.
5928        let mut was = held.spans.iter().zip(held.rows.iter().copied()).peekable();
5929        crate::crypto::seal_batch(|sealer| {
5930            for (member, owed) in now.iter() {
5931                while let Some((_, seq)) = was.next_if(|((m, _), _)| *m < member) {
5932                    delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
5933                }
5934                let seq = match was.next_if(|((m, _), _)| *m == member) {
5935                    Some(((_, before), seq)) if before == owed => seq,
5936                    Some((_, seq)) => {
5937                        update.execute(params![sealer.seal_blob(&departure_body(member, owed))?, seq]).map_err(|e| format!("store departures: {e}"))?;
5938                        seq
5939                    }
5940                    None => {
5941                        insert.execute(params![book, sealer.seal_blob(&departure_body(member, owed))?]).map_err(|e| format!("store departures: {e}"))?;
5942                        tx.last_insert_rowid()
5943                    }
5944                };
5945                rows.push(seq);
5946            }
5947            for (_, seq) in was.by_ref() {
5948                delete.execute(params![seq]).map_err(|e| format!("store departures: {e}"))?;
5949            }
5950            Ok::<(), String>(())
5951        })?;
5952    }
5953    tx.commit().map_err(|e| format!("store departures commit: {e}"))?;
5954    let mut cached = cache.lock().unwrap_or_else(|e| e.into_inner());
5955    let generation = cached.moved(community_id);
5956    cached.put(community_id, generation, std::sync::Arc::new(DeparturesSeen { spans: now, rows }));
5957    Ok(())
5958}
5959
5960fn varint(out: &mut Vec<u8>, mut v: u64) {
5961    while v >= 0x80 {
5962        out.push(v as u8 | 0x80);
5963        v >>= 7;
5964    }
5965    out.push(v as u8);
5966}
5967
5968fn take_varint(rest: &mut &[u8]) -> Option<u64> {
5969    let mut v = 0u64;
5970    for shift in (0..64).step_by(7) {
5971        let (&b, tail) = rest.split_first()?;
5972        *rest = tail;
5973        v |= ((b & 0x7f) as u64).checked_shl(shift)?;
5974        if b & 0x80 == 0 {
5975            return Some(v);
5976        }
5977    }
5978    None
5979}
5980
5981/// A member's owed spans at rest: `[format = 1][member][count][flags: until, kicked][from][until]…`,
5982/// numbers as LEB128. Sealed with the rest, so who left and when is never kept in the clear.
5983fn departure_body(member: &PublicKey, spans: &[crate::community::v2::guestbook::Span]) -> Vec<u8> {
5984    let mut out = Vec::with_capacity(34 + spans.len() * 13);
5985    out.push(1);
5986    out.extend_from_slice(member.as_bytes());
5987    varint(&mut out, spans.len() as u64);
5988    for &(from, until, kicked) in spans {
5989        out.push(until.is_some() as u8 | (kicked as u8) << 1);
5990        varint(&mut out, from);
5991        if let Some(until) = until {
5992            varint(&mut out, until);
5993        }
5994    }
5995    out
5996}
5997
5998fn departure_from_body(body: &[u8]) -> Option<(PublicKey, Vec<crate::community::v2::guestbook::Span>)> {
5999    let (&1, rest) = body.split_first()? else { return None };
6000    let (member, mut rest) = rest.split_at_checked(32)?;
6001    let member = PublicKey::from_byte_array(member.try_into().ok()?);
6002    let count = take_varint(&mut rest)?;
6003    // Each span takes at least two bytes, so a count beyond that is a forged length.
6004    if count > rest.len() as u64 / 2 {
6005        return None;
6006    }
6007    let mut spans = Vec::with_capacity(count as usize);
6008    for _ in 0..count {
6009        let (&flags, tail) = rest.split_first()?;
6010        rest = tail;
6011        if flags & !0b11 != 0 {
6012            return None;
6013        }
6014        let from = take_varint(&mut rest)?;
6015        let until = if flags & 1 != 0 { Some(take_varint(&mut rest)?) } else { None };
6016        spans.push((from, until, flags & 2 != 0));
6017    }
6018    rest.is_empty().then_some((member, spans))
6019}
6020
6021/// Clear `channel_id`'s owed retraction once done, unless more was owed since it was read.
6022pub fn settle_retraction(community_id: &str, channel_id: &str, since: u64, generation: u64) -> Result<(), String> {
6023    let conn = super::get_write_connection_guard_static()?;
6024    conn.execute("DELETE FROM settings WHERE key = ?1 AND value = ?2", params![retraction_key(community_id, channel_id), format!("{since}:{generation}")])
6025        .map_err(|e| format!("settle retraction: {e}"))?;
6026    Ok(())
6027}
6028
6029pub fn get_community_writers(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
6030    let conn = super::get_db_connection_guard_static()?;
6031    let row: Option<(String, i64)> = conn
6032        .query_row(
6033            "SELECT content, version FROM community_writers WHERE community_id = ?1 AND channel_id = ?2",
6034            params![community_id, channel_id],
6035            |r| Ok((r.get(0)?, r.get(1)?)),
6036        )
6037        .optional()
6038        .map_err(|e| format!("get writers: {e}"))?;
6039    Ok(row.map(|(content, version)| (dec_txt(&content), version)))
6040}
6041
6042/// How many held wraps one Channel keeps, how many bytes, how many one author, and how many
6043/// bytes a Community: past any, those dated furthest from now go first, so a flood dated years
6044/// ahead or behind, or one author's, evicts only itself.
6045pub const MAX_HELD_WRAPS: usize = 500;
6046pub const MAX_HELD_BYTES: usize = 4 * 1024 * 1024;
6047pub const MAX_HELD_PER_AUTHOR: usize = MAX_HELD_WRAPS / 10;
6048pub const MAX_HELD_COMMUNITY_BYTES: usize = 16 * 1024 * 1024;
6049
6050/// How far past this device's clock a post may be dated and still be held (CORD-02 §5's horizon):
6051/// a later one is left on the relay for a later read.
6052pub const HELD_HORIZON_MS: u64 = 60 * 60 * 1000;
6053
6054/// Hold `wrap`, a post by `author` (hex) `channel_id`'s rules didn't stand behind on arrival,
6055/// dated `at_ms`. Whether it is held: a post dated past the horizon isn't, nor one the caps
6056/// evict at once. A marked copy kept beside an evicted wrap goes with it.
6057pub fn hold_wrap(community_id: &str, channel_id: &str, wrap_id: &str, wrap: &str, author: &str, at_ms: u64) -> Result<bool, String> {
6058    let now = now_secs().max(0) as u64 * 1000;
6059    if at_ms > now.saturating_add(HELD_HORIZON_MS) {
6060        let held = deferred();
6061        let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
6062        map.insert(wrap_id.to_string(), at_ms);
6063        // Bounded: one dropped costs only a decrypt on the next read.
6064        if map.len() > MAX_DEFERRED {
6065            if let Some(furthest) = map.iter().max_by_key(|(_, at)| **at).map(|(id, _)| id.clone()) {
6066                map.remove(&furthest);
6067            }
6068        }
6069        return Ok(false);
6070    }
6071    let _seal = crate::crypto::gate::sealing();
6072    let enc = enc_txt(wrap)?;
6073    let conn = super::get_write_connection_guard_static()?;
6074    conn.execute(
6075        "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)",
6076        params![wrap_id, community_id, channel_id, enc, at_ms as i64, author, enc.len() as i64],
6077    )
6078    .map_err(|e| format!("hold wrap: {e}"))?;
6079    // Nearest now first, across the Community; each row counts against its Channel and author.
6080    let ranked: Vec<(String, String, String, usize)> = {
6081        let mut stmt = conn
6082            .prepare("SELECT wrap_id, channel_id, author, bytes FROM community_held_wraps WHERE community_id = ?1 ORDER BY ABS(at_ms - ?2), wrap_id")
6083            .map_err(|e| format!("rank held wraps: {e}"))?;
6084        let rows = stmt
6085            .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)))
6086            .map_err(|e| format!("rank held wraps: {e}"))?;
6087        rows.flatten().collect()
6088    };
6089    let (mut channels, mut authors) = (std::collections::HashMap::<&str, (usize, usize)>::new(), std::collections::HashMap::<(&str, &str), usize>::new());
6090    let mut evicted: Vec<&String> = Vec::new();
6091    let mut kept: Vec<(&String, &str, usize)> = Vec::new();
6092    for (id, ch, who, len) in &ranked {
6093        let c = channels.entry(ch.as_str()).or_default();
6094        let a = authors.entry((ch.as_str(), who.as_str())).or_default();
6095        if c.0 >= MAX_HELD_WRAPS || c.1 + len > MAX_HELD_BYTES || (!who.is_empty() && *a >= MAX_HELD_PER_AUTHOR) {
6096            evicted.push(id);
6097            continue;
6098        }
6099        c.0 += 1;
6100        c.1 += len;
6101        *a += 1;
6102        kept.push((id, ch.as_str(), *len));
6103    }
6104    // Past the Community's bytes, the Channel holding the most gives up its furthest-dated first,
6105    // so one Channel's flood never empties another.
6106    let mut total: usize = kept.iter().map(|k| k.2).sum();
6107    while total > MAX_HELD_COMMUNITY_BYTES {
6108        let most = channels.values().map(|c| c.1).max().unwrap_or(0);
6109        let Some(i) = kept.iter().rposition(|k| channels.get(k.1).is_some_and(|c| c.1 == most)) else { break };
6110        let (id, ch, len) = kept.remove(i);
6111        if let Some(c) = channels.get_mut(ch) {
6112            c.1 -= len;
6113        }
6114        total -= len;
6115        evicted.push(id);
6116    }
6117    for id in &evicted {
6118        conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![id]).map_err(|e| format!("trim held wraps: {e}"))?;
6119        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}"))?;
6120    }
6121    Ok(!evicted.iter().any(|id| *id == wrap_id))
6122}
6123
6124// ── Control wraps: every wrap of a Control Plane view this device has read ──
6125
6126/// A stored Control wrap: its id, its own timestamp (seconds), and its body unless it was refused.
6127pub type ControlWrapRow = ([u8; 32], u64, Option<Vec<u8>>);
6128
6129/// Every wrap id held for `view`, the refused ones too, each with its timestamp.
6130pub fn control_wrap_ids(community_id: &str, view: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
6131    let conn = super::get_db_connection_guard_static()?;
6132    let mut stmt = conn
6133        .prepare_cached("SELECT wrap_id, created_at FROM community_control_wraps WHERE community_id = ?1 AND view = ?2")
6134        .map_err(|e| format!("control wrap ids: {e}"))?;
6135    let rows = stmt
6136        .query_map(params![community_id, &view[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
6137        .map_err(|e| format!("control wrap ids: {e}"))?;
6138    let mut out = Vec::new();
6139    for row in rows {
6140        let (id, at) = row.map_err(|e| format!("control wrap ids: {e}"))?;
6141        out.push((id.try_into().map_err(|_| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
6142    }
6143    Ok(out)
6144}
6145
6146/// Store `rows` judged under `rules`, all or none. A wrap already held keeps its row. Returns how
6147/// many were new.
6148pub fn store_control_wraps(community_id: &str, view: &[u8; 32], rules: u32, now_secs: u64, rows: &[ControlWrapRow]) -> Result<usize, String> {
6149    if rows.is_empty() {
6150        return Ok(0);
6151    }
6152    let _seal = crate::crypto::gate::sealing();
6153    let conn = super::get_write_connection_guard_static()?;
6154    let tx = conn.unchecked_transaction().map_err(|e| format!("store control wraps tx: {e}"))?;
6155    let mut stored = 0usize;
6156    {
6157        let mut stmt = tx
6158            .prepare_cached(
6159                "INSERT OR IGNORE INTO community_control_wraps (community_id, view, wrap_id, created_at, wrap, rules, judged_at)
6160                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
6161            )
6162            .map_err(|e| format!("store control wraps: {e}"))?;
6163        crate::crypto::seal_batch(|sealer| -> Result<(), String> {
6164            for (id, at, body) in rows {
6165                let sealed = body.as_deref().map(|b| sealer.seal_blob(b)).transpose()?;
6166                stored += stmt
6167                    .execute(params![community_id, &view[..], &id[..], *at as i64, sealed, rules, now_secs as i64])
6168                    .map_err(|e| format!("store control wraps: {e}"))?;
6169            }
6170            Ok(())
6171        })?;
6172    }
6173    tx.commit().map_err(|e| format!("store control wraps commit: {e}"))?;
6174    Ok(stored)
6175}
6176
6177/// The next `limit` bodies of `view` below `below` (a wrap's timestamp and id), newest first.
6178pub 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> {
6179    let rows: Vec<(Vec<u8>, i64, Vec<u8>)> = {
6180        let conn = super::get_db_connection_guard_static()?;
6181        // The far corner of the order stands in for no bound.
6182        let (at, id) = below.map_or((i64::MAX, vec![0xff; 33]), |(at, id)| (at as i64, id.to_vec()));
6183        let mut stmt = conn
6184            .prepare_cached(
6185                "SELECT wrap_id, created_at, wrap FROM community_control_wraps
6186                 WHERE community_id = ?1 AND view = ?2 AND wrap IS NOT NULL AND (created_at, wrap_id) < (?3, ?4)
6187                 ORDER BY created_at DESC, wrap_id DESC LIMIT ?5",
6188            )
6189            .map_err(|e| format!("control wrap page: {e}"))?;
6190        let rows = stmt
6191            .query_map(params![community_id, &view[..], at, id, limit as i64], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
6192            .map_err(|e| format!("control wrap page: {e}"))?;
6193        rows.collect::<Result<_, _>>().map_err(|e| format!("control wrap page: {e}"))?
6194    };
6195    crate::crypto::open_batch(|o| {
6196        rows.into_iter()
6197            .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))))
6198            .collect()
6199    })
6200}
6201
6202/// The bodies of `ids` in `view`, opened, for those held with one.
6203pub fn control_wrap_bodies(community_id: &str, view: &[u8; 32], ids: &[[u8; 32]]) -> Result<Vec<Vec<u8>>, String> {
6204    let mut sealed: Vec<Vec<u8>> = Vec::with_capacity(ids.len());
6205    {
6206        let conn = super::get_db_connection_guard_static()?;
6207        let mut stmt = conn
6208            .prepare_cached("SELECT wrap FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3 AND wrap IS NOT NULL")
6209            .map_err(|e| format!("control wrap bodies: {e}"))?;
6210        for id in ids {
6211            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}"))? {
6212                sealed.push(body);
6213            }
6214        }
6215    }
6216    crate::crypto::open_batch(|o| Ok(sealed.iter().map(|body| o.open_blob_or_keep(body)).collect()))
6217}
6218
6219/// What `view` holds: bodies, refusals, and the bodies' bytes as stored.
6220pub fn control_wrap_counts(community_id: &str, view: &[u8; 32]) -> Result<(usize, usize, usize), String> {
6221    let conn = super::get_db_connection_guard_static()?;
6222    conn.query_row(
6223        "SELECT COUNT(wrap), COUNT(*) - COUNT(wrap), COALESCE(SUM(length(wrap)), 0) FROM community_control_wraps WHERE community_id = ?1 AND view = ?2",
6224        params![community_id, &view[..]],
6225        |r| Ok((r.get::<_, i64>(0)? as usize, r.get::<_, i64>(1)? as usize, r.get::<_, i64>(2)? as usize)),
6226    )
6227    .map_err(|e| format!("control wrap counts: {e}"))
6228}
6229
6230/// The Guestbook wraps of `plane` this device has read, with their timestamps.
6231pub fn guestbook_wrap_ids(community_id: &str, plane: &[u8; 32]) -> Result<Vec<([u8; 32], u64)>, String> {
6232    let conn = super::get_db_connection_guard_static()?;
6233    let mut stmt = conn
6234        .prepare_cached("SELECT wrap_id, created_at FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2")
6235        .map_err(|e| format!("guestbook wrap ids: {e}"))?;
6236    let rows = stmt
6237        .query_map(params![community_id, &plane[..]], |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, i64>(1)?)))
6238        .map_err(|e| format!("guestbook wrap ids: {e}"))?;
6239    let mut out = Vec::new();
6240    for row in rows {
6241        let (id, at) = row.map_err(|e| format!("guestbook wrap ids: {e}"))?;
6242        out.push((id.try_into().map_err(|_| "guestbook wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64));
6243    }
6244    Ok(out)
6245}
6246
6247/// Record Guestbook wraps as read: (id, timestamp, rules), `rules` 0 for one whose entry is stored.
6248pub fn store_guestbook_wraps(community_id: &str, plane: &[u8; 32], now_secs: u64, rows: &[([u8; 32], u64, u32)]) -> Result<(), String> {
6249    if rows.is_empty() {
6250        return Ok(());
6251    }
6252    let conn = super::get_write_connection_guard_static()?;
6253    let tx = conn.unchecked_transaction().map_err(|e| format!("store guestbook wraps tx: {e}"))?;
6254    {
6255        let mut stmt = tx
6256            .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)")
6257            .map_err(|e| format!("store guestbook wraps: {e}"))?;
6258        for (id, at, rules) in rows {
6259            stmt.execute(params![community_id, &plane[..], &id[..], *at as i64, rules, now_secs as i64]).map_err(|e| format!("store guestbook wraps: {e}"))?;
6260        }
6261    }
6262    tx.commit().map_err(|e| format!("store guestbook wraps commit: {e}"))
6263}
6264
6265/// Forget the Guestbook wraps of any plane but `plane`, the refusals of `plane` judged under
6266/// rules other than `rules`, and the `oldest` longest standing of its other refusals.
6267pub fn forget_guestbook_wraps(community_id: &str, plane: &[u8; 32], rules: u32, oldest: usize) -> Result<(), String> {
6268    let conn = super::get_write_connection_guard_static()?;
6269    conn.execute(
6270        "DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND (plane != ?2 OR (rules != 0 AND rules != ?3))",
6271        params![community_id, &plane[..], rules],
6272    )
6273    .map_err(|e| format!("forget guestbook wraps: {e}"))?;
6274    if oldest > 0 {
6275        conn.execute(
6276            "DELETE FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND wrap_id IN (
6277                 SELECT wrap_id FROM community_guestbook_wraps WHERE community_id = ?1 AND plane = ?2 AND rules != 0 ORDER BY judged_at LIMIT ?3)",
6278            params![community_id, &plane[..], oldest as i64],
6279        )
6280        .map_err(|e| format!("forget guestbook wraps: {e}"))?;
6281    }
6282    Ok(())
6283}
6284
6285/// Drop every Guestbook wrap recorded for a community, and how its relays were read.
6286pub fn purge_guestbook_wraps(community_id: &str) -> Result<(), String> {
6287    let conn = super::get_write_connection_guard_static()?;
6288    conn.execute("DELETE FROM community_guestbook_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
6289    conn.execute("DELETE FROM settings WHERE key = 'gbk_reads:' || ?1", params![community_id]).map_err(|e| format!("purge guestbook wraps: {e}"))?;
6290    Ok(())
6291}
6292
6293/// Drop everything held of a community's Control Plane, and how its relays were read.
6294pub fn purge_control_wraps(community_id: &str) -> Result<(), String> {
6295    let conn = super::get_write_connection_guard_static()?;
6296    conn.execute("DELETE FROM community_control_wraps WHERE community_id = ?1", params![community_id]).map_err(|e| format!("purge control wraps: {e}"))?;
6297    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}"))?;
6298    Ok(())
6299}
6300
6301/// Forget one wrap of `view`, so a sync asks for it again.
6302pub fn drop_control_wrap(community_id: &str, view: &[u8; 32], wrap_id: &[u8; 32]) -> Result<(), String> {
6303    let conn = super::get_write_connection_guard_static()?;
6304    conn.execute(
6305        "DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap_id = ?3",
6306        params![community_id, &view[..], &wrap_id[..]],
6307    )
6308    .map_err(|e| format!("drop control wrap: {e}"))?;
6309    Ok(())
6310}
6311
6312/// Forget `view`'s refusals judged under any rules but `rules`, and the `oldest` longest
6313/// standing of the rest, so each is fetched and judged again. Returns how many went.
6314pub fn forget_control_refusals(community_id: &str, view: &[u8; 32], rules: u32, oldest: usize) -> Result<usize, String> {
6315    let conn = super::get_write_connection_guard_static()?;
6316    let other = conn
6317        .execute(
6318            "DELETE FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL AND rules != ?3",
6319            params![community_id, &view[..], rules],
6320        )
6321        .map_err(|e| format!("forget control refusals: {e}"))?;
6322    let aged = conn
6323        .execute(
6324            "DELETE FROM community_control_wraps WHERE rowid IN (
6325                 SELECT rowid FROM community_control_wraps WHERE community_id = ?1 AND view = ?2 AND wrap IS NULL
6326                 ORDER BY judged_at, wrap_id LIMIT ?3)",
6327            params![community_id, &view[..], oldest as i64],
6328        )
6329        .map_err(|e| format!("forget control refusals: {e}"))?;
6330    Ok(other + aged)
6331}
6332
6333/// Note an Audit Log act no Control edition records (a moderator's delete, a voice directive),
6334/// keyed by the event that carried it so a re-delivery notes nothing twice.
6335pub fn record_audit_local(community_id: &str, id: &str, at_ms: u64, entry: &str) -> Result<(), String> {
6336    let _seal = crate::crypto::gate::sealing();
6337    let enc = enc_txt(entry)?;
6338    let conn = super::get_write_connection_guard_static()?;
6339    conn.execute(
6340        "INSERT OR IGNORE INTO community_audit_local (id, community_id, at_ms, entry) VALUES (?1, ?2, ?3, ?4)",
6341        params![id, community_id, at_ms as i64, enc],
6342    )
6343    .map_err(|e| format!("record audit: {e}"))?;
6344    Ok(())
6345}
6346
6347/// Every act [`record_audit_local`] noted for `community_id`: `(id, at_ms, entry)`.
6348pub fn get_audit_local(community_id: &str) -> Result<Vec<(String, u64, String)>, String> {
6349    let conn = super::get_db_connection_guard_static()?;
6350    let mut stmt = conn
6351        .prepare("SELECT id, at_ms, entry FROM community_audit_local WHERE community_id = ?1 ORDER BY at_ms")
6352        .map_err(|e| format!("read audit: {e}"))?;
6353    let rows = stmt
6354        .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?)))
6355        .map_err(|e| format!("read audit: {e}"))?;
6356    Ok(rows.flatten().map(|(id, at, entry)| (id, at, dec_txt(&entry))).collect())
6357}
6358
6359/// The Channels of `community_id` holding wraps.
6360pub fn held_wrap_channels(community_id: &str) -> Result<Vec<String>, String> {
6361    let conn = super::get_db_connection_guard_static()?;
6362    let mut stmt = conn.prepare("SELECT DISTINCT channel_id FROM community_held_wraps WHERE community_id = ?1").map_err(|e| format!("held channels: {e}"))?;
6363    let rows = stmt.query_map(params![community_id], |r| r.get(0)).map_err(|e| format!("held channels: {e}"))?;
6364    Ok(rows.flatten().collect())
6365}
6366
6367/// The ids of the wraps held for one Channel.
6368pub fn held_wrap_ids_in(community_id: &str, channel_id: &str) -> Result<Vec<String>, String> {
6369    let conn = super::get_db_connection_guard_static()?;
6370    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}"))?;
6371    let rows = stmt.query_map(params![community_id, channel_id], |r| r.get(0)).map_err(|e| format!("held ids: {e}"))?;
6372    Ok(rows.flatten().collect())
6373}
6374
6375/// The wraps held for one Channel, as `(wrap_id, wrap)`, oldest-dated first.
6376pub fn held_wraps_in(community_id: &str, channel_id: &str) -> Result<Vec<(String, String)>, String> {
6377    let conn = super::get_db_connection_guard_static()?;
6378    let mut stmt = conn
6379        .prepare("SELECT wrap_id, wrap FROM community_held_wraps WHERE community_id = ?1 AND channel_id = ?2 ORDER BY at_ms")
6380        .map_err(|e| format!("held wraps: {e}"))?;
6381    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}"))?;
6382    Ok(rows.flatten().map(|(id, wrap)| (id, dec_txt(&wrap))).collect())
6383}
6384
6385/// Every wrap held for `community_id`, as `(wrap_id, channel_id, wrap)`, oldest-dated first.
6386pub fn held_wraps(community_id: &str) -> Result<Vec<(String, String, String)>, String> {
6387    let conn = super::get_db_connection_guard_static()?;
6388    let mut stmt = conn
6389        .prepare("SELECT wrap_id, channel_id, wrap FROM community_held_wraps WHERE community_id = ?1 ORDER BY at_ms")
6390        .map_err(|e| format!("held wraps: {e}"))?;
6391    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}"))?;
6392    Ok(rows.flatten().map(|(id, ch, wrap)| (id, ch, dec_txt(&wrap))).collect())
6393}
6394
6395/// Whether `community_id` holds any wrap.
6396pub fn holds_wraps(community_id: &str) -> bool {
6397    super::get_db_connection_guard_static()
6398        .ok()
6399        .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())
6400        .is_some()
6401}
6402
6403/// Whether `channel_id` holds a wrap by `author` (hex) sent to `address` (a writer address),
6404/// waiting for a later judgment.
6405pub fn holds_wraps_at(community_id: &str, channel_id: &str, author: &str, address: &[u8; 32]) -> bool {
6406    let wraps: Vec<String> = {
6407        let Ok(conn) = super::get_db_connection_guard_static() else { return false };
6408        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 };
6409        let Ok(rows) = stmt.query_map(params![community_id, channel_id, author], |r| r.get::<_, String>(0)) else { return false };
6410        rows.flatten().collect()
6411    };
6412    wraps.iter().any(|w| crate::event_json::event(&dec_txt(w)).is_ok_and(|e| e.pubkey.to_bytes() == *address))
6413}
6414
6415struct DeferredWraps;
6416
6417pub const MAX_DEFERRED: usize = 4096;
6418
6419/// Wraps refused for a date past the horizon, by id: a read skips each until its date nears.
6420fn deferred() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, u64>>> {
6421    super::current_session().scoped::<DeferredWraps, _>()
6422}
6423
6424/// Of `wrap_ids`, those held, or deferred while their date is still past the horizon.
6425pub fn held_wrap_ids(wrap_ids: &[String]) -> std::collections::HashSet<String> {
6426    let now = now_secs().max(0) as u64 * 1000;
6427    let waiting: std::collections::HashSet<String> = {
6428        let held = deferred();
6429        let mut map = held.lock().unwrap_or_else(|e| e.into_inner());
6430        map.retain(|_, at| *at > now.saturating_add(HELD_HORIZON_MS));
6431        wrap_ids.iter().filter(|id| map.contains_key(*id)).cloned().collect()
6432    };
6433    let mut out = held_wrap_rows(wrap_ids);
6434    out.extend(waiting);
6435    out
6436}
6437
6438fn held_wrap_rows(wrap_ids: &[String]) -> std::collections::HashSet<String> {
6439    let Ok(conn) = super::get_db_connection_guard_static() else { return Default::default() };
6440    let Ok(json) = serde_json::to_string(wrap_ids) else { return Default::default() };
6441    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() };
6442    stmt.query_map(params![json], |r| r.get::<_, String>(0)).map(|rows| rows.flatten().collect()).unwrap_or_default()
6443}
6444
6445/// Let `wrap_id` go: it stands now.
6446pub fn release_held_wrap(wrap_id: &str) -> Result<(), String> {
6447    let conn = super::get_write_connection_guard_static()?;
6448    conn.execute("DELETE FROM community_held_wraps WHERE wrap_id = ?1", params![wrap_id]).map_err(|e| format!("release held wrap: {e}"))?;
6449    Ok(())
6450}
6451
6452/// A channel's stored Pin List head: `(raw content, version)`, `None` when no
6453/// edition has ever folded for it.
6454/// Each channel's folded Pin List version, without opening a list.
6455pub fn get_community_pin_versions(community_id: &str) -> Result<std::collections::HashMap<String, i64>, String> {
6456    let conn = super::get_db_connection_guard_static()?;
6457    let mut stmt = conn
6458        .prepare("SELECT channel_id, version FROM community_pins WHERE community_id = ?1")
6459        .map_err(|e| format!("get pin versions: {e}"))?;
6460    let rows = stmt
6461        .query_map(params![community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))
6462        .map_err(|e| format!("get pin versions: {e}"))?;
6463    rows.collect::<Result<_, _>>().map_err(|e| format!("get pin versions: {e}"))
6464}
6465
6466pub fn get_community_pins(community_id: &str, channel_id: &str) -> Result<Option<(String, i64)>, String> {
6467    let conn = super::get_db_connection_guard_static()?;
6468    let row: Option<(String, i64)> = conn
6469        .query_row(
6470            "SELECT content, version FROM community_pins WHERE community_id = ?1 AND channel_id = ?2",
6471            params![community_id, channel_id],
6472            |r| Ok((r.get(0)?, r.get(1)?)),
6473        )
6474        .optional()
6475        .map_err(|e| format!("get pins: {e}"))?;
6476    Ok(row.map(|(content, version)| (dec_txt(&content), version)))
6477}